diff options
author | José Valim <jose.valim@gmail.com> | 2011-05-18 06:13:44 -0700 |
---|---|---|
committer | José Valim <jose.valim@gmail.com> | 2011-05-18 06:13:44 -0700 |
commit | 505defc27ead21c3bab05aa0cde11dddfbd0d179 (patch) | |
tree | 29e31540478d0abff708db605b626823ff47008a | |
parent | 22ab2316accab46ccde0a9eaafebcfc12ed2c7a6 (diff) | |
parent | 00958696d871da3126113be70bb858d078b86ab5 (diff) | |
download | rails-505defc27ead21c3bab05aa0cde11dddfbd0d179.tar.gz rails-505defc27ead21c3bab05aa0cde11dddfbd0d179.tar.bz2 rails-505defc27ead21c3bab05aa0cde11dddfbd0d179.zip |
Merge pull request #1115 from joshk/active_resource_json_updates
ActiveResource json updates
22 files changed, 431 insertions, 407 deletions
diff --git a/activeresource/examples/simple.rb b/activeresource/examples/simple.rb deleted file mode 100644 index 6d2c6e3b1b..0000000000 --- a/activeresource/examples/simple.rb +++ /dev/null @@ -1,15 +0,0 @@ -$LOAD_PATH.unshift "#{File.dirname(__FILE__)}/../lib" -require 'active_resource' -require 'active_support/core_ext/hash/conversions' - -ActiveSupport::XmlMini.backend = ENV['XMLMINI'] || 'REXML' -ActiveResource::HttpMock.respond_to do |mock| - mock.get '/people/1.xml', {}, { :id => 1, :name => 'bob' }.to_xml(:root => 'person') -end - -class Person < ActiveResource::Base - self.site = 'http://localhost/' -end - -bob = Person.find(1) -puts bob.inspect diff --git a/activeresource/lib/active_resource/base.rb b/activeresource/lib/active_resource/base.rb index 7f2a844723..65d285249b 100644 --- a/activeresource/lib/active_resource/base.rb +++ b/activeresource/lib/active_resource/base.rb @@ -81,19 +81,19 @@ module ActiveResource # <tt>post</tt>, <tt>put</tt> and <tt>\delete</tt> methods where you can specify a custom REST method # name to invoke. # - # # POST to the custom 'register' REST method, i.e. POST /people/new/register.xml. + # # POST to the custom 'register' REST method, i.e. POST /people/new/register.json. # Person.new(:name => 'Ryan').post(:register) # # => { :id => 1, :name => 'Ryan', :position => 'Clerk' } # - # # PUT an update by invoking the 'promote' REST method, i.e. PUT /people/1/promote.xml?position=Manager. + # # PUT an update by invoking the 'promote' REST method, i.e. PUT /people/1/promote.json?position=Manager. # Person.find(1).put(:promote, :position => 'Manager') # # => { :id => 1, :name => 'Ryan', :position => 'Manager' } # - # # GET all the positions available, i.e. GET /people/positions.xml. + # # GET all the positions available, i.e. GET /people/positions.json. # Person.get(:positions) # # => [{:name => 'Manager'}, {:name => 'Clerk'}] # - # # DELETE to 'fire' a person, i.e. DELETE /people/1/fire.xml. + # # DELETE to 'fire' a person, i.e. DELETE /people/1/fire.json. # Person.find(1).delete(:fire) # # For more information on using custom REST methods, see the @@ -164,7 +164,7 @@ module ActiveResource # response code will be returned from the server which will raise an ActiveResource::ResourceNotFound # exception. # - # # GET http://api.people.com:3000/people/999.xml + # # GET http://api.people.com:3000/people/999.json # ryan = Person.find(999) # 404, raises ActiveResource::ResourceNotFound # # @@ -218,7 +218,7 @@ module ActiveResource # ryan.save # => false # # # When - # # PUT http://api.people.com:3000/people/1.xml + # # PUT http://api.people.com:3000/people/1.json # # or # # PUT http://api.people.com:3000/people/1.json # # is requested with invalid values, the response is: @@ -489,7 +489,7 @@ module ActiveResource # Person.format = ActiveResource::Formats::XmlFormat # Person.find(1) # => GET /people/1.xml # - # Default format is <tt>:xml</tt>. + # Default format is <tt>:json</tt>. def format=(mime_type_reference_or_format) format = mime_type_reference_or_format.is_a?(Symbol) ? ActiveResource::Formats[mime_type_reference_or_format] : mime_type_reference_or_format @@ -498,9 +498,9 @@ module ActiveResource connection.format = format if site end - # Returns the current format, default is ActiveResource::Formats::XmlFormat. + # Returns the current format, default is ActiveResource::Formats::JsonFormat. def format - self._format || ActiveResource::Formats::XmlFormat + self._format || ActiveResource::Formats::JsonFormat end # Sets the number of seconds after which requests to the REST API should time out. @@ -570,7 +570,7 @@ module ActiveResource attr_accessor_with_default(:primary_key, 'id') #:nodoc: - # Gets the \prefix for a resource's nested URL (e.g., <tt>prefix/collectionname/1.xml</tt>) + # Gets the \prefix for a resource's nested URL (e.g., <tt>prefix/collectionname/1.json</tt>) # This method is regenerated at runtime based on what the \prefix is set to. def prefix(options={}) default = site.path @@ -587,7 +587,7 @@ module ActiveResource prefix_source end - # Sets the \prefix for a resource's nested URL (e.g., <tt>prefix/collectionname/1.xml</tt>). + # Sets the \prefix for a resource's nested URL (e.g., <tt>prefix/collectionname/1.json</tt>). # Default value is <tt>site.path</tt>. def prefix=(value = '/') # Replace :placeholders with '#{embedded options[:lookups]}' @@ -618,21 +618,21 @@ module ActiveResource # # ==== Options # +prefix_options+ - A \hash to add a \prefix to the request for nested URLs (e.g., <tt>:account_id => 19</tt> - # would yield a URL like <tt>/accounts/19/purchases.xml</tt>). + # would yield a URL like <tt>/accounts/19/purchases.json</tt>). # +query_options+ - A \hash to add items to the query string for the request. # # ==== Examples # Post.element_path(1) - # # => /posts/1.xml + # # => /posts/1.json # # Comment.element_path(1, :post_id => 5) - # # => /posts/5/comments/1.xml + # # => /posts/5/comments/1.json # # Comment.element_path(1, :post_id => 5, :active => 1) - # # => /posts/5/comments/1.xml?active=1 + # # => /posts/5/comments/1.json?active=1 # # Comment.element_path(1, {:post_id => 5}, {:active => 1}) - # # => /posts/5/comments/1.xml?active=1 + # # => /posts/5/comments/1.json?active=1 # def element_path(id, prefix_options = {}, query_options = nil) check_prefix_options(prefix_options) @@ -645,14 +645,14 @@ module ActiveResource # # ==== Options # * +prefix_options+ - A hash to add a prefix to the request for nested URLs (e.g., <tt>:account_id => 19</tt> - # would yield a URL like <tt>/accounts/19/purchases/new.xml</tt>). + # would yield a URL like <tt>/accounts/19/purchases/new.json</tt>). # # ==== Examples # Post.new_element_path - # # => /posts/new.xml + # # => /posts/new.json # # Comment.collection_path(:post_id => 5) - # # => /posts/5/comments/new.xml + # # => /posts/5/comments/new.json def new_element_path(prefix_options = {}) "#{prefix(prefix_options)}#{collection_name}/new.#{format.extension}" end @@ -662,21 +662,21 @@ module ActiveResource # # ==== Options # * +prefix_options+ - A hash to add a prefix to the request for nested URLs (e.g., <tt>:account_id => 19</tt> - # would yield a URL like <tt>/accounts/19/purchases.xml</tt>). + # would yield a URL like <tt>/accounts/19/purchases.json</tt>). # * +query_options+ - A hash to add items to the query string for the request. # # ==== Examples # Post.collection_path - # # => /posts.xml + # # => /posts.json # # Comment.collection_path(:post_id => 5) - # # => /posts/5/comments.xml + # # => /posts/5/comments.json # # Comment.collection_path(:post_id => 5, :active => 1) - # # => /posts/5/comments.xml?active=1 + # # => /posts/5/comments.json?active=1 # # Comment.collection_path({:post_id => 5}, {:active => 1}) - # # => /posts/5/comments.xml?active=1 + # # => /posts/5/comments.json?active=1 # def collection_path(prefix_options = {}, query_options = nil) check_prefix_options(prefix_options) @@ -745,34 +745,34 @@ module ActiveResource # # ==== Examples # Person.find(1) - # # => GET /people/1.xml + # # => GET /people/1.json # # Person.find(:all) - # # => GET /people.xml + # # => GET /people.json # # Person.find(:all, :params => { :title => "CEO" }) - # # => GET /people.xml?title=CEO + # # => GET /people.json?title=CEO # # Person.find(:first, :from => :managers) - # # => GET /people/managers.xml + # # => GET /people/managers.json # # Person.find(:last, :from => :managers) - # # => GET /people/managers.xml + # # => GET /people/managers.json # - # Person.find(:all, :from => "/companies/1/people.xml") - # # => GET /companies/1/people.xml + # Person.find(:all, :from => "/companies/1/people.json") + # # => GET /companies/1/people.json # # Person.find(:one, :from => :leader) - # # => GET /people/leader.xml + # # => GET /people/leader.json # # Person.find(:all, :from => :developers, :params => { :language => 'ruby' }) - # # => GET /people/developers.xml?language=ruby + # # => GET /people/developers.json?language=ruby # - # Person.find(:one, :from => "/companies/1/manager.xml") - # # => GET /companies/1/manager.xml + # Person.find(:one, :from => "/companies/1/manager.json") + # # => GET /companies/1/manager.json # # StreetAddress.find(1, :params => { :person_id => 1 }) - # # => GET /people/1/street_addresses/1.xml + # # => GET /people/1/street_addresses/1.json # # == Failure or missing data # A failure to find the requested object raises a ResourceNotFound @@ -833,7 +833,7 @@ module ActiveResource # my_event = Event.find(:first) # let's assume this is event with ID 7 # Event.delete(my_event.id) # sends DELETE /events/7 # - # # Let's assume a request to events/5/cancel.xml + # # Let's assume a request to events/5/cancel.json # Event.delete(params[:id]) # sends DELETE /events/5 def delete(id, options = {}) connection.delete(element_path(id, options)) @@ -1121,7 +1121,7 @@ module ActiveResource # Saves (+POST+) or \updates (+PUT+) a resource. Delegates to +create+ if the object is \new, # +update+ if it exists. If the response to the \save includes a body, it will be assumed that this body - # is XML for the final object as it looked after the \save (which would include attributes like +created_at+ + # is Json for the final object as it looked after the \save (which would include attributes like +created_at+ # that weren't part of the original submit). # # ==== Examples @@ -1232,9 +1232,16 @@ module ActiveResource # your_supplier = Supplier.new # your_supplier.load(my_attrs) # your_supplier.save - def load(attributes) + def load(attributes, remove_root = false) raise ArgumentError, "expected an attributes Hash, got #{attributes.inspect}" unless attributes.is_a?(Hash) @prefix_options, attributes = split_options(attributes) + + if attributes.keys.size == 1 + remove_root = self.class.element_name == attributes.keys.first.to_s + end + + attributes = Formats.remove_root(attributes) if remove_root + attributes.each do |key, value| @attributes[key.to_s] = case value @@ -1285,7 +1292,7 @@ module ActiveResource # resource's attributes, the full body of the request will still be sent # in the save request to the remote service. def update_attributes(attributes) - load(attributes) && save + load(attributes, false) && save end # For checking <tt>respond_to?</tt> without searching the attributes (which is faster). @@ -1339,7 +1346,7 @@ module ActiveResource def load_attributes_from_response(response) if !response['Content-Length'].blank? && response['Content-Length'] != "0" && !response.body.nil? && response.body.strip.size > 0 - load(self.class.format.decode(response.body)) + load(self.class.format.decode(response.body), true) @persisted = true end end diff --git a/activeresource/lib/active_resource/connection.rb b/activeresource/lib/active_resource/connection.rb index 765575d866..d923204dde 100644 --- a/activeresource/lib/active_resource/connection.rb +++ b/activeresource/lib/active_resource/connection.rb @@ -30,7 +30,7 @@ module ActiveResource # The +site+ parameter is required and will set the +site+ # attribute to the URI for the remote resource service. - def initialize(site, format = ActiveResource::Formats::XmlFormat) + def initialize(site, format = ActiveResource::Formats::JsonFormat) raise ArgumentError, 'Missing site URI' unless site @user = @password = nil self.site = site diff --git a/activeresource/lib/active_resource/custom_methods.rb b/activeresource/lib/active_resource/custom_methods.rb index 9879f8cded..c1931b2758 100644 --- a/activeresource/lib/active_resource/custom_methods.rb +++ b/activeresource/lib/active_resource/custom_methods.rb @@ -11,10 +11,10 @@ module ActiveResource # # This route set creates routes for the following HTTP requests: # - # POST /people/new/register.xml # PeopleController.register - # PUT /people/1/promote.xml # PeopleController.promote with :id => 1 - # DELETE /people/1/deactivate.xml # PeopleController.deactivate with :id => 1 - # GET /people/active.xml # PeopleController.active + # POST /people/new/register.json # PeopleController.register + # PUT /people/1/promote.json # PeopleController.promote with :id => 1 + # DELETE /people/1/deactivate.json # PeopleController.deactivate with :id => 1 + # GET /people/active.json # PeopleController.active # # Using this module, Active Resource can use these custom REST methods just like the # standard methods. @@ -23,13 +23,13 @@ module ActiveResource # self.site = "http://37s.sunrise.i:3000" # end # - # Person.new(:name => 'Ryan).post(:register) # POST /people/new/register.xml + # Person.new(:name => 'Ryan).post(:register) # POST /people/new/register.json # # => { :id => 1, :name => 'Ryan' } # - # Person.find(1).put(:promote, :position => 'Manager') # PUT /people/1/promote.xml - # Person.find(1).delete(:deactivate) # DELETE /people/1/deactivate.xml + # Person.find(1).put(:promote, :position => 'Manager') # PUT /people/1/promote.json + # Person.find(1).delete(:deactivate) # DELETE /people/1/deactivate.json # - # Person.get(:active) # GET /people/active.xml + # Person.get(:active) # GET /people/active.json # # => [{:id => 1, :name => 'Ryan'}, {:id => 2, :name => 'Joe'}] # module CustomMethods @@ -41,10 +41,10 @@ module ActiveResource # Invokes a GET to a given custom REST method. For example: # - # Person.get(:active) # GET /people/active.xml + # Person.get(:active) # GET /people/active.json # # => [{:id => 1, :name => 'Ryan'}, {:id => 2, :name => 'Joe'}] # - # Person.get(:active, :awesome => true) # GET /people/active.xml?awesome=true + # Person.get(:active, :awesome => true) # GET /people/active.json?awesome=true # # => [{:id => 1, :name => 'Ryan'}] # # Note: the objects returned from this method are not automatically converted @@ -54,7 +54,9 @@ module ActiveResource # # Person.find(:all, :from => :active) def get(custom_method_name, options = {}) - format.decode(connection.get(custom_method_collection_url(custom_method_name, options), headers).body) + hashified = format.decode(connection.get(custom_method_collection_url(custom_method_name, options), headers).body) + derooted = Formats.remove_root(hashified) + derooted.is_a?(Array) ? derooted.map { |e| Formats.remove_root(e) } : derooted end def post(custom_method_name, options = {}, body = '') diff --git a/activeresource/lib/active_resource/formats.rb b/activeresource/lib/active_resource/formats.rb index 53b75b34e7..f7ad689cc5 100644 --- a/activeresource/lib/active_resource/formats.rb +++ b/activeresource/lib/active_resource/formats.rb @@ -10,5 +10,13 @@ module ActiveResource def self.[](mime_type_reference) ActiveResource::Formats.const_get(ActiveSupport::Inflector.camelize(mime_type_reference.to_s) + "Format") end + + def self.remove_root(data) + if data.is_a?(Hash) && data.keys.size == 1 + data.values.first + else + data + end + end end end diff --git a/activeresource/lib/active_resource/formats/json_format.rb b/activeresource/lib/active_resource/formats/json_format.rb index 9980634921..827d1cc23a 100644 --- a/activeresource/lib/active_resource/formats/json_format.rb +++ b/activeresource/lib/active_resource/formats/json_format.rb @@ -18,7 +18,7 @@ module ActiveResource end def decode(json) - ActiveSupport::JSON.decode(json) + Formats.remove_root(ActiveSupport::JSON.decode(json)) end end end diff --git a/activeresource/lib/active_resource/formats/xml_format.rb b/activeresource/lib/active_resource/formats/xml_format.rb index 3b2575cfa1..49cb9aa1ac 100644 --- a/activeresource/lib/active_resource/formats/xml_format.rb +++ b/activeresource/lib/active_resource/formats/xml_format.rb @@ -18,19 +18,8 @@ module ActiveResource end def decode(xml) - from_xml_data(Hash.from_xml(xml)) + Formats.remove_root(Hash.from_xml(xml)) end - - private - # Manipulate from_xml Hash, because xml_simple is not exactly what we - # want for Active Resource. - def from_xml_data(data) - if data.is_a?(Hash) && data.keys.size == 1 - data.values.first - else - data - end - end end end end diff --git a/activeresource/lib/active_resource/http_mock.rb b/activeresource/lib/active_resource/http_mock.rb index 3bfd536b29..e90580be4f 100644 --- a/activeresource/lib/active_resource/http_mock.rb +++ b/activeresource/lib/active_resource/http_mock.rb @@ -20,10 +20,10 @@ module ActiveResource # * <tt>path</tt> - A string, starting with a "/", defining the URI that is expected to be # called. # * <tt>request_headers</tt> - Headers that are expected along with the request. This argument uses a - # hash format, such as <tt>{ "Content-Type" => "application/xml" }</tt>. This mock will only trigger + # hash format, such as <tt>{ "Content-Type" => "application/json" }</tt>. This mock will only trigger # if your tests sends a request with identical headers. # * <tt>body</tt> - The data to be returned. This should be a string of Active Resource parseable content, - # such as XML. + # such as Json. # * <tt>status</tt> - The HTTP response code, as an integer, to return with the response. # * <tt>response_headers</tt> - Headers to be returned with the response. Uses the same hash format as # <tt>request_headers</tt> listed above. @@ -35,12 +35,12 @@ module ActiveResource # # ==== Example # def setup - # @matz = { :id => 1, :name => "Matz" }.to_xml(:root => "person") + # @matz = { :person => { :id => 1, :name => "Matz" } }.to_json # ActiveResource::HttpMock.respond_to do |mock| - # mock.post "/people.xml", {}, @matz, 201, "Location" => "/people/1.xml" - # mock.get "/people/1.xml", {}, @matz - # mock.put "/people/1.xml", {}, nil, 204 - # mock.delete "/people/1.xml", {}, nil, 200 + # mock.post "/people.json", {}, @matz, 201, "Location" => "/people/1.json" + # mock.get "/people/1.json", {}, @matz + # mock.put "/people/1.json", {}, nil, 204 + # mock.delete "/people/1.json", {}, nil, 200 # end # end # @@ -85,9 +85,9 @@ module ActiveResource # # ==== Example # def setup - # @matz = { :id => 1, :name => "Matz" }.to_xml(:root => "person") + # @matz = { :person => { :id => 1, :name => "Matz" } }.to_json # ActiveResource::HttpMock.respond_to do |mock| - # mock.get "/people/1.xml", {}, @matz + # mock.get "/people/1.json", {}, @matz # end # end # @@ -95,7 +95,7 @@ module ActiveResource # person = Person.find(1) # Call the remote service # # # This request object has the same HTTP method and path as declared by the mock - # expected_request = ActiveResource::Request.new(:get, "/people/1.xml") + # expected_request = ActiveResource::Request.new(:get, "/people/1.json") # # # Assert that the mock received, and responded to, the expected request from the model # assert ActiveResource::HttpMock.requests.include?(expected_request) @@ -117,12 +117,12 @@ module ActiveResource # # === Example # - # @matz = { :id => 1, :name => "Matz" }.to_xml(:root => "person") + # @matz = { :person => { :id => 1, :name => "Matz" } }.to_json # ActiveResource::HttpMock.respond_to do |mock| - # mock.post "/people.xml", {}, @matz, 201, "Location" => "/people/1.xml" - # mock.get "/people/1.xml", {}, @matz - # mock.put "/people/1.xml", {}, nil, 204 - # mock.delete "/people/1.xml", {}, nil, 200 + # mock.post "/people.json", {}, @matz, 201, "Location" => "/people/1.json" + # mock.get "/people/1.json", {}, @matz + # mock.put "/people/1.json", {}, nil, 204 + # mock.delete "/people/1.json", {}, nil, 200 # end # # Alternatively, accepts a hash of <tt>{Request => Response}</tt> pairs allowing you to generate @@ -135,11 +135,11 @@ module ActiveResource # # Request.new(:#{method}, path, nil, request_headers) # - # @matz = { :id => 1, :name => "Matz" }.to_xml(:root => "person") + # @matz = { :person => { :id => 1, :name => "Matz" } }.to_json # - # create_matz = ActiveResource::Request.new(:post, '/people.xml', @matz, {}) - # created_response = ActiveResource::Response.new("", 201, {"Location" => "/people/1.xml"}) - # get_matz = ActiveResource::Request.new(:get, '/people/1.xml', nil) + # create_matz = ActiveResource::Request.new(:post, '/people.json', @matz, {}) + # created_response = ActiveResource::Response.new("", 201, {"Location" => "/people/1.json"}) + # get_matz = ActiveResource::Request.new(:get, '/people/1.json', nil) # ok_response = ActiveResource::Response.new("", 200, {}) # # pairs = {create_matz => created_response, get_matz => ok_response} @@ -154,12 +154,12 @@ module ActiveResource # === Example # # ActiveResource::HttpMock.respond_to do |mock| - # mock.send(:get, "/people/1", {}, "XML1") + # mock.send(:get, "/people/1", {}, "JSON1") # end # ActiveResource::HttpMock.responses.length #=> 1 # # ActiveResource::HttpMock.respond_to(false) do |mock| - # mock.send(:get, "/people/2", {}, "XML2") + # mock.send(:get, "/people/2", {}, "JSON2") # end # ActiveResource::HttpMock.responses.length #=> 2 # @@ -169,11 +169,11 @@ module ActiveResource # === Example # # ActiveResource::HttpMock.respond_to do |mock| - # mock.send(:get, "/people/1", {}, "XML1") + # mock.send(:get, "/people/1", {}, "JSON1") # end # ActiveResource::HttpMock.responses.length #=> 1 # - # get_matz = ActiveResource::Request.new(:get, '/people/1.xml', nil) + # get_matz = ActiveResource::Request.new(:get, '/people/1.json', nil) # ok_response = ActiveResource::Response.new("", 200, {}) # # pairs = {get_matz => ok_response} diff --git a/activeresource/test/abstract_unit.rb b/activeresource/test/abstract_unit.rb index 195f93f2a6..948dd94a1d 100644 --- a/activeresource/test/abstract_unit.rb +++ b/activeresource/test/abstract_unit.rb @@ -20,16 +20,19 @@ rescue LoadError end def setup_response - @default_request_headers = { 'Content-Type' => 'application/xml' } - @matz = { :id => 1, :name => 'Matz' }.to_xml(:root => 'person') - @david = { :id => 2, :name => 'David' }.to_xml(:root => 'person') - @greg = { :id => 3, :name => 'Greg' }.to_xml(:root => 'person') - @addy = { :id => 1, :street => '12345 Street', :country => 'Australia' }.to_xml(:root => 'address') - @rick = { :name => "Rick", :age => 25 }.to_xml(:root => "person") - @joe = { 'person' => { :id => 6, :name => 'Joe' }}.to_json - @people = [{ :id => 1, :name => 'Matz' }, { :id => 2, :name => 'David' }].to_xml(:root => 'people') - @people_david = [{ :id => 2, :name => 'David' }].to_xml(:root => 'people') - @addresses = [{ :id => 1, :street => '12345 Street', :country => 'Australia' }].to_xml(:root => 'addresses') + matz_hash = { 'person' => { :id => 1, :name => 'Matz' } } + + @default_request_headers = { 'Content-Type' => 'application/json' } + @matz = matz_hash.to_json + @matz_xml = matz_hash.to_xml + @david = { :person => { :id => 2, :name => 'David' } }.to_json + @greg = { :person => { :id => 3, :name => 'Greg' } }.to_json + @addy = { :address => { :id => 1, :street => '12345 Street', :country => 'Australia' } }.to_json + @rick = { :person => { :name => "Rick", :age => 25 } }.to_json + @joe = { :person => { :id => 6, :name => 'Joe', :likes_hats => true }}.to_json + @people = { :people => [ { :person => { :id => 1, :name => 'Matz' } }, { :person => { :id => 2, :name => 'David' } }] }.to_json + @people_david = { :people => [ { :person => { :id => 2, :name => 'David' } }] }.to_json + @addresses = { :addresses => [{ :address => { :id => 1, :street => '12345 Street', :country => 'Australia' } }] }.to_json # - deep nested resource - # - Luis (Customer) @@ -48,19 +51,38 @@ def setup_response # - Natacha (Customer::Friend::Brother::Child) # - Milena (Customer::Friend::Brother) # - @luis = {:id => 1, :name => 'Luis', - :friends => [{:name => 'JK', - :brothers => [{:name => 'Mateo', - :children => [{:name => 'Edith'},{:name => 'Martha'}]}, - {:name => 'Felipe', - :children => [{:name => 'Bryan'},{:name => 'Luke'}]}]}, - {:name => 'Eduardo', - :brothers => [{:name => 'Sebas', - :children => [{:name => 'Andres'},{:name => 'Jorge'}]}, - {:name => 'Elsa', - :children => [{:name => 'Natacha'}]}, - {:name => 'Milena', - :children => []}]}]}.to_xml(:root => 'customer') + @luis = { + :customer => { + :id => 1, + :name => 'Luis', + :friends => [{ + :name => 'JK', + :brothers => [ + { + :name => 'Mateo', + :children => [{ :name => 'Edith' },{ :name => 'Martha' }] + }, { + :name => 'Felipe', + :children => [{ :name => 'Bryan' },{ :name => 'Luke' }] + } + ] + }, { + :name => 'Eduardo', + :brothers => [ + { + :name => 'Sebas', + :children => [{ :name => 'Andres' },{ :name => 'Jorge' }] + }, { + :name => 'Elsa', + :children => [{ :name => 'Natacha' }] + }, { + :name => 'Milena', + :children => [] + } + ] + }] + } + }.to_json # - resource with yaml array of strings; for ARs using serialize :bar, Array @marty = <<-eof.strip <?xml version=\"1.0\" encoding=\"UTF-8\"?> @@ -75,49 +97,52 @@ def setup_response </person> eof - @startup_sound = { - :name => "Mac Startup Sound", :author => { :name => "Jim Reekes" } - }.to_xml(:root => 'sound') + @startup_sound = { + :sound => { + :name => "Mac Startup Sound", :author => { :name => "Jim Reekes" } + } + }.to_json ActiveResource::HttpMock.respond_to do |mock| - mock.get "/people/1.xml", {}, @matz + mock.get "/people/1.json", {}, @matz + mock.get "/people/1.xml", {}, @matz_xml mock.get "/people/2.xml", {}, @david mock.get "/people/5.xml", {}, @marty - mock.get "/people/Greg.xml", {}, @greg + mock.get "/people/Greg.json", {}, @greg mock.get "/people/6.json", {}, @joe - mock.get "/people/4.xml", {'key' => 'value'}, nil, 404 - mock.put "/people/1.xml", {}, nil, 204 - mock.delete "/people/1.xml", {}, nil, 200 + mock.get "/people/4.json", { 'key' => 'value' }, nil, 404 + mock.put "/people/1.json", {}, nil, 204 + mock.delete "/people/1.json", {}, nil, 200 mock.delete "/people/2.xml", {}, nil, 400 - mock.get "/people/99.xml", {}, nil, 404 - mock.post "/people.xml", {}, @rick, 201, 'Location' => '/people/5.xml' - mock.get "/people.xml", {}, @people - mock.get "/people/1/addresses.xml", {}, @addresses - mock.get "/people/1/addresses/1.xml", {}, @addy + mock.get "/people/99.json", {}, nil, 404 + mock.post "/people.json", {}, @rick, 201, 'Location' => '/people/5.xml' + mock.get "/people.json", {}, @people + mock.get "/people/1/addresses.json", {}, @addresses + mock.get "/people/1/addresses/1.json", {}, @addy mock.get "/people/1/addresses/2.xml", {}, nil, 404 - mock.get "/people/2/addresses.xml", {}, nil, 404 + mock.get "/people/2/addresses.json", {}, nil, 404 mock.get "/people/2/addresses/1.xml", {}, nil, 404 - mock.get "/people/Greg/addresses/1.xml", {}, @addy - mock.put "/people/1/addresses/1.xml", {}, nil, 204 - mock.delete "/people/1/addresses/1.xml", {}, nil, 200 - mock.post "/people/1/addresses.xml", {}, nil, 201, 'Location' => '/people/1/addresses/5' - mock.get "/people/1/addresses/99.xml", {}, nil, 404 + mock.get "/people/Greg/addresses/1.json", {}, @addy + mock.put "/people/1/addresses/1.json", {}, nil, 204 + mock.delete "/people/1/addresses/1.json", {}, nil, 200 + mock.post "/people/1/addresses.json", {}, nil, 201, 'Location' => '/people/1/addresses/5' + mock.get "/people/1/addresses/99.json", {}, nil, 404 mock.get "/people//addresses.xml", {}, nil, 404 mock.get "/people//addresses/1.xml", {}, nil, 404 mock.put "/people//addresses/1.xml", {}, nil, 404 mock.delete "/people//addresses/1.xml", {}, nil, 404 mock.post "/people//addresses.xml", {}, nil, 404 - mock.head "/people/1.xml", {}, nil, 200 - mock.head "/people/Greg.xml", {}, nil, 200 - mock.head "/people/99.xml", {}, nil, 404 - mock.head "/people/1/addresses/1.xml", {}, nil, 200 - mock.head "/people/1/addresses/2.xml", {}, nil, 404 - mock.head "/people/2/addresses/1.xml", {}, nil, 404 - mock.head "/people/Greg/addresses/1.xml", {}, nil, 200 + mock.head "/people/1.json", {}, nil, 200 + mock.head "/people/Greg.json", {}, nil, 200 + mock.head "/people/99.json", {}, nil, 404 + mock.head "/people/1/addresses/1.json", {}, nil, 200 + mock.head "/people/1/addresses/2.json", {}, nil, 404 + mock.head "/people/2/addresses/1.json", {}, nil, 404 + mock.head "/people/Greg/addresses/1.json", {}, nil, 200 # customer - mock.get "/customers/1.xml", {}, @luis + mock.get "/customers/1.json", {}, @luis # sound - mock.get "/sounds/1.xml", {}, @startup_sound + mock.get "/sounds/1.json", {}, @startup_sound end Person.user = nil diff --git a/activeresource/test/cases/authorization_test.rb b/activeresource/test/cases/authorization_test.rb index a6797643e1..69ef9a2821 100644 --- a/activeresource/test/cases/authorization_test.rb +++ b/activeresource/test/cases/authorization_test.rb @@ -5,36 +5,36 @@ class AuthorizationTest < Test::Unit::TestCase def setup @conn = ActiveResource::Connection.new('http://localhost') - @matz = { :id => 1, :name => 'Matz' }.to_xml(:root => 'person') - @david = { :id => 2, :name => 'David' }.to_xml(:root => 'person') + @matz = { :person => { :id => 1, :name => 'Matz' } }.to_json + @david = { :person => { :id => 2, :name => 'David' } }.to_json @authenticated_conn = ActiveResource::Connection.new("http://david:test123@localhost") @basic_authorization_request_header = { 'Authorization' => 'Basic ZGF2aWQ6dGVzdDEyMw==' } @nonce = "MTI0OTUxMzc4NzpjYWI3NDM3NDNmY2JmODU4ZjQ2ZjcwNGZkMTJiMjE0NA==" ActiveResource::HttpMock.respond_to do |mock| - mock.get "/people/2.xml", @basic_authorization_request_header, @david - mock.get "/people/1.xml", @basic_authorization_request_header, nil, 401, { 'WWW-Authenticate' => 'i_should_be_ignored' } - mock.put "/people/2.xml", @basic_authorization_request_header, nil, 204 - mock.delete "/people/2.xml", @basic_authorization_request_header, nil, 200 - mock.post "/people/2/addresses.xml", @basic_authorization_request_header, nil, 201, 'Location' => '/people/1/addresses/5' - mock.head "/people/2.xml", @basic_authorization_request_header, nil, 200 + mock.get "/people/2.json", @basic_authorization_request_header, @david + mock.get "/people/1.json", @basic_authorization_request_header, nil, 401, { 'WWW-Authenticate' => 'i_should_be_ignored' } + mock.put "/people/2.json", @basic_authorization_request_header, nil, 204 + mock.delete "/people/2.json", @basic_authorization_request_header, nil, 200 + mock.post "/people/2/addresses.json", @basic_authorization_request_header, nil, 201, 'Location' => '/people/1/addresses/5' + mock.head "/people/2.json", @basic_authorization_request_header, nil, 200 - mock.get "/people/2.xml", { 'Authorization' => blank_digest_auth_header("/people/2.xml", "a10c9bd131c9d4d7755b8f4706fd04af") }, nil, 401, { 'WWW-Authenticate' => response_digest_auth_header } - mock.get "/people/2.xml", { 'Authorization' => request_digest_auth_header("/people/2.xml", "912c7a643f18cda562b8d9662c47b6f5") }, @david, 200 - mock.get "/people/1.xml", { 'Authorization' => request_digest_auth_header("/people/1.xml", "d76e675c0ecfa2bb1abe01491b068a06") }, @matz, 200 + mock.get "/people/2.json", { 'Authorization' => blank_digest_auth_header("/people/2.json", "fad396f6a34aeba28e28b9b96ddbb671") }, nil, 401, { 'WWW-Authenticate' => response_digest_auth_header } + mock.get "/people/2.json", { 'Authorization' => request_digest_auth_header("/people/2.json", "c064d5ba8891a25290c76c8c7d31fb7b") }, @david, 200 + mock.get "/people/1.json", { 'Authorization' => request_digest_auth_header("/people/1.json", "f9c0b594257bb8422af4abd429c5bb70") }, @matz, 200 - mock.put "/people/2.xml", { 'Authorization' => blank_digest_auth_header("/people/2.xml", "7de8a265a5be3c4c2d3a246562ecd6bd") }, nil, 401, { 'WWW-Authenticate' => response_digest_auth_header } - mock.put "/people/2.xml", { 'Authorization' => request_digest_auth_header("/people/2.xml", "3fb3b33d9d0b869cc75815aa11faacd9") }, nil, 204 + mock.put "/people/2.json", { 'Authorization' => blank_digest_auth_header("/people/2.json", "50a685d814f94665b9d160fbbaa3958a") }, nil, 401, { 'WWW-Authenticate' => response_digest_auth_header } + mock.put "/people/2.json", { 'Authorization' => request_digest_auth_header("/people/2.json", "5a75cde841122d8e0f20f8fd1f98a743") }, nil, 204 - mock.delete "/people/2.xml", { 'Authorization' => blank_digest_auth_header("/people/2.xml", "07dfc32769a34ea3510d3a77d64ca495") }, nil, 401, { 'WWW-Authenticate' => response_digest_auth_header } - mock.delete "/people/2.xml", { 'Authorization' => request_digest_auth_header("/people/2.xml", "5d438610de7ec163b29096c9afcbb254") }, nil, 200 + mock.delete "/people/2.json", { 'Authorization' => blank_digest_auth_header("/people/2.json", "846f799107eab5ca4285b909ee299a33") }, nil, 401, { 'WWW-Authenticate' => response_digest_auth_header } + mock.delete "/people/2.json", { 'Authorization' => request_digest_auth_header("/people/2.json", "9f5b155224edbbb69fd99d8ce094681e") }, nil, 200 - mock.post "/people/2/addresses.xml", { 'Authorization' => blank_digest_auth_header("/people/2/addresses.xml", "966dab13620421f928d051f2b9d7b9af") }, nil, 401, { 'WWW-Authenticate' => response_digest_auth_header } - mock.post "/people/2/addresses.xml", { 'Authorization' => request_digest_auth_header("/people/2/addresses.xml", "ed540d032c63f8ee34959116c090ec45") }, nil, 201, 'Location' => '/people/1/addresses/5' + mock.post "/people/2/addresses.json", { 'Authorization' => blank_digest_auth_header("/people/2/addresses.json", "6984d405ff3d9ed07bbf747dcf16afb0") }, nil, 401, { 'WWW-Authenticate' => response_digest_auth_header } + mock.post "/people/2/addresses.json", { 'Authorization' => request_digest_auth_header("/people/2/addresses.json", "4bda6a28dbf930b5af9244073623bd04") }, nil, 201, 'Location' => '/people/1/addresses/5' - mock.head "/people/2.xml", { 'Authorization' => blank_digest_auth_header("/people/2.xml", "2854eeb92cce2aed29350ea0ce7ba1e2") }, nil, 401, { 'WWW-Authenticate' => response_digest_auth_header } - mock.head "/people/2.xml", { 'Authorization' => request_digest_auth_header("/people/2.xml", "07cd4d247e9c130f92ba2501a080b328") }, nil, 200 + mock.head "/people/2.json", { 'Authorization' => blank_digest_auth_header("/people/2.json", "15e5ed84ba5c4cfcd5c98a36c2e4f421") }, nil, 401, { 'WWW-Authenticate' => response_digest_auth_header } + mock.head "/people/2.json", { 'Authorization' => request_digest_auth_header("/people/2.json", "d4c6d2bcc8717abb2e2ccb8c49ee6a91") }, nil, 200 end # Make client nonce deterministic @@ -48,7 +48,7 @@ class AuthorizationTest < Test::Unit::TestCase end def test_authorization_header - authorization_header = @authenticated_conn.__send__(:authorization_header, :get, URI.parse('/people/2.xml')) + authorization_header = @authenticated_conn.__send__(:authorization_header, :get, URI.parse('/people/2.json')) assert_equal @basic_authorization_request_header['Authorization'], authorization_header['Authorization'] authorization = authorization_header["Authorization"].to_s.split @@ -58,7 +58,7 @@ class AuthorizationTest < Test::Unit::TestCase def test_authorization_header_with_username_but_no_password @conn = ActiveResource::Connection.new("http://david:@localhost") - authorization_header = @conn.__send__(:authorization_header, :get, URI.parse('/people/2.xml')) + authorization_header = @conn.__send__(:authorization_header, :get, URI.parse('/people/2.json')) authorization = authorization_header["Authorization"].to_s.split assert_equal "Basic", authorization[0] @@ -67,7 +67,7 @@ class AuthorizationTest < Test::Unit::TestCase def test_authorization_header_with_password_but_no_username @conn = ActiveResource::Connection.new("http://:test123@localhost") - authorization_header = @conn.__send__(:authorization_header, :get, URI.parse('/people/2.xml')) + authorization_header = @conn.__send__(:authorization_header, :get, URI.parse('/people/2.json')) authorization = authorization_header["Authorization"].to_s.split assert_equal "Basic", authorization[0] @@ -76,7 +76,7 @@ class AuthorizationTest < Test::Unit::TestCase def test_authorization_header_with_decoded_credentials_from_url @conn = ActiveResource::Connection.new("http://my%40email.com:%31%32%33@localhost") - authorization_header = @conn.__send__(:authorization_header, :get, URI.parse('/people/2.xml')) + authorization_header = @conn.__send__(:authorization_header, :get, URI.parse('/people/2.json')) authorization = authorization_header["Authorization"].to_s.split assert_equal "Basic", authorization[0] @@ -87,7 +87,7 @@ class AuthorizationTest < Test::Unit::TestCase @authenticated_conn = ActiveResource::Connection.new("http://@localhost") @authenticated_conn.user = 'david' @authenticated_conn.password = 'test123' - authorization_header = @authenticated_conn.__send__(:authorization_header, :get, URI.parse('/people/2.xml')) + authorization_header = @authenticated_conn.__send__(:authorization_header, :get, URI.parse('/people/2.json')) assert_equal @basic_authorization_request_header['Authorization'], authorization_header['Authorization'] authorization = authorization_header["Authorization"].to_s.split @@ -98,7 +98,7 @@ class AuthorizationTest < Test::Unit::TestCase def test_authorization_header_explicitly_setting_username_but_no_password @conn = ActiveResource::Connection.new("http://@localhost") @conn.user = "david" - authorization_header = @conn.__send__(:authorization_header, :get, URI.parse('/people/2.xml')) + authorization_header = @conn.__send__(:authorization_header, :get, URI.parse('/people/2.json')) authorization = authorization_header["Authorization"].to_s.split assert_equal "Basic", authorization[0] @@ -108,7 +108,7 @@ class AuthorizationTest < Test::Unit::TestCase def test_authorization_header_explicitly_setting_password_but_no_username @conn = ActiveResource::Connection.new("http://@localhost") @conn.password = "test123" - authorization_header = @conn.__send__(:authorization_header, :get, URI.parse('/people/2.xml')) + authorization_header = @conn.__send__(:authorization_header, :get, URI.parse('/people/2.json')) authorization = authorization_header["Authorization"].to_s.split assert_equal "Basic", authorization[0] @@ -117,7 +117,7 @@ class AuthorizationTest < Test::Unit::TestCase def test_authorization_header_if_credentials_supplied_and_auth_type_is_basic @authenticated_conn.auth_type = :basic - authorization_header = @authenticated_conn.__send__(:authorization_header, :get, URI.parse('/people/2.xml')) + authorization_header = @authenticated_conn.__send__(:authorization_header, :get, URI.parse('/people/2.json')) assert_equal @basic_authorization_request_header['Authorization'], authorization_header['Authorization'] authorization = authorization_header["Authorization"].to_s.split @@ -127,96 +127,96 @@ class AuthorizationTest < Test::Unit::TestCase def test_authorization_header_if_credentials_supplied_and_auth_type_is_digest @authenticated_conn.auth_type = :digest - authorization_header = @authenticated_conn.__send__(:authorization_header, :get, URI.parse('/people/2.xml')) - assert_equal blank_digest_auth_header("/people/2.xml", "a10c9bd131c9d4d7755b8f4706fd04af"), authorization_header['Authorization'] + authorization_header = @authenticated_conn.__send__(:authorization_header, :get, URI.parse('/people/2.json')) + assert_equal blank_digest_auth_header("/people/2.json", "fad396f6a34aeba28e28b9b96ddbb671"), authorization_header['Authorization'] end def test_get - david = decode(@authenticated_conn.get("/people/2.xml")) + david = decode(@authenticated_conn.get("/people/2.json")) assert_equal "David", david["name"] end def test_post - response = @authenticated_conn.post("/people/2/addresses.xml") + response = @authenticated_conn.post("/people/2/addresses.json") assert_equal "/people/1/addresses/5", response["Location"] end def test_put - response = @authenticated_conn.put("/people/2.xml") + response = @authenticated_conn.put("/people/2.json") assert_equal 204, response.code end def test_delete - response = @authenticated_conn.delete("/people/2.xml") + response = @authenticated_conn.delete("/people/2.json") assert_equal 200, response.code end def test_head - response = @authenticated_conn.head("/people/2.xml") + response = @authenticated_conn.head("/people/2.json") assert_equal 200, response.code end def test_get_with_digest_auth_handles_initial_401_response_and_retries @authenticated_conn.auth_type = :digest - response = @authenticated_conn.get("/people/2.xml") + response = @authenticated_conn.get("/people/2.json") assert_equal "David", decode(response)["name"] end def test_post_with_digest_auth_handles_initial_401_response_and_retries @authenticated_conn.auth_type = :digest - response = @authenticated_conn.post("/people/2/addresses.xml") + response = @authenticated_conn.post("/people/2/addresses.json") assert_equal "/people/1/addresses/5", response["Location"] assert_equal 201, response.code end def test_put_with_digest_auth_handles_initial_401_response_and_retries @authenticated_conn.auth_type = :digest - response = @authenticated_conn.put("/people/2.xml") + response = @authenticated_conn.put("/people/2.json") assert_equal 204, response.code end def test_delete_with_digest_auth_handles_initial_401_response_and_retries @authenticated_conn.auth_type = :digest - response = @authenticated_conn.delete("/people/2.xml") + response = @authenticated_conn.delete("/people/2.json") assert_equal 200, response.code end def test_head_with_digest_auth_handles_initial_401_response_and_retries @authenticated_conn.auth_type = :digest - response = @authenticated_conn.head("/people/2.xml") + response = @authenticated_conn.head("/people/2.json") assert_equal 200, response.code end def test_get_with_digest_auth_caches_nonce @authenticated_conn.auth_type = :digest - response = @authenticated_conn.get("/people/2.xml") + response = @authenticated_conn.get("/people/2.json") assert_equal "David", decode(response)["name"] # There is no mock for this request with a non-cached nonce. - response = @authenticated_conn.get("/people/1.xml") + response = @authenticated_conn.get("/people/1.json") assert_equal "Matz", decode(response)["name"] end def test_retry_on_401_only_happens_with_digest_auth - assert_raise(ActiveResource::UnauthorizedAccess) { @authenticated_conn.get("/people/1.xml") } + assert_raise(ActiveResource::UnauthorizedAccess) { @authenticated_conn.get("/people/1.json") } assert_equal "", @authenticated_conn.send(:response_auth_header) end def test_raises_invalid_request_on_unauthorized_requests - assert_raise(ActiveResource::InvalidRequestError) { @conn.get("/people/2.xml") } - assert_raise(ActiveResource::InvalidRequestError) { @conn.post("/people/2/addresses.xml") } - assert_raise(ActiveResource::InvalidRequestError) { @conn.put("/people/2.xml") } - assert_raise(ActiveResource::InvalidRequestError) { @conn.delete("/people/2.xml") } - assert_raise(ActiveResource::InvalidRequestError) { @conn.head("/people/2.xml") } + assert_raise(ActiveResource::InvalidRequestError) { @conn.get("/people/2.json") } + assert_raise(ActiveResource::InvalidRequestError) { @conn.post("/people/2/addresses.json") } + assert_raise(ActiveResource::InvalidRequestError) { @conn.put("/people/2.json") } + assert_raise(ActiveResource::InvalidRequestError) { @conn.delete("/people/2.json") } + assert_raise(ActiveResource::InvalidRequestError) { @conn.head("/people/2.json") } end def test_raises_invalid_request_on_unauthorized_requests_with_digest_auth @conn.auth_type = :digest - assert_raise(ActiveResource::InvalidRequestError) { @conn.get("/people/2.xml") } - assert_raise(ActiveResource::InvalidRequestError) { @conn.post("/people/2/addresses.xml") } - assert_raise(ActiveResource::InvalidRequestError) { @conn.put("/people/2.xml") } - assert_raise(ActiveResource::InvalidRequestError) { @conn.delete("/people/2.xml") } - assert_raise(ActiveResource::InvalidRequestError) { @conn.head("/people/2.xml") } + assert_raise(ActiveResource::InvalidRequestError) { @conn.get("/people/2.json") } + assert_raise(ActiveResource::InvalidRequestError) { @conn.post("/people/2/addresses.json") } + assert_raise(ActiveResource::InvalidRequestError) { @conn.put("/people/2.json") } + assert_raise(ActiveResource::InvalidRequestError) { @conn.delete("/people/2.json") } + assert_raise(ActiveResource::InvalidRequestError) { @conn.head("/people/2.json") } end def test_client_nonce_is_not_nil diff --git a/activeresource/test/cases/base/custom_methods_test.rb b/activeresource/test/cases/base/custom_methods_test.rb index 0fbf94bc0e..3eaa9b1c5b 100644 --- a/activeresource/test/cases/base/custom_methods_test.rb +++ b/activeresource/test/cases/base/custom_methods_test.rb @@ -5,32 +5,32 @@ require 'active_support/core_ext/hash/conversions' class CustomMethodsTest < Test::Unit::TestCase def setup - @matz = { :id => 1, :name => 'Matz' }.to_xml(:root => 'person') - @matz_deep = { :id => 1, :name => 'Matz', :other => 'other' }.to_xml(:root => 'person') - @matz_array = [{ :id => 1, :name => 'Matz' }].to_xml(:root => 'people') - @ryan = { :name => 'Ryan' }.to_xml(:root => 'person') - @addy = { :id => 1, :street => '12345 Street' }.to_xml(:root => 'address') - @addy_deep = { :id => 1, :street => '12345 Street', :zip => "27519" }.to_xml(:root => 'address') + @matz = { :person => { :id => 1, :name => 'Matz' } }.to_json + @matz_deep = { :person => { :id => 1, :name => 'Matz', :other => 'other' } }.to_json + @matz_array = { :people => [{ :person => { :id => 1, :name => 'Matz' } }] }.to_json + @ryan = { :person => { :name => 'Ryan' } }.to_json + @addy = { :address => { :id => 1, :street => '12345 Street' } }.to_json + @addy_deep = { :address => { :id => 1, :street => '12345 Street', :zip => "27519" } }.to_json ActiveResource::HttpMock.respond_to do |mock| - mock.get "/people/1.xml", {}, @matz - mock.get "/people/1/shallow.xml", {}, @matz - mock.get "/people/1/deep.xml", {}, @matz_deep - mock.get "/people/retrieve.xml?name=Matz", {}, @matz_array - mock.get "/people/managers.xml", {}, @matz_array - mock.post "/people/hire.xml?name=Matz", {}, nil, 201 - mock.put "/people/1/promote.xml?position=Manager", {}, nil, 204 - mock.put "/people/promote.xml?name=Matz", {}, nil, 204, {} - mock.put "/people/sort.xml?by=name", {}, nil, 204 - mock.delete "/people/deactivate.xml?name=Matz", {}, nil, 200 - mock.delete "/people/1/deactivate.xml", {}, nil, 200 - mock.post "/people/new/register.xml", {}, @ryan, 201, 'Location' => '/people/5.xml' - mock.post "/people/1/register.xml", {}, @matz, 201 - mock.get "/people/1/addresses/1.xml", {}, @addy - mock.get "/people/1/addresses/1/deep.xml", {}, @addy_deep - mock.put "/people/1/addresses/1/normalize_phone.xml?locale=US", {}, nil, 204 - mock.put "/people/1/addresses/sort.xml?by=name", {}, nil, 204 - mock.post "/people/1/addresses/new/link.xml", {}, { :street => '12345 Street' }.to_xml(:root => 'address'), 201, 'Location' => '/people/1/addresses/2.xml' + mock.get "/people/1.json", {}, @matz + mock.get "/people/1/shallow.json", {}, @matz + mock.get "/people/1/deep.json", {}, @matz_deep + mock.get "/people/retrieve.json?name=Matz", {}, @matz_array + mock.get "/people/managers.json", {}, @matz_array + mock.post "/people/hire.json?name=Matz", {}, nil, 201 + mock.put "/people/1/promote.json?position=Manager", {}, nil, 204 + mock.put "/people/promote.json?name=Matz", {}, nil, 204, {} + mock.put "/people/sort.json?by=name", {}, nil, 204 + mock.delete "/people/deactivate.json?name=Matz", {}, nil, 200 + mock.delete "/people/1/deactivate.json", {}, nil, 200 + mock.post "/people/new/register.json", {}, @ryan, 201, 'Location' => '/people/5.json' + mock.post "/people/1/register.json", {}, @matz, 201 + mock.get "/people/1/addresses/1.json", {}, @addy + mock.get "/people/1/addresses/1/deep.json", {}, @addy_deep + mock.put "/people/1/addresses/1/normalize_phone.json?locale=US", {}, nil, 204 + mock.put "/people/1/addresses/sort.json?by=name", {}, nil, 204 + mock.post "/people/1/addresses/new/link.json", {}, { :address => { :street => '12345 Street' } }.to_json, 201, 'Location' => '/people/1/addresses/2.json' end Person.user = nil @@ -81,14 +81,14 @@ class CustomMethodsTest < Test::Unit::TestCase def test_custom_new_element_method # Test POST against a new element URL ryan = Person.new(:name => 'Ryan') - assert_equal ActiveResource::Response.new(@ryan, 201, {'Location' => '/people/5.xml'}), ryan.post(:register) - expected_request = ActiveResource::Request.new(:post, '/people/new/register.xml', @ryan) + assert_equal ActiveResource::Response.new(@ryan, 201, { 'Location' => '/people/5.json' }), ryan.post(:register) + expected_request = ActiveResource::Request.new(:post, '/people/new/register.json', @ryan) assert_equal expected_request.body, ActiveResource::HttpMock.requests.first.body # Test POST against a nested collection URL addy = StreetAddress.new(:street => '123 Test Dr.', :person_id => 1) - assert_equal ActiveResource::Response.new({ :street => '12345 Street' }.to_xml(:root => 'address'), - 201, {'Location' => '/people/1/addresses/2.xml'}), + assert_equal ActiveResource::Response.new({ :address => { :street => '12345 Street' } }.to_json, + 201, { 'Location' => '/people/1/addresses/2.json' }), addy.post(:link) matz = Person.find(1) diff --git a/activeresource/test/cases/base/load_test.rb b/activeresource/test/cases/base/load_test.rb index 228dc36d9b..d6b04cfaa8 100644 --- a/activeresource/test/cases/base/load_test.rb +++ b/activeresource/test/cases/base/load_test.rb @@ -36,10 +36,10 @@ class BaseLoadTest < Test::Unit::TestCase def setup @matz = { :id => 1, :name => 'Matz' } - @first_address = { :id => 1, :street => '12345 Street' } - @addresses = [@first_address, { :id => 2, :street => '67890 Street' }] - @addresses_from_xml = { :street_addresses => @addresses } - @addresses_from_xml_single = { :street_addresses => [ @first_address ] } + @first_address = { :address => { :id => 1, :street => '12345 Street' } } + @addresses = [@first_address, { :address => { :id => 2, :street => '67890 Street' } }] + @addresses_from_json = { :street_addresses => @addresses } + @addresses_from_json_single = { :street_addresses => [ @first_address ] } @deep = { :id => 1, :street => { :id => 1, :state => { :id => 1, :name => 'Oregon', @@ -72,28 +72,29 @@ class BaseLoadTest < Test::Unit::TestCase def test_after_load_attributes_are_accessible_via_indifferent_access assert_equal Hash.new, @person.attributes + matz_attributes = @matz.values.first assert_equal @matz.stringify_keys, @person.load(@matz).attributes assert_equal @matz[:name], @person.attributes['name'] assert_equal @matz[:name], @person.attributes[:name] end def test_load_one_with_existing_resource - address = @person.load(:street_address => @first_address).street_address + address = @person.load(:street_address => @first_address.values.first).street_address assert_kind_of StreetAddress, address - assert_equal @first_address.stringify_keys, address.attributes + assert_equal @first_address.values.first.stringify_keys, address.attributes end def test_load_one_with_unknown_resource - address = silence_warnings { @person.load(:address => @first_address).address } + address = silence_warnings { @person.load(@first_address).address } assert_kind_of Person::Address, address - assert_equal @first_address.stringify_keys, address.attributes + assert_equal @first_address.values.first.stringify_keys, address.attributes end def test_load_collection_with_existing_resource - addresses = @person.load(@addresses_from_xml).street_addresses + addresses = @person.load(@addresses_from_json).street_addresses assert_kind_of Array, addresses addresses.each { |address| assert_kind_of StreetAddress, address } - assert_equal @addresses.map(&:stringify_keys), addresses.map(&:attributes) + assert_equal @addresses.map { |a| a[:address].stringify_keys }, addresses.map(&:attributes) end def test_load_collection_with_unknown_resource @@ -102,14 +103,14 @@ class BaseLoadTest < Test::Unit::TestCase addresses = silence_warnings { @person.load(:addresses => @addresses).addresses } assert Person.const_defined?(:Address), "Address should have been autocreated" addresses.each { |address| assert_kind_of Person::Address, address } - assert_equal @addresses.map(&:stringify_keys), addresses.map(&:attributes) + assert_equal @addresses.map { |a| a[:address].stringify_keys }, addresses.map(&:attributes) end def test_load_collection_with_single_existing_resource - addresses = @person.load(@addresses_from_xml_single).street_addresses + addresses = @person.load(@addresses_from_json_single).street_addresses assert_kind_of Array, addresses addresses.each { |address| assert_kind_of StreetAddress, address } - assert_equal [ @first_address ].map(&:stringify_keys), addresses.map(&:attributes) + assert_equal [ @first_address.values.first ].map(&:stringify_keys), addresses.map(&:attributes) end def test_load_collection_with_single_unknown_resource @@ -118,7 +119,7 @@ class BaseLoadTest < Test::Unit::TestCase addresses = silence_warnings { @person.load(:addresses => [ @first_address ]).addresses } assert Person.const_defined?(:Address), "Address should have been autocreated" addresses.each { |address| assert_kind_of Person::Address, address } - assert_equal [ @first_address ].map(&:stringify_keys), addresses.map(&:attributes) + assert_equal [ @first_address.values.first ].map(&:stringify_keys), addresses.map(&:attributes) end def test_recursively_loaded_collections @@ -164,7 +165,7 @@ class BaseLoadTest < Test::Unit::TestCase end def test_nested_collections_within_the_same_namespace - n = Highrise::Note.new(:comments => [{ :name => "1" }]) + n = Highrise::Note.new(:comments => [{ :comment => { :name => "1" } }]) assert_kind_of Highrise::Comment, n.comments.first end diff --git a/activeresource/test/cases/base/schema_test.rb b/activeresource/test/cases/base/schema_test.rb index 37f30e4353..48fdeb13df 100644 --- a/activeresource/test/cases/base/schema_test.rb +++ b/activeresource/test/cases/base/schema_test.rb @@ -118,7 +118,7 @@ class SchemaTest < ActiveModel::TestCase test "with two instances, default schema should match the attributes of the individual instances - even if they differ" do matz = Person.find(1) - rick = Person.find(5) + rick = Person.find(6) m_attrs = matz.attributes.keys.sort r_attrs = rick.attributes.keys.sort @@ -376,7 +376,7 @@ class SchemaTest < ActiveModel::TestCase test "with two instances, known attributes should match the attributes of the individual instances - even if they differ" do matz = Person.find(1) - rick = Person.find(5) + rick = Person.find(6) m_attrs = matz.attributes.keys.sort r_attrs = rick.attributes.keys.sort diff --git a/activeresource/test/cases/base_test.rb b/activeresource/test/cases/base_test.rb index 48dacbdf67..f45652d988 100644 --- a/activeresource/test/cases/base_test.rb +++ b/activeresource/test/cases/base_test.rb @@ -448,31 +448,31 @@ class BaseTest < Test::Unit::TestCase end def test_collection_path - assert_equal '/people.xml', Person.collection_path + assert_equal '/people.json', Person.collection_path end def test_collection_path_with_parameters - assert_equal '/people.xml?gender=male', Person.collection_path(:gender => 'male') - assert_equal '/people.xml?gender=false', Person.collection_path(:gender => false) - assert_equal '/people.xml?gender=', Person.collection_path(:gender => nil) + assert_equal '/people.json?gender=male', Person.collection_path(:gender => 'male') + assert_equal '/people.json?gender=false', Person.collection_path(:gender => false) + assert_equal '/people.json?gender=', Person.collection_path(:gender => nil) - assert_equal '/people.xml?gender=male', Person.collection_path('gender' => 'male') + assert_equal '/people.json?gender=male', Person.collection_path('gender' => 'male') # Use includes? because ordering of param hash is not guaranteed - assert Person.collection_path(:gender => 'male', :student => true).include?('/people.xml?') + assert Person.collection_path(:gender => 'male', :student => true).include?('/people.json?') assert Person.collection_path(:gender => 'male', :student => true).include?('gender=male') assert Person.collection_path(:gender => 'male', :student => true).include?('student=true') - assert_equal '/people.xml?name%5B%5D=bob&name%5B%5D=your+uncle%2Bme&name%5B%5D=&name%5B%5D=false', Person.collection_path(:name => ['bob', 'your uncle+me', nil, false]) + assert_equal '/people.json?name%5B%5D=bob&name%5B%5D=your+uncle%2Bme&name%5B%5D=&name%5B%5D=false', Person.collection_path(:name => ['bob', 'your uncle+me', nil, false]) - assert_equal '/people.xml?struct%5Ba%5D%5B%5D=2&struct%5Ba%5D%5B%5D=1&struct%5Bb%5D=fred', Person.collection_path(:struct => ActiveSupport::OrderedHash[:a, [2,1], 'b', 'fred']) + assert_equal '/people.json?struct%5Ba%5D%5B%5D=2&struct%5Ba%5D%5B%5D=1&struct%5Bb%5D=fred', Person.collection_path(:struct => ActiveSupport::OrderedHash[:a, [2,1], 'b', 'fred']) end def test_custom_element_path - assert_equal '/people/1/addresses/1.xml', StreetAddress.element_path(1, :person_id => 1) - assert_equal '/people/1/addresses/1.xml', StreetAddress.element_path(1, 'person_id' => 1) - assert_equal '/people/Greg/addresses/1.xml', StreetAddress.element_path(1, 'person_id' => 'Greg') - assert_equal '/people/ann%20mary/addresses/ann%20mary.xml', StreetAddress.element_path(:'ann mary', 'person_id' => 'ann mary') + assert_equal '/people/1/addresses/1.json', StreetAddress.element_path(1, :person_id => 1) + assert_equal '/people/1/addresses/1.json', StreetAddress.element_path(1, 'person_id' => 1) + assert_equal '/people/Greg/addresses/1.json', StreetAddress.element_path(1, 'person_id' => 'Greg') + assert_equal '/people/ann%20mary/addresses/ann%20mary.json', StreetAddress.element_path(:'ann mary', 'person_id' => 'ann mary') end def test_custom_element_path_without_required_prefix_param @@ -482,7 +482,7 @@ class BaseTest < Test::Unit::TestCase end def test_module_element_path - assert_equal '/sounds/1.xml', Asset::Sound.element_path(1) + assert_equal '/sounds/1.json', Asset::Sound.element_path(1) end def test_custom_element_path_with_redefined_to_param @@ -494,10 +494,10 @@ class BaseTest < Test::Unit::TestCase end # Class method. - assert_equal '/people/Greg.xml', Person.element_path('Greg') + assert_equal '/people/Greg.json', Person.element_path('Greg') # Protected Instance method. - assert_equal '/people/Greg.xml', Person.find('Greg').send(:element_path) + assert_equal '/people/Greg.json', Person.find('Greg').send(:element_path) ensure # revert back to original @@ -509,14 +509,14 @@ class BaseTest < Test::Unit::TestCase end def test_custom_element_path_with_parameters - assert_equal '/people/1/addresses/1.xml?type=work', StreetAddress.element_path(1, :person_id => 1, :type => 'work') - assert_equal '/people/1/addresses/1.xml?type=work', StreetAddress.element_path(1, 'person_id' => 1, :type => 'work') - assert_equal '/people/1/addresses/1.xml?type=work', StreetAddress.element_path(1, :type => 'work', :person_id => 1) - assert_equal '/people/1/addresses/1.xml?type%5B%5D=work&type%5B%5D=play+time', StreetAddress.element_path(1, :person_id => 1, :type => ['work', 'play time']) + assert_equal '/people/1/addresses/1.json?type=work', StreetAddress.element_path(1, :person_id => 1, :type => 'work') + assert_equal '/people/1/addresses/1.json?type=work', StreetAddress.element_path(1, 'person_id' => 1, :type => 'work') + assert_equal '/people/1/addresses/1.json?type=work', StreetAddress.element_path(1, :type => 'work', :person_id => 1) + assert_equal '/people/1/addresses/1.json?type%5B%5D=work&type%5B%5D=play+time', StreetAddress.element_path(1, :person_id => 1, :type => ['work', 'play time']) end def test_custom_element_path_with_prefix_and_parameters - assert_equal '/people/1/addresses/1.xml?type=work', StreetAddress.element_path(1, {:person_id => 1}, {:type => 'work'}) + assert_equal '/people/1/addresses/1.json?type=work', StreetAddress.element_path(1, {:person_id => 1}, {:type => 'work'}) end def test_custom_collection_path_without_required_prefix_param @@ -526,17 +526,17 @@ class BaseTest < Test::Unit::TestCase end def test_custom_collection_path - assert_equal '/people/1/addresses.xml', StreetAddress.collection_path(:person_id => 1) - assert_equal '/people/1/addresses.xml', StreetAddress.collection_path('person_id' => 1) + assert_equal '/people/1/addresses.json', StreetAddress.collection_path(:person_id => 1) + assert_equal '/people/1/addresses.json', StreetAddress.collection_path('person_id' => 1) end def test_custom_collection_path_with_parameters - assert_equal '/people/1/addresses.xml?type=work', StreetAddress.collection_path(:person_id => 1, :type => 'work') - assert_equal '/people/1/addresses.xml?type=work', StreetAddress.collection_path('person_id' => 1, :type => 'work') + assert_equal '/people/1/addresses.json?type=work', StreetAddress.collection_path(:person_id => 1, :type => 'work') + assert_equal '/people/1/addresses.json?type=work', StreetAddress.collection_path('person_id' => 1, :type => 'work') end def test_custom_collection_path_with_prefix_and_parameters - assert_equal '/people/1/addresses.xml?type=work', StreetAddress.collection_path({:person_id => 1}, {:type => 'work'}) + assert_equal '/people/1/addresses.json?type=work', StreetAddress.collection_path({:person_id => 1}, {:type => 'work'}) end def test_custom_element_name @@ -626,7 +626,7 @@ class BaseTest < Test::Unit::TestCase resp = {'Location' => '/foo/bar/1'} assert_equal '1', p.__send__(:id_from_response, resp) - resp['Location'] << '.xml' + resp['Location'] << '.json' assert_equal '1', p.__send__(:id_from_response, resp) end @@ -698,14 +698,14 @@ class BaseTest < Test::Unit::TestCase # Test that save exceptions get bubbled up too ActiveResource::HttpMock.respond_to do |mock| - mock.post "/people.xml", {}, nil, 409 + mock.post "/people.json", {}, nil, 409 end assert_raise(ActiveResource::ResourceConflict) { Person.create(:name => 'Rick') } end def test_create_without_location ActiveResource::HttpMock.respond_to do |mock| - mock.post "/people.xml", {}, nil, 201 + mock.post "/people.json", {}, nil, 201 end person = Person.create(:name => 'Rick') assert_nil person.id @@ -772,8 +772,8 @@ class BaseTest < Test::Unit::TestCase def test_update_conflict ActiveResource::HttpMock.respond_to do |mock| - mock.get "/people/2.xml", {}, @david - mock.put "/people/2.xml", @default_request_headers, nil, 409 + mock.get "/people/2.json", {}, @david + mock.put "/people/2.json", @default_request_headers, nil, 409 end assert_raise(ActiveResource::ResourceConflict) { Person.find(2).save } end @@ -830,7 +830,7 @@ class BaseTest < Test::Unit::TestCase def test_destroy assert Person.find(1).destroy ActiveResource::HttpMock.respond_to do |mock| - mock.get "/people/1.xml", {}, nil, 404 + mock.get "/people/1.json", {}, nil, 404 end assert_raise(ActiveResource::ResourceNotFound) { Person.find(1).destroy } end @@ -838,7 +838,7 @@ class BaseTest < Test::Unit::TestCase def test_destroy_with_custom_prefix assert StreetAddress.find(1, :params => { :person_id => 1 }).destroy ActiveResource::HttpMock.respond_to do |mock| - mock.get "/people/1/addresses/1.xml", {}, nil, 404 + mock.get "/people/1/addresses/1.json", {}, nil, 404 end assert_raise(ActiveResource::ResourceNotFound) { StreetAddress.find(1, :params => { :person_id => 1 }) } end @@ -846,7 +846,7 @@ class BaseTest < Test::Unit::TestCase def test_destroy_with_410_gone assert Person.find(1).destroy ActiveResource::HttpMock.respond_to do |mock| - mock.get "/people/1.xml", {}, nil, 410 + mock.get "/people/1.json", {}, nil, 410 end assert_raise(ActiveResource::ResourceGone) { Person.find(1).destroy } end @@ -854,7 +854,7 @@ class BaseTest < Test::Unit::TestCase def test_delete assert Person.delete(1) ActiveResource::HttpMock.respond_to do |mock| - mock.get "/people/1.xml", {}, nil, 404 + mock.get "/people/1.json", {}, nil, 404 end assert_raise(ActiveResource::ResourceNotFound) { Person.find(1) } end @@ -862,7 +862,7 @@ class BaseTest < Test::Unit::TestCase def test_delete_with_custom_prefix assert StreetAddress.delete(1, :person_id => 1) ActiveResource::HttpMock.respond_to do |mock| - mock.get "/people/1/addresses/1.xml", {}, nil, 404 + mock.get "/people/1/addresses/1.json", {}, nil, 404 end assert_raise(ActiveResource::ResourceNotFound) { StreetAddress.find(1, :params => { :person_id => 1 }) } end @@ -870,7 +870,7 @@ class BaseTest < Test::Unit::TestCase def test_delete_with_410_gone assert Person.delete(1) ActiveResource::HttpMock.respond_to do |mock| - mock.get "/people/1.xml", {}, nil, 410 + mock.get "/people/1.json", {}, nil, 410 end assert_raise(ActiveResource::ResourceGone) { Person.find(1) } end @@ -939,13 +939,14 @@ class BaseTest < Test::Unit::TestCase def test_exists_with_410_gone ActiveResource::HttpMock.respond_to do |mock| - mock.head "/people/1.xml", {}, nil, 410 + mock.head "/people/1.json", {}, nil, 410 end assert !Person.exists?(1) end def test_to_xml + Person.format = :xml matz = Person.find(1) encode = matz.encode xml = matz.to_xml @@ -954,9 +955,12 @@ class BaseTest < Test::Unit::TestCase assert xml.include?('<?xml version="1.0" encoding="UTF-8"?>') assert xml.include?('<name>Matz</name>') assert xml.include?('<id type="integer">1</id>') + ensure + Person.format = :json end def test_to_xml_with_element_name + Person.format = :xml old_elem_name = Person.element_name matz = Person.find(1) Person.element_name = 'ruby_creator' @@ -970,45 +974,45 @@ class BaseTest < Test::Unit::TestCase assert xml.include?('<id type="integer">1</id>') assert xml.include?('</ruby-creator>') ensure + Person.format = :json Person.element_name = old_elem_name end def test_to_xml_with_private_method_name_as_attribute + Person.format = :xml assert_nothing_raised(ArgumentError) { Customer.new(:test => true).to_xml } + ensure + Person.format = :json end def test_to_json Person.include_root_in_json = true - Person.format = :json joe = Person.find(6) encode = joe.encode json = joe.to_json - Person.format = :xml assert_equal encode, json - assert_match %r{^\{"person":\{"person":\{}, json + assert_match %r{^\{"person":\{}, json assert_match %r{"id":6}, json assert_match %r{"name":"Joe"}, json - assert_match %r{\}\}\}$}, json + assert_match %r{\}\}$}, json end def test_to_json_with_element_name old_elem_name = Person.element_name Person.include_root_in_json = true - Person.format = :json joe = Person.find(6) Person.element_name = 'ruby_creator' encode = joe.encode json = joe.to_json - Person.format = :xml assert_equal encode, json - assert_match %r{^\{"ruby_creator":\{"person":\{}, json + assert_match %r{^\{"ruby_creator":\{}, json assert_match %r{"id":6}, json assert_match %r{"name":"Joe"}, json - assert_match %r{\}\}\}$}, json + assert_match %r{\}\}$}, json ensure Person.element_name = old_elem_name end @@ -1043,19 +1047,22 @@ class BaseTest < Test::Unit::TestCase def test_load_yaml_array assert_nothing_raised do + Person.format = :xml marty = Person.find(5) assert_equal 3, marty.colors.size marty.colors.each do |color| assert_kind_of String, color end end + ensure + Person.format = :json end def test_with_custom_formatter - @addresses = [{:id => "1", :street => "1 Infinite Loop", :city => "Cupertino", :state => "CA"}].to_xml(:root => 'addresses') + addresses = [{ :id => "1", :street => "1 Infinite Loop", :city => "Cupertino", :state => "CA" }].to_xml(:root => :addresses) ActiveResource::HttpMock.respond_to do |mock| - mock.get "/addresses.xml", {}, @addresses, 200 + mock.get "/addresses.xml", {}, addresses, 200 end # late bind the site @@ -1066,10 +1073,10 @@ class BaseTest < Test::Unit::TestCase end def test_create_with_custom_primary_key - silver_plan = {:code => "silver", :price => 5.00}.to_xml(:root => "plan") + silver_plan = { :plan => { :code => "silver", :price => 5.00 } }.to_json ActiveResource::HttpMock.respond_to do |mock| - mock.post "/plans.xml", {}, silver_plan, 201, 'Location' => '/plans/silver.xml' + mock.post "/plans.json", {}, silver_plan, 201, 'Location' => '/plans/silver.json' end plan = SubscriptionPlan.new(:code => "silver", :price => 5.00) @@ -1080,12 +1087,12 @@ class BaseTest < Test::Unit::TestCase end def test_update_with_custom_primary_key - silver_plan = {:code => "silver", :price => 5.00}.to_xml(:root => "plan") - silver_plan_updated = {:code => "silver", :price => 10.00}.to_xml(:root => "plan") + silver_plan = { :plan => { :code => "silver", :price => 5.00 } }.to_json + silver_plan_updated = { :plan => { :code => "silver", :price => 10.00 } }.to_json ActiveResource::HttpMock.respond_to do |mock| - mock.get "/plans/silver.xml", {}, silver_plan - mock.put "/plans/silver.xml", {}, silver_plan_updated, 201, 'Location' => '/plans/silver.xml' + mock.get "/plans/silver.json", {}, silver_plan + mock.put "/plans/silver.json", {}, silver_plan_updated, 201, 'Location' => '/plans/silver.json' end plan = SubscriptionPlan.find("silver") @@ -1097,7 +1104,7 @@ class BaseTest < Test::Unit::TestCase plan.save! assert_equal 10.00, plan.price end - + def test_namespacing sound = Asset::Sound.find(1) assert_equal "Asset::Sound::Author", sound.author.class.to_s diff --git a/activeresource/test/connection_test.rb b/activeresource/test/cases/connection_test.rb index 7c36393cf2..09df0fb678 100644 --- a/activeresource/test/connection_test.rb +++ b/activeresource/test/cases/connection_test.rb @@ -5,29 +5,29 @@ class ConnectionTest < Test::Unit::TestCase def setup @conn = ActiveResource::Connection.new('http://localhost') - @matz = { :id => 1, :name => 'Matz' } - @david = { :id => 2, :name => 'David' } - @people = [ @matz, @david ].to_xml(:root => 'people') - @people_single = [ @matz ].to_xml(:root => 'people-single-elements') - @people_empty = [ ].to_xml(:root => 'people-empty-elements') - @matz = @matz.to_xml(:root => 'person') - @david = @david.to_xml(:root => 'person') - @header = {'key' => 'value'}.freeze - - @default_request_headers = { 'Content-Type' => 'application/xml' } + matz = { :person => { :id => 1, :name => 'Matz' } } + david = { :person => { :id => 2, :name => 'David' } } + @people = { :people => [ matz, david ] }.to_json + @people_single = { 'people-single-elements' => [ matz ] }.to_json + @people_empty = { 'people-empty-elements' => [ ] }.to_json + @matz = matz.to_json + @david = david.to_json + @header = { 'key' => 'value' }.freeze + + @default_request_headers = { 'Content-Type' => 'application/json' } ActiveResource::HttpMock.respond_to do |mock| - mock.get "/people/2.xml", @header, @david - mock.get "/people.xml", {}, @people - mock.get "/people_single_elements.xml", {}, @people_single - mock.get "/people_empty_elements.xml", {}, @people_empty - mock.get "/people/1.xml", {}, @matz - mock.put "/people/1.xml", {}, nil, 204 - mock.put "/people/2.xml", {}, @header, 204 - mock.delete "/people/1.xml", {}, nil, 200 - mock.delete "/people/2.xml", @header, nil, 200 - mock.post "/people.xml", {}, nil, 201, 'Location' => '/people/5.xml' - mock.post "/members.xml", {}, @header, 201, 'Location' => '/people/6.xml' - mock.head "/people/1.xml", {}, nil, 200 + mock.get "/people/2.json", @header, @david + mock.get "/people.json", {}, @people + mock.get "/people_single_elements.json", {}, @people_single + mock.get "/people_empty_elements.json", {}, @people_empty + mock.get "/people/1.json", {}, @matz + mock.put "/people/1.json", {}, nil, 204 + mock.put "/people/2.json", {}, @header, 204 + mock.delete "/people/1.json", {}, nil, 200 + mock.delete "/people/2.json", @header, nil, 200 + mock.post "/people.json", {}, nil, 201, 'Location' => '/people/5.json' + mock.post "/members.json", {}, @header, 201, 'Location' => '/people/6.json' + mock.head "/people/1.json", {}, nil, 200 end end @@ -120,64 +120,64 @@ class ConnectionTest < Test::Unit::TestCase end def test_get - matz = decode(@conn.get("/people/1.xml")) + matz = decode(@conn.get("/people/1.json")) assert_equal "Matz", matz["name"] end def test_head - response = @conn.head("/people/1.xml") + response = @conn.head("/people/1.json") assert response.body.blank? assert_equal 200, response.code end def test_get_with_header - david = decode(@conn.get("/people/2.xml", @header)) + david = decode(@conn.get("/people/2.json", @header)) assert_equal "David", david["name"] end def test_get_collection - people = decode(@conn.get("/people.xml")) - assert_equal "Matz", people[0]["name"] - assert_equal "David", people[1]["name"] + people = decode(@conn.get("/people.json")) + assert_equal "Matz", people[0]["person"]["name"] + assert_equal "David", people[1]["person"]["name"] end def test_get_collection_single - people = decode(@conn.get("/people_single_elements.xml")) - assert_equal "Matz", people[0]["name"] + people = decode(@conn.get("/people_single_elements.json")) + assert_equal "Matz", people[0]["person"]["name"] end def test_get_collection_empty - people = decode(@conn.get("/people_empty_elements.xml")) + people = decode(@conn.get("/people_empty_elements.json")) assert_equal [], people end def test_post - response = @conn.post("/people.xml") - assert_equal "/people/5.xml", response["Location"] + response = @conn.post("/people.json") + assert_equal "/people/5.json", response["Location"] end def test_post_with_header - response = @conn.post("/members.xml", @header) - assert_equal "/people/6.xml", response["Location"] + response = @conn.post("/members.json", @header) + assert_equal "/people/6.json", response["Location"] end def test_put - response = @conn.put("/people/1.xml") + response = @conn.put("/people/1.json") assert_equal 204, response.code end def test_put_with_header - response = @conn.put("/people/2.xml", @header) + response = @conn.put("/people/2.json", @header) assert_equal 204, response.code end def test_delete - response = @conn.delete("/people/1.xml") + response = @conn.delete("/people/1.json") assert_equal 200, response.code end def test_delete_with_header - response = @conn.delete("/people/2.xml", @header) + response = @conn.delete("/people/2.json", @header) assert_equal 200, response.code end @@ -185,7 +185,7 @@ class ConnectionTest < Test::Unit::TestCase @http = mock('new Net::HTTP') @conn.expects(:http).returns(@http) @http.expects(:get).raises(Timeout::Error, 'execution expired') - assert_raise(ActiveResource::TimeoutError) { @conn.get('/people_timeout.xml') } + assert_raise(ActiveResource::TimeoutError) { @conn.get('/people_timeout.json') } end def test_setting_timeout @@ -203,8 +203,8 @@ class ConnectionTest < Test::Unit::TestCase @http = mock('new Net::HTTP') @conn.expects(:http).returns(@http) path = '/people/1.xml' - @http.expects(:get).with(path, {'Accept' => 'application/xhtml+xml'}).returns(ActiveResource::Response.new(@matz, 200, {'Content-Type' => 'text/xhtml'})) - assert_nothing_raised(Mocha::ExpectationError) { @conn.get(path, {'Accept' => 'application/xhtml+xml'}) } + @http.expects(:get).with(path, { 'Accept' => 'application/xhtml+xml' }).returns(ActiveResource::Response.new(@matz, 200, { 'Content-Type' => 'text/xhtml' })) + assert_nothing_raised(Mocha::ExpectationError) { @conn.get(path, { 'Accept' => 'application/xhtml+xml' }) } end def test_ssl_options_get_applied_to_http @@ -222,7 +222,7 @@ class ConnectionTest < Test::Unit::TestCase http = Net::HTTP.new('') @conn.expects(:http).returns(http) http.expects(:get).raises(OpenSSL::SSL::SSLError, 'Expired certificate') - assert_raise(ActiveResource::SSLError) { @conn.get('/people/1.xml') } + assert_raise(ActiveResource::SSLError) { @conn.get('/people/1.json') } end def test_auth_type_can_be_string diff --git a/activeresource/test/cases/finder_test.rb b/activeresource/test/cases/finder_test.rb index ebb783996d..9c51f2a390 100644 --- a/activeresource/test/cases/finder_test.rb +++ b/activeresource/test/cases/finder_test.rb @@ -100,23 +100,23 @@ class FinderTest < Test::Unit::TestCase end def test_find_all_by_from - ActiveResource::HttpMock.respond_to { |m| m.get "/companies/1/people.xml", {}, @people_david } + ActiveResource::HttpMock.respond_to { |m| m.get "/companies/1/people.json", {}, @people_david } - people = Person.find(:all, :from => "/companies/1/people.xml") + people = Person.find(:all, :from => "/companies/1/people.json") assert_equal 1, people.size assert_equal "David", people.first.name end def test_find_all_by_from_with_options - ActiveResource::HttpMock.respond_to { |m| m.get "/companies/1/people.xml", {}, @people_david } + ActiveResource::HttpMock.respond_to { |m| m.get "/companies/1/people.json", {}, @people_david } - people = Person.find(:all, :from => "/companies/1/people.xml") + people = Person.find(:all, :from => "/companies/1/people.json") assert_equal 1, people.size assert_equal "David", people.first.name end def test_find_all_by_symbol_from - ActiveResource::HttpMock.respond_to { |m| m.get "/people/managers.xml", {}, @people_david } + ActiveResource::HttpMock.respond_to { |m| m.get "/people/managers.json", {}, @people_david } people = Person.find(:all, :from => :managers) assert_equal 1, people.size @@ -124,14 +124,14 @@ class FinderTest < Test::Unit::TestCase end def test_find_single_by_from - ActiveResource::HttpMock.respond_to { |m| m.get "/companies/1/manager.xml", {}, @david } + ActiveResource::HttpMock.respond_to { |m| m.get "/companies/1/manager.json", {}, @david } - david = Person.find(:one, :from => "/companies/1/manager.xml") + david = Person.find(:one, :from => "/companies/1/manager.json") assert_equal "David", david.name end def test_find_single_by_symbol_from - ActiveResource::HttpMock.respond_to { |m| m.get "/people/leader.xml", {}, @david } + ActiveResource::HttpMock.respond_to { |m| m.get "/people/leader.json", {}, @david } david = Person.find(:one, :from => :leader) assert_equal "David", david.name diff --git a/activeresource/test/cases/format_test.rb b/activeresource/test/cases/format_test.rb index f8d33f99fa..174142ec52 100644 --- a/activeresource/test/cases/format_test.rb +++ b/activeresource/test/cases/format_test.rb @@ -51,28 +51,30 @@ class FormatTest < Test::Unit::TestCase end def test_formats_on_custom_element_method - for format in [ :json, :xml ] + [:json, :xml].each do |format| using_format(Person, format) do + david = (format == :json ? { :person => @david } : @david) ActiveResource::HttpMock.respond_to do |mock| - mock.get "/people/2.#{format}", {'Accept' => ActiveResource::Formats[format].mime_type}, ActiveResource::Formats[format].encode(@david) - mock.get "/people/2/shallow.#{format}", {'Accept' => ActiveResource::Formats[format].mime_type}, ActiveResource::Formats[format].encode(@david) + mock.get "/people/2.#{format}", { 'Accept' => ActiveResource::Formats[format].mime_type }, ActiveResource::Formats[format].encode(david) + mock.get "/people/2/shallow.#{format}", { 'Accept' => ActiveResource::Formats[format].mime_type }, ActiveResource::Formats[format].encode(david) end + remote_programmer = Person.find(2).get(:shallow) assert_equal @david[:id], remote_programmer['id'] assert_equal @david[:name], remote_programmer['name'] end - end - for format in [ :json, :xml ] - ryan = ActiveResource::Formats[format].encode({ :name => 'Ryan' }) + ryan_hash = { :name => 'Ryan' } + ryan_hash = (format == :json ? { :person => ryan_hash } : ryan_hash) + ryan = ActiveResource::Formats[format].encode(ryan_hash) using_format(Person, format) do remote_ryan = Person.new(:name => 'Ryan') - ActiveResource::HttpMock.respond_to.post "/people.#{format}", {'Content-Type' => ActiveResource::Formats[format].mime_type}, ryan, 201, {'Location' => "/people/5.#{format}"} + ActiveResource::HttpMock.respond_to.post "/people.#{format}", { 'Content-Type' => ActiveResource::Formats[format].mime_type}, ryan, 201, { 'Location' => "/people/5.#{format}" } remote_ryan.save remote_ryan = Person.new(:name => 'Ryan') - ActiveResource::HttpMock.respond_to.post "/people/new/register.#{format}", {'Content-Type' => ActiveResource::Formats[format].mime_type}, ryan, 201, {'Location' => "/people/5.#{format}"} - assert_equal ActiveResource::Response.new(ryan, 201, {'Location' => "/people/5.#{format}"}), remote_ryan.post(:register) + ActiveResource::HttpMock.respond_to.post "/people/new/register.#{format}", { 'Content-Type' => ActiveResource::Formats[format].mime_type}, ryan, 201, { 'Location' => "/people/5.#{format}" } + assert_equal ActiveResource::Response.new(ryan, 201, { 'Location' => "/people/5.#{format}" }), remote_ryan.post(:register) end end end diff --git a/activeresource/test/cases/http_mock_test.rb b/activeresource/test/cases/http_mock_test.rb index cd5155924a..d2fd911314 100644 --- a/activeresource/test/cases/http_mock_test.rb +++ b/activeresource/test/cases/http_mock_test.rb @@ -11,10 +11,10 @@ class HttpMockTest < ActiveSupport::TestCase [:post, :put, :get, :delete, :head].each do |method| test "responds to simple #{method} request" do ActiveResource::HttpMock.respond_to do |mock| - mock.send(method, "/people/1", {FORMAT_HEADER[method] => "application/xml"}, "Response") + mock.send(method, "/people/1", { FORMAT_HEADER[method] => "application/json" }, "Response") end - assert_equal "Response", request(method, "/people/1", FORMAT_HEADER[method] => "application/xml").body + assert_equal "Response", request(method, "/people/1", FORMAT_HEADER[method] => "application/json").body end test "adds format header by default to #{method} request" do @@ -22,7 +22,7 @@ class HttpMockTest < ActiveSupport::TestCase mock.send(method, "/people/1", {}, "Response") end - assert_equal "Response", request(method, "/people/1", FORMAT_HEADER[method] => "application/xml").body + assert_equal "Response", request(method, "/people/1", FORMAT_HEADER[method] => "application/json").body end test "respond only when headers match header by default to #{method} request" do @@ -53,8 +53,8 @@ class HttpMockTest < ActiveSupport::TestCase test "responds correctly when format header is given to #{method} request" do ActiveResource::HttpMock.respond_to do |mock| - mock.send(method, "/people/1", {FORMAT_HEADER[method] => "application/xml"}, "XML") - mock.send(method, "/people/1", {FORMAT_HEADER[method] => "application/json"}, "Json") + mock.send(method, "/people/1", { FORMAT_HEADER[method] => "application/xml" }, "XML") + mock.send(method, "/people/1", { FORMAT_HEADER[method] => "application/json" }, "Json") end assert_equal "XML", request(method, "/people/1", FORMAT_HEADER[method] => "application/xml").body @@ -63,22 +63,22 @@ class HttpMockTest < ActiveSupport::TestCase test "raises InvalidRequestError if no response found for the #{method} request" do ActiveResource::HttpMock.respond_to do |mock| - mock.send(method, "/people/1", {FORMAT_HEADER[method] => "application/xml"}, "XML") + mock.send(method, "/people/1", { FORMAT_HEADER[method] => "application/json" }, "json") end assert_raise(::ActiveResource::InvalidRequestError) do - request(method, "/people/1", FORMAT_HEADER[method] => "application/json") + request(method, "/people/1", FORMAT_HEADER[method] => "application/xml") end end end test "allows you to send in pairs directly to the respond_to method" do - matz = { :id => 1, :name => "Matz" }.to_xml(:root => "person") + matz = { :person => { :id => 1, :name => "Matz" } }.to_json - create_matz = ActiveResource::Request.new(:post, '/people.xml', matz, {}) - created_response = ActiveResource::Response.new("", 201, {"Location" => "/people/1.xml"}) - get_matz = ActiveResource::Request.new(:get, '/people/1.xml', nil) + create_matz = ActiveResource::Request.new(:post, '/people.json', matz, {}) + created_response = ActiveResource::Response.new("", 201, { "Location" => "/people/1.json" }) + get_matz = ActiveResource::Request.new(:get, '/people/1.json', nil) ok_response = ActiveResource::Response.new(matz, 200, {}) pairs = {create_matz => created_response, get_matz => ok_response} @@ -91,24 +91,24 @@ class HttpMockTest < ActiveSupport::TestCase test "resets all mocked responses on each call to respond_to with a block by default" do ActiveResource::HttpMock.respond_to do |mock| - mock.send(:get, "/people/1", {}, "XML1") + mock.send(:get, "/people/1", {}, "JSON1") end assert_equal 1, ActiveResource::HttpMock.responses.length ActiveResource::HttpMock.respond_to do |mock| - mock.send(:get, "/people/2", {}, "XML2") + mock.send(:get, "/people/2", {}, "JSON2") end assert_equal 1, ActiveResource::HttpMock.responses.length end test "resets all mocked responses on each call to respond_to by passing pairs by default" do ActiveResource::HttpMock.respond_to do |mock| - mock.send(:get, "/people/1", {}, "XML1") + mock.send(:get, "/people/1", {}, "JSON1") end assert_equal 1, ActiveResource::HttpMock.responses.length - matz = { :id => 1, :name => "Matz" }.to_xml(:root => "person") - get_matz = ActiveResource::Request.new(:get, '/people/1.xml', nil) + matz = { :person => { :id => 1, :name => "Matz" } }.to_json + get_matz = ActiveResource::Request.new(:get, '/people/1.json', nil) ok_response = ActiveResource::Response.new(matz, 200, {}) ActiveResource::HttpMock.respond_to({get_matz => ok_response}) @@ -117,24 +117,24 @@ class HttpMockTest < ActiveSupport::TestCase test "allows you to add new responses to the existing responses by calling a block" do ActiveResource::HttpMock.respond_to do |mock| - mock.send(:get, "/people/1", {}, "XML1") + mock.send(:get, "/people/1", {}, "JSON1") end assert_equal 1, ActiveResource::HttpMock.responses.length ActiveResource::HttpMock.respond_to(false) do |mock| - mock.send(:get, "/people/2", {}, "XML2") + mock.send(:get, "/people/2", {}, "JSON2") end assert_equal 2, ActiveResource::HttpMock.responses.length end test "allows you to add new responses to the existing responses by passing pairs" do ActiveResource::HttpMock.respond_to do |mock| - mock.send(:get, "/people/1", {}, "XML1") + mock.send(:get, "/people/1", {}, "JSON1") end assert_equal 1, ActiveResource::HttpMock.responses.length - matz = { :id => 1, :name => "Matz" }.to_xml(:root => "person") - get_matz = ActiveResource::Request.new(:get, '/people/1.xml', nil) + matz = { :person => { :id => 1, :name => "Matz" } }.to_json + get_matz = ActiveResource::Request.new(:get, '/people/1.json', nil) ok_response = ActiveResource::Response.new(matz, 200, {}) ActiveResource::HttpMock.respond_to({get_matz => ok_response}, false) @@ -143,23 +143,23 @@ class HttpMockTest < ActiveSupport::TestCase test "allows you to replace the existing reponse with the same request by calling a block" do ActiveResource::HttpMock.respond_to do |mock| - mock.send(:get, "/people/1", {}, "XML1") + mock.send(:get, "/people/1", {}, "JSON1") end assert_equal 1, ActiveResource::HttpMock.responses.length ActiveResource::HttpMock.respond_to(false) do |mock| - mock.send(:get, "/people/1", {}, "XML2") + mock.send(:get, "/people/1", {}, "JSON2") end assert_equal 1, ActiveResource::HttpMock.responses.length end test "allows you to replace the existing reponse with the same request by passing pairs" do ActiveResource::HttpMock.respond_to do |mock| - mock.send(:get, "/people/1", {}, "XML1") + mock.send(:get, "/people/1", {}, "JSON1") end assert_equal 1, ActiveResource::HttpMock.responses.length - matz = { :id => 1, :name => "Matz" }.to_xml(:root => "person") + matz = { :person => { :id => 1, :name => "Matz" } }.to_json get_matz = ActiveResource::Request.new(:get, '/people/1', nil) ok_response = ActiveResource::Response.new(matz, 200, {}) @@ -169,19 +169,19 @@ class HttpMockTest < ActiveSupport::TestCase test "do not replace the response with the same path but different method by calling a block" do ActiveResource::HttpMock.respond_to do |mock| - mock.send(:get, "/people/1", {}, "XML1") + mock.send(:get, "/people/1", {}, "JSON1") end assert_equal 1, ActiveResource::HttpMock.responses.length ActiveResource::HttpMock.respond_to(false) do |mock| - mock.send(:put, "/people/1", {}, "XML2") + mock.send(:put, "/people/1", {}, "JSON2") end assert_equal 2, ActiveResource::HttpMock.responses.length end test "do not replace the response with the same path but different method by passing pairs" do ActiveResource::HttpMock.respond_to do |mock| - mock.send(:get, "/people/1", {}, "XML1") + mock.send(:get, "/people/1", {}, "JSON1") end assert_equal 1, ActiveResource::HttpMock.responses.length diff --git a/activeresource/test/cases/log_subscriber_test.rb b/activeresource/test/cases/log_subscriber_test.rb index 3cd96007db..b9143f5b67 100644 --- a/activeresource/test/cases/log_subscriber_test.rb +++ b/activeresource/test/cases/log_subscriber_test.rb @@ -10,9 +10,9 @@ class LogSubscriberTest < ActiveSupport::TestCase def setup super - @matz = { :id => 1, :name => 'Matz' }.to_xml(:root => 'person') + @matz = { :person => { :id => 1, :name => 'Matz' } }.to_json ActiveResource::HttpMock.respond_to do |mock| - mock.get "/people/1.xml", {}, @matz + mock.get "/people/1.json", {}, @matz end ActiveResource::LogSubscriber.attach_to :active_resource @@ -26,7 +26,7 @@ class LogSubscriberTest < ActiveSupport::TestCase matz = Person.find(1) wait assert_equal 2, @logger.logged(:info).size - assert_equal "GET http://37s.sunrise.i:3000/people/1.xml", @logger.logged(:info)[0] - assert_match(/\-\-\> 200 200 106/, @logger.logged(:info)[1]) + assert_equal "GET http://37s.sunrise.i:3000/people/1.json", @logger.logged(:info)[0] + assert_match(/\-\-\> 200 200 33/, @logger.logged(:info)[1]) end end diff --git a/activeresource/test/cases/observing_test.rb b/activeresource/test/cases/observing_test.rb index 925ec7a84a..ca3ab5d03d 100644 --- a/activeresource/test/cases/observing_test.rb +++ b/activeresource/test/cases/observing_test.rb @@ -20,13 +20,13 @@ class ObservingTest < Test::Unit::TestCase end def setup - @matz = { :id => 1, :name => 'Matz' }.to_xml(:root => 'person') + @matz = { 'person' => { :id => 1, :name => 'Matz' } }.to_json ActiveResource::HttpMock.respond_to do |mock| - mock.get "/people/1.xml", {}, @matz - mock.post "/people.xml", {}, @matz, 201, 'Location' => '/people/1.xml' - mock.put "/people/1.xml", {}, nil, 204 - mock.delete "/people/1.xml", {}, nil, 200 + mock.get "/people/1.json", {}, @matz + mock.post "/people.json", {}, @matz, 201, 'Location' => '/people/1.json' + mock.put "/people/1.json", {}, nil, 204 + mock.delete "/people/1.json", {}, nil, 200 end PersonObserver.instance diff --git a/activeresource/test/cases/validations_test.rb b/activeresource/test/cases/validations_test.rb index 3b1caecb04..c6c6e1d786 100644 --- a/activeresource/test/cases/validations_test.rb +++ b/activeresource/test/cases/validations_test.rb @@ -8,9 +8,9 @@ require 'active_support/core_ext/hash/conversions' class ValidationsTest < ActiveModel::TestCase VALID_PROJECT_HASH = { :name => "My Project", :description => "A project" } def setup - @my_proj = VALID_PROJECT_HASH.to_xml(:root => "person") + @my_proj = { "person" => VALID_PROJECT_HASH }.to_json ActiveResource::HttpMock.respond_to do |mock| - mock.post "/projects.xml", {}, @my_proj, 201, 'Location' => '/projects/5.xml' + mock.post "/projects.json", {}, @my_proj, 201, 'Location' => '/projects/5.json' end end diff --git a/activeresource/test/setter_trap.rb b/activeresource/test/setter_trap.rb index 437fbdad32..7cfd9ca111 100644 --- a/activeresource/test/setter_trap.rb +++ b/activeresource/test/setter_trap.rb @@ -1,5 +1,3 @@ -require 'abstract_unit' - class SetterTrap < ActiveSupport::BasicObject class << self def rollback_sets(obj) |