diff options
author | Thom May <thom@chef.io> | 2015-12-02 12:19:33 +0000 |
---|---|---|
committer | Thom May <thom@chef.io> | 2016-01-11 15:40:42 +0000 |
commit | d99e306a41b1402209d320cb7119b12a3bbb962f (patch) | |
tree | f65940702826deb991e6198967d3e9e96cb2857a | |
parent | 1b71aeb423b009f6d1a44215c89e9976957b47e9 (diff) | |
download | chef-d99e306a41b1402209d320cb7119b12a3bbb962f.tar.gz |
Convert all uses of Chef::REST to Chef::ServerAPItm/no_more_rest
In the process, stop auto-expanding JSON in the HTTP client, and let
individual classes control that themselves.
Fixes #2737, Fixes #3518
91 files changed, 586 insertions, 486 deletions
diff --git a/.gitignore b/.gitignore index cdb29d0679..c981191e4e 100644 --- a/.gitignore +++ b/.gitignore @@ -47,3 +47,4 @@ kitchen-tests/nodes/* # Temporary files present during spec runs spec/data/test-dir +config/ diff --git a/lib/chef/api_client/registration.rb b/lib/chef/api_client/registration.rb index bc941d5bfa..99667acc0a 100644 --- a/lib/chef/api_client/registration.rb +++ b/lib/chef/api_client/registration.rb @@ -17,7 +17,7 @@ # require 'chef/config' -require 'chef/rest' +require 'chef/server_api' require 'chef/exceptions' class Chef @@ -45,7 +45,7 @@ class Chef #-- # If client creation fails with a 5xx, it is retried up to 5 times. These # retries are on top of the retries with randomized exponential backoff - # built in to Chef::REST. The retries here are a workaround for failures + # built in to Chef::ServerAPI. The retries here are a workaround for failures # caused by resource contention in Hosted Chef when creating a very large # number of clients simultaneously, (e.g., spinning up 100s of ec2 nodes # at once). Future improvements to the affected component should make diff --git a/lib/chef/application/windows_service.rb b/lib/chef/application/windows_service.rb index 2f938059ca..9becf4b33f 100644 --- a/lib/chef/application/windows_service.rb +++ b/lib/chef/application/windows_service.rb @@ -23,7 +23,7 @@ require 'chef/client' require 'chef/config' require 'chef/handler/error_report' require 'chef/log' -require 'chef/rest' +require 'chef/http' require 'mixlib/cli' require 'socket' require 'uri' @@ -308,7 +308,7 @@ class Chef begin case config[:config_file] when /^(http|https):\/\// - Chef::REST.new("", nil, nil).fetch(config[:config_file]) { |f| apply_config(f.path) } + Chef::HTTP.new("").streaming_request(config[:config_file]) { |f| apply_config(f.path) } else ::File::open(config[:config_file]) { |f| apply_config(f.path) } end diff --git a/lib/chef/audit/audit_reporter.rb b/lib/chef/audit/audit_reporter.rb index d952d8a249..face24f1f5 100644 --- a/lib/chef/audit/audit_reporter.rb +++ b/lib/chef/audit/audit_reporter.rb @@ -127,10 +127,8 @@ class Chef end Chef::Log.debug "Audit Report:\n#{Chef::JSONCompat.to_json_pretty(run_data)}" - # Since we're posting compressed data we can not directly call post_rest which expects JSON begin - audit_url = rest_client.create_url(audit_history_url) - rest_client.post(audit_url, run_data, headers) + rest_client.post(audit_history_url, run_data, headers) rescue StandardError => e if e.respond_to? :response # 404 error code is OK. This means the version of server we're running against doesn't support diff --git a/lib/chef/chef_fs/file_system/chef_server_root_dir.rb b/lib/chef/chef_fs/file_system/chef_server_root_dir.rb index 09181ac4b4..badb70ce50 100644 --- a/lib/chef/chef_fs/file_system/chef_server_root_dir.rb +++ b/lib/chef/chef_fs/file_system/chef_server_root_dir.rb @@ -104,7 +104,7 @@ class Chef end def chef_rest - Chef::REST.new(chef_server_url, chef_username, chef_private_key) + Chef::ServerAPI.new(chef_server_url, :client_name => chef_username, :signing_key_filename => chef_private_key) end def api_path diff --git a/lib/chef/client.rb b/lib/chef/client.rb index 6ac5cecbdf..ead804879f 100644 --- a/lib/chef/client.rb +++ b/lib/chef/client.rb @@ -22,7 +22,7 @@ require 'chef/config' require 'chef/mixin/params_validate' require 'chef/mixin/path_sanity' require 'chef/log' -require 'chef/rest' +require 'chef/server_api' require 'chef/api_client' require 'chef/api_client/registration' require 'chef/audit/runner' @@ -92,7 +92,7 @@ class Chef # # The rest object used to communicate with the Chef server. # - # @return [Chef::REST] + # @return [Chef::ServerAPI] # attr_reader :rest @@ -575,7 +575,7 @@ class Chef # If Chef::Config.client_key does not exist, we register the client with the # Chef server and fire the registration_start and registration_completed events. # - # @return [Chef::REST] The server connection object. + # @return [Chef::ServerAPI] The server connection object. # # @see Chef::Config#chef_server_url # @see Chef::Config#client_key @@ -601,7 +601,8 @@ class Chef events.registration_completed end # We now have the client key, and should use it from now on. - @rest = Chef::REST.new(config[:chef_server_url], client_name, config[:client_key]) + @rest = Chef::ServerAPI.new(config[:chef_server_url], client_name: client_name, + signing_key_filename: config[:client_key]) register_reporters rescue Exception => e # TODO this should probably only ever fire if we *started* registration. diff --git a/lib/chef/cookbook/remote_file_vendor.rb b/lib/chef/cookbook/remote_file_vendor.rb index 7868430227..b118c75f9e 100644 --- a/lib/chef/cookbook/remote_file_vendor.rb +++ b/lib/chef/cookbook/remote_file_vendor.rb @@ -63,7 +63,7 @@ class Chef # (remote, per manifest), do the update. This will also execute if there # is no current checksum. if current_checksum != found_manifest_record['checksum'] - raw_file = @rest.get_rest(found_manifest_record[:url], true) + raw_file = @rest.get(found_manifest_record[:url], true) Chef::Log.debug("Storing updated #{cache_filename} in the cache.") Chef::FileCache.move_to(raw_file.path, cache_filename) diff --git a/lib/chef/cookbook/synchronizer.rb b/lib/chef/cookbook/synchronizer.rb index fc8e739d73..b499963653 100644 --- a/lib/chef/cookbook/synchronizer.rb +++ b/lib/chef/cookbook/synchronizer.rb @@ -1,5 +1,6 @@ require 'chef/client' require 'chef/util/threaded_job_queue' +require 'chef/server_api' require 'singleton' class Chef @@ -274,7 +275,7 @@ class Chef # downloaded to the path +destination+ which is relative to the Chef file # cache root. def download_file(url, destination) - raw_file = server_api.get_rest(url, true) + raw_file = server_api.streaming_request(url) Chef::Log.info("Storing updated #{destination} in the cache.") cache.move_to(raw_file.path, destination) @@ -286,7 +287,7 @@ class Chef end def server_api - Chef::REST.new(Chef::Config[:chef_server_url]) + Chef::ServerAPI.new(Chef::Config[:chef_server_url]) end end diff --git a/lib/chef/cookbook_uploader.rb b/lib/chef/cookbook_uploader.rb index f24ce2cd56..64a8a4e168 100644 --- a/lib/chef/cookbook_uploader.rb +++ b/lib/chef/cookbook_uploader.rb @@ -9,6 +9,7 @@ require 'chef/cookbook/syntax_check' require 'chef/cookbook/file_system_file_vendor' require 'chef/util/threaded_job_queue' require 'chef/sandbox' +require 'chef/server_api' class Chef class CookbookUploader @@ -31,7 +32,7 @@ class Chef # uploading the cookbook. This allows frozen CookbookVersion # documents on the server to be overwritten (otherwise a 409 is # returned by the server) - # * :rest A Chef::REST object that you have configured the way you like it. + # * :rest A Chef::ServerAPI object that you have configured the way you like it. # If you don't provide this, one will be created using the values # in Chef::Config. # * :concurrency An integer that decided how many threads will be used to @@ -39,7 +40,7 @@ class Chef def initialize(cookbooks, opts={}) @opts = opts @cookbooks = Array(cookbooks) - @rest = opts[:rest] || Chef::REST.new(Chef::Config[:chef_server_url]) + @rest = opts[:rest] || Chef::ServerAPI.new(Chef::Config[:chef_server_url]) @concurrency = opts[:concurrency] || 10 @policy_mode = opts[:policy_mode] || false end diff --git a/lib/chef/cookbook_version.rb b/lib/chef/cookbook_version.rb index 0e9617f98c..4eb118d3bc 100644 --- a/lib/chef/cookbook_version.rb +++ b/lib/chef/cookbook_version.rb @@ -25,6 +25,7 @@ require 'chef/cookbook/metadata' require 'chef/version_class' require 'chef/digester' require 'chef/cookbook_manifest' +require 'chef/server_api' class Chef @@ -459,11 +460,13 @@ class Chef end private :preferences_for_path - def self.json_create(o) - cookbook_version = new(o["cookbook_name"]) + def self.from_hash(o) + cookbook_version = new(o["cookbook_name"] || o["name"]) + # We want the Chef::Cookbook::Metadata object to always be inflated cookbook_version.metadata = Chef::Cookbook::Metadata.from_hash(o["metadata"]) cookbook_version.manifest = o + cookbook_version.identifier = o["identifier"] if o.key?("identifier") # We don't need the following step when we decide to stop supporting deprecated operators in the metadata (e.g. <<, >>) cookbook_version.manifest["metadata"] = Chef::JSONCompat.from_json(Chef::JSONCompat.to_json(cookbook_version.metadata)) @@ -472,13 +475,12 @@ class Chef cookbook_version end + def self.json_create(o) + from_hash(o) + end + def self.from_cb_artifact_data(o) - cookbook_version = new(o["name"]) - # We want the Chef::Cookbook::Metadata object to always be inflated - cookbook_version.metadata = Chef::Cookbook::Metadata.from_hash(o["metadata"]) - cookbook_version.manifest = o - cookbook_version.identifier = o["identifier"] - cookbook_version + from_hash(o) end # @deprecated This method was used by the Ruby Chef Server and is no longer @@ -543,22 +545,22 @@ class Chef end def self.chef_server_rest - Chef::REST.new(Chef::Config[:chef_server_url]) + Chef::ServerAPI.new(Chef::Config[:chef_server_url]) end def destroy - chef_server_rest.delete_rest("cookbooks/#{name}/#{version}") + chef_server_rest.delete("cookbooks/#{name}/#{version}") self end def self.load(name, version="_latest") version = "_latest" if version == "latest" - chef_server_rest.get_rest("cookbooks/#{name}/#{version}") + from_hash(chef_server_rest.get("cookbooks/#{name}/#{version}")) end # The API returns only a single version of each cookbook in the result from the cookbooks method def self.list - chef_server_rest.get_rest('cookbooks') + chef_server_rest.get('cookbooks') end # Alias latest_cookbooks as list @@ -567,7 +569,7 @@ class Chef end def self.list_all_versions - chef_server_rest.get_rest('cookbooks?num_versions=all') + chef_server_rest.get('cookbooks?num_versions=all') end ## @@ -577,7 +579,7 @@ class Chef # [String]:: Array of cookbook versions, which are strings like 'x.y.z' # nil:: if the cookbook doesn't exist. an error will also be logged. def self.available_versions(cookbook_name) - chef_server_rest.get_rest("cookbooks/#{cookbook_name}")[cookbook_name]["versions"].map do |cb| + chef_server_rest.get("cookbooks/#{cookbook_name}")[cookbook_name]["versions"].map do |cb| cb["version"] end rescue Net::HTTPServerException => e diff --git a/lib/chef/data_bag.rb b/lib/chef/data_bag.rb index 401ba6f63f..9d0dc53da5 100644 --- a/lib/chef/data_bag.rb +++ b/lib/chef/data_bag.rb @@ -24,6 +24,7 @@ require 'chef/mixin/from_file' require 'chef/data_bag_item' require 'chef/mash' require 'chef/json_compat' +require 'chef/server_api' class Chef class DataBag @@ -70,15 +71,19 @@ class Chef end def chef_server_rest - @chef_server_rest ||= Chef::REST.new(Chef::Config[:chef_server_url]) + @chef_server_rest ||= Chef::ServerAPI.new(Chef::Config[:chef_server_url]) end def self.chef_server_rest - Chef::REST.new(Chef::Config[:chef_server_url]) + Chef::ServerAPI.new(Chef::Config[:chef_server_url]) end # Create a Chef::Role from JSON def self.json_create(o) + from_hash(o) + end + + def self.from_hash(o) bag = new bag.name(o["name"]) bag @@ -104,7 +109,7 @@ class Chef response end else - Chef::REST.new(Chef::Config[:chef_server_url]).get_rest("data") + Chef::ServerAPI.new(Chef::Config[:chef_server_url]).get("data") end end end @@ -120,7 +125,7 @@ class Chef end Dir.glob(File.join(Chef::Util::PathHelper.escape_glob(path, name.to_s), "*.json")).inject({}) do |bag, f| - item = Chef::JSONCompat.from_json(IO.read(f)) + item = Chef::JSONCompat.parse(IO.read(f)) # Check if we have multiple items with similar names (ids) and raise if their content differs if data_bag.has_key?(item["id"]) && data_bag[item["id"]] != item @@ -132,12 +137,12 @@ class Chef end return data_bag else - Chef::REST.new(Chef::Config[:chef_server_url]).get_rest("data/#{name}") + Chef::ServerAPI.new(Chef::Config[:chef_server_url]).get("data/#{name}") end end def destroy - chef_server_rest.delete_rest("data/#{@name}") + chef_server_rest.delete("data/#{@name}") end # Save the Data Bag via RESTful API @@ -156,7 +161,7 @@ class Chef #create a data bag via RESTful API def create - chef_server_rest.post_rest("data", self) + chef_server_rest.post("data", self) self end diff --git a/lib/chef/data_bag_item.rb b/lib/chef/data_bag_item.rb index 31c9b69330..7ef9fffe07 100644 --- a/lib/chef/data_bag_item.rb +++ b/lib/chef/data_bag_item.rb @@ -25,6 +25,7 @@ require 'chef/mixin/params_validate' require 'chef/mixin/from_file' require 'chef/data_bag' require 'chef/mash' +require 'chef/server_api' require 'chef/json_compat' class Chef @@ -58,11 +59,11 @@ class Chef end def chef_server_rest - @chef_server_rest ||= Chef::REST.new(Chef::Config[:chef_server_url]) + @chef_server_rest ||= Chef::ServerAPI.new(Chef::Config[:chef_server_url]) end def self.chef_server_rest - Chef::REST.new(Chef::Config[:chef_server_url]) + Chef::ServerAPI.new(Chef::Config[:chef_server_url]) end def raw_data @@ -125,22 +126,23 @@ class Chef end def self.from_hash(h) + h.delete("chef_type") + h.delete("json_class") + h.delete("name") + item = new - item.raw_data = h + item.data_bag(h.delete("data_bag")) if h.key?("data_bag") + if h.key?("raw_data") + item.raw_data = Mash.new(h["raw_data"]) + else + item.raw_data = h + end item end # Create a Chef::DataBagItem from JSON def self.json_create(o) - bag_item = new - bag_item.data_bag(o["data_bag"]) - o.delete("data_bag") - o.delete("chef_type") - o.delete("json_class") - o.delete("name") - - bag_item.raw_data = Mash.new(o["raw_data"]) - bag_item + from_hash(o) end # Load a Data Bag Item by name via either the RESTful API or local data_bag_path if run in solo mode @@ -149,7 +151,7 @@ class Chef bag = Chef::DataBag.load(data_bag) item = bag[name] else - item = Chef::REST.new(Chef::Config[:chef_server_url]).get_rest("data/#{data_bag}/#{name}") + item = Chef::ServerAPI.new(Chef::Config[:chef_server_url]).get("data/#{data_bag}/#{name}") end if item.kind_of?(DataBagItem) @@ -162,7 +164,7 @@ class Chef end def destroy(data_bag=data_bag(), databag_item=name) - chef_server_rest.delete_rest("data/#{data_bag}/#{databag_item}") + chef_server_rest.delete("data/#{data_bag}/#{databag_item}") end # Save this Data Bag Item via RESTful API @@ -172,18 +174,18 @@ class Chef if Chef::Config[:why_run] Chef::Log.warn("In why-run mode, so NOT performing data bag item save.") else - r.put_rest("data/#{data_bag}/#{item_id}", self) + r.put("data/#{data_bag}/#{item_id}", self) end rescue Net::HTTPServerException => e raise e unless e.response.code == "404" - r.post_rest("data/#{data_bag}", self) + r.post("data/#{data_bag}", self) end self end # Create this Data Bag Item via RESTful API def create - chef_server_rest.post_rest("data/#{data_bag}", self) + chef_server_rest.post("data/#{data_bag}", self) self end diff --git a/lib/chef/environment.rb b/lib/chef/environment.rb index 7d4b410639..5612978a08 100644 --- a/lib/chef/environment.rb +++ b/lib/chef/environment.rb @@ -24,6 +24,7 @@ require 'chef/mash' require 'chef/mixin/params_validate' require 'chef/mixin/from_file' require 'chef/version_constraint' +require 'chef/server_api' class Chef class Environment @@ -47,11 +48,11 @@ class Chef end def chef_server_rest - @chef_server_rest ||= Chef::REST.new(Chef::Config[:chef_server_url]) + @chef_server_rest ||= Chef::ServerAPI.new(Chef::Config[:chef_server_url]) end def self.chef_server_rest - Chef::REST.new(Chef::Config[:chef_server_url]) + Chef::ServerAPI.new(Chef::Config[:chef_server_url]) end def name(arg=nil) @@ -216,6 +217,10 @@ class Chef end def self.json_create(o) + from_hash(o) + end + + def self.from_hash(o) environment = new environment.name(o["name"]) environment.description(o["description"]) @@ -233,7 +238,7 @@ class Chef end response else - chef_server_rest.get_rest("environments") + chef_server_rest.get("environments") end end @@ -241,7 +246,7 @@ class Chef if Chef::Config[:solo] load_from_file(name) else - chef_server_rest.get_rest("environments/#{name}") + chef_server_rest.get("environments/#{name}") end end @@ -267,26 +272,26 @@ class Chef end def destroy - chef_server_rest.delete_rest("environments/#{@name}") + chef_server_rest.delete("environments/#{@name}") end def save begin - chef_server_rest.put_rest("environments/#{@name}", self) + chef_server_rest.put("environments/#{@name}", self) rescue Net::HTTPServerException => e raise e unless e.response.code == "404" - chef_server_rest.post_rest("environments", self) + chef_server_rest.post("environments", self) end self end def create - chef_server_rest.post_rest("environments", self) + chef_server_rest.post("environments", self) self end def self.load_filtered_recipe_list(environment) - chef_server_rest.get_rest("environments/#{environment}/recipes") + chef_server_rest.get("environments/#{environment}/recipes") end def to_s diff --git a/lib/chef/http/simple.rb b/lib/chef/http/simple.rb index 8519554f2b..f59fcaa08b 100644 --- a/lib/chef/http/simple.rb +++ b/lib/chef/http/simple.rb @@ -1,3 +1,21 @@ +# +# Author:: Daniel DeLeo (<dan@chef.io>) +# Copyright:: Copyright (c) 2015 Chef Software, 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 'chef/http' require 'chef/http/authenticator' require 'chef/http/decompressor' diff --git a/lib/chef/http/simple_json.rb b/lib/chef/http/simple_json.rb new file mode 100644 index 0000000000..5dfdfbb680 --- /dev/null +++ b/lib/chef/http/simple_json.rb @@ -0,0 +1,43 @@ +# +# Author:: Thom May (<thom@chef.io>) +# Copyright:: Copyright (c) 2015 Chef Software, 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 'chef/http' +require 'chef/http/authenticator' +require 'chef/http/decompressor' +require 'chef/http/cookie_manager' +require 'chef/http/validate_content_length' + +class Chef + class HTTP + + class SimpleJSON < HTTP + + use JSONInput + use JSONOutput + use CookieManager + use Decompressor + use RemoteRequestID + + # ValidateContentLength should come after Decompressor + # because the order of middlewares is reversed when handling + # responses. + use ValidateContentLength + + end + end +end diff --git a/lib/chef/key.rb b/lib/chef/key.rb index be4be7f230..47bfe1fcee 100644 --- a/lib/chef/key.rb +++ b/lib/chef/key.rb @@ -19,6 +19,7 @@ require 'chef/json_compat' require 'chef/mixin/params_validate' require 'chef/exceptions' +require 'chef/server_api' class Chef # Class for interacting with a chef key object. Can be used to create new keys, @@ -31,7 +32,7 @@ class Chef # @attr [String] public_key the RSA string of this key # @attr [String] private_key the RSA string of the private key if returned via a POST or PUT # @attr [String] expiration_date the ISO formatted string YYYY-MM-DDTHH:MM:SSZ, i.e. 2020-12-24T21:00:00Z - # @attr [String] rest Chef::REST object, initialized and cached via chef_rest method + # @attr [String] rest Chef::ServerAPI object, initialized and cached via chef_rest method # @attr [string] api_base either "users" or "clients", initialized and cached via api_base method # # @attr_reader [String] actor_field_name must be either 'client' or 'user' @@ -60,9 +61,9 @@ class Chef def chef_rest @rest ||= if @actor_field_name == "user" - Chef::REST.new(Chef::Config[:chef_server_root]) + Chef::ServerAPI.new(Chef::Config[:chef_server_root]) else - Chef::REST.new(Chef::Config[:chef_server_url]) + Chef::ServerAPI.new(Chef::Config[:chef_server_url]) end end @@ -151,7 +152,7 @@ class Chef payload['public_key'] = @public_key unless @public_key.nil? payload['create_key'] = @create_key if @create_key payload['expiration_date'] = @expiration_date unless @expiration_date.nil? - result = chef_rest.post_rest("#{api_base}/#{@actor}/keys", payload) + result = chef_rest.post("#{api_base}/#{@actor}/keys", payload) # append the private key to the current key if the server returned one, # since the POST endpoint just returns uri and private_key if needed. new_key = self.to_hash @@ -174,7 +175,7 @@ class Chef # to @name. put_name = @name if put_name.nil? - new_key = chef_rest.put_rest("#{api_base}/#{@actor}/keys/#{put_name}", to_hash) + new_key = chef_rest.put("#{api_base}/#{@actor}/keys/#{put_name}", to_hash) # if the server returned a public_key, remove the create_key field, as we now have a key if new_key["public_key"] self.delete_create_key @@ -197,7 +198,7 @@ class Chef raise Chef::Exceptions::MissingKeyAttribute, "the name field must be populated when delete is called" end - chef_rest.delete_rest("#{api_base}/#{@actor}/keys/#{@name}") + chef_rest.delete("#{api_base}/#{@actor}/keys/#{@name}") end # Class methods @@ -226,22 +227,22 @@ class Chef end def self.list_by_user(actor, inflate=false) - keys = Chef::REST.new(Chef::Config[:chef_server_root]).get_rest("users/#{actor}/keys") + keys = Chef::ServerAPI.new(Chef::Config[:chef_server_root]).get("users/#{actor}/keys") self.list(keys, actor, :load_by_user, inflate) end def self.list_by_client(actor, inflate=false) - keys = Chef::REST.new(Chef::Config[:chef_server_url]).get_rest("clients/#{actor}/keys") + keys = Chef::ServerAPI.new(Chef::Config[:chef_server_url]).get("clients/#{actor}/keys") self.list(keys, actor, :load_by_client, inflate) end def self.load_by_user(actor, key_name) - response = Chef::REST.new(Chef::Config[:chef_server_root]).get_rest("users/#{actor}/keys/#{key_name}") + response = Chef::ServerAPI.new(Chef::Config[:chef_server_root]).get("users/#{actor}/keys/#{key_name}") Chef::Key.from_hash(response.merge({"user" => actor})) end def self.load_by_client(actor, key_name) - response = Chef::REST.new(Chef::Config[:chef_server_url]).get_rest("clients/#{actor}/keys/#{key_name}") + response = Chef::ServerAPI.new(Chef::Config[:chef_server_url]).get("clients/#{actor}/keys/#{key_name}") Chef::Key.from_hash(response.merge({"client" => actor})) end diff --git a/lib/chef/knife.rb b/lib/chef/knife.rb index 2820f58e85..34e437c82f 100644 --- a/lib/chef/knife.rb +++ b/lib/chef/knife.rb @@ -26,14 +26,16 @@ require 'chef/mixin/path_sanity' require 'chef/knife/core/subcommand_loader' require 'chef/knife/core/ui' require 'chef/local_mode' -require 'chef/rest' +require 'chef/server_api' require 'chef/http/authenticator' +require 'chef/http/http_request' +require 'chef/http' require 'pp' class Chef class Knife - Chef::REST::RESTRequest.user_agent = "Chef Knife#{Chef::REST::RESTRequest::UA_COMMON}" + Chef::HTTP::HTTPRequest.user_agent = "Chef Knife#{Chef::HTTP::HTTPRequest::UA_COMMON}" include Mixlib::CLI include Chef::Mixin::PathSanity @@ -551,15 +553,15 @@ class Chef def rest @rest ||= begin - require 'chef/rest' - Chef::REST.new(Chef::Config[:chef_server_url]) + require 'chef/server_api' + Chef::ServerAPI.new(Chef::Config[:chef_server_url]) end end def noauth_rest @rest ||= begin - require 'chef/rest' - Chef::REST.new(Chef::Config[:chef_server_url], false, false) + require 'chef/http/simple_json' + Chef::HTTP::SimpleJSON.new(Chef::Config[:chef_server_url]) end end diff --git a/lib/chef/knife/bootstrap/client_builder.rb b/lib/chef/knife/bootstrap/client_builder.rb index 6414ac5c72..f5a2ff2bb1 100644 --- a/lib/chef/knife/bootstrap/client_builder.rb +++ b/lib/chef/knife/bootstrap/client_builder.rb @@ -17,7 +17,7 @@ # require 'chef/node' -require 'chef/rest' +require 'chef/server_api' require 'chef/api_client/registration' require 'chef/api_client' require 'chef/knife/bootstrap' @@ -185,22 +185,22 @@ class Chef # @param relative_path [String] URI path relative to the chef organization # @return [Boolean] if the relative path exists or returns a 404 def resource_exists?(relative_path) - rest.get_rest(relative_path) + rest.get(relative_path) true rescue Net::HTTPServerException => e raise unless e.response.code == "404" false end - # @return [Chef::REST] REST client using the client credentials + # @return [Chef::ServerAPI] REST client using the client credentials def client_rest - @client_rest ||= Chef::REST.new(chef_server_url, node_name, client_path) + @client_rest ||= Chef::ServerAPI.new(chef_server_url, :client_name => node_name, :signing_key_filename => client_path) end - # @return [Chef::REST] REST client using the cli user's knife credentials + # @return [Chef::ServerAPI] REST client using the cli user's knife credentials # this uses the users's credentials def rest - @rest ||= Chef::REST.new(chef_server_url) + @rest ||= Chef::ServerAPI.new(chef_server_url) end end end diff --git a/lib/chef/knife/cookbook_bulk_delete.rb b/lib/chef/knife/cookbook_bulk_delete.rb index 65fa888486..ec0d06937f 100644 --- a/lib/chef/knife/cookbook_bulk_delete.rb +++ b/lib/chef/knife/cookbook_bulk_delete.rb @@ -60,9 +60,9 @@ class Chef cookbooks_names.each do |cookbook_name| - versions = rest.get_rest("cookbooks/#{cookbook_name}")[cookbook_name]["versions"].map {|v| v["version"]}.flatten + versions = rest.get("cookbooks/#{cookbook_name}")[cookbook_name]["versions"].map {|v| v["version"]}.flatten versions.each do |version| - object = rest.delete_rest("cookbooks/#{cookbook_name}/#{version}#{config[:purge] ? "?purge=true" : ""}") + object = rest.delete("cookbooks/#{cookbook_name}/#{version}#{config[:purge] ? "?purge=true" : ""}") ui.info("Deleted cookbook #{cookbook_name.ljust(25)} [#{version}]") end end diff --git a/lib/chef/knife/cookbook_delete.rb b/lib/chef/knife/cookbook_delete.rb index f436d270bd..5fe0e9664d 100644 --- a/lib/chef/knife/cookbook_delete.rb +++ b/lib/chef/knife/cookbook_delete.rb @@ -85,7 +85,7 @@ class Chef end def available_versions - @available_versions ||= rest.get_rest("cookbooks/#{@cookbook_name}").map do |name, url_and_version| + @available_versions ||= rest.get("cookbooks/#{@cookbook_name}").map do |name, url_and_version| url_and_version["versions"].map {|url_by_version| url_by_version["version"]} end.flatten rescue Net::HTTPServerException => e @@ -143,7 +143,7 @@ class Chef def delete_request(path) path += "?purge=true" if config[:purge] - rest.delete_rest(path) + rest.delete(path) end end diff --git a/lib/chef/knife/cookbook_download.rb b/lib/chef/knife/cookbook_download.rb index cb8eeb8edf..6ba5fc7d6c 100644 --- a/lib/chef/knife/cookbook_download.rb +++ b/lib/chef/knife/cookbook_download.rb @@ -69,7 +69,7 @@ class Chef ui.info("Downloading #{@cookbook_name} cookbook version #{@version}") - cookbook = rest.get_rest("cookbooks/#{@cookbook_name}/#{@version}") + cookbook = Chef::CookbookVersion.load(@cookbook_name, @version) manifest = cookbook.manifest basedir = File.join(config[:download_directory], "#{@cookbook_name}-#{cookbook.version}") @@ -90,8 +90,7 @@ class Chef dest = File.join(basedir, segment_file['path'].gsub('/', File::SEPARATOR)) Chef::Log.debug("Downloading #{segment_file['path']} to #{dest}") FileUtils.mkdir_p(File.dirname(dest)) - rest.sign_on_redirect = false - tempfile = rest.get_rest(segment_file['url'], true) + tempfile = rest.streaming_request(segment_file['url']) FileUtils.mv(tempfile.path, dest) end end diff --git a/lib/chef/knife/cookbook_list.rb b/lib/chef/knife/cookbook_list.rb index 75f18a154b..dd78e854da 100644 --- a/lib/chef/knife/cookbook_list.rb +++ b/lib/chef/knife/cookbook_list.rb @@ -39,7 +39,7 @@ class Chef env = config[:environment] num_versions = config[:all_versions] ? "num_versions=all" : "num_versions=1" api_endpoint = env ? "/environments/#{env}/cookbooks?#{num_versions}" : "/cookbooks?#{num_versions}" - cookbook_versions = rest.get_rest(api_endpoint) + cookbook_versions = rest.get(api_endpoint) ui.output(format_cookbook_list_for_display(cookbook_versions)) end end diff --git a/lib/chef/knife/cookbook_show.rb b/lib/chef/knife/cookbook_show.rb index 7c9cbebdb1..07f7684c27 100644 --- a/lib/chef/knife/cookbook_show.rb +++ b/lib/chef/knife/cookbook_show.rb @@ -67,9 +67,9 @@ class Chef cookbook_name, segment, filename = @name_args[0], @name_args[2], @name_args[3] cookbook_version = @name_args[1] == 'latest' ? '_latest' : @name_args[1] - cookbook = rest.get_rest("cookbooks/#{cookbook_name}/#{cookbook_version}") + cookbook = rest.get("cookbooks/#{cookbook_name}/#{cookbook_version}") manifest_entry = cookbook.preferred_manifest_record(node, segment, filename) - temp_file = rest.get_rest(manifest_entry[:url], true) + temp_file = rest.get(manifest_entry[:url], true) # the temp file is cleaned up elsewhere temp_file.open if temp_file.closed? @@ -77,16 +77,16 @@ class Chef when 3 # We are showing a specific part of the cookbook cookbook_version = @name_args[1] == 'latest' ? '_latest' : @name_args[1] - result = rest.get_rest("cookbooks/#{@name_args[0]}/#{cookbook_version}") + result = rest.get("cookbooks/#{@name_args[0]}/#{cookbook_version}") output(result.manifest[@name_args[2]]) when 2 # We are showing the whole cookbook data cookbook_version = @name_args[1] == 'latest' ? '_latest' : @name_args[1] - output(rest.get_rest("cookbooks/#{@name_args[0]}/#{cookbook_version}")) + output(rest.get("cookbooks/#{@name_args[0]}/#{cookbook_version}")) when 1 # We are showing the cookbook versions (all of them) cookbook_name = @name_args[0] env = config[:environment] api_endpoint = env ? "environments/#{env}/cookbooks/#{cookbook_name}" : "cookbooks/#{cookbook_name}" - output(format_cookbook_list_for_display(rest.get_rest(api_endpoint))) + output(format_cookbook_list_for_display(rest.get(api_endpoint))) when 0 show_usage ui.fatal("You must specify a cookbook name") diff --git a/lib/chef/knife/cookbook_site_download.rb b/lib/chef/knife/cookbook_site_download.rb index 3e586e6542..72608f3a30 100644 --- a/lib/chef/knife/cookbook_site_download.rb +++ b/lib/chef/knife/cookbook_site_download.rb @@ -63,7 +63,7 @@ class Chef def current_cookbook_data @current_cookbook_data ||= begin - noauth_rest.get_rest "#{cookbooks_api_url}/#{@name_args[0]}" + noauth_rest.get "#{cookbooks_api_url}/#{@name_args[0]}" end end @@ -79,14 +79,14 @@ class Chef specific_cookbook_version_url end - noauth_rest.get_rest uri + noauth_rest.get uri end end def download_cookbook ui.info "Downloading #{@name_args[0]} from Supermarket at version #{version} to #{download_location}" noauth_rest.sign_on_redirect = false - tf = noauth_rest.get_rest desired_cookbook_data["file"], true + tf = noauth_rest.get desired_cookbook_data["file"], true ::FileUtils.cp tf.path, download_location ui.info "Cookbook saved: #{download_location}" diff --git a/lib/chef/knife/cookbook_site_list.rb b/lib/chef/knife/cookbook_site_list.rb index 846123c867..b5354ed6e6 100644 --- a/lib/chef/knife/cookbook_site_list.rb +++ b/lib/chef/knife/cookbook_site_list.rb @@ -42,7 +42,7 @@ class Chef def get_cookbook_list(items=10, start=0, cookbook_collection={}) cookbooks_url = "https://supermarket.chef.io/api/v1/cookbooks?items=#{items}&start=#{start}" - cr = noauth_rest.get_rest(cookbooks_url) + cr = noauth_rest.get(cookbooks_url) cr["items"].each do |cookbook| cookbook_collection[cookbook["cookbook_name"]] = cookbook end diff --git a/lib/chef/knife/cookbook_site_search.rb b/lib/chef/knife/cookbook_site_search.rb index 0baaf90f1c..decbf6c2c3 100644 --- a/lib/chef/knife/cookbook_site_search.rb +++ b/lib/chef/knife/cookbook_site_search.rb @@ -30,7 +30,7 @@ class Chef def search_cookbook(query, items=10, start=0, cookbook_collection={}) cookbooks_url = "https://supermarket.chef.io/api/v1/search?q=#{query}&items=#{items}&start=#{start}" - cr = noauth_rest.get_rest(cookbooks_url) + cr = noauth_rest.get(cookbooks_url) cr["items"].each do |cookbook| cookbook_collection[cookbook["cookbook_name"]] = cookbook end diff --git a/lib/chef/knife/cookbook_site_share.rb b/lib/chef/knife/cookbook_site_share.rb index beb98b71b8..043ca84a58 100644 --- a/lib/chef/knife/cookbook_site_share.rb +++ b/lib/chef/knife/cookbook_site_share.rb @@ -108,7 +108,7 @@ class Chef def get_category(cookbook_name) begin - data = noauth_rest.get_rest("https://supermarket.chef.io/api/v1/cookbooks/#{@name_args[0]}") + data = noauth_rest.get("https://supermarket.chef.io/api/v1/cookbooks/#{@name_args[0]}") if !data["category"] && data["error_code"] ui.fatal("Received an error from Supermarket: #{data["error_code"]}. On the first time you upload it, you are required to specify the category you want to share this cookbook to.") exit(1) diff --git a/lib/chef/knife/cookbook_site_show.rb b/lib/chef/knife/cookbook_site_show.rb index 6b65b62570..521a60eb36 100644 --- a/lib/chef/knife/cookbook_site_show.rb +++ b/lib/chef/knife/cookbook_site_show.rb @@ -31,15 +31,15 @@ class Chef def get_cookbook_data case @name_args.length when 1 - noauth_rest.get_rest("https://supermarket.chef.io/api/v1/cookbooks/#{@name_args[0]}") + noauth_rest.get("https://supermarket.chef.io/api/v1/cookbooks/#{@name_args[0]}") when 2 - noauth_rest.get_rest("https://supermarket.chef.io/api/v1/cookbooks/#{@name_args[0]}/versions/#{name_args[1].gsub('.', '_')}") + noauth_rest.get("https://supermarket.chef.io/api/v1/cookbooks/#{@name_args[0]}/versions/#{name_args[1].gsub('.', '_')}") end end def get_cookbook_list(items=10, start=0, cookbook_collection={}) cookbooks_url = "https://supermarket.chef.io/api/v1/cookbooks?items=#{items}&start=#{start}" - cr = noauth_rest.get_rest(cookbooks_url) + cr = noauth_rest.get(cookbooks_url) cr["items"].each do |cookbook| cookbook_collection[cookbook["cookbook_name"]] = cookbook end diff --git a/lib/chef/knife/cookbook_site_unshare.rb b/lib/chef/knife/cookbook_site_unshare.rb index 77bb18322c..0c196c328a 100644 --- a/lib/chef/knife/cookbook_site_unshare.rb +++ b/lib/chef/knife/cookbook_site_unshare.rb @@ -41,7 +41,7 @@ class Chef confirm "Do you really want to unshare all versions of the cookbook #{@cookbook_name}" begin - rest.delete_rest "https://supermarket.chef.io/api/v1/cookbooks/#{@name_args[0]}" + rest.delete "https://supermarket.chef.io/api/v1/cookbooks/#{@name_args[0]}" rescue Net::HTTPServerException => e raise e unless e.message =~ /Forbidden/ ui.error "Forbidden: You must be the maintainer of #{@cookbook_name} to unshare it." diff --git a/lib/chef/knife/data_bag_create.rb b/lib/chef/knife/data_bag_create.rb index f8a7619a8a..1becad88b9 100644 --- a/lib/chef/knife/data_bag_create.rb +++ b/lib/chef/knife/data_bag_create.rb @@ -51,7 +51,7 @@ class Chef # create the data bag begin - rest.post_rest("data", { "name" => @data_bag_name }) + rest.post("data", { "name" => @data_bag_name }) ui.info("Created data_bag[#{@data_bag_name}]") rescue Net::HTTPServerException => e raise unless e.to_s =~ /^409/ @@ -68,7 +68,7 @@ class Chef output end) item.data_bag(@data_bag_name) - rest.post_rest("data/#{@data_bag_name}", item) + rest.post("data/#{@data_bag_name}", item) end end end diff --git a/lib/chef/knife/data_bag_delete.rb b/lib/chef/knife/data_bag_delete.rb index 575e9d604d..a3215d4c54 100644 --- a/lib/chef/knife/data_bag_delete.rb +++ b/lib/chef/knife/data_bag_delete.rb @@ -32,11 +32,11 @@ class Chef def run if @name_args.length == 2 delete_object(Chef::DataBagItem, @name_args[1], "data_bag_item") do - rest.delete_rest("data/#{@name_args[0]}/#{@name_args[1]}") + rest.delete("data/#{@name_args[0]}/#{@name_args[1]}") end elsif @name_args.length == 1 delete_object(Chef::DataBag, @name_args[0], "data_bag") do - rest.delete_rest("data/#{@name_args[0]}") + rest.delete("data/#{@name_args[0]}") end else show_usage diff --git a/lib/chef/knife/data_bag_edit.rb b/lib/chef/knife/data_bag_edit.rb index 6ef4b33f59..88c5669508 100644 --- a/lib/chef/knife/data_bag_edit.rb +++ b/lib/chef/knife/data_bag_edit.rb @@ -65,7 +65,7 @@ class Chef item_to_save = edited_item end - rest.put_rest("data/#{@name_args[0]}/#{@name_args[1]}", item_to_save) + rest.put("data/#{@name_args[0]}/#{@name_args[1]}", item_to_save) stdout.puts("Saved data_bag_item[#{@name_args[1]}]") ui.output(edited_item) if config[:print_after] end diff --git a/lib/chef/knife/environment_compare.rb b/lib/chef/knife/environment_compare.rb index 792ec444ea..54f011f323 100644 --- a/lib/chef/knife/environment_compare.rb +++ b/lib/chef/knife/environment_compare.rb @@ -57,7 +57,7 @@ class Chef end # Get all cookbooks so we can compare them all - cookbooks = rest.get_rest("/cookbooks?num_versions=1") if config[:all] + cookbooks = rest.get("/cookbooks?num_versions=1") if config[:all] # display matrix view of in the requested format. if config[:format] == 'summary' diff --git a/lib/chef/knife/index_rebuild.rb b/lib/chef/knife/index_rebuild.rb index 4b9fcdd159..95b0dcaffb 100644 --- a/lib/chef/knife/index_rebuild.rb +++ b/lib/chef/knife/index_rebuild.rb @@ -38,7 +38,7 @@ class Chef else deprecated_server_message nag - output rest.post_rest("/search/reindex", {}) + output rest.post("/search/reindex", {}) end end @@ -50,7 +50,7 @@ class Chef # for a node we know won't exist; the 404 response that comes # back will give us what we want dummy_node = "knife_index_rebuild_test_#{rand(1000000)}" - rest.get_rest("/nodes/#{dummy_node}") + rest.get("/nodes/#{dummy_node}") rescue Net::HTTPServerException => exception r = exception.response parse_api_info(r) diff --git a/lib/chef/knife/raw.rb b/lib/chef/knife/raw.rb index 601cfcef9b..de8742deb9 100644 --- a/lib/chef/knife/raw.rb +++ b/lib/chef/knife/raw.rb @@ -1,4 +1,5 @@ require 'chef/knife' +require 'chef/http' class Chef class Knife diff --git a/lib/chef/knife/recipe_list.rb b/lib/chef/knife/recipe_list.rb index ed7d2a9509..46ad619f1d 100644 --- a/lib/chef/knife/recipe_list.rb +++ b/lib/chef/knife/recipe_list.rb @@ -22,7 +22,7 @@ class Chef::Knife::RecipeList < Chef::Knife banner "knife recipe list [PATTERN]" def run - recipes = rest.get_rest('cookbooks/_recipes') + recipes = rest.get('cookbooks/_recipes') if pattern = @name_args.first recipes = recipes.grep(Regexp.new(pattern)) end diff --git a/lib/chef/node.rb b/lib/chef/node.rb index 0c13e5474a..759a45e878 100644 --- a/lib/chef/node.rb +++ b/lib/chef/node.rb @@ -27,7 +27,7 @@ require 'chef/mixin/deep_merge' require 'chef/dsl/include_attribute' require 'chef/dsl/platform_introspection' require 'chef/environment' -require 'chef/rest' +require 'chef/server_api' require 'chef/run_list' require 'chef/node/attribute' require 'chef/mash' @@ -99,10 +99,10 @@ class Chef # for saving node data we use validate_utf8: false which will not # raise an exception on bad utf8 data, but will replace the bad # characters and render valid JSON. - @chef_server_rest ||= Chef::REST.new( + @chef_server_rest ||= Chef::ServerAPI.new( Chef::Config[:chef_server_url], - Chef::Config[:node_name], - Chef::Config[:client_key], + client_name: Chef::Config[:node_name], + signing_key_filename: Chef::Config[:client_key], validate_utf8: false, ) end @@ -532,6 +532,11 @@ class Chef # Create a Chef::Node from JSON def self.json_create(o) + from_hash(o) + end + + def self.from_hash(o) + return o if o.kind_of? Chef::Node node = new node.name(o["name"]) node.chef_environment(o["chef_environment"]) @@ -561,7 +566,7 @@ class Chef Chef::Search::Query.new.search(:node, "chef_environment:#{environment}") {|n| response[n.name] = n unless n.nil?} response else - Chef::REST.new(Chef::Config[:chef_server_url]).get_rest("environments/#{environment}/nodes") + Chef::ServerAPI.new(Chef::Config[:chef_server_url]).get("environments/#{environment}/nodes") end end @@ -569,11 +574,12 @@ class Chef if inflate response = Hash.new Chef::Search::Query.new.search(:node) do |n| + n = Chef::Node.from_hash(n) response[n.name] = n unless n.nil? end response else - Chef::REST.new(Chef::Config[:chef_server_url]).get_rest("nodes") + Chef::ServerAPI.new(Chef::Config[:chef_server_url]).get("nodes") end end @@ -594,12 +600,12 @@ class Chef # Load a node by name def self.load(name) - Chef::REST.new(Chef::Config[:chef_server_url]).get_rest("nodes/#{name}") + from_hash(Chef::ServerAPI.new(Chef::Config[:chef_server_url]).get("nodes/#{name}")) end # Remove this node via the REST API def destroy - chef_server_rest.delete_rest("nodes/#{name}") + chef_server_rest.delete("nodes/#{name}") end # Save this node via the REST API @@ -610,11 +616,11 @@ class Chef if Chef::Config[:why_run] Chef::Log.warn("In why-run mode, so NOT performing node save.") else - chef_server_rest.put_rest("nodes/#{name}", data_for_save) + chef_server_rest.put("nodes/#{name}", data_for_save) end rescue Net::HTTPServerException => e if e.response.code == "404" - chef_server_rest.post_rest("nodes", data_for_save) + chef_server_rest.post("nodes", data_for_save) # Chef Server before 12.3 rejects node JSON with 'policy_name' or # 'policy_group' keys, but 'policy_name' will be detected first. # Backcompat can be removed in 13.0 @@ -629,14 +635,14 @@ class Chef # Create the node via the REST API def create - chef_server_rest.post_rest("nodes", data_for_save) + chef_server_rest.post("nodes", data_for_save) self rescue Net::HTTPServerException => e # Chef Server before 12.3 rejects node JSON with 'policy_name' or # 'policy_group' keys, but 'policy_name' will be detected first. # Backcompat can be removed in 13.0 if e.response.code == "400" && e.response.body.include?("Invalid key policy_name") - chef_server_rest.post_rest("nodes", data_for_save_without_policyfile_attrs) + chef_server_rest.post("nodes", data_for_save_without_policyfile_attrs) else raise end @@ -663,10 +669,10 @@ class Chef def save_without_policyfile_attrs trimmed_data = data_for_save_without_policyfile_attrs - chef_server_rest.put_rest("nodes/#{name}", trimmed_data) + chef_server_rest.put("nodes/#{name}", trimmed_data) rescue Net::HTTPServerException => e raise e unless e.response.code == "404" - chef_server_rest.post_rest("nodes", trimmed_data) + chef_server_rest.post("nodes", trimmed_data) end def data_for_save_without_policyfile_attrs diff --git a/lib/chef/org.rb b/lib/chef/org.rb index 41d74b6186..81eca6a991 100644 --- a/lib/chef/org.rb +++ b/lib/chef/org.rb @@ -18,7 +18,7 @@ require 'chef/json_compat' require 'chef/mixin/params_validate' -require 'chef/rest' +require 'chef/server_api' class Chef class Org @@ -35,7 +35,7 @@ class Chef end def chef_rest - @chef_rest ||= Chef::REST.new(Chef::Config[:chef_server_root]) + @chef_rest ||= Chef::ServerAPI.new(Chef::Config[:chef_server_root]) end def name(arg=nil) @@ -74,18 +74,18 @@ class Chef def create payload = {:name => self.name, :full_name => self.full_name} - new_org = chef_rest.post_rest("organizations", payload) + new_org = chef_rest.post("organizations", payload) Chef::Org.from_hash(self.to_hash.merge(new_org)) end def update payload = {:name => self.name, :full_name => self.full_name} - new_org = chef_rest.put_rest("organizations/#{name}", payload) + new_org = chef_rest.put("organizations/#{name}", payload) Chef::Org.from_hash(self.to_hash.merge(new_org)) end def destroy - chef_rest.delete_rest("organizations/#{@name}") + chef_rest.delete("organizations/#{@name}") end def save @@ -102,13 +102,13 @@ class Chef def associate_user(username) request_body = {:user => username} - response = chef_rest.post_rest "organizations/#{@name}/association_requests", request_body + response = chef_rest.post "organizations/#{@name}/association_requests", request_body association_id = response["uri"].split("/").last - chef_rest.put_rest "users/#{username}/association_requests/#{association_id}", { :response => 'accept' } + chef_rest.put "users/#{username}/association_requests/#{association_id}", { :response => 'accept' } end def dissociate_user(username) - chef_rest.delete_rest "organizations/#{name}/users/#{username}" + chef_rest.delete "organizations/#{name}/users/#{username}" end # Class methods @@ -129,12 +129,12 @@ class Chef end def self.load(org_name) - response = Chef::REST.new(Chef::Config[:chef_server_root]).get_rest("organizations/#{org_name}") + response = Chef::ServerAPI.new(Chef::Config[:chef_server_root]).get("organizations/#{org_name}") Chef::Org.from_hash(response) end def self.list(inflate=false) - orgs = Chef::REST.new(Chef::Config[:chef_server_root]).get_rest('organizations') + orgs = Chef::ServerAPI.new(Chef::Config[:chef_server_root]).get('organizations') if inflate orgs.inject({}) do |org_map, (name, _url)| org_map[name] = Chef::Org.load(name) diff --git a/lib/chef/policy_builder/dynamic.rb b/lib/chef/policy_builder/dynamic.rb index c9842ba532..d4b3df748e 100644 --- a/lib/chef/policy_builder/dynamic.rb +++ b/lib/chef/policy_builder/dynamic.rb @@ -19,7 +19,6 @@ require 'forwardable' require 'chef/log' -require 'chef/rest' require 'chef/run_context' require 'chef/config' require 'chef/node' diff --git a/lib/chef/policy_builder/expand_node_object.rb b/lib/chef/policy_builder/expand_node_object.rb index 848dd00684..870351b6fb 100644 --- a/lib/chef/policy_builder/expand_node_object.rb +++ b/lib/chef/policy_builder/expand_node_object.rb @@ -20,7 +20,7 @@ # require 'chef/log' -require 'chef/rest' +require 'chef/server_api' require 'chef/run_context' require 'chef/config' require 'chef/node' @@ -198,7 +198,12 @@ class Chef begin events.cookbook_resolution_start(@expanded_run_list_with_versions) cookbook_hash = api_service.post("environments/#{node.chef_environment}/cookbook_versions", - {:run_list => @expanded_run_list_with_versions}) + {:run_list => @expanded_run_list_with_versions}) + + cookbook_hash = cookbook_hash.inject({}) do |memo, (key, value)| + memo[key] = Chef::CookbookVersion.from_hash(value) + memo + end rescue Exception => e # TODO: wrap/munge exception to provide helpful error output events.cookbook_resolution_failed(@expanded_run_list_with_versions, e) @@ -257,7 +262,7 @@ class Chef end def api_service - @api_service ||= Chef::REST.new(config[:chef_server_url]) + @api_service ||= Chef::ServerAPI.new(config[:chef_server_url]) end def config diff --git a/lib/chef/policy_builder/policyfile.rb b/lib/chef/policy_builder/policyfile.rb index 3633110d6c..249bebbd98 100644 --- a/lib/chef/policy_builder/policyfile.rb +++ b/lib/chef/policy_builder/policyfile.rb @@ -20,10 +20,10 @@ # require 'chef/log' -require 'chef/rest' require 'chef/run_context' require 'chef/config' require 'chef/node' +require 'chef/server_api' class Chef module PolicyBuilder @@ -455,7 +455,7 @@ class Chef # @api private def http_api - @api_service ||= Chef::REST.new(config[:chef_server_url]) + @api_service ||= Chef::ServerAPI.new(config[:chef_server_url]) end # @api private diff --git a/lib/chef/resource_reporter.rb b/lib/chef/resource_reporter.rb index 1175b0afb3..e2c71f7bd5 100644 --- a/lib/chef/resource_reporter.rb +++ b/lib/chef/resource_reporter.rb @@ -121,7 +121,7 @@ class Chef if reporting_enabled? begin resource_history_url = "reports/nodes/#{node_name}/runs" - server_response = @rest_client.post_rest(resource_history_url, {:action => :start, :run_id => run_id, + server_response = @rest_client.post(resource_history_url, {:action => :start, :run_id => run_id, :start_time => start_time.to_s}, headers) rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e handle_error_starting_run(e, resource_history_url) @@ -230,10 +230,9 @@ class Chef Chef::Log.debug run_data.inspect compressed_data = encode_gzip(Chef::JSONCompat.to_json(run_data)) Chef::Log.debug("Sending compressed run data...") - # Since we're posting compressed data we can not directly call post_rest which expects JSON - reporting_url = @rest_client.create_url(resource_history_url) + # Since we're posting compressed data we can not directly call post which expects JSON begin - @rest_client.raw_http_request(:POST, reporting_url, headers({'Content-Encoding' => 'gzip'}), compressed_data) + @rest_client.raw_request(:POST, resource_history_url, headers({'Content-Encoding' => 'gzip'}), compressed_data) rescue StandardError => e if e.respond_to? :response Chef::FileCache.store("failed-reporting-data.json", Chef::JSONCompat.to_json_pretty(run_data), 0640) diff --git a/lib/chef/role.rb b/lib/chef/role.rb index c085d1d714..6984a8a245 100644 --- a/lib/chef/role.rb +++ b/lib/chef/role.rb @@ -24,6 +24,7 @@ require 'chef/mixin/from_file' require 'chef/run_list' require 'chef/mash' require 'chef/json_compat' +require 'chef/server_api' require 'chef/search/query' class Chef @@ -45,11 +46,11 @@ class Chef end def chef_server_rest - @chef_server_rest ||= Chef::REST.new(Chef::Config[:chef_server_url]) + @chef_server_rest ||= Chef::ServerAPI.new(Chef::Config[:chef_server_url]) end def self.chef_server_rest - Chef::REST.new(Chef::Config[:chef_server_url]) + Chef::ServerAPI.new(Chef::Config[:chef_server_url]) end def name(arg=nil) @@ -170,6 +171,10 @@ class Chef # Create a Chef::Role from JSON def self.json_create(o) + from_hash(o) + end + + def self.from_hash(o) role = new role.name(o["name"]) role.description(o["description"]) @@ -199,42 +204,42 @@ class Chef end response else - chef_server_rest.get_rest("roles") + chef_server_rest.get("roles") end end # Load a role by name from the API def self.load(name) - chef_server_rest.get_rest("roles/#{name}") + from_hash(chef_server_rest.get("roles/#{name}")) end def environment(env_name) - chef_server_rest.get_rest("roles/#{@name}/environments/#{env_name}") + chef_server_rest.get("roles/#{@name}/environments/#{env_name}") end def environments - chef_server_rest.get_rest("roles/#{@name}/environments") + chef_server_rest.get("roles/#{@name}/environments") end # Remove this role via the REST API def destroy - chef_server_rest.delete_rest("roles/#{@name}") + chef_server_rest.delete("roles/#{@name}") end # Save this role via the REST API def save begin - chef_server_rest.put_rest("roles/#{@name}", self) + chef_server_rest.put("roles/#{@name}", self) rescue Net::HTTPServerException => e raise e unless e.response.code == "404" - chef_server_rest.post_rest("roles", self) + chef_server_rest.post("roles", self) end self end # Create the role via the REST API def create - chef_server_rest.post_rest("roles", self) + chef_server_rest.post("roles", self) self end @@ -258,7 +263,8 @@ class Chef if js_path && File.exists?(js_path) # from_json returns object.class => json_class in the JSON. - return Chef::JSONCompat.from_json(IO.read(js_path)) + hsh = Chef::JSONCompat.parse(IO.read(js_path)) + return from_hash(hsh) elsif rb_path && File.exists?(rb_path) role = Chef::Role.new role.name(name) diff --git a/lib/chef/run_list/run_list_expansion.rb b/lib/chef/run_list/run_list_expansion.rb index 64e4326fb8..2f2d170446 100644 --- a/lib/chef/run_list/run_list_expansion.rb +++ b/lib/chef/run_list/run_list_expansion.rb @@ -21,7 +21,7 @@ require 'chef/mash' require 'chef/mixin/deep_merge' require 'chef/role' -require 'chef/rest' +require 'chef/server_api' require 'chef/json_compat' class Chef @@ -45,7 +45,7 @@ class Chef attr_reader :missing_roles_with_including_role # The data source passed to the constructor. Not used in this class. - # In subclasses, this is a couchdb or Chef::REST object pre-configured + # In subclasses, this is a Chef::ServerAPI object pre-configured # to fetch roles from their correct location. attr_reader :source @@ -214,11 +214,11 @@ class Chef class RunListExpansionFromAPI < RunListExpansion def rest - @rest ||= (source || Chef::REST.new(Chef::Config[:chef_server_url])) + @rest ||= (source || Chef::ServerAPI.new(Chef::Config[:chef_server_url])) end def fetch_role(name, included_by) - rest.get_rest("roles/#{name}") + Chef::Role.from_hash(rest.get("roles/#{name}")) rescue Net::HTTPServerException => e if e.message == '404 "Not Found"' role_not_found(name, included_by) diff --git a/lib/chef/search/query.rb b/lib/chef/search/query.rb index 658af8779c..c5c6bc6ce0 100644 --- a/lib/chef/search/query.rb +++ b/lib/chef/search/query.rb @@ -18,7 +18,7 @@ require 'chef/config' require 'chef/exceptions' -require 'chef/rest' +require 'chef/server_api' require 'uri' @@ -35,7 +35,7 @@ class Chef end def rest - @rest ||= Chef::REST.new(@url || @config[:chef_server_url]) + @rest ||= Chef::ServerAPI.new(@url || @config[:chef_server_url]) end # Backwards compatability for cookbooks. @@ -150,12 +150,26 @@ WARNDEP query_string = create_query_string(type, query, rows, start, sort) if filter_result - response = rest.post_rest(query_string, filter_result) + response = rest.post(query_string, filter_result) # response returns rows in the format of # { "url" => url_to_node, "data" => filter_result_hash } response['rows'].map! { |row| row['data'] } else - response = rest.get_rest(query_string) + response = rest.get(query_string) + response['rows'].map! do |row| + case type.to_s + when 'node' + Chef::Node.from_hash(row) + when 'role' + Chef::Role.from_hash(row) + when 'environment' + Chef::Environment.from_hash(row) + when 'client' + Chef::ApiClient.from_hash(row) + else + Chef::DataBagItem.from_hash(row) + end + end end response diff --git a/lib/chef/server_api.rb b/lib/chef/server_api.rb index 764296f8c8..6c864d53fb 100644 --- a/lib/chef/server_api.rb +++ b/lib/chef/server_api.rb @@ -23,6 +23,7 @@ require 'chef/http/decompressor' require 'chef/http/json_input' require 'chef/http/json_output' require 'chef/http/remote_request_id' +require 'chef/http/validate_content_length' class Chef class ServerAPI < Chef::HTTP @@ -31,6 +32,7 @@ class Chef options[:client_name] ||= Chef::Config[:node_name] options[:signing_key_filename] ||= Chef::Config[:client_key] options[:signing_key_filename] = nil if chef_zero_uri?(url) + options[:inflate_json_class] = false super(url, options) end @@ -40,6 +42,30 @@ class Chef use Chef::HTTP::Decompressor use Chef::HTTP::Authenticator use Chef::HTTP::RemoteRequestID + + # ValidateContentLength should come after Decompressor + # because the order of middlewares is reversed when handling + # responses. + use Chef::HTTP::ValidateContentLength + + # Makes an HTTP request to +path+ with the given +method+, +headers+, and + # +data+ (if applicable). Does not apply any middleware, besides that + # needed for Authentication. + def raw_request(method, path, headers={}, data=false) + url = create_url(path) + method, url, headers, data = Chef::HTTP::Authenticator.new(options).handle_request(method, url, headers, data) + method, url, headers, data = Chef::HTTP::RemoteRequestID.new(options).handle_request(method, url, headers, data) + response, rest_request, return_value = send_http_request(method, url, headers, data) + response.error! unless success_response?(response) + return_value + rescue Exception => exception + log_failed_request(response, return_value) unless response.nil? + + if exception.respond_to?(:chef_rest_request=) + exception.chef_rest_request = rest_request + end + raise + end end end diff --git a/lib/chef/shell/ext.rb b/lib/chef/shell/ext.rb index d516524765..17525d777c 100644 --- a/lib/chef/shell/ext.rb +++ b/lib/chef/shell/ext.rb @@ -23,7 +23,7 @@ require 'chef/dsl/platform_introspection' require 'chef/version' require 'chef/shell/shell_session' require 'chef/shell/model_wrapper' -require 'chef/shell/shell_rest' +require 'chef/server_api' require 'chef/json_compat' module Shell @@ -536,7 +536,7 @@ E desc "A REST Client configured to authenticate with the API" def api - @rest = Shell::ShellREST.new(Chef::Config[:chef_server_url]) + @rest = Chef::ServerAPI.new(Chef::Config[:chef_server_url]) end end diff --git a/lib/chef/shell/shell_rest.rb b/lib/chef/shell/shell_rest.rb deleted file mode 100644 index a485a0a1a8..0000000000 --- a/lib/chef/shell/shell_rest.rb +++ /dev/null @@ -1,28 +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. -# - -module Shell - class ShellREST < Chef::REST - - alias :get :get_rest - alias :put :put_rest - alias :post :post_rest - alias :delete :delete_rest - - end -end diff --git a/lib/chef/shell/shell_session.rb b/lib/chef/shell/shell_session.rb index 73e6c34ebb..7b3939da69 100644 --- a/lib/chef/shell/shell_session.rb +++ b/lib/chef/shell/shell_session.rb @@ -201,7 +201,7 @@ module Shell def rebuild_context @run_status = Chef::RunStatus.new(@node, @events) - Chef::Cookbook::FileVendor.fetch_from_remote(Chef::REST.new(Chef::Config[:chef_server_url])) + Chef::Cookbook::FileVendor.fetch_from_remote(Chef::ServerAPI.new(Chef::Config[:chef_server_url])) cookbook_hash = @client.sync_cookbooks cookbook_collection = Chef::CookbookCollection.new(cookbook_hash) @run_context = Chef::RunContext.new(node, cookbook_collection, @events) @@ -253,7 +253,8 @@ module Shell end def register - @rest = Chef::REST.new(Chef::Config[:chef_server_url], Chef::Config[:node_name], Chef::Config[:client_key]) + @rest = Chef::ServerAPI.new(Chef::Config[:chef_server_url], :client_name => Chef::Config[:node_name], + :signing_key_filename => Chef::Config[:client_key]) end end diff --git a/lib/chef/user_v1.rb b/lib/chef/user_v1.rb index 31cb0576a2..077fca50b9 100644 --- a/lib/chef/user_v1.rb +++ b/lib/chef/user_v1.rb @@ -140,7 +140,7 @@ class Chef def destroy # will default to the current API version (Chef::Authenticator::DEFAULT_SERVER_API_VERSION) - Chef::REST.new(Chef::Config[:chef_server_url]).delete("users/#{@username}") + Chef::ServerAPI.new(Chef::Config[:chef_server_url]).delete("users/#{@username}") end def create @@ -287,7 +287,7 @@ class Chef end def self.list(inflate=false) - response = Chef::REST.new(Chef::Config[:chef_server_url]).get('users') + response = Chef::ServerAPI.new(Chef::Config[:chef_server_url]).get('users') users = if response.is_a?(Array) # EC 11 / CS 12 V0, V1 # GET /organizations/<org>/users @@ -312,7 +312,7 @@ class Chef def self.load(username) # will default to the current API version (Chef::Authenticator::DEFAULT_SERVER_API_VERSION) - response = Chef::REST.new(Chef::Config[:chef_server_url]).get("users/#{username}") + response = Chef::ServerAPI.new(Chef::Config[:chef_server_url]).get("users/#{username}") Chef::UserV1.from_hash(response) end diff --git a/spec/functional/resource/registry_spec.rb b/spec/functional/resource/registry_spec.rb index f112ad9b00..c0682fefc8 100644 --- a/spec/functional/resource/registry_spec.rb +++ b/spec/functional/resource/registry_spec.rb @@ -111,7 +111,7 @@ describe Chef::Resource::RegistryKey, :windows_only, :broken => true do before do @node.name("windowsbox") - @rest_client = double("Chef::REST (mock)") + @rest_client = double("Chef::ServerAPI (mock)") allow(@rest_client).to receive(:create_url).and_return("reports/nodes/windowsbox/runs/#{@run_id}"); allow(@rest_client).to receive(:raw_http_request).and_return({"result"=>"ok"}); allow(@rest_client).to receive(:post_rest).and_return({"uri"=>"https://example.com/reports/nodes/windowsbox/runs/#{@run_id}"}); diff --git a/spec/functional/tiny_server_spec.rb b/spec/functional/tiny_server_spec.rb index 87be948a0d..d21248062a 100644 --- a/spec/functional/tiny_server_spec.rb +++ b/spec/functional/tiny_server_spec.rb @@ -70,8 +70,8 @@ describe TinyServer::Manager do TinyServer::API.instance.get("/index", 200, "[\"hello\"]") - rest = Chef::REST.new('http://localhost:9000', false, false) - expect(rest.get_rest("index")).to eq(["hello"]) + rest = Chef::HTTP.new('http://localhost:9000') + expect(rest.get("index")).to eq("[\"hello\"]") @server.stop end diff --git a/spec/support/shared/context/client.rb b/spec/support/shared/context/client.rb index eb537e9889..cb387a9478 100644 --- a/spec/support/shared/context/client.rb +++ b/spec/support/shared/context/client.rb @@ -68,9 +68,9 @@ shared_context "a client run" do let(:api_client_exists?) { false } let(:enable_fork) { false } - let(:http_cookbook_sync) { double("Chef::REST (cookbook sync)") } - let(:http_node_load) { double("Chef::REST (node)") } - let(:http_node_save) { double("Chef::REST (node save)") } + let(:http_cookbook_sync) { double("Chef::ServerAPI (cookbook sync)") } + let(:http_node_load) { double("Chef::ServerAPI (node)") } + let(:http_node_save) { double("Chef::ServerAPI (node save)") } let(:runner) { instance_double("Chef::Runner") } let(:audit_runner) { instance_double("Chef::Audit::Runner", :failed? => false) } @@ -93,10 +93,11 @@ shared_context "a client run" do def stub_for_node_load # Client.register will then turn around create another - # Chef::REST object, this time with the client key it got from the + # Chef::ServerAPI object, this time with the client key it got from the # previous step. - expect(Chef::REST).to receive(:new). - with(Chef::Config[:chef_server_url], fqdn, Chef::Config[:client_key]). + expect(Chef::ServerAPI).to receive(:new). + with(Chef::Config[:chef_server_url], client_name: fqdn, + signing_key_filename: Chef::Config[:client_key]). exactly(:once). and_return(http_node_load) @@ -115,7 +116,7 @@ shared_context "a client run" do # ---Client#sync_cookbooks -- downloads the list of cookbooks to sync # expect_any_instance_of(Chef::CookbookSynchronizer).to receive(:sync_cookbooks) - expect(Chef::REST).to receive(:new).with(Chef::Config[:chef_server_url]).and_return(http_cookbook_sync) + expect(Chef::ServerAPI).to receive(:new).with(Chef::Config[:chef_server_url]).and_return(http_cookbook_sync) expect(http_cookbook_sync).to receive(:post). with("environments/_default/cookbook_versions", {:run_list => []}). and_return({}) @@ -175,8 +176,9 @@ shared_context "converge completed" do allow(node).to receive(:data_for_save).and_return(node.for_json) # --Client#save_updated_node - expect(Chef::REST).to receive(:new).with(Chef::Config[:chef_server_url], fqdn, Chef::Config[:client_key], validate_utf8: false).and_return(http_node_save) - expect(http_node_save).to receive(:put_rest).with("nodes/#{fqdn}", node.for_json).and_return(true) + expect(Chef::ServerAPI).to receive(:new).with(Chef::Config[:chef_server_url], client_name: fqdn, + signing_key_filename: Chef::Config[:client_key], validate_utf8: false).and_return(http_node_save) + expect(http_node_save).to receive(:put).with("nodes/#{fqdn}", node.for_json).and_return(true) end end diff --git a/spec/unit/api_client_spec.rb b/spec/unit/api_client_spec.rb index a0e399b470..810c806af5 100644 --- a/spec/unit/api_client_spec.rb +++ b/spec/unit/api_client_spec.rb @@ -275,7 +275,7 @@ describe Chef::ApiClient do describe "when requesting a new key" do before do - @http_client = double("Chef::REST mock") + @http_client = double("Chef::ServerAPI mock") allow(Chef::ServerAPI).to receive(:new).and_return(@http_client) end diff --git a/spec/unit/audit/audit_reporter_spec.rb b/spec/unit/audit/audit_reporter_spec.rb index 46c2a96b4c..1a8cee1cd5 100644 --- a/spec/unit/audit/audit_reporter_spec.rb +++ b/spec/unit/audit/audit_reporter_spec.rb @@ -57,7 +57,6 @@ describe Chef::Audit::AuditReporter do before do allow(reporter).to receive(:auditing_enabled?).and_return(true) allow(reporter).to receive(:run_status).and_return(run_status) - allow(rest).to receive(:create_url).and_return(true) allow(rest).to receive(:post).and_return(true) allow(reporter).to receive(:audit_data).and_return(audit_data) allow(reporter).to receive(:run_status).and_return(run_status) @@ -75,16 +74,12 @@ describe Chef::Audit::AuditReporter do end it "posts audit data to server endpoint" do - endpoint = "api.opscode.us/orgname/controls" headers = { 'X-Ops-Audit-Report-Protocol-Version' => Chef::Audit::AuditReporter::PROTOCOL_VERSION } - expect(rest).to receive(:create_url). - with("controls"). - and_return(endpoint) expect(rest).to receive(:post). - with(endpoint, run_data, headers) + with("controls", run_data, headers) reporter.run_completed(node) end @@ -255,7 +250,6 @@ EOM context "when no prior exception is stored" do it "reports no error" do - expect(rest).to receive(:create_url) expect(rest).to receive(:post) reporter.run_failed(run_error) expect(run_data).to_not have_key(:error) @@ -268,7 +262,6 @@ EOM end it "reports the prior error" do - expect(rest).to receive(:create_url) expect(rest).to receive(:post) reporter.run_failed(run_error) expect(run_data).to have_key(:error) diff --git a/spec/unit/client_spec.rb b/spec/unit/client_spec.rb index c270ddc092..ca7440061e 100644 --- a/spec/unit/client_spec.rb +++ b/spec/unit/client_spec.rb @@ -23,7 +23,7 @@ require 'spec/support/shared/context/client' require 'spec/support/shared/examples/client' require 'chef/run_context' -require 'chef/rest' +require 'chef/server_api' require 'rbconfig' class FooError < RuntimeError @@ -169,7 +169,7 @@ describe Chef::Client do # ---Client#sync_cookbooks -- downloads the list of cookbooks to sync # expect_any_instance_of(Chef::CookbookSynchronizer).to receive(:sync_cookbooks) - expect(Chef::REST).to receive(:new).with(Chef::Config[:chef_server_url]).and_return(http_cookbook_sync) + expect(Chef::ServerAPI).to receive(:new).with(Chef::Config[:chef_server_url]).and_return(http_cookbook_sync) expect(http_cookbook_sync).to receive(:post). with("environments/_default/cookbook_versions", {:run_list => ["override_recipe"]}). and_return({}) @@ -203,7 +203,7 @@ describe Chef::Client do # ---Client#sync_cookbooks -- downloads the list of cookbooks to sync # expect_any_instance_of(Chef::CookbookSynchronizer).to receive(:sync_cookbooks) - expect(Chef::REST).to receive(:new).with(Chef::Config[:chef_server_url]).and_return(http_cookbook_sync) + expect(Chef::ServerAPI).to receive(:new).with(Chef::Config[:chef_server_url]).and_return(http_cookbook_sync) expect(http_cookbook_sync).to receive(:post). with("environments/_default/cookbook_versions", {:run_list => ["new_run_list_recipe"]}). and_return({}) @@ -336,9 +336,9 @@ describe Chef::Client do # build_node will call Node#expand! with server, which will # eventually hit the server to expand the included role. - mock_chef_rest = double("Chef::REST") - expect(mock_chef_rest).to receive(:get_rest).with("roles/role_containing_cookbook1").and_return(role_containing_cookbook1) - expect(Chef::REST).to receive(:new).and_return(mock_chef_rest) + mock_chef_rest = double("Chef::ServerAPI") + expect(mock_chef_rest).to receive(:get).with("roles/role_containing_cookbook1").and_return(role_containing_cookbook1.to_hash) + expect(Chef::ServerAPI).to receive(:new).and_return(mock_chef_rest) # check pre-conditions. expect(node[:roles]).to be_nil @@ -372,9 +372,9 @@ describe Chef::Client do test_env = Chef::Environment.new test_env.name("A") - mock_chef_rest = double("Chef::REST") - expect(mock_chef_rest).to receive(:get_rest).with("environments/A").and_return(test_env) - expect(Chef::REST).to receive(:new).and_return(mock_chef_rest) + mock_chef_rest = double("Chef::ServerAPI") + expect(mock_chef_rest).to receive(:get).with("environments/A").and_return(test_env) + expect(Chef::ServerAPI).to receive(:new).and_return(mock_chef_rest) allow(client.policy_builder).to receive(:node).and_return(node) client.policy_builder.select_implementation(node) allow(client.policy_builder.implementation).to receive(:node).and_return(node) diff --git a/spec/unit/cookbook/file_vendor_spec.rb b/spec/unit/cookbook/file_vendor_spec.rb index 145541a63f..8bf2d3c2a3 100644 --- a/spec/unit/cookbook/file_vendor_spec.rb +++ b/spec/unit/cookbook/file_vendor_spec.rb @@ -23,7 +23,7 @@ describe Chef::Cookbook::FileVendor do context "when configured to fetch files over http" do - let(:http) { double("Chef::REST") } + let(:http) { double("Chef::ServerAPI") } before do file_vendor_class.fetch_from_remote(http) diff --git a/spec/unit/cookbook/synchronizer_spec.rb b/spec/unit/cookbook/synchronizer_spec.rb index 2b040f3c95..30ddaad1d7 100644 --- a/spec/unit/cookbook/synchronizer_spec.rb +++ b/spec/unit/cookbook/synchronizer_spec.rb @@ -38,7 +38,6 @@ describe Chef::CookbookCacheCleaner do unused_template_files.each do |cbf| expect(file_cache).to receive(:delete).with(cbf) end - cookbook_hash = {"valid1"=> {}, "valid2" => {}} allow(cleaner).to receive(:cache).and_return(file_cache) cleaner.cleanup_file_cache end @@ -224,8 +223,8 @@ describe Chef::CookbookSynchronizer do and_return(false) # Fetch and copy default.rb recipe - expect(server_api).to receive(:get_rest). - with('http://chef.example.com/abc123', true). + expect(server_api).to receive(:streaming_request). + with('http://chef.example.com/abc123'). and_return(cookbook_a_default_recipe_tempfile) expect(file_cache).to receive(:move_to). with("/tmp/cookbook_a_recipes_default_rb", "cookbooks/cookbook_a/recipes/default.rb") @@ -234,8 +233,8 @@ describe Chef::CookbookSynchronizer do and_return("/file-cache/cookbooks/cookbook_a/recipes/default.rb") # Fetch and copy default.rb attribute file - expect(server_api).to receive(:get_rest). - with('http://chef.example.com/abc456', true). + expect(server_api).to receive(:streaming_request). + with('http://chef.example.com/abc456'). and_return(cookbook_a_default_attribute_tempfile) expect(file_cache).to receive(:move_to). with("/tmp/cookbook_a_attributes_default_rb", "cookbooks/cookbook_a/attributes/default.rb") @@ -252,8 +251,8 @@ describe Chef::CookbookSynchronizer do with("cookbooks/cookbook_a/templates/default/apache2.conf.erb"). and_return(false) - expect(server_api).to receive(:get_rest). - with('http://chef.example.com/megaman.conf', true). + expect(server_api).to receive(:streaming_request). + with('http://chef.example.com/megaman.conf'). and_return(cookbook_a_file_default_tempfile) expect(file_cache).to receive(:move_to). with("/tmp/cookbook_a_file_default_tempfile", "cookbooks/cookbook_a/files/default/megaman.conf") @@ -261,8 +260,8 @@ describe Chef::CookbookSynchronizer do with("cookbooks/cookbook_a/files/default/megaman.conf", false). and_return("/file-cache/cookbooks/cookbook_a/default/megaman.conf") - expect(server_api).to receive(:get_rest). - with('http://chef.example.com/ffffff', true). + expect(server_api).to receive(:streaming_request). + with('http://chef.example.com/ffffff'). and_return(cookbook_a_template_default_tempfile) expect(file_cache).to receive(:move_to). with("/tmp/cookbook_a_template_default_tempfile", "cookbooks/cookbook_a/templates/default/apache2.conf.erb") @@ -281,8 +280,8 @@ describe Chef::CookbookSynchronizer do and_return(true) # Fetch and copy default.rb recipe - expect(server_api).to receive(:get_rest). - with('http://chef.example.com/abc123', true). + expect(server_api).to receive(:streaming_request). + with('http://chef.example.com/abc123'). and_return(cookbook_a_default_recipe_tempfile) expect(file_cache).to receive(:move_to). with("/tmp/cookbook_a_recipes_default_rb", "cookbooks/cookbook_a/recipes/default.rb") @@ -297,8 +296,8 @@ describe Chef::CookbookSynchronizer do and_return("fff000") # Fetch and copy default.rb attribute file - expect(server_api).to receive(:get_rest). - with('http://chef.example.com/abc456', true). + expect(server_api).to receive(:streaming_request). + with('http://chef.example.com/abc456'). and_return(cookbook_a_default_attribute_tempfile) expect(file_cache).to receive(:move_to). with("/tmp/cookbook_a_attributes_default_rb", "cookbooks/cookbook_a/attributes/default.rb") @@ -323,8 +322,8 @@ describe Chef::CookbookSynchronizer do and_return(true) # Fetch and copy megaman.conf - expect(server_api).to receive(:get_rest). - with('http://chef.example.com/megaman.conf', true). + expect(server_api).to receive(:streaming_request). + with('http://chef.example.com/megaman.conf'). and_return(cookbook_a_file_default_tempfile) expect(file_cache).to receive(:move_to). with("/tmp/cookbook_a_file_default_tempfile", "cookbooks/cookbook_a/files/default/megaman.conf") @@ -334,8 +333,8 @@ describe Chef::CookbookSynchronizer do and_return("/file-cache/cookbooks/cookbook_a/default/megaman.conf") # Fetch and copy apache2.conf template - expect(server_api).to receive(:get_rest). - with('http://chef.example.com/ffffff', true). + expect(server_api).to receive(:streaming_request). + with('http://chef.example.com/ffffff'). and_return(cookbook_a_template_default_tempfile) expect(file_cache).to receive(:move_to). with("/tmp/cookbook_a_template_default_tempfile", "cookbooks/cookbook_a/templates/default/apache2.conf.erb") @@ -416,7 +415,7 @@ describe Chef::CookbookSynchronizer do end describe "when syncing cookbooks with the server" do - let(:server_api) { double("Chef::REST (mock)") } + let(:server_api) { double("Chef::ServerAPI (mock)") } let(:file_cache) { double("Chef::FileCache (mock)") } @@ -442,8 +441,8 @@ describe Chef::CookbookSynchronizer do it "does not fetch templates or cookbook files" do # Implicitly tested in previous test; this test is just for behavior specification. - expect(server_api).not_to receive(:get_rest). - with('http://chef.example.com/ffffff', true) + expect(server_api).not_to receive(:streaming_request). + with('http://chef.example.com/ffffff') synchronizer.sync_cookbooks end @@ -502,7 +501,7 @@ describe Chef::CookbookSynchronizer do it "does not update files" do expect(file_cache).not_to receive(:move_to) - expect(server_api).not_to receive(:get_rest) + expect(server_api).not_to receive(:streaming_request) synchronizer.sync_cookbooks end end @@ -512,7 +511,7 @@ describe Chef::CookbookSynchronizer do it "does not update files" do expect(file_cache).not_to receive(:move_to) - expect(server_api).not_to receive(:get_rest) + expect(server_api).not_to receive(:streaming_request) synchronizer.sync_cookbooks end end diff --git a/spec/unit/cookbook_uploader_spec.rb b/spec/unit/cookbook_uploader_spec.rb index 76727c18e2..a08b6b29d0 100644 --- a/spec/unit/cookbook_uploader_spec.rb +++ b/spec/unit/cookbook_uploader_spec.rb @@ -20,7 +20,7 @@ require 'spec_helper' describe Chef::CookbookUploader do - let(:http_client) { double("Chef::REST") } + let(:http_client) { double("Chef::ServerAPI") } let(:cookbook_loader) do loader = Chef::CookbookLoader.new(File.join(CHEF_SPEC_DATA, "cookbooks")) @@ -64,8 +64,8 @@ describe Chef::CookbookUploader do end it "creates an HTTP client with default configuration when not initialized with one" do - default_http_client = double("Chef::REST") - expect(Chef::REST).to receive(:new).with(Chef::Config[:chef_server_url]).and_return(default_http_client) + default_http_client = double("Chef::ServerAPI") + expect(Chef::ServerAPI).to receive(:new).with(Chef::Config[:chef_server_url]).and_return(default_http_client) uploader = described_class.new(cookbooks_to_upload) expect(uploader.rest).to eq(default_http_client) end diff --git a/spec/unit/data_bag_item_spec.rb b/spec/unit/data_bag_item_spec.rb index 497817ecf1..47042aa7ba 100644 --- a/spec/unit/data_bag_item_spec.rb +++ b/spec/unit/data_bag_item_spec.rb @@ -214,7 +214,7 @@ describe Chef::DataBagItem do end describe "save" do - let(:server) { instance_double(Chef::REST) } + let(:server) { instance_double(Chef::ServerAPI) } let(:data_bag_item) { data_bag_item = Chef::DataBagItem.new @@ -225,18 +225,18 @@ describe Chef::DataBagItem do } before do - expect(Chef::REST).to receive(:new).and_return(server) + expect(Chef::ServerAPI).to receive(:new).and_return(server) end it "should update the item when it already exists" do - expect(server).to receive(:put_rest).with("data/books/heart_of_darkness", data_bag_item) + expect(server).to receive(:put).with("data/books/heart_of_darkness", data_bag_item) data_bag_item.save end it "should create if the item is not found" do exception = double("404 error", :code => "404") - expect(server).to receive(:put_rest).and_raise(Net::HTTPServerException.new("foo", exception)) - expect(server).to receive(:post_rest).with("data/books", data_bag_item) + expect(server).to receive(:put).and_raise(Net::HTTPServerException.new("foo", exception)) + expect(server).to receive(:post).with("data/books", data_bag_item) data_bag_item.save end @@ -249,8 +249,8 @@ describe Chef::DataBagItem do end it "should not save" do - expect(server).not_to receive(:put_rest) - expect(server).not_to receive(:post_rest) + expect(server).not_to receive(:put) + expect(server).not_to receive(:post) data_bag_item.data_bag("books") data_bag_item.save end @@ -259,7 +259,7 @@ describe Chef::DataBagItem do end describe "destroy" do - let(:server) { instance_double(Chef::REST) } + let(:server) { instance_double(Chef::ServerAPI) } let(:data_bag_item) { data_bag_item = Chef::DataBagItem.new @@ -269,8 +269,8 @@ describe Chef::DataBagItem do } it "should set default parameters" do - expect(Chef::REST).to receive(:new).and_return(server) - expect(server).to receive(:delete_rest).with("data/a_baggy_bag/data_bag_item_a_baggy_bag_some_id") + expect(Chef::ServerAPI).to receive(:new).and_return(server) + expect(server).to receive(:delete).with("data/a_baggy_bag/data_bag_item_a_baggy_bag_some_id") data_bag_item.destroy end @@ -283,21 +283,21 @@ describe Chef::DataBagItem do end describe "from an API call" do - let(:http_client) { double("Chef::REST") } + let(:http_client) { double("Chef::ServerAPI") } before do - allow(Chef::REST).to receive(:new).and_return(http_client) + allow(Chef::ServerAPI).to receive(:new).and_return(http_client) end it "converts raw data to a data bag item" do - expect(http_client).to receive(:get_rest).with("data/users/charlie").and_return(data_bag_item.to_hash) + expect(http_client).to receive(:get).with("data/users/charlie").and_return(data_bag_item.to_hash) item = Chef::DataBagItem.load(:users, "charlie") expect(item).to be_a_kind_of(Chef::DataBagItem) expect(item).to eq(data_bag_item) end it "does not convert when a DataBagItem is returned from the API call" do - expect(http_client).to receive(:get_rest).with("data/users/charlie").and_return(data_bag_item) + expect(http_client).to receive(:get).with("data/users/charlie").and_return(data_bag_item) item = Chef::DataBagItem.load(:users, "charlie") expect(item).to be_a_kind_of(Chef::DataBagItem) expect(item).to equal(data_bag_item) diff --git a/spec/unit/data_bag_spec.rb b/spec/unit/data_bag_spec.rb index 13b835d120..a325b1260f 100644 --- a/spec/unit/data_bag_spec.rb +++ b/spec/unit/data_bag_spec.rb @@ -83,18 +83,18 @@ describe Chef::DataBag do describe "when saving" do before do @data_bag.name('piggly_wiggly') - @rest = double("Chef::REST") - allow(Chef::REST).to receive(:new).and_return(@rest) + @rest = double("Chef::ServerAPI") + allow(Chef::ServerAPI).to receive(:new).and_return(@rest) end it "should silently proceed when the data bag already exists" do exception = double("409 error", :code => "409") - expect(@rest).to receive(:post_rest).and_raise(Net::HTTPServerException.new("foo", exception)) + expect(@rest).to receive(:post).and_raise(Net::HTTPServerException.new("foo", exception)) @data_bag.save end it "should create the data bag" do - expect(@rest).to receive(:post_rest).with("data", @data_bag) + expect(@rest).to receive(:post).with("data", @data_bag) @data_bag.save end @@ -106,7 +106,7 @@ describe Chef::DataBag do Chef::Config[:why_run] = false end it "should not save" do - expect(@rest).not_to receive(:post_rest) + expect(@rest).not_to receive(:post) @data_bag.save end end @@ -116,18 +116,18 @@ describe Chef::DataBag do describe "from an API call" do before do Chef::Config[:chef_server_url] = 'https://myserver.example.com' - @http_client = double('Chef::REST') + @http_client = double('Chef::ServerAPI') end it "should get the data bag from the server" do - expect(Chef::REST).to receive(:new).with('https://myserver.example.com').and_return(@http_client) - expect(@http_client).to receive(:get_rest).with('data/foo') + expect(Chef::ServerAPI).to receive(:new).with('https://myserver.example.com').and_return(@http_client) + expect(@http_client).to receive(:get).with('data/foo') Chef::DataBag.load('foo') end it "should return the data bag" do - allow(Chef::REST).to receive(:new).and_return(@http_client) - expect(@http_client).to receive(:get_rest).with('data/foo').and_return({'bar' => 'https://myserver.example.com/data/foo/bar'}) + allow(Chef::ServerAPI).to receive(:new).and_return(@http_client) + expect(@http_client).to receive(:get).with('data/foo').and_return({'bar' => 'https://myserver.example.com/data/foo/bar'}) data_bag = Chef::DataBag.load('foo') expect(data_bag).to eq({'bar' => 'https://myserver.example.com/data/foo/bar'}) end diff --git a/spec/unit/environment_spec.rb b/spec/unit/environment_spec.rb index 64617e0888..4116150d6e 100644 --- a/spec/unit/environment_spec.rb +++ b/spec/unit/environment_spec.rb @@ -365,8 +365,8 @@ describe Chef::Environment do describe "api model" do before(:each) do - @rest = double("Chef::REST") - allow(Chef::REST).to receive(:new).and_return(@rest) + @rest = double("Chef::ServerAPI") + allow(Chef::ServerAPI).to receive(:new).and_return(@rest) @query = double("Chef::Search::Query") allow(Chef::Search::Query).to receive(:new).and_return(@query) end @@ -382,7 +382,7 @@ describe Chef::Environment do end it "should return a hash of environment names and urls" do - expect(@rest).to receive(:get_rest).and_return({ "one" => "http://foo" }) + expect(@rest).to receive(:get).and_return({ "one" => "http://foo" }) r = Chef::Environment.list expect(r["one"]).to eq("http://foo") end diff --git a/spec/unit/key_spec.rb b/spec/unit/key_spec.rb index 94ebbf6ae8..66f5fb9b13 100644 --- a/spec/unit/key_spec.rb +++ b/spec/unit/key_spec.rb @@ -342,7 +342,7 @@ EOS Chef::Config[:chef_server_root] = "http://www.example.com" Chef::Config[:chef_server_url] = "http://www.example.com/organizations/test_org" r = double('rest') - allow(Chef::REST).to receive(:new).and_return(r) + allow(Chef::ServerAPI).to receive(:new).and_return(r) r end @@ -362,13 +362,13 @@ EOS let(:inflated_response) { {"foobar" => user_key} } it "lists all keys" do - expect(rest).to receive(:get_rest).with("users/#{user_key.actor}/keys").and_return(response) + expect(rest).to receive(:get).with("users/#{user_key.actor}/keys").and_return(response) expect(Chef::Key.list_by_user("foobar")).to eq(response) end it "inflate all keys" do allow(Chef::Key).to receive(:load_by_user).with(user_key.actor, "foobar").and_return(user_key) - expect(rest).to receive(:get_rest).with("users/#{user_key.actor}/keys").and_return(response) + expect(rest).to receive(:get).with("users/#{user_key.actor}/keys").and_return(response) expect(Chef::Key.list_by_user("foobar", true)).to eq(inflated_response) end @@ -379,13 +379,13 @@ EOS let(:inflated_response) { {"foobar" => client_key} } it "lists all keys" do - expect(rest).to receive(:get_rest).with("clients/#{client_key.actor}/keys").and_return(response) + expect(rest).to receive(:get).with("clients/#{client_key.actor}/keys").and_return(response) expect(Chef::Key.list_by_client("foobar")).to eq(response) end it "inflate all keys" do allow(Chef::Key).to receive(:load_by_client).with(client_key.actor, "foobar").and_return(client_key) - expect(rest).to receive(:get_rest).with("clients/#{user_key.actor}/keys").and_return(response) + expect(rest).to receive(:get).with("clients/#{user_key.actor}/keys").and_return(response) expect(Chef::Key.list_by_client("foobar", true)).to eq(inflated_response) end @@ -408,7 +408,7 @@ EOS end it "creates a new key via the API with the fingerprint as the name" do - expect(rest).to receive(:post_rest).with(url, + expect(rest).to receive(:post).with(url, {"name" => "12:3e:33:73:0b:f4:ec:72:dc:f0:4c:51:62:27:08:76:96:24:f4:4a", "public_key" => key.public_key, "expiration_date" => key.expiration_date}).and_return({}) @@ -426,7 +426,7 @@ EOS context "when create_key is false" do it "creates a new key via the API" do - expect(rest).to receive(:post_rest).with(url, + expect(rest).to receive(:post).with(url, {"name" => key.name, "public_key" => key.public_key, "expiration_date" => key.expiration_date}).and_return({}) @@ -453,13 +453,13 @@ EOS end it "should create a new key via the API" do - expect(rest).to receive(:post_rest).with(url, $expected_input).and_return({}) + expect(rest).to receive(:post).with(url, $expected_input).and_return({}) key.create end context "when the server returns the private_key via key.create" do before do - allow(rest).to receive(:post_rest).with(url, $expected_input).and_return({"private_key" => "this_private_key"}) + allow(rest).to receive(:post).with(url, $expected_input).and_return({"private_key" => "this_private_key"}) end it "key.create returns the original key plus the private_key" do @@ -512,7 +512,7 @@ EOS end it "should update the key via the API" do - expect(rest).to receive(:put_rest).with(url, key.to_hash).and_return({}) + expect(rest).to receive(:put).with(url, key.to_hash).and_return({}) key.update end end @@ -523,7 +523,7 @@ EOS end it "passes @name in the body and the arg in the PUT URL" do - expect(rest).to receive(:put_rest).with(update_name_url, key.to_hash).and_return({}) + expect(rest).to receive(:put).with(update_name_url, key.to_hash).and_return({}) key.update("old_name") end end @@ -532,7 +532,7 @@ EOS before do key.name "key_name" key.create_key true - allow(rest).to receive(:put_rest).with(url, key.to_hash).and_return({ + allow(rest).to receive(:put).with(url, key.to_hash).and_return({ "key" => "key_name", "public_key" => public_key_string }) @@ -572,7 +572,7 @@ EOS describe "load" do shared_examples_for "load" do it "should load a named key from the API" do - expect(rest).to receive(:get_rest).with(url).and_return({"user" => "foobar", "name" => "test_key_name", "public_key" => public_key_string, "expiration_date" => "infinity"}) + expect(rest).to receive(:get).with(url).and_return({"user" => "foobar", "name" => "test_key_name", "public_key" => public_key_string, "expiration_date" => "infinity"}) key = Chef::Key.send(load_method, "foobar", "test_key_name") expect(key.actor).to eq("foobar") expect(key.name).to eq("test_key_name") @@ -610,7 +610,7 @@ EOS end context "when name is not missing" do it "should delete the key via the API" do - expect(rest).to receive(:delete_rest).with(url).and_return({}) + expect(rest).to receive(:delete).with(url).and_return({}) key.destroy end end diff --git a/spec/unit/knife/bootstrap/client_builder_spec.rb b/spec/unit/knife/bootstrap/client_builder_spec.rb index f17a6af878..6812a24c91 100644 --- a/spec/unit/knife/bootstrap/client_builder_spec.rb +++ b/spec/unit/knife/bootstrap/client_builder_spec.rb @@ -32,7 +32,7 @@ describe Chef::Knife::Bootstrap::ClientBuilder do let(:node_name) { "bevell.wat" } - let(:rest) { double("Chef::REST") } + let(:rest) { double("Chef::ServerAPI") } let(:client_builder) { client_builder = Chef::Knife::Bootstrap::ClientBuilder.new(knife_config: knife_config, chef_config: chef_config, ui: ui) @@ -53,14 +53,14 @@ describe Chef::Knife::Bootstrap::ClientBuilder do end it "exits when the node exists and the user does not want to delete" do - expect(rest).to receive(:get_rest).with("nodes/#{node_name}") + expect(rest).to receive(:get).with("nodes/#{node_name}") expect(ui.stdin).to receive(:readline).and_return('n') expect { client_builder.run }.to raise_error(SystemExit) end it "exits when the client exists and the user does not want to delete" do - expect(rest).to receive(:get_rest).with("nodes/#{node_name}").and_raise(exception_404) - expect(rest).to receive(:get_rest).with("clients/#{node_name}") + expect(rest).to receive(:get).with("nodes/#{node_name}").and_raise(exception_404) + expect(rest).to receive(:get).with("clients/#{node_name}") expect(ui.stdin).to receive(:readline).and_return('n') expect { client_builder.run }.to raise_error(SystemExit) end @@ -74,30 +74,30 @@ describe Chef::Knife::Bootstrap::ClientBuilder do end it "when both the client and node do not exist it succeeds" do - expect(rest).to receive(:get_rest).with("nodes/#{node_name}").and_raise(exception_404) - expect(rest).to receive(:get_rest).with("clients/#{node_name}").and_raise(exception_404) + expect(rest).to receive(:get).with("nodes/#{node_name}").and_raise(exception_404) + expect(rest).to receive(:get).with("clients/#{node_name}").and_raise(exception_404) expect { client_builder.run }.not_to raise_error end it "when we are allowed to delete an old node" do - expect(rest).to receive(:get_rest).with("nodes/#{node_name}") + expect(rest).to receive(:get).with("nodes/#{node_name}") expect(ui.stdin).to receive(:readline).and_return('y') - expect(rest).to receive(:get_rest).with("clients/#{node_name}").and_raise(exception_404) + expect(rest).to receive(:get).with("clients/#{node_name}").and_raise(exception_404) expect(rest).to receive(:delete).with("nodes/#{node_name}") expect { client_builder.run }.not_to raise_error end it "when we are allowed to delete an old client" do - expect(rest).to receive(:get_rest).with("nodes/#{node_name}").and_raise(exception_404) - expect(rest).to receive(:get_rest).with("clients/#{node_name}") + expect(rest).to receive(:get).with("nodes/#{node_name}").and_raise(exception_404) + expect(rest).to receive(:get).with("clients/#{node_name}") expect(ui.stdin).to receive(:readline).and_return('y') expect(rest).to receive(:delete).with("clients/#{node_name}") expect { client_builder.run }.not_to raise_error end it "when we are are allowed to delete both an old client and node" do - expect(rest).to receive(:get_rest).with("nodes/#{node_name}") - expect(rest).to receive(:get_rest).with("clients/#{node_name}") + expect(rest).to receive(:get).with("nodes/#{node_name}") + expect(rest).to receive(:get).with("clients/#{node_name}") expect(ui.stdin).to receive(:readline).twice.and_return('y') expect(rest).to receive(:delete).with("nodes/#{node_name}") expect(rest).to receive(:delete).with("clients/#{node_name}") @@ -143,7 +143,7 @@ describe Chef::Knife::Bootstrap::ClientBuilder do expect(node).to receive(:save) end - let(:client_rest) { double("Chef::REST (client)") } + let(:client_rest) { double("Chef::ServerAPI (client)") } let(:node) { double("Chef::Node") } diff --git a/spec/unit/knife/configure_spec.rb b/spec/unit/knife/configure_spec.rb index e3ea1f052c..89874cfdf9 100644 --- a/spec/unit/knife/configure_spec.rb +++ b/spec/unit/knife/configure_spec.rb @@ -6,7 +6,7 @@ describe Chef::Knife::Configure do Chef::Config[:node_name] = "webmonkey.example.com" @knife = Chef::Knife::Configure.new - @rest_client = double("null rest client", :post_rest => { :result => :true }) + @rest_client = double("null rest client", :post => { :result => :true }) allow(@knife).to receive(:rest).and_return(@rest_client) @out = StringIO.new diff --git a/spec/unit/knife/cookbook_bulk_delete_spec.rb b/spec/unit/knife/cookbook_bulk_delete_spec.rb index 98cd06bbbc..7d6e851589 100644 --- a/spec/unit/knife/cookbook_bulk_delete_spec.rb +++ b/spec/unit/knife/cookbook_bulk_delete_spec.rb @@ -36,9 +36,9 @@ describe Chef::Knife::CookbookBulkDelete do cookbook = Chef::CookbookVersion.new(cookbook_name) @cookbooks[cookbook_name] = cookbook end - @rest = double("Chef::REST") - allow(@rest).to receive(:get_rest).and_return(@cookbooks) - allow(@rest).to receive(:delete_rest).and_return(true) + @rest = double("Chef::ServerAPI") + allow(@rest).to receive(:get).and_return(@cookbooks) + allow(@rest).to receive(:delete).and_return(true) allow(@knife).to receive(:rest).and_return(@rest) allow(Chef::CookbookVersion).to receive(:list).and_return(@cookbooks) @@ -49,11 +49,11 @@ describe Chef::Knife::CookbookBulkDelete do describe "when there are several cookbooks on the server" do before do @cheezburger = {'cheezburger' => {"url" => "file:///dev/null", "versions" => [{"url" => "file:///dev/null-cheez", "version" => "1.0.0"}]}} - allow(@rest).to receive(:get_rest).with('cookbooks/cheezburger').and_return(@cheezburger) + allow(@rest).to receive(:get).with('cookbooks/cheezburger').and_return(@cheezburger) @pizza = {'pizza' => {"url" => "file:///dev/null", "versions" => [{"url" => "file:///dev/null-pizza", "version" => "2.0.0"}]}} - allow(@rest).to receive(:get_rest).with('cookbooks/pizza').and_return(@pizza) + allow(@rest).to receive(:get).with('cookbooks/pizza').and_return(@pizza) @lasagna = {'lasagna' => {"url" => "file:///dev/null", "versions" => [{"url" => "file:///dev/null-lasagna", "version" => "3.0.0"}]}} - allow(@rest).to receive(:get_rest).with('cookbooks/lasagna').and_return(@lasagna) + allow(@rest).to receive(:get).with('cookbooks/lasagna').and_return(@lasagna) end it "should print the cookbooks you are about to delete" do @@ -69,14 +69,14 @@ describe Chef::Knife::CookbookBulkDelete do it "should delete each cookbook" do {"cheezburger" => "1.0.0", "pizza" => "2.0.0", "lasagna" => '3.0.0'}.each do |cookbook_name, version| - expect(@rest).to receive(:delete_rest).with("cookbooks/#{cookbook_name}/#{version}") + expect(@rest).to receive(:delete).with("cookbooks/#{cookbook_name}/#{version}") end @knife.run end it "should only delete cookbooks that match the regex" do @knife.name_args = ["cheezburger"] - expect(@rest).to receive(:delete_rest).with('cookbooks/cheezburger/1.0.0') + expect(@rest).to receive(:delete).with('cookbooks/cheezburger/1.0.0') @knife.run end end diff --git a/spec/unit/knife/cookbook_delete_spec.rb b/spec/unit/knife/cookbook_delete_spec.rb index 4e75a689e3..e9085e9512 100644 --- a/spec/unit/knife/cookbook_delete_spec.rb +++ b/spec/unit/knife/cookbook_delete_spec.rb @@ -134,19 +134,19 @@ describe Chef::Knife::CookbookDelete do end it 'should return the list of versions of the cookbook' do - expect(@rest_mock).to receive(:get_rest).with('cookbooks/foobar').and_return(@cookbook_data) + expect(@rest_mock).to receive(:get).with('cookbooks/foobar').and_return(@cookbook_data) expect(@knife.available_versions).to eq(['1.0.0', '1.1.0', '2.0.0']) end it 'should raise if an error other than HTTP 404 is returned' do exception = Net::HTTPServerException.new('500 Internal Server Error', '500') - expect(@rest_mock).to receive(:get_rest).and_raise(exception) + expect(@rest_mock).to receive(:get).and_raise(exception) expect { @knife.available_versions }.to raise_error Net::HTTPServerException end describe "if the cookbook can't be found" do before(:each) do - expect(@rest_mock).to receive(:get_rest). + expect(@rest_mock).to receive(:get). and_raise(Net::HTTPServerException.new('404 Not Found', '404')) end diff --git a/spec/unit/knife/cookbook_download_spec.rb b/spec/unit/knife/cookbook_download_spec.rb index 7ca1adfcb5..8b85e52b75 100644 --- a/spec/unit/knife/cookbook_download_spec.rb +++ b/spec/unit/knife/cookbook_download_spec.rb @@ -69,8 +69,8 @@ describe Chef::Knife::CookbookDownload do @cookbook_mock = double('cookbook') allow(@cookbook_mock).to receive(:version).and_return('1.0.0') allow(@cookbook_mock).to receive(:manifest).and_return(@manifest_data) - expect(@rest_mock).to receive(:get_rest).with('cookbooks/foobar/1.0.0'). - and_return(@cookbook_mock) + expect(Chef::CookbookVersion).to receive(:load).with("foobar", "1.0.0"). + and_return(@cookbook_mock) end it 'should determine which version if one was not explicitly specified'do @@ -106,11 +106,10 @@ describe Chef::Knife::CookbookDownload do end @files_mocks.each_pair do |file, mock| - expect(@rest_mock).to receive(:get_rest).with("http://example.org/files/#{file}", true). + expect(@rest_mock).to receive(:streaming_request).with("http://example.org/files/#{file}"). and_return(mock) end - expect(@rest_mock).to receive(:sign_on_redirect=).with(false).at_least(:once) @files.each do |f| expect(FileUtils).to receive(:mv). with("/var/tmp/#{File.basename(f)}", "/var/tmp/chef/foobar-1.0.0/#{f}") diff --git a/spec/unit/knife/cookbook_list_spec.rb b/spec/unit/knife/cookbook_list_spec.rb index 559f700bb4..fc07c8af3f 100644 --- a/spec/unit/knife/cookbook_list_spec.rb +++ b/spec/unit/knife/cookbook_list_spec.rb @@ -37,7 +37,7 @@ describe Chef::Knife::CookbookList do describe 'run' do it 'should display the latest version of the cookbooks' do - expect(@rest_mock).to receive(:get_rest).with('/cookbooks?num_versions=1'). + expect(@rest_mock).to receive(:get).with('/cookbooks?num_versions=1'). and_return(@cookbook_data) @knife.run @cookbook_names.each do |item| @@ -47,7 +47,7 @@ describe Chef::Knife::CookbookList do it 'should query cookbooks for the configured environment' do @knife.config[:environment] = 'production' - expect(@rest_mock).to receive(:get_rest). + expect(@rest_mock).to receive(:get). with('/environments/production/cookbooks?num_versions=1'). and_return(@cookbook_data) @knife.run @@ -56,7 +56,7 @@ describe Chef::Knife::CookbookList do describe 'with -w or --with-uri' do it 'should display the cookbook uris' do @knife.config[:with_uri] = true - allow(@rest_mock).to receive(:get_rest).and_return(@cookbook_data) + allow(@rest_mock).to receive(:get).and_return(@cookbook_data) @knife.run @cookbook_names.each do |item| pattern = /#{Regexp.escape(@cookbook_data[item]['versions'].first['url'])}/ @@ -75,7 +75,7 @@ describe Chef::Knife::CookbookList do it 'should display all versions of the cookbooks' do @knife.config[:all_versions] = true - expect(@rest_mock).to receive(:get_rest).with('/cookbooks?num_versions=all'). + expect(@rest_mock).to receive(:get).with('/cookbooks?num_versions=all'). and_return(@cookbook_data) @knife.run @cookbook_names.each do |item| diff --git a/spec/unit/knife/cookbook_show_spec.rb b/spec/unit/knife/cookbook_show_spec.rb index bf480e3678..a06e53b9a1 100644 --- a/spec/unit/knife/cookbook_show_spec.rb +++ b/spec/unit/knife/cookbook_show_spec.rb @@ -25,7 +25,7 @@ describe Chef::Knife::CookbookShow do @knife = Chef::Knife::CookbookShow.new @knife.config = { } @knife.name_args = [ "cookbook_name" ] - @rest = double(Chef::REST) + @rest = double(Chef::ServerAPI) allow(@knife).to receive(:rest).and_return(@rest) allow(@knife).to receive(:pretty_print).and_return(true) allow(@knife).to receive(:output).and_return(true) @@ -56,14 +56,14 @@ describe Chef::Knife::CookbookShow do end it "should show the raw cookbook data" do - expect(@rest).to receive(:get_rest).with("cookbooks/cookbook_name").and_return(@response) + expect(@rest).to receive(:get).with("cookbooks/cookbook_name").and_return(@response) expect(@knife).to receive(:format_cookbook_list_for_display).with(@response) @knife.run end it "should respect the user-supplied environment" do @knife.config[:environment] = "foo" - expect(@rest).to receive(:get_rest).with("environments/foo/cookbooks/cookbook_name").and_return(@response) + expect(@rest).to receive(:get).with("environments/foo/cookbooks/cookbook_name").and_return(@response) expect(@knife).to receive(:format_cookbook_list_for_display).with(@response) @knife.run end @@ -76,7 +76,7 @@ describe Chef::Knife::CookbookShow do end it "should show the specific part of a cookbook" do - expect(@rest).to receive(:get_rest).with("cookbooks/cookbook_name/0.1.0").and_return(@response) + expect(@rest).to receive(:get).with("cookbooks/cookbook_name/0.1.0").and_return(@response) expect(@knife).to receive(:output).with(@response) @knife.run end @@ -101,7 +101,7 @@ describe Chef::Knife::CookbookShow do end it "should print the json of the part" do - expect(@rest).to receive(:get_rest).with("cookbooks/cookbook_name/0.1.0").and_return(@cookbook_response) + expect(@rest).to receive(:get).with("cookbooks/cookbook_name/0.1.0").and_return(@cookbook_response) expect(@knife).to receive(:output).with(@cookbook_response.manifest["recipes"]) @knife.run end @@ -125,8 +125,8 @@ describe Chef::Knife::CookbookShow do end it "should print the raw result of the request (likely a file!)" do - expect(@rest).to receive(:get_rest).with("cookbooks/cookbook_name/0.1.0").and_return(@cookbook_response) - expect(@rest).to receive(:get_rest).with("http://example.org/files/default.rb", true).and_return(StringIO.new(@response)) + expect(@rest).to receive(:get).with("cookbooks/cookbook_name/0.1.0").and_return(@cookbook_response) + expect(@rest).to receive(:get).with("http://example.org/files/default.rb", true).and_return(StringIO.new(@response)) expect(@knife).to receive(:pretty_print).with(@response) @knife.run end @@ -177,8 +177,8 @@ describe Chef::Knife::CookbookShow do @knife.config[:platform] = "example_platform" @knife.config[:platform_version] = "1.0" @knife.config[:fqdn] = "examplehost.example.org" - expect(@rest).to receive(:get_rest).with("cookbooks/cookbook_name/0.1.0").and_return(@cookbook_response) - expect(@rest).to receive(:get_rest).with("http://example.org/files/1111", true).and_return(StringIO.new(@response)) + expect(@rest).to receive(:get).with("cookbooks/cookbook_name/0.1.0").and_return(@cookbook_response) + expect(@rest).to receive(:get).with("http://example.org/files/1111", true).and_return(StringIO.new(@response)) expect(@knife).to receive(:pretty_print).with(@response) @knife.run end @@ -189,8 +189,8 @@ describe Chef::Knife::CookbookShow do @knife.config[:platform] = "ubuntu" @knife.config[:platform_version] = "1.0" @knife.config[:fqdn] = "differenthost.example.org" - expect(@rest).to receive(:get_rest).with("cookbooks/cookbook_name/0.1.0").and_return(@cookbook_response) - expect(@rest).to receive(:get_rest).with("http://example.org/files/3333", true).and_return(StringIO.new(@response)) + expect(@rest).to receive(:get).with("cookbooks/cookbook_name/0.1.0").and_return(@cookbook_response) + expect(@rest).to receive(:get).with("http://example.org/files/3333", true).and_return(StringIO.new(@response)) expect(@knife).to receive(:pretty_print).with(@response) @knife.run end @@ -201,8 +201,8 @@ describe Chef::Knife::CookbookShow do @knife.config[:platform] = "ubuntu" @knife.config[:platform_version] = "9.10" @knife.config[:fqdn] = "differenthost.example.org" - expect(@rest).to receive(:get_rest).with("cookbooks/cookbook_name/0.1.0").and_return(@cookbook_response) - expect(@rest).to receive(:get_rest).with("http://example.org/files/2222", true).and_return(StringIO.new(@response)) + expect(@rest).to receive(:get).with("cookbooks/cookbook_name/0.1.0").and_return(@cookbook_response) + expect(@rest).to receive(:get).with("http://example.org/files/2222", true).and_return(StringIO.new(@response)) expect(@knife).to receive(:pretty_print).with(@response) @knife.run end @@ -210,8 +210,8 @@ describe Chef::Knife::CookbookShow do describe "with none of the arguments, it should use the default" do it "should pass them all" do - expect(@rest).to receive(:get_rest).with("cookbooks/cookbook_name/0.1.0").and_return(@cookbook_response) - expect(@rest).to receive(:get_rest).with("http://example.org/files/4444", true).and_return(StringIO.new(@response)) + expect(@rest).to receive(:get).with("cookbooks/cookbook_name/0.1.0").and_return(@cookbook_response) + expect(@rest).to receive(:get).with("http://example.org/files/4444", true).and_return(StringIO.new(@response)) expect(@knife).to receive(:pretty_print).with(@response) @knife.run end diff --git a/spec/unit/knife/cookbook_site_download_spec.rb b/spec/unit/knife/cookbook_site_download_spec.rb index fdf4c2197b..35c6544d58 100644 --- a/spec/unit/knife/cookbook_site_download_spec.rb +++ b/spec/unit/knife/cookbook_site_download_spec.rb @@ -35,7 +35,7 @@ describe Chef::Knife::CookbookSiteDownload do allow(@knife.ui).to receive(:stderr).and_return(@stderr) allow(@knife).to receive(:noauth_rest).and_return(@noauth_rest) - expect(@noauth_rest).to receive(:get_rest). + expect(@noauth_rest).to receive(:get). with("#{@cookbook_api_url}/apache2"). and_return(@current_data) end @@ -66,10 +66,10 @@ describe Chef::Knife::CookbookSiteDownload do context 'downloading the latest version' do before do - expect(@noauth_rest).to receive(:get_rest). + expect(@noauth_rest).to receive(:get). with(@current_data['latest_version']). and_return(@cookbook_data) - expect(@noauth_rest).to receive(:get_rest). + expect(@noauth_rest).to receive(:get). with(@cookbook_data['file'], true). and_return(@temp_file) end @@ -131,10 +131,10 @@ describe Chef::Knife::CookbookSiteDownload do end it 'should download the desired version' do - expect(@noauth_rest).to receive(:get_rest). + expect(@noauth_rest).to receive(:get). with("#{@cookbook_api_url}/apache2/versions/#{@version_us}"). and_return(@cookbook_data) - expect(@noauth_rest).to receive(:get_rest). + expect(@noauth_rest).to receive(:get). with(@cookbook_data['file'], true). and_return(@temp_file) expect(FileUtils).to receive(:cp).with(@temp_file.path, @file) diff --git a/spec/unit/knife/cookbook_site_share_spec.rb b/spec/unit/knife/cookbook_site_share_spec.rb index a7caca9744..1b2ffd10fb 100644 --- a/spec/unit/knife/cookbook_site_share_spec.rb +++ b/spec/unit/knife/cookbook_site_share_spec.rb @@ -36,7 +36,7 @@ describe Chef::Knife::CookbookSiteShare do allow(@cookbook_loader).to receive(:[]).and_return(@cookbook) allow(Chef::CookbookLoader).to receive(:new).and_return(@cookbook_loader) - @noauth_rest = double(Chef::REST) + @noauth_rest = double(Chef::ServerAPI) allow(@knife).to receive(:noauth_rest).and_return(@noauth_rest) @cookbook_uploader = Chef::CookbookUploader.new('herpderp', :rest => "norest") @@ -78,21 +78,21 @@ describe Chef::Knife::CookbookSiteShare do it 'should not fail when given only 1 argument and can determine category' do @knife.name_args = ['cookbook_name'] - expect(@noauth_rest).to receive(:get_rest).with("https://supermarket.chef.io/api/v1/cookbooks/cookbook_name").and_return(@category_response) + expect(@noauth_rest).to receive(:get).with("https://supermarket.chef.io/api/v1/cookbooks/cookbook_name").and_return(@category_response) expect(@knife).to receive(:do_upload) @knife.run end it 'should print error and exit when given only 1 argument and cannot determine category' do @knife.name_args = ['cookbook_name'] - expect(@noauth_rest).to receive(:get_rest).with("https://supermarket.chef.io/api/v1/cookbooks/cookbook_name").and_return(@bad_category_response) + expect(@noauth_rest).to receive(:get).with("https://supermarket.chef.io/api/v1/cookbooks/cookbook_name").and_return(@bad_category_response) expect(@knife.ui).to receive(:fatal) expect { @knife.run }.to raise_error(SystemExit) end - it 'should print error and exit when given only 1 argument and Chef::REST throws an exception' do + it 'should print error and exit when given only 1 argument and Chef::ServerAPI throws an exception' do @knife.name_args = ['cookbook_name'] - expect(@noauth_rest).to receive(:get_rest).with("https://supermarket.chef.io/api/v1/cookbooks/cookbook_name") { raise Errno::ECONNREFUSED, "Connection refused" } + expect(@noauth_rest).to receive(:get).with("https://supermarket.chef.io/api/v1/cookbooks/cookbook_name") { raise Errno::ECONNREFUSED, "Connection refused" } expect(@knife.ui).to receive(:fatal) expect { @knife.run }.to raise_error(SystemExit) end diff --git a/spec/unit/knife/cookbook_site_unshare_spec.rb b/spec/unit/knife/cookbook_site_unshare_spec.rb index ec46a8705c..aafb7c1507 100644 --- a/spec/unit/knife/cookbook_site_unshare_spec.rb +++ b/spec/unit/knife/cookbook_site_unshare_spec.rb @@ -26,8 +26,8 @@ describe Chef::Knife::CookbookSiteUnshare do @knife.name_args = ['cookbook_name'] allow(@knife).to receive(:confirm).and_return(true) - @rest = double('Chef::REST') - allow(@rest).to receive(:delete_rest).and_return(true) + @rest = double('Chef::ServerAPI') + allow(@rest).to receive(:delete).and_return(true) allow(@knife).to receive(:rest).and_return(@rest) @stdout = StringIO.new allow(@knife.ui).to receive(:stdout).and_return(@stdout) @@ -50,20 +50,20 @@ describe Chef::Knife::CookbookSiteUnshare do end it 'should send a delete request to the cookbook site' do - expect(@rest).to receive(:delete_rest) + expect(@rest).to receive(:delete) @knife.run end it 'should log an error and exit when forbidden' do exception = double('403 "Forbidden"', :code => '403') - allow(@rest).to receive(:delete_rest).and_raise(Net::HTTPServerException.new('403 "Forbidden"', exception)) + allow(@rest).to receive(:delete).and_raise(Net::HTTPServerException.new('403 "Forbidden"', exception)) expect(@knife.ui).to receive(:error) expect { @knife.run }.to raise_error(SystemExit) end - it 'should re-raise any non-forbidden errors on delete_rest' do + it 'should re-raise any non-forbidden errors on delete' do exception = double('500 "Application Error"', :code => '500') - allow(@rest).to receive(:delete_rest).and_raise(Net::HTTPServerException.new('500 "Application Error"', exception)) + allow(@rest).to receive(:delete).and_raise(Net::HTTPServerException.new('500 "Application Error"', exception)) expect { @knife.run }.to raise_error(Net::HTTPServerException) end diff --git a/spec/unit/knife/data_bag_create_spec.rb b/spec/unit/knife/data_bag_create_spec.rb index c31c88577d..d022cc7f7d 100644 --- a/spec/unit/knife/data_bag_create_spec.rb +++ b/spec/unit/knife/data_bag_create_spec.rb @@ -28,7 +28,7 @@ describe Chef::Knife::DataBagCreate do k end - let(:rest) { double("Chef::REST") } + let(:rest) { double("Chef::ServerAPI") } let(:stdout) { StringIO.new } let(:bag_name) { "sudoing_admins" } @@ -58,7 +58,7 @@ describe Chef::Knife::DataBagCreate do end it "creates a data bag" do - expect(rest).to receive(:post_rest).with("data", {"name" => bag_name}) + expect(rest).to receive(:post).with("data", {"name" => bag_name}) expect(knife.ui).to receive(:info).with("Created data_bag[#{bag_name}]") knife.run @@ -75,8 +75,8 @@ describe Chef::Knife::DataBagCreate do it "creates a data bag item" do expect(knife).to receive(:create_object).and_yield(raw_hash) expect(knife).to receive(:encryption_secret_provided?).and_return(false) - expect(rest).to receive(:post_rest).with("data", {'name' => bag_name}).ordered - expect(rest).to receive(:post_rest).with("data/#{bag_name}", item).ordered + expect(rest).to receive(:post).with("data", {'name' => bag_name}).ordered + expect(rest).to receive(:post).with("data/#{bag_name}", item).ordered knife.run end @@ -99,8 +99,8 @@ describe Chef::Knife::DataBagCreate do .to receive(:encrypt_data_bag_item) .with(raw_hash, secret) .and_return(encoded_data) - expect(rest).to receive(:post_rest).with("data", {"name" => bag_name}).ordered - expect(rest).to receive(:post_rest).with("data/#{bag_name}", item).ordered + expect(rest).to receive(:post).with("data", {"name" => bag_name}).ordered + expect(rest).to receive(:post).with("data/#{bag_name}", item).ordered knife.run end diff --git a/spec/unit/knife/data_bag_edit_spec.rb b/spec/unit/knife/data_bag_edit_spec.rb index 6f19b5e63e..f1bcae990b 100644 --- a/spec/unit/knife/data_bag_edit_spec.rb +++ b/spec/unit/knife/data_bag_edit_spec.rb @@ -37,7 +37,7 @@ describe Chef::Knife::DataBagEdit do let(:db) { Chef::DataBagItem.from_hash(raw_hash)} let(:raw_edited_hash) { {"login_name" => "rho", "id" => "item_name", "new_key" => "new_value"} } - let(:rest) { double("Chef::REST") } + let(:rest) { double("Chef::ServerAPI") } let(:stdout) { StringIO.new } let(:bag_name) { "sudoing_admins" } @@ -56,7 +56,7 @@ describe Chef::Knife::DataBagEdit do expect(Chef::DataBagItem).to receive(:load).with(bag_name, item_name).and_return(db) expect(knife).to receive(:encrypted?).with(db.raw_data).and_return(is_encrypted?) expect(knife).to receive(:edit_data).with(data_to_edit).and_return(raw_edited_hash) - expect(rest).to receive(:put_rest).with("data/#{bag_name}/#{item_name}", transmitted_hash).ordered + expect(rest).to receive(:put).with("data/#{bag_name}/#{item_name}", transmitted_hash).ordered knife.run end diff --git a/spec/unit/knife/data_bag_from_file_spec.rb b/spec/unit/knife/data_bag_from_file_spec.rb index 8b6502145c..dc65a3e64c 100644 --- a/spec/unit/knife/data_bag_from_file_spec.rb +++ b/spec/unit/knife/data_bag_from_file_spec.rb @@ -79,7 +79,7 @@ describe Chef::Knife::DataBagFromFile do } } let(:enc_data) { Chef::EncryptedDataBagItem.encrypt_data_bag_item(plain_data, secret) } - let(:rest) { double("Chef::REST") } + let(:rest) { double("Chef::ServerAPI") } let(:stdout) { StringIO.new } let(:bag_name) { "sudoing_admins" } diff --git a/spec/unit/knife/data_bag_show_spec.rb b/spec/unit/knife/data_bag_show_spec.rb index 1125d99c2a..48a0071b49 100644 --- a/spec/unit/knife/data_bag_show_spec.rb +++ b/spec/unit/knife/data_bag_show_spec.rb @@ -39,7 +39,7 @@ describe Chef::Knife::DataBagShow do k end - let(:rest) { double("Chef::REST") } + let(:rest) { double("Chef::ServerAPI") } let(:stdout) { StringIO.new } let(:bag_name) { "sudoing_admins" } diff --git a/spec/unit/knife/environment_compare_spec.rb b/spec/unit/knife/environment_compare_spec.rb index 6d4d3ead52..81ec19d7af 100644 --- a/spec/unit/knife/environment_compare_spec.rb +++ b/spec/unit/knife/environment_compare_spec.rb @@ -51,7 +51,7 @@ describe Chef::Knife::EnvironmentCompare do 'url' => "#{@base_url}/#{item}/1.0.1"}]} end - allow(@rest_double).to receive(:get_rest).with("/cookbooks?num_versions=1").and_return(@cookbook_data) + allow(@rest_double).to receive(:get).with("/cookbooks?num_versions=1").and_return(@cookbook_data) @stdout = StringIO.new allow(@knife.ui).to receive(:stdout).and_return(@stdout) diff --git a/spec/unit/knife/index_rebuild_spec.rb b/spec/unit/knife/index_rebuild_spec.rb index 6c3b60bd88..d8a0dd72d7 100644 --- a/spec/unit/knife/index_rebuild_spec.rb +++ b/spec/unit/knife/index_rebuild_spec.rb @@ -21,7 +21,7 @@ require 'spec_helper' describe Chef::Knife::IndexRebuild do let(:knife){Chef::Knife::IndexRebuild.new} - let(:rest_client){double(Chef::REST)} + let(:rest_client){double(Chef::ServerAPI)} let(:stub_rest!) do expect(knife).to receive(:rest).and_return(rest_client) @@ -45,7 +45,7 @@ describe Chef::Knife::IndexRebuild do before(:each) do stub_rest! - allow(rest_client).to receive(:get_rest).and_raise(http_server_exception) + allow(rest_client).to receive(:get).and_raise(http_server_exception) end context "against a Chef 11 server" do @@ -110,7 +110,7 @@ describe Chef::Knife::IndexRebuild do let(:api_info){ {} } let(:server_specific_stubs!) do stub_rest! - expect(rest_client).to receive(:post_rest).with("/search/reindex", {}).and_return("representative output") + expect(rest_client).to receive(:post).with("/search/reindex", {}).and_return("representative output") expect(knife).not_to receive(:unsupported_server_message) expect(knife).to receive(:deprecated_server_message) expect(knife).to receive(:nag) diff --git a/spec/unit/knife_spec.rb b/spec/unit/knife_spec.rb index 5ab8e84eac..c2127fdfd5 100644 --- a/spec/unit/knife_spec.rb +++ b/spec/unit/knife_spec.rb @@ -156,8 +156,8 @@ describe Chef::Knife do "Accept-Encoding"=>"gzip;q=1.0,deflate;q=0.6,identity;q=0.3", 'X-Chef-Version' => Chef::VERSION, "Host"=>"api.opscode.piab", - "X-REMOTE-REQUEST-ID"=>request_id, - 'X-Ops-Server-API-Version' => Chef::HTTP::Authenticator::DEFAULT_SERVER_API_VERSION}} + "X-REMOTE-REQUEST-ID"=>request_id + }} let(:request_id) {"1234"} @@ -201,7 +201,7 @@ describe Chef::Knife do it "confirms that the headers include X-Remote-Request-Id" do expect(Net::HTTP::Get).to receive(:new).with("/monkey", headers).and_return(request_mock) - rest.get_rest("monkey") + rest.get("monkey") end end diff --git a/spec/unit/node_spec.rb b/spec/unit/node_spec.rb index 76cf451323..d7cee80d40 100644 --- a/spec/unit/node_spec.rb +++ b/spec/unit/node_spec.rb @@ -1271,8 +1271,8 @@ describe Chef::Node do describe "api model" do before(:each) do - @rest = double("Chef::REST") - allow(Chef::REST).to receive(:new).and_return(@rest) + @rest = double("Chef::ServerAPI") + allow(Chef::ServerAPI).to receive(:new).and_return(@rest) @query = double("Chef::Search::Query") allow(Chef::Search::Query).to receive(:new).and_return(@query) end @@ -1281,6 +1281,7 @@ describe Chef::Node do describe "inflated" do it "should return a hash of node names and objects" do n1 = double("Chef::Node", :name => "one") + allow(n1).to receive(:kind_of?).with(Chef::Node) { true } expect(@query).to receive(:search).with(:node).and_yield(n1) r = Chef::Node.list(true) expect(r["one"]).to eq(n1) @@ -1288,7 +1289,7 @@ describe Chef::Node do end it "should return a hash of node names and urls" do - expect(@rest).to receive(:get_rest).and_return({ "one" => "http://foo" }) + expect(@rest).to receive(:get).and_return({ "one" => "http://foo" }) r = Chef::Node.list expect(r["one"]).to eq("http://foo") end @@ -1296,14 +1297,19 @@ describe Chef::Node do describe "load" do it "should load a node by name" do - expect(@rest).to receive(:get_rest).with("nodes/monkey").and_return("foo") - expect(Chef::Node.load("monkey")).to eq("foo") + node.from_file(File.expand_path("nodes/test.example.com.rb", CHEF_SPEC_DATA)) + json = Chef::JSONCompat.to_json(node) + parsed = Chef::JSONCompat.parse(json) + expect(@rest).to receive(:get).with("nodes/test.example.com").and_return(parsed) + serialized_node = Chef::Node.load("test.example.com") + expect(serialized_node).to be_a_kind_of(Chef::Node) + expect(serialized_node.name).to eql(node.name) end end describe "destroy" do it "should destroy a node" do - expect(@rest).to receive(:delete_rest).with("nodes/monkey").and_return("foo") + expect(@rest).to receive(:delete).with("nodes/monkey").and_return("foo") node.name("monkey") node.destroy end @@ -1313,15 +1319,15 @@ describe Chef::Node do it "should update a node if it already exists" do node.name("monkey") allow(node).to receive(:data_for_save).and_return({}) - expect(@rest).to receive(:put_rest).with("nodes/monkey", {}).and_return("foo") + expect(@rest).to receive(:put).with("nodes/monkey", {}).and_return("foo") node.save end it "should not try and create if it can update" do node.name("monkey") allow(node).to receive(:data_for_save).and_return({}) - expect(@rest).to receive(:put_rest).with("nodes/monkey", {}).and_return("foo") - expect(@rest).not_to receive(:post_rest) + expect(@rest).to receive(:put).with("nodes/monkey", {}).and_return("foo") + expect(@rest).not_to receive(:post) node.save end @@ -1329,8 +1335,8 @@ describe Chef::Node do node.name("monkey") allow(node).to receive(:data_for_save).and_return({}) exception = double("404 error", :code => "404") - expect(@rest).to receive(:put_rest).and_raise(Net::HTTPServerException.new("foo", exception)) - expect(@rest).to receive(:post_rest).with("nodes", {}) + expect(@rest).to receive(:put).and_raise(Net::HTTPServerException.new("foo", exception)) + expect(@rest).to receive(:post).with("nodes", {}) node.save end @@ -1343,8 +1349,8 @@ describe Chef::Node do end it "should not save" do node.name("monkey") - expect(@rest).not_to receive(:put_rest) - expect(@rest).not_to receive(:post_rest) + expect(@rest).not_to receive(:put) + expect(@rest).not_to receive(:post) node.save end end @@ -1388,7 +1394,7 @@ describe Chef::Node do node.name("picky-monkey") allow(node).to receive(:for_json).and_return(data) - expect(@rest).to receive(:put_rest).with("nodes/picky-monkey", selected_data).and_return("foo") + expect(@rest).to receive(:put).with("nodes/picky-monkey", selected_data).and_return("foo") node.save end @@ -1422,7 +1428,7 @@ describe Chef::Node do node.name("falsey-monkey") allow(node).to receive(:for_json).and_return(data) - expect(@rest).to receive(:put_rest).with("nodes/falsey-monkey", selected_data).and_return("foo") + expect(@rest).to receive(:put).with("nodes/falsey-monkey", selected_data).and_return("foo") node.save end @@ -1445,7 +1451,7 @@ describe Chef::Node do node.name("picky-monkey") allow(node).to receive(:for_json).and_return(data) - expect(@rest).to receive(:put_rest).with("nodes/picky-monkey", selected_data).and_return("foo") + expect(@rest).to receive(:put).with("nodes/picky-monkey", selected_data).and_return("foo") node.save end end @@ -1461,12 +1467,12 @@ describe Chef::Node do context "and the server supports policyfile attributes in node JSON" do it "creates the object normally" do - expect(@rest).to receive(:post_rest).with("nodes", node.for_json) + expect(@rest).to receive(:post).with("nodes", node.for_json) node.create end it "saves the node object normally" do - expect(@rest).to receive(:put_rest).with("nodes/example-node", node.for_json) + expect(@rest).to receive(:put).with("nodes/example-node", node.for_json) node.save end end @@ -1514,8 +1520,8 @@ describe Chef::Node do context "when the node exists" do it "falls back to saving without policyfile attributes" do - expect(@rest).to receive(:put_rest).with("nodes/example-node", node.for_json).and_raise(http_exception) - expect(@rest).to receive(:put_rest).with("nodes/example-node", trimmed_node).and_return(@node) + expect(@rest).to receive(:put).with("nodes/example-node", node.for_json).and_raise(http_exception) + expect(@rest).to receive(:put).with("nodes/example-node", trimmed_node).and_return(@node) expect { node.save }.to_not raise_error end @@ -1536,15 +1542,15 @@ describe Chef::Node do end it "falls back to saving without policyfile attributes" do - expect(@rest).to receive(:put_rest).with("nodes/example-node", node.for_json).and_raise(http_exception) - expect(@rest).to receive(:put_rest).with("nodes/example-node", trimmed_node).and_raise(http_exception_404) - expect(@rest).to receive(:post_rest).with("nodes", trimmed_node).and_return(@node) + expect(@rest).to receive(:put).with("nodes/example-node", node.for_json).and_raise(http_exception) + expect(@rest).to receive(:put).with("nodes/example-node", trimmed_node).and_raise(http_exception_404) + expect(@rest).to receive(:post).with("nodes", trimmed_node).and_return(@node) node.save end it "creates the node without policyfile attributes" do - expect(@rest).to receive(:post_rest).with("nodes", node.for_json).and_raise(http_exception) - expect(@rest).to receive(:post_rest).with("nodes", trimmed_node).and_return(@node) + expect(@rest).to receive(:post).with("nodes", node.for_json).and_raise(http_exception) + expect(@rest).to receive(:post).with("nodes", trimmed_node).and_return(@node) node.create end end diff --git a/spec/unit/org_spec.rb b/spec/unit/org_spec.rb index cd6cc94d91..97e1b87704 100644 --- a/spec/unit/org_spec.rb +++ b/spec/unit/org_spec.rb @@ -136,7 +136,7 @@ describe Chef::Org do let(:rest) do Chef::Config[:chef_server_root] = "http://www.example.com" r = double('rest') - allow(Chef::REST).to receive(:new).and_return(r) + allow(Chef::ServerAPI).to receive(:new).and_return(r) r end @@ -151,27 +151,27 @@ describe Chef::Org do let(:inflated_response) { {"foobar" => org } } it "lists all orgs" do - expect(rest).to receive(:get_rest).with("organizations").and_return(response) + expect(rest).to receive(:get).with("organizations").and_return(response) expect(Chef::Org.list).to eq(response) end it "inflate all orgs" do allow(Chef::Org).to receive(:load).with("foobar").and_return(org) - expect(rest).to receive(:get_rest).with("organizations").and_return(response) + expect(rest).to receive(:get).with("organizations").and_return(response) expect(Chef::Org.list(true)).to eq(inflated_response) end end describe "create" do it "creates a new org via the API" do - expect(rest).to receive(:post_rest).with("organizations", {:name => "foobar", :full_name => "foo bar bat"}).and_return({}) + expect(rest).to receive(:post).with("organizations", {:name => "foobar", :full_name => "foo bar bat"}).and_return({}) org.create end end describe "read" do it "loads a named org from the API" do - expect(rest).to receive(:get_rest).with("organizations/foobar").and_return({"name" => "foobar", "full_name" => "foo bar bat", "private_key" => "private"}) + expect(rest).to receive(:get).with("organizations/foobar").and_return({"name" => "foobar", "full_name" => "foo bar bat", "private_key" => "private"}) org = Chef::Org.load("foobar") expect(org.name).to eq("foobar") expect(org.full_name).to eq("foo bar bat") @@ -181,14 +181,14 @@ describe Chef::Org do describe "update" do it "updates an existing org on via the API" do - expect(rest).to receive(:put_rest).with("organizations/foobar", {:name => "foobar", :full_name => "foo bar bat"}).and_return({}) + expect(rest).to receive(:put).with("organizations/foobar", {:name => "foobar", :full_name => "foo bar bat"}).and_return({}) org.update end end describe "destroy" do it "deletes the specified org via the API" do - expect(rest).to receive(:delete_rest).with("organizations/foobar") + expect(rest).to receive(:delete).with("organizations/foobar") org.destroy end end diff --git a/spec/unit/policy_builder/expand_node_object_spec.rb b/spec/unit/policy_builder/expand_node_object_spec.rb index 306d677108..944d4d3387 100644 --- a/spec/unit/policy_builder/expand_node_object_spec.rb +++ b/spec/unit/policy_builder/expand_node_object_spec.rb @@ -290,7 +290,7 @@ describe Chef::PolicyBuilder::ExpandNodeObject do node end - let(:chef_http) { double("Chef::REST") } + let(:chef_http) { double("Chef::ServerAPI") } let(:cookbook_resolve_url) { "environments/#{node.chef_environment}/cookbook_versions" } let(:cookbook_resolve_post_data) { {:run_list=>["first::default", "second::default"]} } @@ -298,7 +298,8 @@ describe Chef::PolicyBuilder::ExpandNodeObject do # cookbook_hash is just a hash, but since we're passing it between mock # objects, we get a little better test strictness by using a double (which # will have object equality rather than semantic equality #== semantics). - let(:cookbook_hash) { double("cookbook hash", :each => nil) } + let(:cookbook_hash) { double("cookbook hash") } + let(:expanded_cookbook_hash) { double("expanded cookbook hash", :each => nil) } let(:cookbook_synchronizer) { double("CookbookSynchronizer") } @@ -310,8 +311,9 @@ describe Chef::PolicyBuilder::ExpandNodeObject do run_list_expansion = policy_builder.run_list_expansion + expect(cookbook_hash).to receive(:inject).and_return(expanded_cookbook_hash) expect(chef_http).to receive(:post).with(cookbook_resolve_url, cookbook_resolve_post_data).and_return(cookbook_hash) - expect(Chef::CookbookSynchronizer).to receive(:new).with(cookbook_hash, events).and_return(cookbook_synchronizer) + expect(Chef::CookbookSynchronizer).to receive(:new).with(expanded_cookbook_hash, events).and_return(cookbook_synchronizer) expect(cookbook_synchronizer).to receive(:sync_cookbooks) expect_any_instance_of(Chef::RunContext).to receive(:load).with(run_list_expansion) diff --git a/spec/unit/policy_builder/policyfile_spec.rb b/spec/unit/policy_builder/policyfile_spec.rb index ed893260c2..3dfa8d9802 100644 --- a/spec/unit/policy_builder/policyfile_spec.rb +++ b/spec/unit/policy_builder/policyfile_spec.rb @@ -98,10 +98,10 @@ describe Chef::PolicyBuilder::Policyfile do let(:err_namespace) { Chef::PolicyBuilder::Policyfile } it "configures a Chef HTTP API client" do - http = double("Chef::REST") + http = double("Chef::ServerAPI") server_url = "https://api.opscode.com/organizations/example" Chef::Config[:chef_server_url] = server_url - expect(Chef::REST).to receive(:new).with(server_url).and_return(http) + expect(Chef::ServerAPI).to receive(:new).with(server_url).and_return(http) expect(policy_builder.http_api).to eq(http) end @@ -151,7 +151,7 @@ describe Chef::PolicyBuilder::Policyfile do describe "loading policy data" do - let(:http_api) { double("Chef::REST") } + let(:http_api) { double("Chef::ServerAPI") } let(:configured_environment) { nil } diff --git a/spec/unit/provider/http_request_spec.rb b/spec/unit/provider/http_request_spec.rb index a84dd5e2a0..980458abd3 100644 --- a/spec/unit/provider/http_request_spec.rb +++ b/spec/unit/provider/http_request_spec.rb @@ -34,7 +34,7 @@ describe Chef::Provider::HttpRequest do describe "load_current_resource" do - it "should set up a Chef::REST client, with no authentication" do + it "should set up a Chef::ServerAPI client, with no authentication" do expect(Chef::HTTP::Simple).to receive(:new).with(@new_resource.url) @provider.load_current_resource end @@ -45,7 +45,7 @@ describe Chef::Provider::HttpRequest do # run_action(x) forces load_current_resource to run; # that would overwrite our supplied mock Chef::Rest # object allow(@provider).to receive(:load_current_resource).and_return(true) - @http = double("Chef::REST") + @http = double("Chef::ServerAPI") @provider.http = @http end diff --git a/spec/unit/resource_reporter_spec.rb b/spec/unit/resource_reporter_spec.rb index f2c0b8fd8b..5b991b5f38 100644 --- a/spec/unit/resource_reporter_spec.rb +++ b/spec/unit/resource_reporter_spec.rb @@ -36,8 +36,8 @@ describe Chef::ResourceReporter do before do @node = Chef::Node.new @node.name("spitfire") - @rest_client = double("Chef::REST (mock)") - allow(@rest_client).to receive(:post_rest).and_return(true) + @rest_client = double("Chef::ServerAPI (mock)") + allow(@rest_client).to receive(:post).and_return(true) @resource_reporter = Chef::ResourceReporter.new(@rest_client) @new_resource = Chef::Resource::File.new("/tmp/a-file.txt") @cookbook_name = "monkey" @@ -92,9 +92,8 @@ describe Chef::ResourceReporter do context "when chef fails" do before do - allow(@rest_client).to receive(:create_url).and_return("reports/nodes/spitfire/runs/#{@run_id}"); - allow(@rest_client).to receive(:raw_http_request).and_return({"result"=>"ok"}); - allow(@rest_client).to receive(:post_rest).and_return({"uri"=>"https://example.com/reports/nodes/spitfire/runs/#{@run_id}"}); + allow(@rest_client).to receive(:raw_request).and_return({"result"=>"ok"}); + allow(@rest_client).to receive(:post).and_return({"uri"=>"https://example.com/reports/nodes/spitfire/runs/#{@run_id}"}); end @@ -260,9 +259,8 @@ describe Chef::ResourceReporter do describe "when generating a report for the server" do before do - allow(@rest_client).to receive(:create_url).and_return("reports/nodes/spitfire/runs/#{@run_id}"); - allow(@rest_client).to receive(:raw_http_request).and_return({"result"=>"ok"}); - allow(@rest_client).to receive(:post_rest).and_return({"uri"=>"https://example.com/reports/nodes/spitfire/runs/#{@run_id}"}); + allow(@rest_client).to receive(:raw_request).and_return({"result"=>"ok"}); + allow(@rest_client).to receive(:post).and_return({"uri"=>"https://example.com/reports/nodes/spitfire/runs/#{@run_id}"}); @resource_reporter.run_started(@run_status) end @@ -592,7 +590,7 @@ describe Chef::ResourceReporter do # 404 getting the run_id @response = Net::HTTPNotFound.new("a response body", "404", "Not Found") @error = Net::HTTPServerException.new("404 message", @response) - expect(@rest_client).to receive(:post_rest). + expect(@rest_client).to receive(:post). with("reports/nodes/spitfire/runs", {:action => :start, :run_id => @run_id, :start_time => @start_time.to_s}, {'X-Ops-Reporting-Protocol-Version' => Chef::ResourceReporter::PROTOCOL_VERSION}). @@ -606,7 +604,7 @@ describe Chef::ResourceReporter do it "does not send a resource report to the server" do @resource_reporter.run_started(@run_status) - expect(@rest_client).not_to receive(:post_rest) + expect(@rest_client).not_to receive(:post) @resource_reporter.run_completed(@node) end @@ -622,7 +620,7 @@ describe Chef::ResourceReporter do # 500 getting the run_id @response = Net::HTTPInternalServerError.new("a response body", "500", "Internal Server Error") @error = Net::HTTPServerException.new("500 message", @response) - expect(@rest_client).to receive(:post_rest). + expect(@rest_client).to receive(:post). with("reports/nodes/spitfire/runs", {:action => :start, :run_id => @run_id, :start_time => @start_time.to_s}, {'X-Ops-Reporting-Protocol-Version' => Chef::ResourceReporter::PROTOCOL_VERSION}). and_raise(@error) @@ -635,7 +633,7 @@ describe Chef::ResourceReporter do it "does not send a resource report to the server" do @resource_reporter.run_started(@run_status) - expect(@rest_client).not_to receive(:post_rest) + expect(@rest_client).not_to receive(:post) @resource_reporter.run_completed(@node) end @@ -652,7 +650,7 @@ describe Chef::ResourceReporter do # 500 getting the run_id @response = Net::HTTPInternalServerError.new("a response body", "500", "Internal Server Error") @error = Net::HTTPServerException.new("500 message", @response) - expect(@rest_client).to receive(:post_rest). + expect(@rest_client).to receive(:post). with("reports/nodes/spitfire/runs", {:action => :start, :run_id => @run_id, :start_time => @start_time.to_s}, {'X-Ops-Reporting-Protocol-Version' => Chef::ResourceReporter::PROTOCOL_VERSION}). and_raise(@error) @@ -673,7 +671,7 @@ describe Chef::ResourceReporter do context "after creating the run history document" do before do response = {"uri"=>"https://example.com/reports/nodes/spitfire/runs/@run_id"} - expect(@rest_client).to receive(:post_rest). + expect(@rest_client).to receive(:post). with("reports/nodes/spitfire/runs", {:action => :start, :run_id => @run_id, :start_time => @start_time.to_s}, {'X-Ops-Reporting-Protocol-Version' => Chef::ResourceReporter::PROTOCOL_VERSION}). and_return(response) @@ -693,16 +691,10 @@ describe Chef::ResourceReporter do allow(@resource_reporter).to receive(:end_time).and_return(@end_time) @expected_data = @resource_reporter.prepare_run_data - post_url = "https://chef_server/example_url" response = {"result"=>"ok"} - expect(@rest_client).to receive(:create_url). - with("reports/nodes/spitfire/runs/#{@run_id}"). - ordered. - and_return(post_url) - expect(@rest_client).to receive(:raw_http_request).ordered do |method, url, headers, data| + expect(@rest_client).to receive(:raw_request).ordered do |method, url, headers, data| expect(method).to eq(:POST) - expect(url).to eq(post_url) expect(headers).to eq({'Content-Encoding' => 'gzip', 'X-Ops-Reporting-Protocol-Version' => Chef::ResourceReporter::PROTOCOL_VERSION }) @@ -720,8 +712,6 @@ describe Chef::ResourceReporter do before do @enable_reporting_url_fatals = Chef::Config[:enable_reporting_url_fatals] Chef::Config[:enable_reporting_url_fatals] = true - # this call doesn't matter for this context - allow(@rest_client).to receive(:create_url) end after do @@ -731,7 +721,7 @@ describe Chef::ResourceReporter do it "should log 4xx errors" do response = Net::HTTPClientError.new("forbidden", "403", "Forbidden") error = Net::HTTPServerException.new("403 message", response) - allow(@rest_client).to receive(:raw_http_request).and_raise(error) + allow(@rest_client).to receive(:raw_request).and_raise(error) expect(Chef::Log).to receive(:error).with(/403/) @resource_reporter.post_reporting_data @@ -740,14 +730,14 @@ describe Chef::ResourceReporter do it "should log error 5xx errors" do response = Net::HTTPServerError.new("internal error", "500", "Internal Server Error") error = Net::HTTPFatalError.new("500 message", response) - allow(@rest_client).to receive(:raw_http_request).and_raise(error) + allow(@rest_client).to receive(:raw_request).and_raise(error) expect(Chef::Log).to receive(:error).with(/500/) @resource_reporter.post_reporting_data end it "should log if a socket error happens" do - allow(@rest_client).to receive(:raw_http_request).and_raise(SocketError.new("test socket error")) + allow(@rest_client).to receive(:raw_request).and_raise(SocketError.new("test socket error")) expect(Chef::Log).to receive(:error).with(/test socket error/) @resource_reporter.post_reporting_data @@ -755,7 +745,7 @@ describe Chef::ResourceReporter do end it "should raise if an unkwown error happens" do - allow(@rest_client).to receive(:raw_http_request).and_raise(Exception.new) + allow(@rest_client).to receive(:raw_request).and_raise(Exception.new) expect { @resource_reporter.post_reporting_data diff --git a/spec/unit/role_spec.rb b/spec/unit/role_spec.rb index ecc7945a08..6e9b133c50 100644 --- a/spec/unit/role_spec.rb +++ b/spec/unit/role_spec.rb @@ -201,7 +201,7 @@ describe Chef::Role do describe "and it has per-environment run lists" do before do @role.env_run_lists("_default" => ['one', 'two', 'role[a]'], "production" => ['role[monitoring]', 'role[auditing]', 'role[apache]'], "dev" => ["role[nginx]"]) - @serialized_role = Chef::JSONCompat.from_json(Chef::JSONCompat.to_json(@role), :create_additions => false) + @serialized_role = Chef::JSONCompat.parse(Chef::JSONCompat.to_json(@role), :create_additions => false) end it "includes the per-environment run lists" do @@ -229,7 +229,7 @@ describe Chef::Role do @role.run_list('one', 'two', 'role[a]') @role.default_attributes({ 'el_groupo' => 'nuevo' }) @role.override_attributes({ 'deloused' => 'in the comatorium' }) - @deserial = Chef::JSONCompat.from_json(Chef::JSONCompat.to_json(@role)) + @deserial = Chef::Role.from_hash(Chef::JSONCompat.parse(Chef::JSONCompat.to_json(@role))) end it "should deserialize to a Chef::Role object" do diff --git a/spec/unit/run_list_spec.rb b/spec/unit/run_list_spec.rb index e150579431..634b5c54cf 100644 --- a/spec/unit/run_list_spec.rb +++ b/spec/unit/run_list_spec.rb @@ -172,10 +172,11 @@ describe Chef::RunList do @role.run_list "one", "two" @role.default_attributes :one => :two @role.override_attributes :three => :four + @role.env_run_list["production"] = Chef::RunList.new( "one", "two", "five") allow(Chef::Role).to receive(:load).and_return(@role) - @rest = double("Chef::REST", { :get_rest => @role, :url => "/" }) - allow(Chef::REST).to receive(:new).and_return(@rest) + @rest = double("Chef::ServerAPI", { :get => @role.to_hash, :url => "/" }) + allow(Chef::ServerAPI).to receive(:new).and_return(@rest) @run_list << "role[stubby]" @run_list << "kitty" @@ -196,21 +197,17 @@ describe Chef::RunList do describe "from the chef server" do it "should load the role from the chef server" do - #@rest.should_receive(:get_rest).with("roles/stubby") + #@rest.should_receive(:get).with("roles/stubby") expansion = @run_list.expand("_default", "server") expect(expansion.recipes).to eq(['one', 'two', 'kitty']) end it "should default to expanding from the server" do - expect(@rest).to receive(:get_rest).with("roles/stubby") + expect(@rest).to receive(:get).with("roles/stubby") @run_list.expand("_default") end describe "with an environment set" do - before do - @role.env_run_list["production"] = Chef::RunList.new( "one", "two", "five") - end - it "expands the run list using the environment specific run list" do expansion = @run_list.expand("production", "server") expect(expansion.recipes).to eq(%w{one two five kitty}) @@ -218,7 +215,7 @@ describe Chef::RunList do describe "and multiply nested roles" do before do - @multiple_rest_requests = double("Chef::REST") + @multiple_rest_requests = double("Chef::ServerAPI") @role.env_run_list["production"] << "role[prod-base]" @@ -233,10 +230,10 @@ describe Chef::RunList do end it "expands the run list using the specified environment for all nested roles" do - allow(Chef::REST).to receive(:new).and_return(@multiple_rest_requests) - expect(@multiple_rest_requests).to receive(:get_rest).with("roles/stubby").and_return(@role) - expect(@multiple_rest_requests).to receive(:get_rest).with("roles/prod-base").and_return(@role_prod_base) - expect(@multiple_rest_requests).to receive(:get_rest).with("roles/nested-deeper").and_return(@role_nested_deeper) + allow(Chef::ServerAPI).to receive(:new).and_return(@multiple_rest_requests) + expect(@multiple_rest_requests).to receive(:get).with("roles/stubby").and_return(@role.to_hash) + expect(@multiple_rest_requests).to receive(:get).with("roles/prod-base").and_return(@role_prod_base.to_hash) + expect(@multiple_rest_requests).to receive(:get).with("roles/nested-deeper").and_return(@role_nested_deeper.to_hash) expansion = @run_list.expand("production", "server") expect(expansion.recipes).to eq(%w{one two five prod-secret-sauce kitty}) diff --git a/spec/unit/search/query_spec.rb b/spec/unit/search/query_spec.rb index f85b1760d4..c390f658bc 100644 --- a/spec/unit/search/query_spec.rb +++ b/spec/unit/search/query_spec.rb @@ -20,7 +20,7 @@ require 'spec_helper' require 'chef/search/query' describe Chef::Search::Query do - let(:rest) { double("Chef::REST") } + let(:rest) { double("Chef::ServerAPI") } let(:query) { Chef::Search::Query.new } shared_context "filtered search" do @@ -76,8 +76,8 @@ describe Chef::Search::Query do end before(:each) do - allow(Chef::REST).to receive(:new).and_return(rest) - allow(rest).to receive(:get_rest).and_return(response) + allow(Chef::ServerAPI).to receive(:new).and_return(rest) + allow(rest).to receive(:get).and_return(response) end describe "search" do @@ -91,6 +91,7 @@ describe Chef::Search::Query do { "name" => "my-name-is-node", "chef_environment" => "elysium", "platform" => "rhel", + "run_list" => [], "automatic" => { "languages" => { "ruby" => { @@ -104,6 +105,7 @@ describe Chef::Search::Query do { "name" => "my-name-is-jonas", "chef_environment" => "hades", "platform" => "rhel", + "run_list" => [], "automatic" => { "languages" => { "ruby" => { @@ -117,6 +119,7 @@ describe Chef::Search::Query do { "name" => "my-name-is-flipper", "chef_environment" => "elysium", "platform" => "rhel", + "run_list" => [], "automatic" => { "languages" => { "ruby" => { @@ -130,6 +133,7 @@ describe Chef::Search::Query do { "name" => "my-name-is-butters", "chef_environment" => "moon", "platform" => "rhel", + "run_list" => [], "automatic" => { "languages" => { "ruby" => { @@ -173,27 +177,27 @@ describe Chef::Search::Query do end it "queries for every object of a type by default" do - expect(rest).to receive(:get_rest).with("search/node?q=*:*&sort=X_CHEF_id_CHEF_X%20asc&start=0").and_return(response) + expect(rest).to receive(:get).with("search/node?q=*:*&sort=X_CHEF_id_CHEF_X%20asc&start=0").and_return(response) query.search(:node) end it "allows a custom query" do - expect(rest).to receive(:get_rest).with("search/node?q=platform:rhel&sort=X_CHEF_id_CHEF_X%20asc&start=0").and_return(response) + expect(rest).to receive(:get).with("search/node?q=platform:rhel&sort=X_CHEF_id_CHEF_X%20asc&start=0").and_return(response) query.search(:node, "platform:rhel") end it "lets you set a sort order" do - expect(rest).to receive(:get_rest).with("search/node?q=platform:rhel&sort=id%20desc&start=0").and_return(response) + expect(rest).to receive(:get).with("search/node?q=platform:rhel&sort=id%20desc&start=0").and_return(response) query.search(:node, "platform:rhel", sort: "id desc") end it "lets you set a starting object" do - expect(rest).to receive(:get_rest).with("search/node?q=platform:rhel&sort=X_CHEF_id_CHEF_X%20asc&start=2").and_return(response) + expect(rest).to receive(:get).with("search/node?q=platform:rhel&sort=X_CHEF_id_CHEF_X%20asc&start=2").and_return(response) query.search(:node, "platform:rhel", start: 2) end it "lets you set how many rows to return" do - expect(rest).to receive(:get_rest).with("search/node?q=platform:rhel&sort=X_CHEF_id_CHEF_X%20asc&start=0&rows=40").and_return(response) + expect(rest).to receive(:get).with("search/node?q=platform:rhel&sort=X_CHEF_id_CHEF_X%20asc&start=0&rows=40").and_return(response) query.search(:node, "platform:rhel", rows: 40) end @@ -211,27 +215,27 @@ describe Chef::Search::Query do it "calls a block for each object in the response" do @call_me = double("blocky") - response["rows"].each { |r| expect(@call_me).to receive(:do).with(r) } + response["rows"].each { |r| expect(@call_me).to receive(:do).with(Chef::Node.from_hash(r)) } query.search(:node) { |r| @call_me.do(r) } end it "pages through the responses" do @call_me = double("blocky") - response["rows"].each { |r| expect(@call_me).to receive(:do).with(r) } + response["rows"].each { |r| expect(@call_me).to receive(:do).with(Chef::Node.from_hash(r)) } query.search(:node, "*:*", sort: nil, start: 0, rows: 4) { |r| @call_me.do(r) } end it "sends multiple API requests when the server indicates there is more data" do - expect(rest).to receive(:get_rest).with(query_string).and_return(big_response) - expect(rest).to receive(:get_rest).with(query_string_continue).and_return(big_response_end) + expect(rest).to receive(:get).with(query_string).and_return(big_response) + expect(rest).to receive(:get).with(query_string_continue).and_return(big_response_end) query.search(:node, "platform:rhel") do |r| nil end end it "paginates correctly in the face of filtered nodes" do - expect(rest).to receive(:get_rest).with(query_string_with_rows).and_return(big_response_empty) - expect(rest).to receive(:get_rest).with(query_string_continue_with_rows).and_return(big_response_end) + expect(rest).to receive(:get).with(query_string_with_rows).and_return(big_response_empty) + expect(rest).to receive(:get).with(query_string_continue_with_rows).and_return(big_response_end) query.search(:node, "platform:rhel", rows: 4) do |r| nil end @@ -242,7 +246,7 @@ describe Chef::Search::Query do let(:filter_key) { :filter_result } before(:each) do - expect(rest).to receive(:post_rest).with(query_string, args[filter_key]).and_return(response) + expect(rest).to receive(:post).with(query_string, args[filter_key]).and_return(response) end it "returns start" do @@ -276,7 +280,7 @@ describe Chef::Search::Query do end it "returns an array of filtered hashes" do - expect(rest).to receive(:post_rest).with(query_string, args[filter_key]).and_return(response) + expect(rest).to receive(:post).with(query_string, args[filter_key]).and_return(response) results = query.partial_search(:node, "platform:rhel", args) expect(results[0]).to match_array(response_rows) end diff --git a/spec/unit/shell/shell_session_spec.rb b/spec/unit/shell/shell_session_spec.rb index d72e3fa1bb..d1cedb3236 100644 --- a/spec/unit/shell/shell_session_spec.rb +++ b/spec/unit/shell/shell_session_spec.rb @@ -50,7 +50,7 @@ end describe Shell::ClientSession do before do Chef::Config[:shell_config] = { :override_runlist => [Chef::RunList::RunListItem.new('shell::override')] } - @chef_rest = double("Chef::REST") + @chef_rest = double("Chef::ServerAPI") @session = Shell::ClientSession.instance @node = Chef::Node.build("foo") @session.node = @node @@ -67,7 +67,7 @@ describe Shell::ClientSession do @expansion = Chef::RunList::RunListExpansion.new(@node.chef_environment, []) expect(@node.run_list).to receive(:expand).with(@node.chef_environment).and_return(@expansion) - expect(Chef::REST).to receive(:new).with(Chef::Config[:chef_server_url]).and_return(@chef_rest) + expect(Chef::ServerAPI).to receive(:new).with(Chef::Config[:chef_server_url]).and_return(@chef_rest) @session.rebuild_context end diff --git a/spec/unit/user_v1_spec.rb b/spec/unit/user_v1_spec.rb index 8fd370a010..a981de1d8c 100644 --- a/spec/unit/user_v1_spec.rb +++ b/spec/unit/user_v1_spec.rb @@ -539,8 +539,8 @@ describe Chef::UserV1 do before (:each) do @user = Chef::UserV1.new @user.username "foobar" - @http_client = double("Chef::REST mock") - allow(Chef::REST).to receive(:new).and_return(@http_client) + @http_client = double("Chef::ServerAPI mock") + allow(Chef::ServerAPI).to receive(:new).and_return(@http_client) end describe "list" do |