diff options
Diffstat (limited to 'chef/spec')
-rw-r--r-- | chef/spec/unit/api_client_spec.rb | 35 | ||||
-rw-r--r-- | chef/spec/unit/certificate_spec.rb | 76 | ||||
-rw-r--r-- | chef/spec/unit/checksum_spec.rb | 94 | ||||
-rw-r--r-- | chef/spec/unit/client_spec.rb | 13 | ||||
-rw-r--r-- | chef/spec/unit/cookbook_version_spec.rb | 138 | ||||
-rw-r--r-- | chef/spec/unit/couchdb_spec.rb | 274 | ||||
-rw-r--r-- | chef/spec/unit/environment_spec.rb | 130 | ||||
-rw-r--r-- | chef/spec/unit/exceptions_spec.rb | 5 | ||||
-rw-r--r-- | chef/spec/unit/index_queue_spec.rb | 391 | ||||
-rw-r--r-- | chef/spec/unit/knife/ssh_spec.rb | 6 | ||||
-rw-r--r-- | chef/spec/unit/lwrp_spec.rb | 6 | ||||
-rw-r--r-- | chef/spec/unit/mixin/params_validate_spec.rb | 6 | ||||
-rw-r--r-- | chef/spec/unit/node_spec.rb | 76 | ||||
-rw-r--r-- | chef/spec/unit/openid_registration_spec.rb | 153 | ||||
-rw-r--r-- | chef/spec/unit/provider/ohai_spec.rb | 4 | ||||
-rw-r--r-- | chef/spec/unit/run_list_spec.rb | 209 | ||||
-rw-r--r-- | chef/spec/unit/solr_query/query_transform_spec.rb | 454 | ||||
-rw-r--r-- | chef/spec/unit/solr_query/solr_http_request_spec.rb | 244 | ||||
-rw-r--r-- | chef/spec/unit/solr_query_spec.rb | 203 |
19 files changed, 44 insertions, 2473 deletions
diff --git a/chef/spec/unit/api_client_spec.rb b/chef/spec/unit/api_client_spec.rb index b9d9cecc01..e01243152e 100644 --- a/chef/spec/unit/api_client_spec.rb +++ b/chef/spec/unit/api_client_spec.rb @@ -6,9 +6,9 @@ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -57,8 +57,8 @@ describe Chef::ApiClient do end it "should return the current admin value" do - @client.admin true - @client.admin.should == true + @client.admin true + @client.admin.should == true end it "should default to false" do @@ -82,7 +82,7 @@ describe Chef::ApiClient do it "should throw an ArgumentError if you feed it something lame" do lambda { @client.public_key Hash.new }.should raise_error(ArgumentError) - end + end end describe "private_key" do @@ -97,27 +97,6 @@ describe Chef::ApiClient do it "should throw an ArgumentError if you feed it something lame" do lambda { @client.private_key Hash.new }.should raise_error(ArgumentError) - end - end - - describe "create_keys" do - before(:each) do - Chef::Certificate.stub!(:gen_keypair).and_return(["cert", "key"]) - end - - it "should create a certificate based on the client name" do - Chef::Certificate.should_receive(:gen_keypair).with(@client.name) - @client.create_keys - end - - it "should set the private key" do - @client.create_keys - @client.private_key.should == "key" - end - - it "should set the public key" do - @client.create_keys - @client.public_key.should == "cert" end end @@ -136,7 +115,7 @@ describe Chef::ApiClient do %w{ name public_key - }.each do |t| + }.each do |t| it "should include '#{t}'" do @serial.should =~ /"#{t}":"#{@client.send(t.to_sym)}"/ end @@ -168,7 +147,7 @@ describe Chef::ApiClient do name public_key admin - }.each do |t| + }.each do |t| it "should match '#{t}'" do @deserial.send(t.to_sym).should == @client.send(t.to_sym) end diff --git a/chef/spec/unit/certificate_spec.rb b/chef/spec/unit/certificate_spec.rb deleted file mode 100644 index 4f0b07519f..0000000000 --- a/chef/spec/unit/certificate_spec.rb +++ /dev/null @@ -1,76 +0,0 @@ -# -# Author:: Adam Jacob (<adam@opscode.com>) -# Copyright:: Copyright (c) 2009 Opscode, Inc. -# License:: Apache License, Version 2.0 -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -require 'spec_helper' - -require 'chef/certificate' -require 'ostruct' -require 'tempfile' - -class FakeFile - attr_accessor :data - - def write(arg) - @data = arg - end -end - -describe Chef::Certificate do - describe "generate_signing_ca" do - before(:each) do - Chef::Config[:signing_ca_user] = nil - Chef::Config[:signing_ca_group] = nil - FileUtils.stub!(:mkdir_p).and_return(true) - FileUtils.stub!(:chown).and_return(true) - File.stub!(:open).and_return(true) - File.stub!(:exists?).and_return(false) - @ca_cert = FakeFile.new - @ca_key = FakeFile.new - end - - it "should generate a ca certificate" do - File.should_receive(:open).with(Chef::Config[:signing_ca_cert], "w").and_yield(@ca_cert) - Chef::Certificate.generate_signing_ca - @ca_cert.data.should =~ /BEGIN CERTIFICATE/ - end - - it "should generate an RSA private key" do - File.should_receive(:open).with(Chef::Config[:signing_ca_key], File::WRONLY|File::EXCL|File::CREAT, 0600).and_yield(@ca_key) - FileUtils.should_not_receive(:chown) - Chef::Certificate.generate_signing_ca - @ca_key.data.should =~ /BEGIN RSA PRIVATE KEY/ - end - - it "should generate an RSA private key with user and group" do - Chef::Config[:signing_ca_user] = "funky" - Chef::Config[:signing_ca_group] = "fresh" - File.should_receive(:open).with(Chef::Config[:signing_ca_key], File::WRONLY|File::EXCL|File::CREAT, 0600).and_yield(@ca_key) - FileUtils.should_receive(:chown).with(Chef::Config[:signing_ca_user], Chef::Config[:signing_ca_group], Chef::Config[:signing_ca_key]) - Chef::Certificate.generate_signing_ca - @ca_key.data.should =~ /BEGIN RSA PRIVATE KEY/ - end - end - - describe "generate_keypair" do - it "should return a client certificate" do - public_key, private_key = Chef::Certificate.gen_keypair("oasis") - public_key.to_s.should =~ /(BEGIN RSA PUBLIC KEY|BEGIN PUBLIC KEY)/ - private_key.to_s.should =~ /BEGIN RSA PRIVATE KEY/ - end - end -end diff --git a/chef/spec/unit/checksum_spec.rb b/chef/spec/unit/checksum_spec.rb deleted file mode 100644 index aad559cf3d..0000000000 --- a/chef/spec/unit/checksum_spec.rb +++ /dev/null @@ -1,94 +0,0 @@ -# -# Author:: Daniel DeLeo (<dan@opscode.com>) -# Copyright:: Copyright (c) 2010 Opscode, Inc. -# License:: Apache License, Version 2.0 -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -require 'spec_helper' -require 'chef/checksum' - -describe Chef::Checksum do - - before do - Chef::Log.logger = Logger.new(StringIO.new) - - @now = Time.now - - Time.stub!(:now).and_return(@now) - - @checksum_of_the_file = "3fafecfb15585ede6b840158cbc2f399" - @checksum = Chef::Checksum.new(@checksum_of_the_file) - end - - it "has no original committed file location" do - @checksum.original_committed_file_location.should be_nil - end - - it "has the MD5 checksum of the file it represents" do - @checksum.checksum.should == @checksum_of_the_file - end - - it "stores the time it was created" do - @checksum.create_time.should == @now.iso8601 - end - - it "commits a sandbox file from a given location to the checksum repo location" do - @checksum.storage.should_receive(:commit).with("/tmp/arbitrary_file_location") - @checksum.should_receive(:cdb_save) - @checksum.commit_sandbox_file("/tmp/arbitrary_file_location") - @checksum.original_committed_file_location.should == "/tmp/arbitrary_file_location" - end - - it "reverts committing a sandbox file" do - @checksum.storage.should_receive(:commit).with("/tmp/arbitrary_file_location") - @checksum.should_receive(:cdb_save) - @checksum.commit_sandbox_file("/tmp/arbitrary_file_location") - @checksum.original_committed_file_location.should == "/tmp/arbitrary_file_location" - - @checksum.storage.should_receive(:revert).with("/tmp/arbitrary_file_location") - @checksum.should_receive(:cdb_destroy) - @checksum.revert_sandbox_file_commit - end - - it "raises an error when trying to revert a checksum that was not previously committed" do - lambda {@checksum.revert_sandbox_file_commit}.should raise_error(Chef::Exceptions::IllegalChecksumRevert) - end - - it "deletes the file and its document from couchdb" do - @checksum.should_receive(:cdb_destroy) - @checksum.storage.should_receive(:purge) - @checksum.purge - end - - describe "when converted to json" do - before do - @checksum_as_json = @checksum.to_json - @checksum_as_hash_from_json = Chef::JSONCompat.from_json(@checksum_as_json, :create_additions => false) - end - - it "contains the file's MD5 checksum" do - @checksum_as_hash_from_json["checksum"].should == @checksum_of_the_file - end - - it "contains the creation time" do - @checksum_as_hash_from_json["create_time"].should == @now.iso8601 - end - - it "uses the file's MD5 checksum for its 'name' property" do - @checksum_as_hash_from_json["name"].should == @checksum_of_the_file - end - end - -end diff --git a/chef/spec/unit/client_spec.rb b/chef/spec/unit/client_spec.rb index e8a75b7009..9d0c88dad1 100644 --- a/chef/spec/unit/client_spec.rb +++ b/chef/spec/unit/client_spec.rb @@ -41,7 +41,7 @@ shared_examples_for Chef::Client do ohai_data.stub!(:data).and_return(ohai_data) Ohai::System.stub!(:new).and_return(ohai_data) - @node = Chef::Node.new(@hostname) + @node = Chef::Node.new @node.name(@fqdn) @node.chef_environment("_default") @@ -90,7 +90,7 @@ shared_examples_for Chef::Client do Chef::REST.should_receive(:new).with(Chef::Config[:client_url], Chef::Config[:validation_client_name], Chef::Config[:validation_key]).exactly(1).and_return(mock_chef_rest_for_client) mock_chef_rest_for_client.should_receive(:register).with(@fqdn, Chef::Config[:client_key]).exactly(1).and_return(true) # Client.register will then turn around create another - + # Chef::REST object, this time with the client key it got from the # previous step. Chef::REST.should_receive(:new).with(Chef::Config[:chef_server_url], @fqdn, Chef::Config[:client_key]).exactly(1).and_return(mock_chef_rest_for_node) @@ -139,7 +139,6 @@ shared_examples_for Chef::Client do res.replace(string) end pipe_sim.should_receive(:gets).and_return(res) - Chef::CouchDB.should_receive(:new).and_return(nil) IO.should_receive(:pipe).and_return([pipe_sim, pipe_sim]) IO.should_receive(:select).and_return(true) end @@ -151,7 +150,7 @@ shared_examples_for Chef::Client do block.call end end - + # This is what we're testing. @client.run @@ -160,7 +159,7 @@ shared_examples_for Chef::Client do @node.automatic_attrs[:platform_version].should == "example-platform-1.0" end end - + describe "when notifying other objects of the status of the chef run" do before do Chef::Client.clear_notifications @@ -235,7 +234,7 @@ shared_examples_for Chef::Client do describe "when a run list override is provided" do before do - @node = Chef::Node.new(@hostname) + @node = Chef::Node.new @node.name(@fqdn) @node.chef_environment("_default") @node.automatic_attrs[:platform] = "example-platform" @@ -265,7 +264,7 @@ shared_examples_for Chef::Client do @node.should_receive(:save).and_return(nil) @client.build_node - + @node[:roles].should_not be_nil @node[:roles].should eql(['test_role']) @node[:recipes].should eql(['cookbook1']) diff --git a/chef/spec/unit/cookbook_version_spec.rb b/chef/spec/unit/cookbook_version_spec.rb index 90f411d8b2..85e1db1fae 100644 --- a/chef/spec/unit/cookbook_version_spec.rb +++ b/chef/spec/unit/cookbook_version_spec.rb @@ -6,9 +6,9 @@ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,56 +17,10 @@ require 'spec_helper' -describe Chef::MinimalCookbookVersion do - describe "when first created" do - before do - @params = { "id"=>"1a806f1c-b409-4d8e-abab-fa414ff5b96d", - "key"=>"activemq", - "value"=>{"version"=>"0.3.3", "deps"=>{"java"=>">= 0.0.0", "runit"=>">= 0.0.0"}}} - @minimal_cookbook_version = Chef::MinimalCookbookVersion.new(@params) - end - - it "has a name" do - @minimal_cookbook_version.name.should == 'activemq' - end - - it "has a version" do - @minimal_cookbook_version.version.should == '0.3.3' - end - - it "has a list of dependencies" do - @minimal_cookbook_version.deps.should == {"java" => ">= 0.0.0", "runit" => ">= 0.0.0"} - end - - it "has cookbook metadata" do - metadata = @minimal_cookbook_version.metadata - - metadata.name.should == 'activemq' - metadata.dependencies['java'].should == '>= 0.0.0' - metadata.dependencies['runit'].should == '>= 0.0.0' - end - end - - describe "when created from cookbooks with old style version contraints" do - before do - @params = { "id"=>"1a806f1c-b409-4d8e-abab-fa414ff5b96d", - "key"=>"activemq", - "value"=>{"version"=>"0.3.3", "deps"=>{"apt" => ">> 1.0.0"}}} - @minimal_cookbook_version = Chef::MinimalCookbookVersion.new(@params) - end - - it "translates the version constraints" do - metadata = @minimal_cookbook_version.metadata - metadata.dependencies['apt'].should == '> 1.0.0' - end - end -end - describe Chef::CookbookVersion do describe "when first created" do before do - @couchdb_driver = Chef::CouchDB.new - @cookbook_version = Chef::CookbookVersion.new("tatft", @couchdb_driver) + @cookbook_version = Chef::CookbookVersion.new("tatft") end it "has a name" do @@ -114,14 +68,6 @@ describe Chef::CookbookVersion do @cookbook_version.should be_frozen_version end - it "has no couchdb id" do - @cookbook_version.couchdb_id.should be_nil - end - - it "has the couchdb driver it was given on create" do - @cookbook_version.couchdb.should equal(@couchdb_driver) - end - it "is \"ready\"" do # WTF is this? what are the valid states? and why aren't they set with encapsulating methods? # [Dan 15-Jul-2010] @@ -133,19 +79,19 @@ describe Chef::CookbookVersion do end it "creates a manifest hash of its contents" do - expected = {"recipes"=>[], - "definitions"=>[], - "libraries"=>[], - "attributes"=>[], - "files"=>[], - "templates"=>[], - "resources"=>[], - "providers"=>[], - "root_files"=>[], - "cookbook_name"=>"tatft", + expected = {"recipes"=>[], + "definitions"=>[], + "libraries"=>[], + "attributes"=>[], + "files"=>[], + "templates"=>[], + "resources"=>[], + "providers"=>[], + "root_files"=>[], + "cookbook_name"=>"tatft", "metadata"=>Chef::Cookbook::Metadata.new, - "version"=>"0.0.0", - "name"=>"tatft-0.0.0"} + "version"=>"0.0.0", + "name"=>"tatft-0.0.0"} @cookbook_version.manifest.should == expected end end @@ -280,7 +226,7 @@ describe Chef::CookbookVersion do useful_explanation = Regexp.new(Regexp.escape("Cookbook 'tatft' (0.0.0) does not contain")) @attempt_to_load_file.should raise_error(Chef::Exceptions::FileNotFound, useful_explanation) end - + it "lists suggested places to look" do useful_explanation = Regexp.new(Regexp.escape("files/default/no-such-thing.txt")) @attempt_to_load_file.should raise_error(Chef::Exceptions::FileNotFound, useful_explanation) @@ -325,7 +271,7 @@ describe Chef::CookbookVersion do b.version = "1.2.0" a.should == b end - + it "should not allow you to sort cookbooks with different names" do apt = Chef::CookbookVersion.new "apt" @@ -358,54 +304,4 @@ describe Chef::CookbookVersion do end - describe "when deleting in the database" do - before do - @couchdb_driver = Chef::CouchDB.new - @cookbook_version = Chef::CookbookVersion.new("tatft", @couchdb_driver) - @cookbook_version.version = "1.2.3" - @couchdb_rev = "_123456789" - @cookbook_version.couchdb_rev = @couchdb_rev - end - - it "deletes its document from couchdb" do - @couchdb_driver.should_receive(:delete).with("cookbook_version", "tatft-1.2.3", @couchdb_rev) - @cookbook_version.cdb_destroy - end - - it "deletes associated checksum objects when purged" do - checksums = {"12345" => "/tmp/foo", "23456" => "/tmp/bar", "34567" => "/tmp/baz"} - @cookbook_version.stub!(:checksums).and_return(checksums) - - chksum_docs = checksums.map do |md5, path| - cksum_doc = mock("Chef::Checksum for #{md5} at #{path}") - Chef::Checksum.should_receive(:cdb_load).with(md5, @couchdb_driver).and_return(cksum_doc) - cksum_doc.should_receive(:purge) - cksum_doc - end - - @cookbook_version.should_receive(:cdb_destroy) - @cookbook_version.purge - end - - it "successfully purges when associated checksum objects are missing" do - checksums = {"12345" => "/tmp/foo", "23456" => "/tmp/bar", "34567" => "/tmp/baz"} - - chksum_docs = checksums.map do |md5, path| - cksum_doc = mock("Chef::Checksum for #{md5} at #{path}") - Chef::Checksum.should_receive(:cdb_load).with(md5, @couchdb_driver).and_return(cksum_doc) - cksum_doc.should_receive(:purge) - cksum_doc - end - - missing_checksum = {"99999" => "/tmp/qux"} - Chef::Checksum.should_receive(:cdb_load).with("99999", @couchdb_driver).and_raise(Chef::Exceptions::CouchDBNotFound) - - @cookbook_version.stub!(:checksums).and_return(checksums.merge(missing_checksum)) - - @cookbook_version.should_receive(:cdb_destroy) - lambda {@cookbook_version.purge}.should_not raise_error - end - - end - end diff --git a/chef/spec/unit/couchdb_spec.rb b/chef/spec/unit/couchdb_spec.rb deleted file mode 100644 index 480dd61980..0000000000 --- a/chef/spec/unit/couchdb_spec.rb +++ /dev/null @@ -1,274 +0,0 @@ -# -# Author:: Adam Jacob (<adam@opscode.com>) -# Copyright:: Copyright (c) 2008 Opscode, Inc. -# License:: Apache License, Version 2.0 -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -require 'spec_helper' - -describe Chef::CouchDB do - before(:each) do - Chef::Config[:couchdb_database] = "chef" - @rest = mock("Chef::REST") - @rest.stub!(:run_request).and_return({"couchdb" => "Welcome", "version" =>"0.9.0"}) - @rest.stub!(:url).and_return("http://localhost:5984") - Chef::REST.stub!(:new).and_return(@rest) - @couchdb = Chef::CouchDB.new - end - - describe "new" do - it "should create a new Chef::REST object from the default url" do - old_url = Chef::Config[:couchdb_url] - Chef::Config[:couchdb_url] = "http://monkey" - Chef::REST.should_receive(:new).with("http://monkey", nil, nil) - Chef::CouchDB.new - Chef::Config[:couchdb_url] = old_url - end - - it "should create a new Chef::REST object from a provided url" do - Chef::REST.should_receive(:new).with("http://monkeypants", nil, nil) - Chef::CouchDB.new("http://monkeypants") - end - end - - describe "create_db" do - before(:each) do - @couchdb.stub!(:create_design_document).and_return(true) - end - - it "should get a list of current databases" do - @rest.should_receive(:get_rest).and_return(["chef"]) - @couchdb.create_db - end - - it "should create the chef database if it does not exist" do - @rest.stub!(:get_rest).and_return([]) - @rest.should_receive(:put_rest).with("chef", {}).and_return(true) - @couchdb.create_db - end - - it "should not create the chef database if it does exist" do - @rest.stub!(:get_rest).and_return(["chef"]) - @rest.should_not_receive(:put_rest) - @couchdb.create_db - end - - it "should return 'chef'" do - @rest.should_receive(:get_rest).with("_all_dbs").and_return(%w{chef}) - @couchdb.create_db.should eql("chef") - end - end - - describe "create_design_document" do - before(:each) do - @mock_design = { - "version" => 1, - "_rev" => 1 - } - @mock_data = { - "version" => 1, - "language" => "javascript", - "views" => { - "all" => { - "map" => <<-EOJS - function(doc) { - if (doc.chef_type == "node") { - emit(doc.name, doc); - } - } - EOJS - }, - } - } - @rest.stub!(:get_rest).and_return(@mock_design) - @rest.stub!(:put_rest).and_return(true) - @couchdb.stub!(:create_db).and_return(true) - end - - def do_create_design_document - @couchdb.create_design_document("bob", @mock_data) - end - - it "should fetch the existing design document" do - @rest.should_receive(:get_rest).with("chef/_design/bob") - do_create_design_document - end - - it "should populate the _rev in the new design if the versions dont match" do - @mock_data["version"] = 2 - do_create_design_document - @mock_data["_rev"].should eql(1) - end - - it "should create the view if it requires updating" do - @mock_data["version"] = 2 - @rest.should_receive(:put_rest).with("chef/_design%2Fbob", @mock_data) - do_create_design_document - end - - it "should not create the view if it does not require updating" do - @mock_data["version"] = 1 - @rest.should_not_receive(:put_rest) - do_create_design_document - end - end - - describe "store" do - before(:each) do - @mock_results = { - "rows" => [ - "id" => 'a0934635-e111-45d9-8223-cb58e1c9434c' - ] - } - @couchdb.stub!(:get_view).with("id_map", "name_to_id", :key => [ "node", "bob" ]).and_return(@mock_results) - end - - it "should put the object into couchdb with a pre-existing GUID" do - item_to_store = {} - item_to_store.should_receive(:add_to_index) - @rest.should_receive(:put_rest).with("chef/#{@mock_results["rows"][0]["id"]}", item_to_store).and_return(true) - @couchdb.store("node", "bob", item_to_store) - end - - it "should put the object into couchdb with a new GUID" do - @mock_results = { "rows" => [] } - item_to_store = {} - item_to_store.should_receive(:add_to_index).with(:database => "chef", :id => "aaaaaaaa-xxxx-xxxx-xxxx-xxxxxxxxxxx", :type => "node") - @couchdb.stub!(:get_view).with("id_map", "name_to_id", :key => [ "node", "bob" ]).and_return(@mock_results) - UUIDTools::UUID.stub!(:random_create).and_return("aaaaaaaa-xxxx-xxxx-xxxx-xxxxxxxxxxx") - @rest.should_receive(:put_rest).with("chef/aaaaaaaa-xxxx-xxxx-xxxx-xxxxxxxxxxx", item_to_store).and_return(true) - @couchdb.store("node", "bob", item_to_store) - end - - end - - describe "when fetching the database status" do - it "gets couchdb's version string'" do - @rest.should_receive(:get_rest).with('/').and_return({"couchdb" => "Welcome","version" => "1.0.1"}) - @couchdb.server_stats.should == {"couchdb" => "Welcome","version" => "1.0.1"} - end - - it "gets database stats" do - db_stats = {"db_name" => "opscode_account","doc_count" => 206,"doc_del_count" => 1,"update_seq" => 208,"purge_seq" => 0, - "compact_running" => false,"disk_size" => 122969,"instance_start_time" => "1298070021394804","disk_format_version" => 5,"committed_update_seq" => 208} - @rest.should_receive(:get_rest).with('/chef').and_return(db_stats) - @couchdb.db_stats.should == db_stats - end - - end - - describe "load" do - before(:each) do - @mock_node = Chef::Node.new() - @mock_node.name("bob") - @couchdb.stub!(:find_by_name).with("node", "bob").and_return(@mock_node) - end - - it "should load the object from couchdb" do - @couchdb.load("node", "bob").should eql(@mock_node) - end - end - - describe "delete" do - before(:each) do - @mock_current = { - "version" => 1, - "_rev" => 1 - } - @rest.stub!(:get_rest).and_return(@mock_current) - @rest.stub!(:delete_rest).and_return(true) - @node = Chef::Node.new() - @node.name("bob") - @node.couchdb_rev = 15 - @couchdb.stub!(:find_by_name).with("node", "bob", true).and_return([ @node, "ax" ]) - end - - def do_delete(rev=nil) - @couchdb.delete("node", "bob", rev) - end - - it "should remove the object from couchdb with a specific revision" do - @node.should_receive(:delete_from_index) - @rest.should_receive(:delete_rest).with("chef/ax?rev=1") - do_delete(1) - end - - it "should remove the object from couchdb based on the couchdb_rev of the current obj" do - @node.should_receive(:delete_from_index) - @rest.should_receive(:delete_rest).with("chef/ax?rev=15") - do_delete - end - end - - describe "list" do - before(:each) do - Chef::Config.stub!(:[]).with(:couchdb_database).and_return("chef") - @mock_response = {"rows" => []} - end - - describe "on couchdb 0.9+" do - before do - Chef::Config.stub!(:[]).with(:couchdb_version).and_return(0.9) - end - - it "should get the view for all objects if inflate is true" do - @rest.should_receive(:get_rest).with("chef/_design/node/_view/all").and_return(@mock_response) - @couchdb.list("node", true) - end - - it "should get the view for just the object id's if inflate is false" do - @rest.should_receive(:get_rest).with("chef/_design/node/_view/all_id").and_return(@mock_response) - @couchdb.list("node", false) - end - end - end - - describe "has_key?" do - it "should return true if the object exists" do - @couchdb.stub!(:find_by_name).with("node", "bob").and_return(true) - @couchdb.has_key?("node", "bob").should eql(true) - end - - it "should return false if the object does not exist" do - @couchdb.stub!(:find_by_name).and_raise(Chef::Exceptions::CouchDBNotFound) - @couchdb.has_key?("node", "bob").should eql(false) - end - end - - describe "get_view" do - it "should construct a call to the view for the proper design document" do - @rest.should_receive(:get_rest).with("chef/_design/nodes/_view/mastodon") - @couchdb.get_view("nodes", "mastodon") - end - - it "should allow arguments to the view" do - @rest.should_receive(:get_rest).with("chef/_design/nodes/_view/mastodon?startkey=%22dont%20stay%22") - @couchdb.get_view("nodes", "mastodon", :startkey => "dont stay") - end - - end - - describe "view_uri" do - it "should output an appropriately formed view URI" do - @couchdb.should_receive(:view_uri).with("nodes", "all").and_return("chef/_design/nodes/_view/all") - @couchdb.view_uri("nodes", "all") - end - end - -end - - - - diff --git a/chef/spec/unit/environment_spec.rb b/chef/spec/unit/environment_spec.rb index 7b0a835e8c..97f0c3395e 100644 --- a/chef/spec/unit/environment_spec.rb +++ b/chef/spec/unit/environment_spec.rb @@ -235,107 +235,6 @@ describe Chef::Environment do end end - describe "when listing the available cookbooks filtered by policy" do - before(:each) do - @environment.name "prod" - @environment.cookbook_versions({ - "apt" => "= 1.0.0", - "apache2" => "= 2.0.0" - }) - Chef::Environment.stub!(:cdb_load).and_return @environment - - @all_cookbooks = [] - @all_cookbooks << begin - cv = Chef::CookbookVersion.new("apt") - cv.version = "1.0.0" - cv.recipe_filenames = ["default.rb", "only-in-1-0.rb"] - cv - end - @all_cookbooks << begin - cv = Chef::CookbookVersion.new("apt") - cv.version = "1.1.0" - cv.recipe_filenames = ["default.rb", "only-in-1-1.rb"] - cv - end - @all_cookbooks << begin - cv = Chef::CookbookVersion.new("apache2") - cv.version = "2.0.0" - cv.recipe_filenames = ["default.rb", "mod_ssl.rb"] - cv - end - @all_cookbooks << begin - cv = Chef::CookbookVersion.new("god") - cv.version = "4.2.0" - cv.recipe_filenames = ["default.rb"] - cv - end - Chef::CookbookVersion.stub!(:cdb_list).and_return @all_cookbooks - end - - it "should load the environment" do - Chef::Environment.should_receive(:cdb_load).with("prod", nil) - Chef::Environment.cdb_load_filtered_cookbook_versions("prod") - end - - it "should handle cookbooks with no available version" do - @environment.cookbook_versions({ - "apt" => "> 999.0.0", - "apache2" => "= 2.0.0" - }) - Chef::Environment.should_receive(:cdb_load).with("prod", nil) - recipes = Chef::Environment.cdb_load_filtered_recipe_list("prod") - # order doesn't matter - recipes.should =~ ["god", "apache2", "apache2::mod_ssl"] - end - - - it "should load all the cookbook versions" do - Chef::CookbookVersion.should_receive(:cdb_list) - Chef::Environment.cdb_load_filtered_cookbook_versions("prod") - recipes = Chef::Environment.cdb_load_filtered_recipe_list("prod") - recipes.should =~ ["apache2", "apache2::mod_ssl", "apt", - "apt::only-in-1-0", "god"] - end - - it "should load all the cookbook versions with no policy" do - @environment.cookbook_versions({}) - Chef::CookbookVersion.should_receive(:cdb_list) - Chef::Environment.cdb_load_filtered_cookbook_versions("prod") - recipes = Chef::Environment.cdb_load_filtered_recipe_list("prod") - recipes.should =~ ["apache2", "apache2::mod_ssl", "apt", - "apt::only-in-1-1", "god"] - end - - it "should restrict the cookbook versions, as specified in the environment" do - res = Chef::Environment.cdb_load_filtered_cookbook_versions("prod") - res["apt"].detect {|cb| cb.version == "1.0.0"}.should_not == nil - res["apache2"].detect {|cb| cb.version == "2.0.0"}.should_not == nil - res["god"].detect {|cb| cb.version == "4.2.0"}.should_not == nil - end - - it "should produce correct results, regardless of the cookbook order in couch" do - # a bug present before the environments feature defaulted to the last CookbookVersion - # object for a cookbook as returned from couchdb when fetching cookbooks for a node - # this is a regression test - @all_cookbooks << begin - cv = Chef::CookbookVersion.new("god") - cv.version = "0.0.1" - cv - end - res = Chef::Environment.cdb_load_filtered_cookbook_versions("prod") - res["apt"].detect {|cb| cb.version == "1.0.0"}.should_not == nil - res["apache2"].detect {|cb| cb.version == "2.0.0"}.should_not == nil - res["god"].detect {|cb| cb.version == "4.2.0"}.should_not == nil - end - - it "should return all versions of a cookbook that meet the version requirement" do - @environment.cookbook "apt", ">= 1.0.0" - res = Chef::Environment.cdb_load_filtered_cookbook_versions("prod") - res["apt"].detect {|cb| cb.version == "1.0.0"}.should_not == nil - res["apt"].detect {|cb| cb.version == "1.1.0"}.should_not == nil - end - end - describe "self.validate_cookbook_versions" do before(:each) do @cookbook_versions = { @@ -376,35 +275,6 @@ describe Chef::Environment do end end - describe "self.create_default_environment" do - it "should check if the '_default' environment exists" do - @couchdb = Chef::CouchDB.new - Chef::CouchDB.stub!(:new).and_return @couchdb - Chef::Environment.should_receive(:cdb_load).with('_default', Chef::CouchDB.new) - Chef::Environment.create_default_environment - end - - it "should not re-create the environment if it exists" do - @couchdb = Chef::CouchDB.new - Chef::CouchDB.stub!(:new).and_return @couchdb - Chef::Environment.should_receive(:cdb_load).with('_default', Chef::CouchDB.new).and_return true - Chef::Environment.should_not_receive(:new) - Chef::Environment.create_default_environment - end - - it "should create the environment if it doesn't exist" do - @env = Chef::Environment.new - @env.stub!(:cdb_save).and_return true - @couchdb = Chef::CouchDB.new - Chef::Environment.stub!(:new).and_return @env - Chef::CouchDB.stub!(:new).and_return @couchdb - - Chef::Environment.should_receive(:cdb_load).with('_default', Chef::CouchDB.new).and_raise(Chef::Exceptions::CouchDBNotFound) - Chef::Environment.should_receive(:new) - Chef::Environment.create_default_environment - end - end - describe "when updating from a parameter hash" do before do @environment = Chef::Environment.new diff --git a/chef/spec/unit/exceptions_spec.rb b/chef/spec/unit/exceptions_spec.rb index fe920fd817..a979d2f6b9 100644 --- a/chef/spec/unit/exceptions_spec.rb +++ b/chef/spec/unit/exceptions_spec.rb @@ -8,9 +8,9 @@ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -40,7 +40,6 @@ describe Chef::Exceptions do Chef::Exceptions::Group => RuntimeError, Chef::Exceptions::Link => RuntimeError, Chef::Exceptions::Mount => RuntimeError, - Chef::Exceptions::CouchDBNotFound => RuntimeError, Chef::Exceptions::PrivateKeyMissing => RuntimeError, Chef::Exceptions::CannotWritePrivateKey => RuntimeError, Chef::Exceptions::RoleNotFound => RuntimeError, diff --git a/chef/spec/unit/index_queue_spec.rb b/chef/spec/unit/index_queue_spec.rb deleted file mode 100644 index 3043585757..0000000000 --- a/chef/spec/unit/index_queue_spec.rb +++ /dev/null @@ -1,391 +0,0 @@ -# -# Author:: Daniel DeLeo (<dan@kallistec.com>) -# Copyright:: Copyright (c) 2009 Daniel DeLeo -# License:: Apache License, Version 2.0 -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -require 'spec_helper' - -class Chef - class IndexableTestHarness - include Chef::IndexQueue::Indexable - attr_reader :couchdb_id - def couchdb_id=(value) - self.index_id = @couchdb_id = value - end - attr_reader :index_id - def index_id=(value) - @index_id = value - end - - def to_hash - {"ohai_world" => "I am IndexableTestHarness", "object_id" => object_id} - end - - end -end - -class IndexQueueSpecError < RuntimeError ; end - -class FauxQueue - - attr_reader :published_message, :publish_options - - # Note: If publish is not called, this published_message will cause - # JSON parsing to die with "can't convert Symbol into String" - def initialize - @published_message = :epic_fail! - @publish_options = :epic_fail! - end - - def publish(message, options=nil) - @published_message = message - @publish_options = options - end -end - -class IndexConsumerTestHarness - include Chef::IndexQueue::Consumer - - attr_reader :last_indexed_object, :unexposed_attr - - expose :index_this - - def index_this(object_to_index) - @last_indexed_object = object_to_index - end - - def not_exposed(arg) - @unexposed_attr = arg - end -end - -describe Chef::IndexQueue::Indexable do - def a_uuid - /[0-9a-f]{8}\-[0-9a-f]{4}\-[0-9a-f]{4}\-[0-9a-f]{4}\-[0-9a-f]{12}/ - end - - before do - Chef::IndexableTestHarness.reset_index_metadata! - @publisher = Chef::IndexQueue::AmqpClient.instance - @indexable_obj = Chef::IndexableTestHarness.new - @item_as_hash = {"ohai_world" => "I am IndexableTestHarness", "object_id" => @indexable_obj.object_id} - - @now = Time.now - Time.stub!(:now).and_return(@now) - end - - it "downcases the class name for the index_object_type when it's not explicitly set" do - @indexable_obj.index_object_type.should == "indexable_test_harness" - end - - it "uses an explicitly set index_object_type" do - Chef::IndexableTestHarness.index_object_type :a_weird_name - @indexable_obj.index_object_type.should == "a_weird_name" - end - - it "adds 'database', 'type', and 'id' (UUID) keys to the published object" do - with_metadata = @indexable_obj.with_indexer_metadata(:database => "foo", :id=>UUIDTools::UUID.random_create.to_s) - with_metadata.should have(5).keys - with_metadata.keys.should include("type", "id", "item", "database", "enqueued_at") - with_metadata["type"].should == "indexable_test_harness" - with_metadata["database"].should == "foo" - with_metadata["item"].should == @item_as_hash - with_metadata["id"].should match(a_uuid) - with_metadata["enqueued_at"].should == @now.utc.to_i - end - - it "uses the couchdb_id if available" do - expected_uuid = "0000000-1111-2222-3333-444444444444" - @indexable_obj.couchdb_id = expected_uuid - metadata_id = @indexable_obj.with_indexer_metadata["id"] - metadata_id.should == expected_uuid - end - - describe "adds and removes items to and from the index and respects Chef::Config[:persistent_queue]" do - before do - @exchange = mock("Bunny::Exchange") - @amqp_client = mock("Bunny::Client", :start => true, :exchange => @exchange) - @publisher.stub!(:amqp_client).and_return(@amqp_client) - @queue = FauxQueue.new - @publisher.should_receive(:queue_for_object).with("0000000-1111-2222-3333-444444444444").and_yield(@queue) - Chef::Config[:persistent_queue] = false - end - - it "adds items to the index" do - @amqp_client.should_not_receive(:tx_select) - @amqp_client.should_not_receive(:tx_commit) - @amqp_client.should_not_receive(:tx_rollback) - - @indexable_obj.add_to_index(:database => "couchdb@localhost,etc.", :id=>"0000000-1111-2222-3333-444444444444") - - published_message = Chef::JSONCompat.from_json(@queue.published_message) - published_message.should == {"action" => "add", "payload" => {"item" => @item_as_hash, - "type" => "indexable_test_harness", - "database" => "couchdb@localhost,etc.", - "id" => "0000000-1111-2222-3333-444444444444", - "enqueued_at" => @now.utc.to_i}} - @queue.publish_options[:persistent].should == false - end - - it "adds items to the index transactionactionally when Chef::Config[:persistent_queue] == true" do - @amqp_client.should_receive(:tx_select) - @amqp_client.should_receive(:tx_commit) - @amqp_client.should_not_receive(:tx_rollback) - - # set and restore Chef::Config[:persistent_queue] to true - orig_value = Chef::Config[:persistent_queue] - Chef::Config[:persistent_queue] = true - begin - @indexable_obj.add_to_index(:database => "couchdb@localhost,etc.", :id=>"0000000-1111-2222-3333-444444444444") - ensure - Chef::Config[:persistent_queue] = orig_value - end - - published_message = Chef::JSONCompat.from_json(@queue.published_message) - published_message.should == {"action" => "add", "payload" => {"item" => @item_as_hash, - "type" => "indexable_test_harness", - "database" => "couchdb@localhost,etc.", - "id" => "0000000-1111-2222-3333-444444444444", - "enqueued_at" => @now.utc.to_i}} - @queue.publish_options[:persistent].should == true - end - - it "adds items to the index transactionally when Chef::Config[:persistent_queue] == true and rolls it back when there is a failure" do - @amqp_client.should_receive(:tx_select) - @amqp_client.should_receive(:tx_rollback) - @amqp_client.should_not_receive(:tx_commit) - - # cause the publish to fail, and make sure the failure is our own - # by using a specific class - @queue.should_receive(:publish).and_raise(IndexQueueSpecError) - - # set and restore Chef::Config[:persistent_queue] to true - orig_value = Chef::Config[:persistent_queue] - Chef::Config[:persistent_queue] = true - begin - lambda{ - @indexable_obj.add_to_index(:database => "couchdb@localhost,etc.", :id=>"0000000-1111-2222-3333-444444444444") - }.should raise_error(IndexQueueSpecError) - ensure - Chef::Config[:persistent_queue] = orig_value - end - end - - it "removes items from the index" do - @amqp_client.should_not_receive(:tx_select) - @amqp_client.should_not_receive(:tx_commit) - @amqp_client.should_not_receive(:tx_rollback) - - @indexable_obj.delete_from_index(:database => "couchdb2@localhost", :id=>"0000000-1111-2222-3333-444444444444") - published_message = Chef::JSONCompat.from_json(@queue.published_message) - published_message.should == {"action" => "delete", "payload" => { "item" => @item_as_hash, - "type" => "indexable_test_harness", - "database" => "couchdb2@localhost", - "id" => "0000000-1111-2222-3333-444444444444", - "enqueued_at" => @now.utc.to_i}} - @queue.publish_options[:persistent].should == false - end - - it "removes items from the index transactionactionally when Chef::Config[:persistent_queue] == true" do - @amqp_client.should_receive(:tx_select) - @amqp_client.should_receive(:tx_commit) - @amqp_client.should_not_receive(:tx_rollback) - - # set and restore Chef::Config[:persistent_queue] to true - orig_value = Chef::Config[:persistent_queue] - Chef::Config[:persistent_queue] = true - begin - @indexable_obj.delete_from_index(:database => "couchdb2@localhost", :id=>"0000000-1111-2222-3333-444444444444") - ensure - Chef::Config[:persistent_queue] = orig_value - end - - published_message = Chef::JSONCompat.from_json(@queue.published_message) - published_message.should == {"action" => "delete", "payload" => { "item" => @item_as_hash, - "type" => "indexable_test_harness", - "database" => "couchdb2@localhost", - "id" => "0000000-1111-2222-3333-444444444444", - "enqueued_at" => @now.utc.to_i}} - @queue.publish_options[:persistent].should == true - end - - it "remove items from the index transactionally when Chef::Config[:persistent_queue] == true and rolls it back when there is a failure" do - @amqp_client.should_receive(:tx_select) - @amqp_client.should_receive(:tx_rollback) - @amqp_client.should_not_receive(:tx_commit) - - # cause the publish to fail, and make sure the failure is our own - # by using a specific class - @queue.should_receive(:publish).and_raise(IndexQueueSpecError) - - # set and restore Chef::Config[:persistent_queue] to true - orig_value = Chef::Config[:persistent_queue] - Chef::Config[:persistent_queue] = true - begin - lambda{ - @indexable_obj.delete_from_index(:database => "couchdb2@localhost", :id=>"0000000-1111-2222-3333-444444444444") }.should raise_error(IndexQueueSpecError) - ensure - Chef::Config[:persistent_queue] = orig_value - end - end - end - -end - -describe Chef::IndexQueue::Consumer do - before do - @amqp_client = Chef::IndexQueue::AmqpClient.instance - @consumer = IndexConsumerTestHarness.new - end - - it "keeps a whitelist of exposed methods" do - IndexConsumerTestHarness.exposed_methods.should == [:index_this] - IndexConsumerTestHarness.whitelisted?(:index_this).should be_true - IndexConsumerTestHarness.whitelisted?(:not_exposed).should be_false - end - - it "doesn't route non-whitelisted methods" do - payload_json = {"payload" => {"a_placeholder" => "object"}, "action" => "not_exposed"}.to_json - received_message = {:payload => payload_json} - lambda {@consumer.call_action_for_message(received_message)}.should raise_error(ArgumentError) - @consumer.unexposed_attr.should be_nil - end - - it "routes message payloads to the correct method" do - payload_json = {"payload" => {"a_placeholder" => "object"}, "action" => "index_this"}.to_json - received_message = {:payload => payload_json} - @consumer.call_action_for_message(received_message) - @consumer.last_indexed_object.should == {"a_placeholder" => "object"} - - end - - it "subscribes to the queue for the indexer" do - payload_json = {"payload" => {"a_placeholder" => "object"}, "action" => "index_this"}.to_json - message = {:payload => payload_json} - queue = mock("Bunny::Queue") - @amqp_client.stub!(:queue).and_return(queue) - queue.should_receive(:subscribe).with(:timeout => false, :ack => true).and_yield(message) - @consumer.run - @consumer.last_indexed_object.should == {"a_placeholder" => "object"} - end - -end - - -describe Chef::IndexQueue::AmqpClient do - before do - Chef::Config[:amqp_host] = '4.3.2.1' - Chef::Config[:amqp_port] = '1337' - Chef::Config[:amqp_user] = 'teh_rspecz' - Chef::Config[:amqp_pass] = 'access_granted2rspec' - Chef::Config[:amqp_vhost] = '/chef-specz' - Chef::Config[:amqp_consumer_id] = nil - - @publisher = Chef::IndexQueue::AmqpClient.instance - @exchange = mock("Bunny::Exchange") - - @amqp_client = mock("Bunny::Client", :start => true, :exchange => @exchange) - def @amqp_client.connected?; false; end # stubbing predicate methods not working? - Bunny.stub!(:new).and_return(@amqp_client) - - @publisher.reset! - end - - after do - @publisher.disconnected! - end - - it "is a singleton" do - lambda {Chef::IndexQueue::Indexable::AmqpClient.new}.should raise_error - end - - it "creates an amqp client object on demand, starts a connection, and caches it" do - @amqp_client.should_receive(:start).once - @amqp_client.should_receive(:qos).with(:prefetch_count => 1) - ::Bunny.should_receive(:new).once.and_return(@amqp_client) - @publisher.amqp_client.should == @amqp_client - @publisher.amqp_client - end - - it "configures the amqp client with credentials from the config file" do - @publisher.reset! - Bunny.should_receive(:new).with(:spec => '08', :host => '4.3.2.1', :port => '1337', :user => "teh_rspecz", - :pass => "access_granted2rspec", :vhost => '/chef-specz').and_return(@amqp_client) - @amqp_client.should_receive(:qos).with(:prefetch_count => 1) - @publisher.amqp_client.should == @amqp_client - end - - it "creates an amqp exchange on demand and caches it" do - @amqp_client.stub!(:qos) - @publisher.exchange.should == @exchange - @amqp_client.should_not_receive(:exchange) - @publisher.exchange.should == @exchange - end - - describe "publishing" do - - before do - @queue_1 = FauxQueue.new - @queue_2 = FauxQueue.new - - @amqp_client.stub!(:qos) - #@amqp_client.stub!(:queue).and_return(@queue) - @data = {"some_data" => "in_a_hash"} - end - - it "resets the client upon a Bunny::ServerDownError when publishing" do - Bunny.stub!(:new).and_return(@amqp_client) - @amqp_client.should_receive(:queue).with("vnode-68", {:passive=>false, :durable=>true, :exclusive=>false, :auto_delete=>false}).twice.and_return(@queue_1, @queue_2) - - @queue_1.should_receive(:publish).with(@data).and_raise(Bunny::ServerDownError) - @queue_2.should_receive(:publish).with(@data).and_raise(Bunny::ServerDownError) - - @publisher.should_receive(:disconnected!).at_least(3).times - lambda {@publisher.queue_for_object("00000000-1111-2222-3333-444444444444") {|q| q.publish(@data)}}.should raise_error(Bunny::ServerDownError) - end - - it "resets the client upon a Bunny::ConnectionError when publishing" do - Bunny.stub!(:new).and_return(@amqp_client) - @amqp_client.should_receive(:queue).with("vnode-68", {:passive=>false, :durable=>true, :exclusive=>false, :auto_delete=>false}).twice.and_return(@queue_1, @queue_2) - - @queue_1.should_receive(:publish).with(@data).and_raise(Bunny::ConnectionError) - @queue_2.should_receive(:publish).with(@data).and_raise(Bunny::ConnectionError) - - @publisher.should_receive(:disconnected!).at_least(3).times - lambda {@publisher.queue_for_object("00000000-1111-2222-3333-444444444444") {|q| q.publish(@data)}}.should raise_error(Bunny::ConnectionError) - end - - it "resets the client upon a Errno::ECONNRESET when publishing" do - Bunny.stub!(:new).and_return(@amqp_client) - @amqp_client.should_receive(:queue).with("vnode-68", {:passive=>false, :durable=>true, :exclusive=>false, :auto_delete=>false}).twice.and_return(@queue_1, @queue_2) - - @queue_1.should_receive(:publish).with(@data).and_raise(Errno::ECONNRESET) - @queue_2.should_receive(:publish).with(@data).and_raise(Errno::ECONNRESET) - - @publisher.should_receive(:disconnected!).at_least(3).times - lambda {@publisher.queue_for_object("00000000-1111-2222-3333-444444444444") {|q| q.publish(@data)}}.should raise_error(Errno::ECONNRESET) - end - - end - - it "stops bunny and clears subscriptions" do - bunny_client = mock("Bunny::Client") - @publisher.instance_variable_set(:@amqp_client, bunny_client) - bunny_client.should_receive(:stop) - @publisher.stop - end - -end diff --git a/chef/spec/unit/knife/ssh_spec.rb b/chef/spec/unit/knife/ssh_spec.rb index a4853e11cc..6e90a87f01 100644 --- a/chef/spec/unit/knife/ssh_spec.rb +++ b/chef/spec/unit/knife/ssh_spec.rb @@ -36,10 +36,10 @@ describe Chef::Knife::Ssh do @knife = Chef::Knife::Ssh.new @knife.config.clear @knife.config[:attribute] = "fqdn" - @node_foo = Chef::Node.new('foo') + @node_foo = Chef::Node.new @node_foo.automatic_attrs[:fqdn] = "foo.example.org" @node_foo.automatic_attrs[:ipaddress] = "10.0.0.1" - @node_bar = Chef::Node.new('bar') + @node_bar = Chef::Node.new @node_bar.automatic_attrs[:fqdn] = "bar.example.org" @node_bar.automatic_attrs[:ipaddress] = "10.0.0.2" end @@ -64,7 +64,7 @@ describe Chef::Knife::Ssh do @knife.should_receive(:session_from_list).with(['10.0.0.1', '10.0.0.2']) @knife.configure_session end - + it "returns an array of the attributes specified on the command line even when a config value is set" do @knife.config[:attribute] = "config_file" # this value will be the config file @knife.config[:override_attribute] = "ipaddress" # this is the value of the command line via #configure_attribute diff --git a/chef/spec/unit/lwrp_spec.rb b/chef/spec/unit/lwrp_spec.rb index 76834cf182..da2278e547 100644 --- a/chef/spec/unit/lwrp_spec.rb +++ b/chef/spec/unit/lwrp_spec.rb @@ -6,9 +6,9 @@ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -94,7 +94,7 @@ describe "LWRP" do end it "should have access to the run context and node during class definition" do - node = Chef::Node.new(nil) + node = Chef::Node.new node.normal[:penguin_name] = "jackass" run_context = Chef::RunContext.new(node, Chef::CookbookCollection.new, @events) diff --git a/chef/spec/unit/mixin/params_validate_spec.rb b/chef/spec/unit/mixin/params_validate_spec.rb index dd0366c37c..b79156109b 100644 --- a/chef/spec/unit/mixin/params_validate_spec.rb +++ b/chef/spec/unit/mixin/params_validate_spec.rb @@ -330,10 +330,12 @@ describe Chef::Mixin::ParamsValidate do it "asserts that a value returns false from a predicate method" do lambda do - @vo.validate({:not_blank => "should pass"}, {:not_blank => {:cannot_be => :blank}}) + @vo.validate({:not_blank => "should pass"}, + {:not_blank => {:cannot_be => :nil, :cannot_be => :empty}}) end.should_not raise_error lambda do - @vo.validate({:not_blank => ""}, {:not_blank => {:cannot_be => :blank}}) + @vo.validate({:not_blank => ""}, + {:not_blank => {:cannot_be => :nil, :cannot_be => :empty}}) end.should raise_error(Chef::Exceptions::ValidationFailed) end diff --git a/chef/spec/unit/node_spec.rb b/chef/spec/unit/node_spec.rb index 4577d5098b..b6f63c9651 100644 --- a/chef/spec/unit/node_spec.rb +++ b/chef/spec/unit/node_spec.rb @@ -681,80 +681,4 @@ describe Chef::Node do end end - describe "acting as a CouchDB-backed model" do - before(:each) do - @couchdb = Chef::CouchDB.new - @mock_couch = mock('couch mock') - end - - describe "list" do - before(:each) do - @mock_couch.stub!(:list).and_return( - { "rows" => [ { "value" => "a", "key" => "avenue" } ] } - ) - Chef::CouchDB.stub!(:new).and_return(@mock_couch) - end - - it "should retrieve a list of nodes from CouchDB" do - Chef::Node.cdb_list.should eql(["avenue"]) - end - - it "should return just the ids if inflate is false" do - Chef::Node.cdb_list(false).should eql(["avenue"]) - end - - it "should return the full objects if inflate is true" do - Chef::Node.cdb_list(true).should eql(["a"]) - end - end - - describe "when loading a given node" do - it "should load a node from couchdb by name" do - @couchdb.should_receive(:load).with("node", "coffee").and_return(true) - Chef::CouchDB.stub!(:new).and_return(@couchdb) - Chef::Node.cdb_load("coffee") - end - end - - describe "when destroying a Node" do - it "should delete this node from couchdb" do - @couchdb.should_receive(:delete).with("node", "bob", 1).and_return(true) - Chef::CouchDB.stub!(:new).and_return(@couchdb) - node = Chef::Node.new - node.name "bob" - node.couchdb_rev = 1 - node.cdb_destroy - end - end - - describe "when saving a Node" do - before(:each) do - @couchdb.stub!(:store).and_return({ "rev" => 33 }) - Chef::CouchDB.stub!(:new).and_return(@couchdb) - @node = Chef::Node.new - @node.name "bob" - @node.couchdb_rev = 1 - end - - it "should save the node to couchdb" do - @couchdb.should_receive(:store).with("node", "bob", @node).and_return({ "rev" => 33 }) - @node.cdb_save - end - - it "should store the new couchdb_rev" do - @node.cdb_save - @node.couchdb_rev.should eql(33) - end - end - - describe "create_design_document" do - it "should create our design document" do - @couchdb.should_receive(:create_design_document).with("nodes", Chef::Node::DESIGN_DOCUMENT) - Chef::CouchDB.stub!(:new).and_return(@couchdb) - Chef::Node.create_design_document - end - end - - end - end diff --git a/chef/spec/unit/openid_registration_spec.rb b/chef/spec/unit/openid_registration_spec.rb deleted file mode 100644 index 70d4964104..0000000000 --- a/chef/spec/unit/openid_registration_spec.rb +++ /dev/null @@ -1,153 +0,0 @@ -# -# Author:: Adam Jacob (<adam@opscode.com>) -# Copyright:: Copyright (c) 2008 Opscode, Inc. -# License:: Apache License, Version 2.0 -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -require 'spec_helper' - -describe Chef::OpenIDRegistration, "initialize" do - it "should return a new Chef::OpenIDRegistration object" do - Chef::OpenIDRegistration.new.should be_kind_of(Chef::OpenIDRegistration) - end -end - -describe Chef::OpenIDRegistration, "set_password" do - it "should generate a salt for this object" do - oreg = Chef::OpenIDRegistration.new - oreg.salt.should eql(nil) - oreg.set_password("foolio") - oreg.salt.should_not eql(nil) - end - - it "should encrypt the password with the salt and the plaintext password" do - oreg = Chef::OpenIDRegistration.new - oreg.set_password("foolio") - oreg.password.should_not eql(nil) - end -end - -describe Chef::OpenIDRegistration, "to_json" do - it "should serialize itself as json" do - oreg = Chef::OpenIDRegistration.new - oreg.set_password("monkey") - json = oreg.to_json - %w{json_class chef_type name salt password validated}.each do |verify| - json.should =~ /#{verify}/ - end - end -end - -describe Chef::OpenIDRegistration, "from_json" do - it "should serialize itself as json" do - oreg = Chef::OpenIDRegistration.new() - oreg.name = "foobar" - oreg.set_password("monkey") - oreg_json = oreg.to_json - nreg = Chef::JSONCompat.from_json(oreg_json) - nreg.should be_a_kind_of(Chef::OpenIDRegistration) - %w{name salt password validated}.each do |verify| - nreg.send(verify.to_sym).should eql(oreg.send(verify.to_sym)) - end - end -end - -describe Chef::OpenIDRegistration, "list" do - before(:each) do - @mock_couch = mock("Chef::CouchDB") - @mock_couch.stub!(:list).and_return({ - "rows" => [ - { - "value" => "a", - "key" => "avenue" - } - ] - }) - Chef::CouchDB.stub!(:new).and_return(@mock_couch) - end - - it "should retrieve a list of nodes from CouchDB" do - Chef::OpenIDRegistration.list.should eql(["avenue"]) - end - - it "should return just the ids if inflate is false" do - Chef::OpenIDRegistration.list(false).should eql(["avenue"]) - end - - it "should return the full objects if inflate is true" do - Chef::OpenIDRegistration.list(true).should eql(["a"]) - end -end - -describe Chef::OpenIDRegistration, "load" do - it "should load a registration from couchdb by name" do - @mock_couch = mock("Chef::CouchDB") - Chef::CouchDB.stub!(:new).and_return(@mock_couch) - @mock_couch.should_receive(:load).with("openid_registration", "coffee").and_return(true) - Chef::OpenIDRegistration.load("coffee") - end -end - -describe Chef::OpenIDRegistration, "destroy" do - it "should delete this registration from couchdb" do - @mock_couch = mock("Chef::CouchDB") - @mock_couch.should_receive(:delete).with("openid_registration", "bob", 1).and_return(true) - Chef::CouchDB.stub!(:new).and_return(@mock_couch) - reg = Chef::OpenIDRegistration.new - reg.name = "bob" - reg.couchdb_rev = 1 - reg.destroy - end -end - -describe Chef::OpenIDRegistration, "save" do - before(:each) do - @mock_couch = mock("Chef::CouchDB") - Chef::CouchDB.stub!(:new).and_return(@mock_couch) - @reg = Chef::OpenIDRegistration.new - @reg.name = "bob" - @reg.couchdb_rev = 1 - end - - it "should save the registration to couchdb" do - @mock_couch.should_receive(:store).with("openid_registration", "bob", @reg).and_return({ "rev" => 33 }) - @reg.save - end - - it "should store the new couchdb_rev" do - @mock_couch.stub!(:store).with("openid_registration", "bob", @reg).and_return({ "rev" => 33 }) - @reg.save - @reg.couchdb_rev.should eql(33) - end -end - -describe Chef::OpenIDRegistration, "create_design_document" do - it "should create our design document" do - mock_couch = mock("Chef::CouchDB") - mock_couch.should_receive(:create_design_document).with("registrations", Chef::OpenIDRegistration::DESIGN_DOCUMENT) - Chef::CouchDB.stub!(:new).and_return(mock_couch) - Chef::OpenIDRegistration.create_design_document - end -end - -describe Chef::OpenIDRegistration, "has_key?" do - it "should check with CouchDB for a registration with this key" do - @mock_couch = mock("Chef::CouchDB") - @mock_couch.should_receive(:has_key?).with("openid_registration", "bob").and_return(true) - Chef::CouchDB.stub!(:new).and_return(@mock_couch) - Chef::OpenIDRegistration.has_key?("bob") - end -end - diff --git a/chef/spec/unit/provider/ohai_spec.rb b/chef/spec/unit/provider/ohai_spec.rb index c86ad288eb..8402c92e97 100644 --- a/chef/spec/unit/provider/ohai_spec.rb +++ b/chef/spec/unit/provider/ohai_spec.rb @@ -34,7 +34,7 @@ describe Chef::Provider::Ohai do :platform => @platform, :platform_version => @platform_version, :data => { - :origdata => "somevalue" + :origdata => "somevalue" }, :data2 => { :origdata => "somevalue", @@ -49,7 +49,7 @@ describe Chef::Provider::Ohai do Chef::Platform.stub!(:find_platform_and_version).and_return({ "platform" => @platform, "platform_version" => @platform_version}) # Fake node with a dummy save - @node = Chef::Node.new(@hostname) + @node = Chef::Node.new @node.name(@fqdn) @node.stub!(:save).and_return(@node) @events = Chef::EventDispatch::Dispatcher.new diff --git a/chef/spec/unit/run_list_spec.rb b/chef/spec/unit/run_list_spec.rb index cc261edbd8..f18f21a82b 100644 --- a/chef/spec/unit/run_list_spec.rb +++ b/chef/spec/unit/run_list_spec.rb @@ -23,13 +23,6 @@ require 'spec_helper' require 'chef/version_class' require 'chef/version_constraint' -# dep_selector/gecode on many platforms is currenly a bowel of hurt -begin -require 'chef/cookbook_version_selector' -rescue LoadError - STDERR.puts "\n*** dep_selector not installed. marking all unit tests 'pending' that have a transitive dependency on dep_selector. ***\n\n" -end - describe Chef::RunList do before(:each) do @run_list = Chef::RunList.new @@ -255,13 +248,6 @@ describe Chef::RunList do end - describe "from couchdb" do - it "should load the role from couchdb" do - Chef::Role.should_receive(:cdb_load).and_return(@role) - @run_list.expand("_default", "couchdb") - end - end - it "should return the list of expanded recipes" do expansion = @run_list.expand("_default") expansion.recipes[0].should == "one" @@ -323,199 +309,4 @@ describe Chef::RunList do end - describe "constrain" do - - pending "=> can't find 'dep_selector' gem...skipping Chef::CookbookVersionSelector related tests" do - - @fake_db = Object.new - - def cookbook_maker(name, version, deps) - book = Chef::CookbookVersion.new(name, @fake_db) - book.version = version - deps.each { |dep_name, vc| book.metadata.depends(dep_name, vc) } - book - end - - def vc_maker(cookbook_name, version_constraint) - vc = Chef::VersionConstraint.new(version_constraint) - { :name => cookbook_name, :version_constraint => vc } - end - - def assert_failure_unsatisfiable_item(run_list, all_cookbooks, constraints, expected_message) - begin - Chef::CookbookVersionSelector.constrain(all_cookbooks, constraints) - fail "Should have raised a Chef::Exceptions::CookbookVersionSelection::UnsatisfiableRunListItem exception" - rescue Chef::Exceptions::CookbookVersionSelection::UnsatisfiableRunListItem => urli - urli.message.should include(expected_message) - end - end - - def assert_failure_invalid_items(run_list, all_cookbooks, constraints, expected_message) - begin - Chef::CookbookVersionSelector.constrain(all_cookbooks, constraints) - fail "Should have raised a Chef::Exceptions::CookbookVersionSelection::InvalidRunListItems exception" - rescue Chef::Exceptions::CookbookVersionSelection::InvalidRunListItems => irli - irli.message.should include(expected_message) - end - end - - before(:each) do - a1 = cookbook_maker("a", "1.0", [["c", "< 4.0"]]) - b1 = cookbook_maker("b", "1.0", [["c", "< 3.0"]]) - - c2 = cookbook_maker("c", "2.0", [["d", "> 1.0"], ["f", nil]]) - c3 = cookbook_maker("c", "3.0", [["d", "> 2.0"], ["e", nil]]) - - d1_1 = cookbook_maker("d", "1.1", []) - d2_1 = cookbook_maker("d", "2.1", []) - e1 = cookbook_maker("e", "1.0", []) - f1 = cookbook_maker("f", "1.0", []) - g1 = cookbook_maker("g", "1.0", [["d", "> 5.0"]]) - - n1_1 = cookbook_maker("n", "1.1", []) - n1_2 = cookbook_maker("n", "1.2", []) - n1_10 = cookbook_maker("n", "1.10", []) - - depends_on_nosuch = cookbook_maker("depends_on_nosuch", "1.0", [["nosuch", nil]]) - - @all_cookbooks = { - "a" => [a1], - "b" => [b1], - "c" => [c2, c3], - "d" => [d1_1, d2_1], - "e" => [e1], - "f" => [f1], - "g" => [g1], - "n" => [n1_1, n1_2, n1_10], - "depends_on_nosuch" => [depends_on_nosuch] - } - - $stderr.reopen DEV_NULL - end - - after do - $stderr.reopen STDERR - end - - it "pulls in transitive dependencies" do - constraints = [vc_maker("a", "~> 1.0")] - cookbooks = Chef::CookbookVersionSelector.constrain(@all_cookbooks, constraints) - %w(a c d e).each { |k| cookbooks.should have_key k } - cookbooks.size.should == 4 - cookbooks["c"].version.should == "3.0.0" - cookbooks["d"].version.should == "2.1.0" - end - - it "should satisfy recipe-specific dependencies" do - depends_on_recipe = cookbook_maker("depends_on_recipe", "1.0", [["f::recipe", "1.0"]]) - @all_cookbooks["depends_on_recipe"] = [depends_on_recipe] - constraints = [vc_maker("depends_on_recipe", "= 1.0")] - cookbooks = Chef::CookbookVersionSelector.constrain(@all_cookbooks, constraints) - cookbooks["f"].version.should == "1.0.0" - end - - it "properly sorts version triples, treating each term numerically" do - constraints = [vc_maker("n", "> 1.2")] - cookbooks = Chef::CookbookVersionSelector.constrain(@all_cookbooks, constraints) - cookbooks.size.should == 1 - cookbooks["n"].version.should == "1.10.0" - end - - it "should fail to find a solution when a run list item is constrained to a range that includes no cookbooks" do - constraints = [vc_maker("d", "> 5.0")] - assert_failure_invalid_items(@run_list, @all_cookbooks, constraints, "Run list contains invalid items: no versions match the constraints on cookbook d.") - end - - it "should fail to find a solution when a run list item's dependency is constrained to a range that includes no cookbooks" do - constraints = [vc_maker("g", nil)] - assert_failure_unsatisfiable_item(@run_list, @all_cookbooks, constraints, "Unable to satisfy constraints on cookbook d due to run list item (g >= 0.0.0)") - end - - it "selects 'd 2.1.0' given constraint 'd > 1.2.3'" do - constraints = [vc_maker("d", "> 1.2.3")] - cookbooks = Chef::CookbookVersionSelector.constrain(@all_cookbooks, constraints) - cookbooks.size.should == 1 - cookbooks["d"].version.should == "2.1.0" - end - - it "selects largest version when constraint allows multiple" do - constraints = [vc_maker("d", "> 1.0")] - cookbooks = Chef::CookbookVersionSelector.constrain(@all_cookbooks, constraints) - cookbooks.size.should == 1 - cookbooks["d"].version.should == "2.1.0" - end - - it "selects 'd 1.1.0' given constraint 'd ~> 1.0'" do - constraints = [vc_maker("d", "~> 1.0")] - cookbooks = Chef::CookbookVersionSelector.constrain(@all_cookbooks, constraints) - cookbooks.size.should == 1 - cookbooks["d"].version.should == "1.1.0" - end - - it "raises InvalidRunListItems for an unknown cookbook in the run list" do - constraints = [vc_maker("nosuch", "1.0.0")] - assert_failure_invalid_items(@run_list, @all_cookbooks, constraints, "Run list contains invalid items: no such cookbook nosuch.") - end - - it "raises CookbookVersionConflict for an unknown cookbook in a cookbook's dependencies" do - constraints = [vc_maker("depends_on_nosuch", "1.0.0")] - assert_failure_unsatisfiable_item(@run_list, @all_cookbooks, constraints, "Unable to satisfy constraints on cookbook nosuch, which does not exist, due to run list item (depends_on_nosuch = 1.0.0). Run list items that may result in a constraint on nosuch: [(depends_on_nosuch = 1.0.0) -> (nosuch >= 0.0.0)]") - end - - it "raises UnsatisfiableRunListItem for direct conflict" do - constraints = [vc_maker("d", "= 1.1.0"), vc_maker("d", ">= 2.0")] - assert_failure_unsatisfiable_item(@run_list, @all_cookbooks, constraints, "Unable to satisfy constraints on cookbook d due to run list item (d >= 2.0.0)") - end - - describe "should solve regardless of constraint order" do - - it "raises CookbookVersionConflict a then b" do - # Cookbooks a and b both have a dependency on c, but with - # differing constraints. - constraints = [vc_maker("a", "1.0"), vc_maker("b", "1.0")] - cookbooks = Chef::CookbookVersionSelector.constrain(@all_cookbooks, constraints) - cookbooks.size.should == 5 - %w(a b c d f).each { |k| cookbooks.should have_key k } - cookbooks["a"].version.should == "1.0.0" - cookbooks["b"].version.should == "1.0.0" - cookbooks["c"].version.should == "2.0.0" - cookbooks["d"].version.should == "2.1.0" - end - - it "resolves b then a" do - # See above comment for a then b. When b is pulled in first, - # we should get a version of c that satifies the constraints - # on the c dependency for both b and a. - constraints = [vc_maker("b", "1.0"), vc_maker("a", "1.0")] - cookbooks = Chef::CookbookVersionSelector.constrain(@all_cookbooks, constraints) - cookbooks.size.should == 5 - %w(a b c d f).each { |k| cookbooks.should have_key k } - cookbooks["a"].version.should == "1.0.0" - cookbooks["b"].version.should == "1.0.0" - cookbooks["c"].version.should == "2.0.0" - cookbooks["d"].version.should == "2.1.0" - end - - it "resolves a then d" do - constraints = [vc_maker("a", "1.0"), vc_maker("d", "1.1")] - cookbooks = Chef::CookbookVersionSelector.constrain(@all_cookbooks, constraints) - cookbooks.size.should == 4 - %w(a c d f).each { |k| cookbooks.should have_key k } - cookbooks["a"].version.should == "1.0.0" - cookbooks["c"].version.should == "2.0.0" - cookbooks["d"].version.should == "1.1.0" - end - - it "resolves d then a" do - constraints = [vc_maker("d", "1.1"), vc_maker("a", "1.0")] - cookbooks = Chef::CookbookVersionSelector.constrain(@all_cookbooks, constraints) - cookbooks.size.should == 4 - %w(a c d f).each { |k| cookbooks.should have_key k } - cookbooks["a"].version.should == "1.0.0" - cookbooks["c"].version.should == "2.0.0" - cookbooks["d"].version.should == "1.1.0" - end - end - end - end end diff --git a/chef/spec/unit/solr_query/query_transform_spec.rb b/chef/spec/unit/solr_query/query_transform_spec.rb deleted file mode 100644 index f3fc746746..0000000000 --- a/chef/spec/unit/solr_query/query_transform_spec.rb +++ /dev/null @@ -1,454 +0,0 @@ -# -# Author:: Seth Falcon (<seth@opscode.com>) -# Copyright:: Copyright (c) 2010-2011 Opscode, Inc. -# License:: Apache License, Version 2.0 -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -require 'spec_helper' -require 'chef/solr_query/query_transform' - -describe "Chef::SolrQuery::QueryTransform" do - before(:each) do - @parser = Chef::SolrQuery::QueryTransform - @parseError = Chef::Exceptions::QueryParseError - end - - describe "single term queries" do - basic_terms = %w(a ab 123 a1 2b foo_bar baz-baz) - basic_terms << " leading" - basic_terms << "trailing " - basic_terms += %w(XAND ANDX XOR ORX XNOT NOTX) - basic_terms.each do |term| - expect = "T:#{term.strip}" - it "'#{term}' => #{expect}" do - @parser.parse(term).should == expect - end - end - describe "invalid" do - %w(AND OR NOT :).each do |t| - it "'#{t}' => ParseError" do - lambda { @parser.parse(t) }.should raise_error(@parseError) - end - end - end - - describe "wildcards in terms" do - it "allows * as a wildcard" do - @parser.parse("foo*bar").should == "T:foo*bar" - end - - it "allows a single ? as a wildcard" do - @parser.parse("foo?bar").should == "T:foo?bar" - end - - it "allows multiple ? as fixed length wildcards" do - @parser.parse("foo???bar").should == "T:foo???bar" - end - - it "allows a leading wildcard with *" do - # NOTE: This is not valid lucene query syntax. However, our - # index format and query transformation can allow it because - # the transformed query ends up with the '*' not in leading - # position. We decided that allowing it makes sense because - # queries like ec2:* are useful and many users expect this - # behavior to work. - @parser.parse("*foobar").should == "T:*foobar" - end - - it "does not allow a leading wildcard with ?" do - lambda { @parser.parse("?foobar") }.should raise_error(@parseError) - end - - it "does not allow a leading wildcard with ?" do - lambda { @parser.parse("afield:?foobar") }.should raise_error(@parseError) - end - - end - - describe "escaped special characters in terms" do - special_chars = ["!", "(", ")", "{", "}", "[", "]", "^", "\"", - "~", "*", "?", ":", "\\", "&", "|", "+", "-"] - example_fmts = ['foo%sbar', '%sb', 'a%s'] - special_chars.each do |char| - example_fmts.each do |fmt| - input = fmt % ("\\" + char) - expect = "T:#{input}" - it "'#{input}' => #{expect}" do - @parser.parse(input).should == expect - end - end - end - end - - describe "special characters in terms are not allowed" do - # NOTE: '*' is not a valid start letter for a lucene search - # term, however, we can support it because of our index - # structure and query transformation. We decided to keep this - # flexibility because queries like ec2:* are common and useful. - prefix_ok = ["!", "+", "-", "*"] - suffix_ok = ["*", "?", "~", "-"] - # FIXME: ideally, '!' would not be allowed in the middle of a - # term. Currently we parse foo!bar the same as foo !bar. - # Also '+' might be nice to disallow - embed_ok = ["*", "?", ":", "-", "!", "+"] - special_chars = ["!", "(", ")", "{", "}", "[", "]", "^", "\"", - "~", "*", "?", ":", "\\", "&", "|", "+", "-"] - example_fmts = { - :prefix => '%sb', - :middle => 'foo%sbar', - :suffix => 'a%s' - } - special_chars.each do |char| - example_fmts.keys.each do |key| - fmt = example_fmts[key] - if key == :prefix && prefix_ok.include?(char) - :pass - elsif key == :middle && embed_ok.include?(char) - :pass - elsif key == :suffix && suffix_ok.include?(char) - :pass - else - input = fmt % char - it "disallows: '#{input}'" do - lambda { @parser.parse(input) }.should raise_error(@parseError) - end - end - end - end - end - - end - - describe "multiple terms" do - it "should allow multiple terms" do - @parser.parse("a b cdefg").should == "T:a T:b T:cdefg" - end - end - - describe "boolean queries" do - describe "two term basic and/or" do - binary_operators = [['AND', 'AND'], ['&&', 'AND'], ['OR', 'OR'], ['||', 'OR']] - binary_operators.each do |op, op_name| - expect = "(OP:#{op_name} T:t1 T:t2)" - it "should parse 't1 #{op} t2' => #{expect}" do - @parser.parse("t1 #{op} t2").should == expect - end - end - end - - it "should allow a string of terms with ands and ors" do - expect = "(OP:AND T:t1 (OP:OR T:t2 (OP:AND T:t3 T:t4)))" - @parser.parse("t1 AND t2 OR t3 AND t4").should == expect - end - end - - describe "grouping with parens" do - it "should create a single group for (aterm)" do - @parser.parse("(aterm)").should == "(T:aterm)" - end - - describe "and booleans" do - - %w(AND &&).each do |op| - expect = "((OP:AND T:a T:b))" - input = "(a #{op} b)" - it "parses #{input} => #{expect}" do - @parser.parse(input).should == expect - end - end - - %w(OR ||).each do |op| - expect = "((OP:OR T:a T:b))" - input = "(a #{op} b)" - it "parses #{input} => #{expect}" do - @parser.parse(input).should == expect - end - end - - it "should handle a LHS group" do - expect = "(OP:OR ((OP:AND T:a T:b)) T:c)" - @parser.parse("(a && b) OR c").should == expect - @parser.parse("(a && b) || c").should == expect - end - - it "should handle a RHS group" do - expect = "(OP:OR T:c ((OP:AND T:a T:b)))" - @parser.parse("c OR (a && b)").should == expect - @parser.parse("c OR (a AND b)").should == expect - end - - it "should handle both sides as groups" do - expect = "(OP:OR ((OP:AND T:c T:d)) ((OP:AND T:a T:b)))" - @parser.parse("(c AND d) OR (a && b)").should == expect - end - end - end - - describe "NOT queries" do - # input, output - [ - ["a NOT b", "T:a (OP:NOT T:b)"], - ["a ! b", "T:a (OP:NOT T:b)"], - ["a !b", "T:a (OP:NOT T:b)"], - ["a NOT (b || c)", "T:a (OP:NOT ((OP:OR T:b T:c)))"], - ["a ! (b || c)", "T:a (OP:NOT ((OP:OR T:b T:c)))"], - ["a !(b || c)", "T:a (OP:NOT ((OP:OR T:b T:c)))"] - ].each do |input, expected| - it "should parse '#{input}' => #{expected.inspect}" do - @parser.parse(input).should == expected - end - end - - ["NOT", "a NOT", "(NOT)"].each do |d| - it "should raise a ParseError on '#{d}'" do - lambda { @parser.parse(d) }.should raise_error(@parseError) - end - end - end - - describe 'required and prohibited prefixes (+/-)' do - ["+", "-"].each do |kind| - [ - ["#{kind}foo", "(OP:#{kind} T:foo)"], - ["bar #{kind}foo", "T:bar (OP:#{kind} T:foo)"], - ["(#{kind}oneA twoA) b", "((OP:#{kind} T:oneA) T:twoA) T:b"] - ].each do |input, expect| - it "should parse '#{input} => #{expect.inspect}" do - @parser.parse(input).should == expect - end - end - end - - # it 'ignores + embedded in a term' do - # @parser.parse("one+two").should == "T:one+two" - # end - - it 'ignores - embedded in a term' do - @parser.parse("one-two").should == "T:one-two" - end - - it "allows a trailing dash" do - @parser.parse("one-").should == "T:one-" - end - - end - - describe "phrases (strings)" do - phrases = [['"single"', 'STR:"single"'], - ['"two term"', 'STR:"two term"'], - ['"has \"escaped\" quote\"s"', 'STR:"has \"escaped\" quote\"s"'] - ] - phrases.each do |phrase, expect| - it "'#{phrase}' => #{expect}" do - @parser.parse(phrase).should == expect - end - end - - describe "invalid" do - bad = ['""', '":not:a:term"', '"a :bad:'] - bad.each do |t| - it "'#{t}' => ParseError" do - lambda { @parser.parse(t) }.should raise_error(@parseError) - end - end - end - - it "allows phrases to be required with '+'" do - @parser.parse('+"a b c"').should == '(OP:+ STR:"a b c")' - end - - it "allows phrases to be prohibited with '-'" do - @parser.parse('-"a b c"').should == '(OP:- STR:"a b c")' - end - - it "allows phrases to be excluded with NOT" do - @parser.parse('a NOT "b c"').should == 'T:a (OP:NOT STR:"b c")' - end - - end - - describe "fields" do - it "parses a term annotated with a field" do - @parser.parse("afield:aterm").should == "(F:afield T:aterm)" - end - - it "allows underscore in a field name" do - @parser.parse("a_field:aterm").should == "(F:a_field T:aterm)" - end - - it "parses a group annotated with a field" do - @parser.parse("afield:(a b c)").should == "(F:afield (T:a T:b T:c))" - end - - it "parses a phrase annotated with a field" do - @parser.parse('afield:"a b c"').should == '(F:afield STR:"a b c")' - end - - it "allows @ in a term" do - @parser.parse('afield:foo@acme.org').should == '(F:afield T:foo@acme.org)' - end - - describe "and binary operators" do - examples = [ - ['term1 AND afield:term2', "(OP:AND T:term1 (F:afield T:term2))"], - ['afield:term1 AND term2', "(OP:AND (F:afield T:term1) T:term2)"], - ['afield:term1 AND bfield:term2', - "(OP:AND (F:afield T:term1) (F:bfield T:term2))"]] - examples.each do |input, want| - it "'#{input}' => '#{want}'" do - @parser.parse(input).should == want - end - end - end - - describe "and unary operators" do - examples = [ - ['term1 AND NOT afield:term2', - "(OP:AND T:term1 (OP:NOT (F:afield T:term2)))"], - ['term1 AND ! afield:term2', - "(OP:AND T:term1 (OP:NOT (F:afield T:term2)))"], - ['term1 AND !afield:term2', - "(OP:AND T:term1 (OP:NOT (F:afield T:term2)))"], - ['term1 AND -afield:term2', - "(OP:AND T:term1 (OP:- (F:afield T:term2)))"], - ['-afield:[* TO *]', - "(OP:- (FR:afield [*] [*]))"] - ] - examples.each do |input, want| - it "#{input} => #{want}" do - @parser.parse(input).should == want - end - end - end - end - - describe "range queries" do - before(:each) do - @kinds = { - "inclusive" => {:left => "[", :right => "]"}, - "exclusive" => {:left => "{", :right => "}"} - } - end - - def make_expect(kind, field, s, e) - expect_fmt = "(FR:%s %s%s%s %s%s%s)" - left = @kinds[kind][:left] - right = @kinds[kind][:right] - expect_fmt % [field, left, s, right, left, e, right] - end - - def make_query(kind, field, s, e) - query_fmt = "%s:%s%s TO %s%s" - left = @kinds[kind][:left] - right = @kinds[kind][:right] - query_fmt % [field, left, s, e, right] - end - - ["inclusive", "exclusive"].each do |kind| - tests = [["afield", "start", "end"], - ["afield", "start", "*"], - ["afield", "*", "end"], - ["afield", "*", "*"] - ] - tests.each do |field, s, e| - it "parses an #{kind} range query #{s} TO #{e}" do - expect = make_expect(kind, field, s, e) - query = make_query(kind, field, s, e) - @parser.parse(query).should == expect - end - end - end - - describe "and binary operators" do - [["afield:[start TO end] AND term", - "(OP:AND (FR:afield [start] [end]) T:term)"], - ["term OR afield:[start TO end]", - "(OP:OR T:term (FR:afield [start] [end]))"], - ["f1:[s1 TO e1] OR f2:[s2 TO e2]", - "(OP:OR (FR:f1 [s1] [e1]) (FR:f2 [s2] [e2]))"] - ].each do |q, want| - it "parses '#{q}'" do - @parser.parse(q).should == want - end - end - end - - describe "and unary operators" do - [["t1 NOT afield:[start TO end]", - "T:t1 (OP:NOT (FR:afield [start] [end]))"] - ].each do |input, want| - it "#{input} => #{want}" do - @parser.parse(input).should == want - end - end - end - end - - describe "proximity query" do - [ - ['"one two"~10', '(OP:~ STR:"one two" 10)'], - ['word~', '(OP:~ T:word)'], - ['word~0.5', '(OP:~ T:word 0.5)'] - ].each do |input, expect| - it "'#{input}' => #{expect}" do - @parser.parse(input).should == expect - end - end - end - - describe "term boosting" do - [ - ['"one two"^10', '(OP:^ STR:"one two" 10)'], - ['word^0.5', '(OP:^ T:word 0.5)'] - ].each do |input, expect| - it "'#{input}' => #{expect}" do - @parser.parse(input).should == expect - end - end - - it "should fail to parse if no boosting argument is given" do - lambda { @parser.parse("foo^")}.should raise_error(@parseError) - end - end - - describe "examples" do - examples = [['tags:apples*.for.eating.com', "(F:tags T:apples*.for.eating.com)"], - ['ohai_time:[1234.567 TO *]', "(FR:ohai_time [1234.567] [*])"], - ['ohai_time:[* TO 1234.567]', "(FR:ohai_time [*] [1234.567])"], - ['ohai_time:[* TO *]', "(FR:ohai_time [*] [*])"]] - # ['aterm AND afield:aterm', "((OP:AND T:aterm ((F:afield T:aterm))))"], - # ['role:prod AND aterm', "blah"], - # ['role:prod AND xy:true', "blah"]] - examples.each do |input, want| - it "'#{input}' => '#{want}'" do - @parser.parse(input).should == want - end - end - end - - describe "transform queries for solr schema" do - testcase_file = "#{CHEF_SPEC_DATA}/search_queries_to_transform.txt" - lines = File.readlines(testcase_file).map { |line| line.strip } - lines = lines.select { |line| !line.empty? } - testcases = Hash[*(lines)] - testcases.keys.sort.each do |input| - expected = testcases[input] - it "from> #{input}\n to> #{expected}\n" do - @parser.transform(input).should == expected - end - end - end - -end diff --git a/chef/spec/unit/solr_query/solr_http_request_spec.rb b/chef/spec/unit/solr_query/solr_http_request_spec.rb deleted file mode 100644 index c70c347a14..0000000000 --- a/chef/spec/unit/solr_query/solr_http_request_spec.rb +++ /dev/null @@ -1,244 +0,0 @@ -# Author:: Daniel DeLeo (<dan@opscode.com>) -# Copyright:: Copyright (c) 2011 Opscode, inc. -# License:: Apache License, Version 2.0 -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -require 'spec_helper' - -require 'chef/solr_query' -require 'net/http' - -describe Chef::SolrQuery::SolrHTTPRequest do - before do - Chef::Config[:solr_url] = "http://example.com:8983" - Chef::SolrQuery::SolrHTTPRequest.instance_variable_set(:@solr_url, nil) - Chef::SolrQuery::SolrHTTPRequest.instance_variable_set(:@url_prefix, nil) - - @request = Chef::SolrQuery::SolrHTTPRequest.new(:GET, '/solr/select') - end - - it "defaults to using the configured solr_url" do - Chef::SolrQuery::SolrHTTPRequest.solr_url.should == "http://example.com:8983" - end - - it "supports solr_url with a path" do - Chef::Config[:solr_url] = "http://example.com:8983/test" - Chef::SolrQuery::SolrHTTPRequest.instance_variable_set(:@solr_url, nil) - - Chef::SolrQuery::SolrHTTPRequest.solr_url.should == "http://example.com:8983/test" - end - - it "updates the Solr URL as you like" do - Chef::SolrQuery::SolrHTTPRequest.solr_url = "http://chunkybacon.org:1234" - Chef::SolrQuery::SolrHTTPRequest.solr_url.should == "http://chunkybacon.org:1234" - end - - it "updates the URL prefix with a path" do - Chef::SolrQuery::SolrHTTPRequest.solr_url = "http://chunkybacon.org:1234/something" - Chef::SolrQuery::SolrHTTPRequest.url_prefix.should == "/something" - end - - it "removes extra / at the end of solr_url" do - Chef::SolrQuery::SolrHTTPRequest.solr_url = "http://chunkybacon.org:1234/extra/" - Chef::SolrQuery::SolrHTTPRequest.url_prefix.should == "/extra" - end - - it "creates a Net::HTTP client for the base Solr URL" do - Chef::SolrQuery::SolrHTTPRequest.solr_url = "http://chunkybacon.org:1234" - http_client = Chef::SolrQuery::SolrHTTPRequest.http_client - http_client.address.should == "chunkybacon.org" - http_client.port.should == 1234 - end - - it "creates a Net::HTTP client for the base Solr URL ignoring the path" do - Chef::SolrQuery::SolrHTTPRequest.solr_url = "http://chunkybacon.org:1234/test" - http_client = Chef::SolrQuery::SolrHTTPRequest.http_client - http_client.address.should == "chunkybacon.org" - http_client.port.should == 1234 - end - - it "defaults url_prefix to /solr if the configured solr_url has no path" do - Chef::SolrQuery::SolrHTTPRequest.solr_url = "http://chunkybacon.org:1234" - Chef::SolrQuery::SolrHTTPRequest.url_prefix.should == "/solr" - end - - it "defaults url_prefix to the path from the configured solr_url" do - Chef::SolrQuery::SolrHTTPRequest.solr_url = "http://chunkybacon.org:1234/test" - Chef::SolrQuery::SolrHTTPRequest.url_prefix.should == "/test" - end - - describe "when configured with the Solr URL" do - before do - @http_response = mock( - "Net::HTTP::Response", - :kind_of? => Net::HTTPSuccess, - :body => "{ :some => :hash }" - ) - @http_request = mock( - "Net::HTTP::Request", - :body= => true - ) - @http = mock("Net::HTTP", :request => @http_response) - Chef::SolrQuery::SolrHTTPRequest.stub!(:http_client).and_return(@http) - end - - describe "when executing a select query" do - before(:each) do - @http_response = mock( - "Net::HTTP::Response", - :kind_of? => Net::HTTPSuccess, - :body => '{"some": "hash" }' - ) - @solr = Chef::SolrQuery.from_params(:type => 'node', - :q => "hostname:latte") - @params = @solr.to_hash - @http = mock("Net::HTTP", :request => @http_response) - Chef::SolrQuery::SolrHTTPRequest.stub!(:http_client).and_return(@http) - end - - describe "when the HTTP call is successful" do - it "should call get to /solr/select with the escaped query" do - txfm_query = "q=content%3Ahostname__%3D__latte" - Net::HTTP::Get.should_receive(:new).with(%r(/solr/select?.+#{txfm_query})) - Chef::SolrQuery::SolrHTTPRequest.select(@params) - end - - it "uses Solr's JSON response format" do - Net::HTTP::Get.should_receive(:new).with(%r(wt=json)) - Chef::SolrQuery::SolrHTTPRequest.select(@params) - end - - it "uses indent=off to get a compact response" do - Net::HTTP::Get.should_receive(:new).with(%r(indent=off)) - Chef::SolrQuery::SolrHTTPRequest.select(@params) - end - - it "uses the filter query to restrict the result set" do - filter_query =@solr.filter_query.gsub('+', '%2B').gsub(':', "%3A").gsub(' ', '+') - Net::HTTP::Get.should_receive(:new).with(/fq=#{Regexp.escape(filter_query)}/) - Chef::SolrQuery::SolrHTTPRequest.select(@params) - end - - it "returns the evaluated response body" do - res = Chef::SolrQuery::SolrHTTPRequest.select(@params) - res.should == {"some" => "hash" } - end - end - end - - describe "when updating" do - before do - Net::HTTP::Post.stub!(:new).and_return(@http_request) - end - - it "should post to /solr/update" do - @doc = "<xml is the old tldr>" - Net::HTTP::Post.should_receive(:new).with("/solr/update", "Content-Type" => "text/xml").and_return(@http_request) - Chef::SolrQuery::SolrHTTPRequest.update(@doc) - end - - it "should set the body of the request to the stringified doc" do - @http_request.should_receive(:body=).with("foo") - Chef::SolrQuery::SolrHTTPRequest.update(:foo) - end - - it "should send the request to solr" do - @http.should_receive(:request).with(@http_request).and_return(@http_response) - Chef::SolrQuery::SolrHTTPRequest.update(:foo) - end - - end - - describe "when the HTTP call is unsuccessful" do - [Timeout::Error, EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError, Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::ETIMEDOUT, Errno::EINVAL].each do |exception| - it "should rescue, log an error message, and raise a SolrConnectionError encountering exception #{exception}" do - response = mock("Net:HTTPResponse test double", :code => 500, :message => "oops", :class => exception) - @http.should_receive(:request).with(instance_of(Net::HTTP::Get)).and_return(response) - response.should_receive(:error!).and_raise(exception) - Chef::Log.should_receive(:fatal).with("Search Query to Solr failed (#{exception} 500 oops)") - - lambda {@request.run('Search Query to Solr')}.should raise_error(Chef::Exceptions::SolrConnectionError) - end - end - - it "should rescue, log an error message, and raise a SolrConnectionError when encountering exception NoMethodError and net/http closed? bug" do - @no_method_error = NoMethodError.new("undefined method 'closed\?' for nil:NilClass") - @http.should_receive(:request).with(instance_of(Net::HTTP::Get)).and_raise(@no_method_error) - Chef::Log.should_receive(:fatal).with("HTTP Request to Solr failed. Chef::Exceptions::SolrConnectionError exception: Errno::ECONNREFUSED (net/http undefined method closed?) attempting to contact http://example.com:8983") - lambda { - @request.run - }.should raise_error(Chef::Exceptions::SolrConnectionError) - end - end - - end - - describe "when configured with the Solr URL with a path" do - before do - Chef::Config[:solr_url] = "http://example.com:8983/test" - Chef::SolrQuery::SolrHTTPRequest.instance_variable_set(:@solr_url, nil) - Chef::SolrQuery::SolrHTTPRequest.instance_variable_set(:@url_prefix, nil) - - @request = Chef::SolrQuery::SolrHTTPRequest.new(:GET, '/solr/select') - - @http_response = mock( - "Net::HTTP::Response", - :kind_of? => Net::HTTPSuccess, - :body => "{ :some => :hash }" - ) - @http_request = mock( - "Net::HTTP::Request", - :body= => true - ) - @http = mock("Net::HTTP", :request => @http_response) - Chef::SolrQuery::SolrHTTPRequest.stub!(:http_client).and_return(@http) - end - - describe "when executing a select query" do - before(:each) do - @http_response = mock( - "Net::HTTP::Response", - :kind_of? => Net::HTTPSuccess, - :body => '{"some": "hash" }' - ) - @solr = Chef::SolrQuery.from_params(:type => 'node', - :q => "hostname:latte") - @params = @solr.to_hash - @http = mock("Net::HTTP", :request => @http_response) - Chef::SolrQuery::SolrHTTPRequest.stub!(:http_client).and_return(@http) - end - - describe "when the HTTP call is successful" do - it "should call get to /test/select with the escaped query" do - txfm_query = "q=content%3Ahostname__%3D__latte" - Net::HTTP::Get.should_receive(:new).with(%r(/test/select?.+#{txfm_query})) - Chef::SolrQuery::SolrHTTPRequest.select(@params) - end - end - end - - describe "when updating" do - before do - Net::HTTP::Post.stub!(:new).and_return(@http_request) - end - - it "should post to /test/update" do - @doc = "<xml is the old tldr>" - Net::HTTP::Post.should_receive(:new).with("/test/update", "Content-Type" => "text/xml").and_return(@http_request) - Chef::SolrQuery::SolrHTTPRequest.update(@doc) - end - end - end -end diff --git a/chef/spec/unit/solr_query_spec.rb b/chef/spec/unit/solr_query_spec.rb deleted file mode 100644 index 8b48011713..0000000000 --- a/chef/spec/unit/solr_query_spec.rb +++ /dev/null @@ -1,203 +0,0 @@ -# Author:: Daniel DeLeo (<dan@opscode.com>) -# Copyright:: Copyright (c) 2010, 2011 Opscode, inc. -# License:: Apache License, Version 2.0 -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -require 'spec_helper' - -require 'chef/solr_query' -require 'net/http' - -#require 'rspec/mocks' - -describe Chef::SolrQuery do - before do - Chef::SolrQuery::SolrHTTPRequest.solr_url = "http://example.com:8983" - - @http_response = mock( - "Net::HTTP::Response", - :kind_of? => Net::HTTPSuccess, - :body => "{ :some => :hash }" - ) - @http_request = mock( - "Net::HTTP::Request", - :body= => true - ) - @http = mock("Net::HTTP", :request => @http_response) - Chef::SolrQuery::SolrHTTPRequest.stub!(:http_client).and_return(@http) - Net::HTTP::Post.stub!(:new).and_return(@http_request) - Net::HTTP::Get.stub!(:new).and_return(@http_request) - @doc = { "foo" => "bar" } - end - - before(:each) do - @solr = Chef::SolrQuery.new - end - - it "sets filter query params" do - @solr.filter_by(:database => 'chef') - @solr.filter_query.should == "+X_CHEF_database_CHEF_X:chef" - end - - it "filters by type when querying for a builtin type" do - @solr.filter_by_type("node") - @solr.filter_query.should == "+X_CHEF_type_CHEF_X:node" - end - - it "filters by type for data bag items" do - @solr.filter_by_type("users") - @solr.filter_query.split(" ").sort.should == ['+X_CHEF_type_CHEF_X:data_bag_item', '+data_bag:users'] - end - - it "stores the main query" do - @solr.query = "role:prod AND tags:chef-server" - @solr.query.should == "role:prod AND tags:chef-server" - end - - describe "when generating query params for select" do - before(:each) do - @solr = Chef::SolrQuery.from_params(:type => 'node', :q => "hostname:latte") - @params = @solr.to_hash - end - - it "includes the query as q" do - @params[:q].should == "content:hostname__=__latte" - end - - it "sets the response format to json" do - @params[:wt].should == "json" - end - - it "uses indent=off to get a compact response" do - @params[:indent].should == "off" - end - - it "includes the filter query to restrict the result set" do - @params[:fq].should == @solr.filter_query - end - - it "defaults to returning 1000 rows" do - @params[:rows].should == 1000 - end - - it "returns the number of rows requested" do - @solr.params[:rows] = 500 - @solr.to_hash[:rows].should == 500 - end - - it "offsets the row selection if requested" do - @solr.params[:start] = 500 - @solr.to_hash[:start].should == 500 - end - - end - - describe "when querying solr" do - before do - @couchdb = mock("CouchDB Test Double", :couchdb_database => "chunky_bacon") - @couchdb.stub!(:kind_of?).with(Chef::CouchDB).and_return(true) #ugh. - @solr = Chef::SolrQuery.from_params({:type => 'node', :q => "hostname:latte", :start => 10, :rows => 5}, @couchdb) - @docs = [1,2,3,4,5].map { |doc_id| {'X_CHEF_id_CHEF_X' => doc_id} } - @solr_response = {"response" => {"docs" => @docs, "start" => 10, "results" => 123}} - Chef::SolrQuery::SolrHTTPRequest.should_receive(:select).with(@solr.to_hash).and_return(@solr_response) - end - - it "it collects the document ids from the response" do - @solr.object_ids.should == [1,2,3,4,5] - end - - it "does a bulk get of the objects from CouchDB" do - @couchdb.should_receive(:bulk_get).with([1,2,3,4,5]).and_return(%w{obj1 obj2 obj3 obj4 obj5}) - @solr.objects.should == %w{obj1 obj2 obj3 obj4 obj5} - end - - end - - describe "when forcing a Solr commit" do - it "sends valid commit xml to solr" do - Chef::SolrQuery::SolrHTTPRequest.should_receive(:update).with("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<commit/>\n") - @solr.commit - end - end - - describe "when deleting a database from Solr" do - it "sends a valid delete query to solr and forces a commit" do - Chef::SolrQuery::SolrHTTPRequest.should_receive(:update).with("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<delete><query>X_CHEF_database_CHEF_X:chef</query></delete>\n") - @solr.should_receive(:commit) - @solr.delete_database("chef") - end - end - - describe "rebuilding the index" do - before do - Chef::Config[:couchdb_database] = "chunky_bacon" - end - - it "deletes the index and commits" do - @solr.should_receive(:delete_database).with("chunky_bacon") - @solr.stub!(:reindex_all) - Chef::DataBag.stub!(:cdb_list).and_return([]) - @solr.rebuild_index - end - - it "reindexes Chef::ApiClient, Chef::Node, and Chef::Role objects, reporting the results as a hash" do - @solr.should_receive(:delete_database).with("chunky_bacon") - @solr.should_receive(:reindex_all).with(Chef::ApiClient).and_return(true) - @solr.should_receive(:reindex_all).with(Chef::Environment).and_return(true) - @solr.should_receive(:reindex_all).with(Chef::Node).and_return(true) - @solr.should_receive(:reindex_all).with(Chef::Role).and_return(true) - Chef::DataBag.stub!(:cdb_list).and_return([]) - - result = @solr.rebuild_index - result["Chef::ApiClient"].should == "success" - result["Chef::Node"].should == "success" - result["Chef::Role"].should == "success" - end - - it "does not reindex Chef::OpenIDRegistration or Chef::WebUIUser objects" do - # hi there. the reason we're specifying this behavior is because these objects - # are not properly indexed in the first place and trying to reindex them - # tickles a bug in our CamelCase to snake_case code. See CHEF-1009. - @solr.should_receive(:delete_database).with("chunky_bacon") - @solr.stub!(:reindex_all).with(Chef::ApiClient) - @solr.stub!(:reindex_all).with(Chef::Node) - @solr.stub!(:reindex_all).with(Chef::Role) - @solr.should_not_receive(:reindex_all).with(Chef::OpenIDRegistration) - @solr.should_not_receive(:reindex_all).with(Chef::WebUIUser) - Chef::DataBag.stub!(:cdb_list).and_return([]) - - @solr.rebuild_index - end - - it "reindexes databags" do - one_data_item = Chef::DataBagItem.new - one_data_item.raw_data = {"maybe"=>"snakes actually are evil", "id" => "just_sayin"} - two_data_item = Chef::DataBagItem.new - two_data_item.raw_data = {"tone_depth"=>"rumble_fish", "id" => "eff_yes"} - data_bag = Chef::DataBag.new - data_bag.stub!(:list).and_return([one_data_item, two_data_item]) - - @solr.should_receive(:delete_database).with("chunky_bacon") - @solr.stub!(:reindex_all) - Chef::DataBag.stub!(:cdb_list).and_return([data_bag]) - - data_bag.should_receive(:add_to_index) - one_data_item.should_receive(:add_to_index) - two_data_item.should_receive(:add_to_index) - - @solr.rebuild_index["Chef::DataBag"].should == "success" - end - end -end |