diff --git a/.rubocop-https---raw-githubusercontent-com-rails-rails-master--rubocop-yml b/.rubocop-https---raw-githubusercontent-com-rails-rails-master--rubocop-yml new file mode 100644 index 0000000000..615a229432 --- /dev/null +++ b/.rubocop-https---raw-githubusercontent-com-rails-rails-master--rubocop-yml @@ -0,0 +1,221 @@ +AllCops: + TargetRubyVersion: 2.4 + # RuboCop has a bunch of cops enabled by default. This setting tells RuboCop + # to ignore them, so only the ones explicitly set in this file are enabled. + DisabledByDefault: true + Exclude: + - '**/templates/**/*' + - '**/vendor/**/*' + - 'actionpack/lib/action_dispatch/journey/parser.rb' + - 'railties/test/fixtures/tmp/**/*' + - 'node_modules/**/*' + +Performance: + Exclude: + - '**/test/**/*' + +Rails: + Enabled: true + +# Prefer assert_not over assert ! +Rails/AssertNot: + Include: + - '**/test/**/*' + +# Prefer assert_not_x over refute_x +Rails/RefuteMethods: + Include: + - '**/test/**/*' + +# Prefer &&/|| over and/or. +Style/AndOr: + Enabled: true + +# Do not use braces for hash literals when they are the last argument of a +# method call. +Style/BracesAroundHashParameters: + Enabled: true + EnforcedStyle: context_dependent + +# Align `when` with `case`. +Layout/CaseIndentation: + Enabled: true + +# Align comments with method definitions. +Layout/CommentIndentation: + Enabled: true + +Layout/ElseAlignment: + Enabled: true + +# Align `end` with the matching keyword or starting expression except for +# assignments, where it should be aligned with the LHS. +Layout/EndAlignment: + Enabled: true + EnforcedStyleAlignWith: variable + AutoCorrect: true + +Layout/EmptyLineAfterMagicComment: + Enabled: true + +Layout/EmptyLinesAroundBlockBody: + Enabled: true + +# In a regular class definition, no empty lines around the body. +Layout/EmptyLinesAroundClassBody: + Enabled: true + +# In a regular method definition, no empty lines around the body. +Layout/EmptyLinesAroundMethodBody: + Enabled: true + +# In a regular module definition, no empty lines around the body. +Layout/EmptyLinesAroundModuleBody: + Enabled: true + +Layout/FirstParameterIndentation: + Enabled: true + +# Use Ruby >= 1.9 syntax for hashes. Prefer { a: :b } over { :a => :b }. +Style/HashSyntax: + Enabled: true + +# Method definitions after `private` or `protected` isolated calls need one +# extra level of indentation. +Layout/IndentationConsistency: + Enabled: true + EnforcedStyle: rails + +# Two spaces, no tabs (for indentation). +Layout/IndentationWidth: + Enabled: true + +Layout/LeadingCommentSpace: + Enabled: true + +Layout/SpaceAfterColon: + Enabled: true + +Layout/SpaceAfterComma: + Enabled: true + +Layout/SpaceAroundEqualsInParameterDefault: + Enabled: true + +Layout/SpaceAroundKeyword: + Enabled: true + +Layout/SpaceAroundOperators: + Enabled: true + +Layout/SpaceBeforeComma: + Enabled: true + +Layout/SpaceBeforeFirstArg: + Enabled: true + +Style/DefWithParentheses: + Enabled: true + +# Defining a method with parameters needs parentheses. +Style/MethodDefParentheses: + Enabled: true + +Style/FrozenStringLiteralComment: + Enabled: true + EnforcedStyle: always + Exclude: + - 'actionview/test/**/*.builder' + - 'actionview/test/**/*.ruby' + - 'actionpack/test/**/*.builder' + - 'actionpack/test/**/*.ruby' + - 'activestorage/db/migrate/**/*.rb' + +Style/RedundantFreeze: + Enabled: true + Exclude: + - 'actionpack/lib/action_dispatch/journey/router/utils.rb' + - 'activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb' + +# Use `foo {}` not `foo{}`. +Layout/SpaceBeforeBlockBraces: + Enabled: true + +# Use `foo { bar }` not `foo {bar}`. +Layout/SpaceInsideBlockBraces: + Enabled: true + EnforcedStyleForEmptyBraces: space + +# Use `{ a: 1 }` not `{a:1}`. +Layout/SpaceInsideHashLiteralBraces: + Enabled: true + +Layout/SpaceInsideParens: + Enabled: true + +# Check quotes usage according to lint rule below. +Style/StringLiterals: + Enabled: true + EnforcedStyle: double_quotes + +# Detect hard tabs, no hard tabs. +Layout/Tab: + Enabled: true + +# Blank lines should not have any spaces. +Layout/TrailingBlankLines: + Enabled: true + +# No trailing whitespace. +Layout/TrailingWhitespace: + Enabled: true + +# Use quotes for string literals when they are enough. +Style/UnneededPercentQ: + Enabled: true + +# Use my_method(my_arg) not my_method( my_arg ) or my_method my_arg. +Lint/RequireParentheses: + Enabled: true + +Lint/StringConversionInInterpolation: + Enabled: true + +Lint/UriEscapeUnescape: + Enabled: true + +Style/ParenthesesAroundCondition: + Enabled: true + +Style/RedundantReturn: + Enabled: true + AllowMultipleReturnValues: true + +Style/Semicolon: + Enabled: true + AllowAsExpressionSeparator: true + +# Prefer Foo.method over Foo::method +Style/ColonMethodCall: + Enabled: true + +Style/TrivialAccessors: + Enabled: true + +Performance/FlatMap: + Enabled: true + +Performance/RedundantMerge: + Enabled: true + +Performance/StartWith: + Enabled: true + +Performance/EndWith: + Enabled: true + +Performance/RegexpMatch: + Enabled: true + +Performance/UnfreezeString: + Enabled: true diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 0000000000..6306f10e24 --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,5 @@ +inherit_from: https://raw.githubusercontent.com/rails/rails/master/.rubocop.yml + +AllCops: + TargetRubyVersion: 2.2 + DisabledByDefault: true diff --git a/Gemfile b/Gemfile index 187cc13901..92f2a83739 100644 --- a/Gemfile +++ b/Gemfile @@ -1,16 +1,18 @@ -source 'https://rubygems.org' +# frozen_string_literal: true + +source "https://rubygems.org" git_source(:github) { |repo| "https://github.com/#{repo}" } -branch = ENV.fetch('BRANCH', 'master') -gem 'activesupport', github: 'rails/rails', branch: branch -gem 'activemodel', github: 'rails/rails', branch: branch -gem 'activejob', github: 'rails/rails', branch: branch +branch = ENV.fetch("BRANCH", "master") +gem "activesupport", github: "rails/rails", branch: branch +gem "activemodel", github: "rails/rails", branch: branch +gem "activejob", github: "rails/rails", branch: branch gemspec platform :mri do group :test do - gem 'ruby-prof' + gem "ruby-prof" end end diff --git a/Rakefile b/Rakefile index db6f6418d9..0509fe47cb 100644 --- a/Rakefile +++ b/Rakefile @@ -1,27 +1,29 @@ #!/usr/bin/env rake -require 'rake/testtask' -require 'bundler' +# frozen_string_literal: true + +require "rake/testtask" +require "bundler" Bundler::GemHelper.install_tasks desc "Default Task" -task :default => [ :test ] +task default: [ :test ] # Run the unit tests Rake::TestTask.new { |t| t.libs << "test" - t.pattern = 'test/**/*_test.rb' + t.pattern = "test/**/*_test.rb" t.warning = true t.verbose = true } namespace :test do task :isolated do - ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME')) + ruby = File.join(*RbConfig::CONFIG.values_at("bindir", "RUBY_INSTALL_NAME")) activesupport_path = "#{File.dirname(__FILE__)}/../activesupport/lib" Dir.glob("test/**/*_test.rb").all? do |file| - sh(ruby, '-w', "-Ilib:test:#{activesupport_path}", file) - end or raise "Failures" + sh(ruby, "-w", "-Ilib:test:#{activesupport_path}", file) + end || raise("Failures") end end diff --git a/activeresource.gemspec b/activeresource.gemspec index bf51af104d..26b8aaac04 100644 --- a/activeresource.gemspec +++ b/activeresource.gemspec @@ -1,30 +1,32 @@ +# frozen_string_literal: true + $LOAD_PATH.push File.expand_path("../lib", __FILE__) -require 'active_resource/version' +require "active_resource/version" Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY - s.name = 'activeresource' + s.name = "activeresource" s.version = ActiveResource::VERSION::STRING - s.summary = 'REST modeling framework (part of Rails).' - s.description = 'REST on Rails. Wrap your RESTful web app with Ruby classes and work with them like Active Record models.' - s.license = 'MIT' + s.summary = "REST modeling framework (part of Rails)." + s.description = "REST on Rails. Wrap your RESTful web app with Ruby classes and work with them like Active Record models." + s.license = "MIT" - s.author = 'David Heinemeier Hansson' - s.email = 'david@loudthinking.com' - s.homepage = 'http://www.rubyonrails.org' + s.author = "David Heinemeier Hansson" + s.email = "david@loudthinking.com" + s.homepage = "http://www.rubyonrails.org" - s.files = Dir['MIT-LICENSE', 'README.rdoc', 'lib/**/*'] - s.require_path = 'lib' + s.files = Dir["MIT-LICENSE", "README.rdoc", "lib/**/*"] + s.require_path = "lib" s.extra_rdoc_files = %w( README.rdoc ) - s.rdoc_options.concat ['--main', 'README.rdoc'] + s.rdoc_options.concat ["--main", "README.rdoc"] - s.required_ruby_version = '>= 2.2.2' + s.required_ruby_version = ">= 2.2.2" - s.add_dependency('activesupport', '>= 5.0', '< 7') - s.add_dependency('activemodel', '>= 5.0', '< 7') - s.add_dependency('activemodel-serializers-xml', '~> 1.0') + s.add_dependency("activesupport", ">= 5.0", "< 7") + s.add_dependency("activemodel", ">= 5.0", "< 7") + s.add_dependency("activemodel-serializers-xml", "~> 1.0") - s.add_development_dependency('rake') - s.add_development_dependency('mocha', '>= 0.13.0') + s.add_development_dependency("rake") + s.add_development_dependency("mocha", ">= 0.13.0") end diff --git a/examples/performance.rb b/examples/performance.rb index e4df7a38a4..075ac329ea 100644 --- a/examples/performance.rb +++ b/examples/performance.rb @@ -1,51 +1,53 @@ -require 'rubygems' -require 'active_resource' -require 'benchmark' +# frozen_string_literal: true -TIMES = (ENV['N'] || 10_000).to_i +require "rubygems" +require "active_resource" +require "benchmark" + +TIMES = (ENV["N"] || 10_000).to_i # deep nested resource attrs = { - :id => 1, - :name => 'Luis', - :age => 21, - :friends => [ + id: 1, + name: "Luis", + age: 21, + friends: [ { - :name => 'JK', - :age => 24, - :colors => ['red', 'green', 'blue'], - :brothers => [ + name: "JK", + age: 24, + colors: ["red", "green", "blue"], + brothers: [ { - :name => 'Mateo', - :age => 35, - :children => [{ :name => 'Edith', :age => 5 }, { :name => 'Martha', :age => 4 }] + name: "Mateo", + age: 35, + children: [{ name: "Edith", age: 5 }, { name: "Martha", age: 4 }] }, { - :name => 'Felipe', - :age => 33, - :children => [{ :name => 'Bryan', :age => 1 }, { :name => 'Luke', :age => 0 }] + name: "Felipe", + age: 33, + children: [{ name: "Bryan", age: 1 }, { name: "Luke", age: 0 }] } ] }, { - :name => 'Eduardo', - :age => 20, - :colors => [], - :brothers => [ + name: "Eduardo", + age: 20, + colors: [], + brothers: [ { - :name => 'Sebas', - :age => 23, - :children => [{ :name => 'Andres', :age => 0 }, { :name => 'Jorge', :age => 2 }] + name: "Sebas", + age: 23, + children: [{ name: "Andres", age: 0 }, { name: "Jorge", age: 2 }] }, { - :name => 'Elsa', - :age => 19, - :children => [{ :name => 'Natacha', :age => 1 }] + name: "Elsa", + age: 19, + children: [{ name: "Natacha", age: 1 }] }, { - :name => 'Milena', - :age => 16, - :children => [] + name: "Milena", + age: 16, + children: [] } ] } @@ -63,8 +65,8 @@ class Customer < ActiveResource::Base end Benchmark.bm(40) do |x| - x.report('Model.new (instantiation)') { TIMES.times { Customer.new } } - x.report('Nested::Model.new (instantiation)') { TIMES.times { Nested::Customer.new } } - x.report('Model.new (setting attributes)') { TIMES.times { Customer.new attrs } } - x.report('Nested::Model.new (setting attributes)') { TIMES.times { Nested::Customer.new attrs } } + x.report("Model.new (instantiation)") { TIMES.times { Customer.new } } + x.report("Nested::Model.new (instantiation)") { TIMES.times { Nested::Customer.new } } + x.report("Model.new (setting attributes)") { TIMES.times { Customer.new attrs } } + x.report("Nested::Model.new (setting attributes)") { TIMES.times { Nested::Customer.new attrs } } end diff --git a/lib/active_resource.rb b/lib/active_resource.rb index b43d8a96fc..729ad530d6 100644 --- a/lib/active_resource.rb +++ b/lib/active_resource.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + #-- # Copyright (c) 2006-2012 David Heinemeier Hansson # @@ -21,10 +23,10 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #++ -require 'active_support' -require 'active_model' -require 'active_resource/exceptions' -require 'active_resource/version' +require "active_support" +require "active_model" +require "active_resource/exceptions" +require "active_resource/version" module ActiveResource extend ActiveSupport::Autoload @@ -41,4 +43,4 @@ module ActiveResource autoload :Collection end -require 'active_resource/railtie' if defined?(Rails.application) +require "active_resource/railtie" if defined?(Rails.application) diff --git a/lib/active_resource/active_job_serializer.rb b/lib/active_resource/active_job_serializer.rb index e4fb030224..8aef668bfd 100644 --- a/lib/active_resource/active_job_serializer.rb +++ b/lib/active_resource/active_job_serializer.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ActiveResource class ActiveJobSerializer < ActiveJob::Serializers::ObjectSerializer def serialize(resource) diff --git a/lib/active_resource/associations.rb b/lib/active_resource/associations.rb index af4b5e5c90..ad39e7dd1e 100644 --- a/lib/active_resource/associations.rb +++ b/lib/active_resource/associations.rb @@ -1,10 +1,11 @@ -module ActiveResource::Associations +# frozen_string_literal: true +module ActiveResource::Associations module Builder - autoload :Association, 'active_resource/associations/builder/association' - autoload :HasMany, 'active_resource/associations/builder/has_many' - autoload :HasOne, 'active_resource/associations/builder/has_one' - autoload :BelongsTo, 'active_resource/associations/builder/belongs_to' + autoload :Association, "active_resource/associations/builder/association" + autoload :HasMany, "active_resource/associations/builder/has_many" + autoload :HasOne, "active_resource/associations/builder/has_one" + autoload :BelongsTo, "active_resource/associations/builder/belongs_to" end @@ -112,7 +113,7 @@ def has_one(name, options = {}) # belongs_to :customer, :foreign_key => 'user_id' # Creates a belongs_to association called customer which would be resolved by the foreign_key user_id instead of customer_id # - def belongs_to(name, options={}) + def belongs_to(name, options = {}) Builder::BelongsTo.build(self, name, options) end @@ -147,7 +148,7 @@ def defines_has_many_finder_method(reflection) elsif attributes.include?(method_name) attributes[method_name] elsif !new_record? - instance_variable_set(ivar_name, reflection.klass.find(:all, :params => {:"#{self.class.element_name}_id" => self.id})) + instance_variable_set(ivar_name, reflection.klass.find(:all, params: { :"#{self.class.element_name}_id" => self.id })) else instance_variable_set(ivar_name, self.class.collection_parser.new) end @@ -165,11 +166,10 @@ def defines_has_one_finder_method(reflection) elsif attributes.include?(method_name) attributes[method_name] elsif reflection.klass.respond_to?(:singleton_name) - instance_variable_set(ivar_name, reflection.klass.find(:params => {:"#{self.class.element_name}_id" => self.id})) + instance_variable_set(ivar_name, reflection.klass.find(params: { :"#{self.class.element_name}_id" => self.id })) else - instance_variable_set(ivar_name, reflection.klass.find(:one, :from => "/#{self.class.collection_name}/#{self.id}/#{method_name}#{self.class.format_extension}")) + instance_variable_set(ivar_name, reflection.klass.find(:one, from: "/#{self.class.collection_name}/#{self.id}/#{method_name}#{self.class.format_extension}")) end end end - end diff --git a/lib/active_resource/associations/builder/association.rb b/lib/active_resource/associations/builder/association.rb index 2580633472..6c1b583485 100644 --- a/lib/active_resource/associations/builder/association.rb +++ b/lib/active_resource/associations/builder/association.rb @@ -1,6 +1,7 @@ +# frozen_string_literal: true + module ActiveResource::Associations::Builder class Association #:nodoc: - # providing a Class-Variable, which will have a different store of subclasses class_attribute :valid_options self.valid_options = [:class_name] @@ -25,8 +26,8 @@ def build private - def validate_options - options.assert_valid_keys(self.class.valid_options) - end + def validate_options + options.assert_valid_keys(self.class.valid_options) + end end end diff --git a/lib/active_resource/associations/builder/belongs_to.rb b/lib/active_resource/associations/builder/belongs_to.rb index 144d97c7ef..c5f903dbf5 100644 --- a/lib/active_resource/associations/builder/belongs_to.rb +++ b/lib/active_resource/associations/builder/belongs_to.rb @@ -1,4 +1,6 @@ -module ActiveResource::Associations::Builder +# frozen_string_literal: true + +module ActiveResource::Associations::Builder class BelongsTo < Association self.valid_options += [:foreign_key] @@ -8,7 +10,7 @@ def build validate_options reflection = model.create_reflection(self.class.macro, name, options) model.defines_belongs_to_finder_method(reflection) - return reflection + reflection end end end diff --git a/lib/active_resource/associations/builder/has_many.rb b/lib/active_resource/associations/builder/has_many.rb index 560a084612..84c860037a 100644 --- a/lib/active_resource/associations/builder/has_many.rb +++ b/lib/active_resource/associations/builder/has_many.rb @@ -1,4 +1,6 @@ -module ActiveResource::Associations::Builder +# frozen_string_literal: true + +module ActiveResource::Associations::Builder class HasMany < Association self.macro = :has_many diff --git a/lib/active_resource/associations/builder/has_one.rb b/lib/active_resource/associations/builder/has_one.rb index e3a5192617..d83ed48790 100644 --- a/lib/active_resource/associations/builder/has_one.rb +++ b/lib/active_resource/associations/builder/has_one.rb @@ -1,7 +1,9 @@ -module ActiveResource::Associations::Builder +# frozen_string_literal: true + +module ActiveResource::Associations::Builder class HasOne < Association self.macro = :has_one - + def build validate_options model.create_reflection(self.class.macro, name, options).tap do |reflection| diff --git a/lib/active_resource/base.rb b/lib/active_resource/base.rb index 5a86fa8161..abb90acfd4 100644 --- a/lib/active_resource/base.rb +++ b/lib/active_resource/base.rb @@ -1,26 +1,28 @@ -require 'active_support' -require 'active_support/core_ext/class/attribute_accessors' -require 'active_support/core_ext/class/attribute' -require 'active_support/core_ext/hash/indifferent_access' -require 'active_support/core_ext/kernel/reporting' -require 'active_support/core_ext/module/delegation' -require 'active_support/core_ext/module/aliasing' -require 'active_support/core_ext/object/blank' -require 'active_support/core_ext/object/to_query' -require 'active_support/core_ext/object/duplicable' -require 'set' -require 'uri' - -require 'active_support/core_ext/uri' -require 'active_resource/connection' -require 'active_resource/formats' -require 'active_resource/schema' -require 'active_resource/log_subscriber' -require 'active_resource/associations' -require 'active_resource/reflection' -require 'active_resource/threadsafe_attributes' - -require 'active_model/serializers/xml' +# frozen_string_literal: true + +require "active_support" +require "active_support/core_ext/class/attribute_accessors" +require "active_support/core_ext/class/attribute" +require "active_support/core_ext/hash/indifferent_access" +require "active_support/core_ext/kernel/reporting" +require "active_support/core_ext/module/delegation" +require "active_support/core_ext/module/aliasing" +require "active_support/core_ext/object/blank" +require "active_support/core_ext/object/to_query" +require "active_support/core_ext/object/duplicable" +require "set" +require "uri" + +require "active_support/core_ext/uri" +require "active_resource/connection" +require "active_resource/formats" +require "active_resource/schema" +require "active_resource/log_subscriber" +require "active_resource/associations" +require "active_resource/reflection" +require "active_resource/threadsafe_attributes" + +require "active_model/serializers/xml" module ActiveResource # ActiveResource::Base is the main class for mapping RESTful resources as models in a Rails application. @@ -383,7 +385,7 @@ def schema(&block) @schema ||= {}.with_indifferent_access @known_attributes ||= [] - schema_definition.attrs.each do |k,v| + schema_definition.attrs.each do |k, v| @schema[k] = v @known_attributes << k end @@ -422,7 +424,7 @@ def schema=(the_schema) raise ArgumentError, "Expected a hash" unless the_schema.kind_of? Hash schema do - the_schema.each {|k,v| attribute(k,v) } + the_schema.each { |k, v| attribute(k, v) } end end @@ -624,7 +626,7 @@ def read_timeout # * :ssl_timeout -The SSL timeout in seconds. def ssl_options=(options) self._connection = nil - @ssl_options = options + @ssl_options = options end # Returns the SSL options hash. @@ -689,15 +691,15 @@ def primary_key return primary_key if primary_key.is_a?(Symbol) primary_key.dup.freeze else - 'id' + "id" end end # Gets the \prefix for a resource's nested URL (e.g., prefix/collectionname/1.json) # This method is regenerated at runtime based on what the \prefix is set to. - def prefix(options={}) + def prefix(options = {}) default = site.path - default << '/' unless default[-1..-1] == '/' + default << "/" unless default[-1..-1] == "/" # generate the actual method based on the current site path self.prefix = default prefix(options) @@ -712,7 +714,7 @@ def prefix_source # Sets the \prefix for a resource's nested URL (e.g., prefix/collectionname/1.json). # Default value is site.path. - def prefix=(value = '/') + def prefix=(value = "/") # Replace :placeholders with '#{embedded options[:lookups]}' prefix_call = value.gsub(/:\w+/) { |key| "\#{URI.parser.escape options[#{key}].to_s}" } @@ -1006,7 +1008,7 @@ def all(*args) def where(clauses = {}) raise ArgumentError, "expected a clauses Hash, got #{clauses.inspect}" unless clauses.is_a? Hash - find(:all, :params => clauses) + find(:all, params: clauses) end @@ -1068,7 +1070,7 @@ def find_every(options) else prefix_options, query_options = split_options(options[:params]) path = collection_path(prefix_options, query_options) - instantiate_collection( (format.decode(connection.get(path, headers).body) || []), query_options, prefix_options ) + instantiate_collection((format.decode(connection.get(path, headers).body) || []), query_options, prefix_options) end rescue ActiveResource::ResourceNotFound # Swallowing ResourceNotFound exceptions and return nil - as per @@ -1201,13 +1203,13 @@ def initialize(attributes = {}, persisted = false) # not_ryan.hash # => {:not => "an ARes instance"} def clone # Clone all attributes except the pk and any nested ARes - cloned = Hash[attributes.reject {|k,v| k == self.class.primary_key || v.is_a?(ActiveResource::Base)}.map { |k, v| [k, v.clone] }] + cloned = Hash[attributes.reject { |k, v| k == self.class.primary_key || v.is_a?(ActiveResource::Base) }.map { |k, v| [k, v.clone] }] # Form the new resource - bypass initialize of resource with 'new' as that will call 'load' which # attempts to convert hashes into member objects and arrays into collections of objects. We want # the raw objects to be cloned so we bypass load by directly setting the attributes hash. resource = self.class.new({}) resource.prefix_options = self.prefix_options - resource.send :instance_variable_set, '@attributes', cloned + resource.send :instance_variable_set, "@attributes", cloned resource end @@ -1382,13 +1384,13 @@ def destroy # Person.delete(guys_id) # that_guy.exists? # => false def exists? - !new? && self.class.exists?(to_param, :params => prefix_options) + !new? && self.class.exists?(to_param, params: prefix_options) end # Returns the serialized string representation of the resource in the configured # serialization format specified in ActiveResource::Base.format. The options # applicable depend on the configured encoding format. - def encode(options={}) + def encode(options = {}) send("to_#{self.class.format.extension}", options) end @@ -1404,7 +1406,7 @@ def encode(options={}) # my_branch.reload # my_branch.name # => "Wilson Road" def reload - self.load(self.class.find(to_param, :params => @prefix_options).attributes, false, true) + self.load(self.class.find(to_param, params: @prefix_options).attributes, false, true) end # A method to manually load attributes from a \hash. Recursively loads collections of @@ -1445,21 +1447,21 @@ def load(attributes, remove_root = false, persisted = false) attributes.each do |key, value| @attributes[key.to_s] = case value - when Array - resource = nil - value.map do |attrs| - if attrs.is_a?(Hash) - resource ||= find_or_create_resource_for_collection(key) - resource.new(attrs, persisted) - else - attrs.duplicable? ? attrs.dup : attrs - end + when Array + resource = nil + value.map do |attrs| + if attrs.is_a?(Hash) + resource ||= find_or_create_resource_for_collection(key) + resource.new(attrs, persisted) + else + attrs.duplicable? ? attrs.dup : attrs end - when Hash - resource = find_or_create_resource_for(key) - resource.new(value, persisted) - else - value.duplicable? ? value.dup : value + end + when Hash + resource = find_or_create_resource_for(key) + resource.new(value, persisted) + else + value.duplicable? ? value.dup : value end end self @@ -1516,12 +1518,12 @@ def respond_to_missing?(method, include_priv = false) end end - def to_json(options={}) - super(include_root_in_json ? { :root => self.class.element_name }.merge(options) : options) + def to_json(options = {}) + super(include_root_in_json ? { root: self.class.element_name }.merge(options) : options) end - def to_xml(options={}) - super({ :root => self.class.element_name }.merge(options)) + def to_xml(options = {}) + super({ root: self.class.element_name }.merge(options)) end def read_attribute_for_serialization(n) @@ -1557,9 +1559,9 @@ def create end def load_attributes_from_response(response) - if (response_code_allows_body?(response.code.to_i) && - (response['Content-Length'].nil? || response['Content-Length'] != "0") && - !response.body.nil? && response.body.strip.size > 0) + if response_code_allows_body?(response.code.to_i) && + (response["Content-Length"].nil? || response["Content-Length"] != "0") && + !response.body.nil? && response.body.strip.size > 0 load(self.class.format.decode(response.body), true, true) @persisted = true end @@ -1567,7 +1569,7 @@ def load_attributes_from_response(response) # Takes a response from a typical create post and pulls the ID out def id_from_response(response) - response['Location'][/\/([^\/]*?)(\.\w+)?$/, 1] if response['Location'] + response["Location"][/\/([^\/]*?)(\.\w+)?$/, 1] if response["Location"] end def element_path(options = nil) @@ -1590,7 +1592,7 @@ def collection_path(options = nil) # Determine whether the response is allowed to have a body per HTTP 1.1 spec section 4.4.1 def response_code_allows_body?(c) - !((100..199).include?(c) || [204,304].include?(c)) + !((100..199).include?(c) || [204, 304].include?(c)) end # Tries to find a resource for a given collection name; if it fails, then the resource is created @@ -1603,7 +1605,7 @@ def find_or_create_resource_for_collection(name) # if it fails, then the resource is created def find_or_create_resource_in_modules(resource_name, module_names) receiver = Object - namespaces = module_names[0, module_names.size-1].map do |module_name| + namespaces = module_names[0, module_names.size - 1].map do |module_name| receiver = receiver.const_get(module_name) end const_args = [resource_name, false] @@ -1623,7 +1625,7 @@ def find_or_create_resource_for(name) if !const_valid?(*const_args) # resource_name is not a valid ruby module name and cannot be created normally - find_or_create_resource_for(:UnnamedResource) + find_or_create_resource_for(:UnnamedResource) elsif self.class.const_defined?(*const_args) self.class.const_get(*const_args) else diff --git a/lib/active_resource/callbacks.rb b/lib/active_resource/callbacks.rb index a852102738..c8f04cec94 100644 --- a/lib/active_resource/callbacks.rb +++ b/lib/active_resource/callbacks.rb @@ -1,4 +1,6 @@ -require 'active_support/core_ext/array/wrap' +# frozen_string_literal: true + +require "active_support/core_ext/array/wrap" module ActiveResource module Callbacks diff --git a/lib/active_resource/collection.rb b/lib/active_resource/collection.rb index de481eee00..7a6e8f0876 100644 --- a/lib/active_resource/collection.rb +++ b/lib/active_resource/collection.rb @@ -1,11 +1,13 @@ -require 'active_support/core_ext/module/delegation' -require 'active_support/inflector' +# frozen_string_literal: true + +require "active_support/core_ext/module/delegation" +require "active_support/inflector" module ActiveResource # :nodoc: class Collection # :nodoc: SELF_DEFINE_METHODS = [:to_a, :collect!, :map!] include Enumerable - delegate :to_yaml, :all?, *(Array.instance_methods(false) - SELF_DEFINE_METHODS), :to => :to_a + delegate :to_yaml, :all?, *(Array.instance_methods(false) - SELF_DEFINE_METHODS), to: :to_a # The array of actual elements returned by index actions attr_accessor :elements, :resource_class, :original_params diff --git a/lib/active_resource/connection.rb b/lib/active_resource/connection.rb index 82cc8cc311..7c644252a1 100644 --- a/lib/active_resource/connection.rb +++ b/lib/active_resource/connection.rb @@ -1,23 +1,24 @@ -require 'active_support/core_ext/benchmark' -require 'active_support/core_ext/uri' -require 'active_support/core_ext/object/inclusion' -require 'net/https' -require 'date' -require 'time' -require 'uri' +# frozen_string_literal: true + +require "active_support/core_ext/benchmark" +require "active_support/core_ext/uri" +require "active_support/core_ext/object/inclusion" +require "net/https" +require "date" +require "time" +require "uri" module ActiveResource # Class to handle connections to remote web services. # This class is used by ActiveResource::Base to interface with REST # services. class Connection - - HTTP_FORMAT_HEADER_NAMES = { :get => 'Accept', - :put => 'Content-Type', - :post => 'Content-Type', - :patch => 'Content-Type', - :delete => 'Accept', - :head => 'Accept' + HTTP_FORMAT_HEADER_NAMES = { get: "Accept", + put: "Content-Type", + post: "Content-Type", + patch: "Content-Type", + delete: "Accept", + head: "Accept" } attr_reader :site, :user, :password, :bearer_token, :auth_type, :timeout, :open_timeout, :read_timeout, :proxy, :ssl_options @@ -32,7 +33,7 @@ def requests # 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::JsonFormat, logger: nil) - raise ArgumentError, 'Missing site URI' unless site + raise ArgumentError, "Missing site URI" unless site @proxy = @user = @password = @bearer_token = nil self.site = site self.format = format @@ -53,19 +54,13 @@ def proxy=(proxy) end # Sets the user for remote service. - def user=(user) - @user = user - end + attr_writer :user # Sets the password for remote service. - def password=(password) - @password = password - end + attr_writer :password # Sets the bearer token for remote service. - def bearer_token=(bearer_token) - @bearer_token = bearer_token - end + attr_writer :bearer_token # Sets the auth type for remote service. def auth_type=(auth_type) @@ -73,24 +68,16 @@ def auth_type=(auth_type) end # Sets the number of seconds after which HTTP requests to the remote service should time out. - def timeout=(timeout) - @timeout = timeout - end + attr_writer :timeout # Sets the number of seconds after which HTTP connects to the remote service should time out. - def open_timeout=(timeout) - @open_timeout = timeout - end + attr_writer :open_timeout # Sets the number of seconds after which HTTP read requests to the remote service should time out. - def read_timeout=(timeout) - @read_timeout = timeout - end + attr_writer :read_timeout # Hash of options applied to Net::HTTP instance when +site+ protocol is 'https'. - def ssl_options=(options) - @ssl_options = options - end + attr_writer :ssl_options # Executes a GET request. # Used to get (find) resources. @@ -106,19 +93,19 @@ def delete(path, headers = {}) # Executes a PATCH request (see HTTP protocol documentation if unfamiliar). # Used to update resources. - def patch(path, body = '', headers = {}) + def patch(path, body = "", headers = {}) with_auth { request(:patch, path, body.to_s, build_request_headers(headers, :patch, self.site.merge(path))) } end # Executes a PUT request (see HTTP protocol documentation if unfamiliar). # Used to update resources. - def put(path, body = '', headers = {}) + def put(path, body = "", headers = {}) with_auth { request(:put, path, body.to_s, build_request_headers(headers, :put, self.site.merge(path))) } end # Executes a POST request. # Used to create new resources. - def post(path, body = '', headers = {}) + def post(path, body = "", headers = {}) with_auth { request(:post, path, body.to_s, build_request_headers(headers, :post, self.site.merge(path))) } end @@ -146,32 +133,32 @@ def request(method, path, *arguments) # Handles response and error codes from the remote service. def handle_response(response) case response.code.to_i - when 301, 302, 303, 307 - raise(Redirection.new(response)) - when 200...400 - response - when 400 - raise(BadRequest.new(response)) - when 401 - raise(UnauthorizedAccess.new(response)) - when 403 - raise(ForbiddenAccess.new(response)) - when 404 - raise(ResourceNotFound.new(response)) - when 405 - raise(MethodNotAllowed.new(response)) - when 409 - raise(ResourceConflict.new(response)) - when 410 - raise(ResourceGone.new(response)) - when 422 - raise(ResourceInvalid.new(response)) - when 401...500 - raise(ClientError.new(response)) - when 500...600 - raise(ServerError.new(response)) - else - raise(ConnectionError.new(response, "Unknown response code: #{response.code}")) + when 301, 302, 303, 307 + raise(Redirection.new(response)) + when 200...400 + response + when 400 + raise(BadRequest.new(response)) + when 401 + raise(UnauthorizedAccess.new(response)) + when 403 + raise(ForbiddenAccess.new(response)) + when 404 + raise(ResourceNotFound.new(response)) + when 405 + raise(MethodNotAllowed.new(response)) + when 409 + raise(ResourceConflict.new(response)) + when 410 + raise(ResourceGone.new(response)) + when 422 + raise(ResourceInvalid.new(response)) + when 401...500 + raise(ClientError.new(response)) + when 500...600 + raise(ServerError.new(response)) + else + raise(ConnectionError.new(response, "Unknown response code: #{response.code}")) end end @@ -233,7 +220,7 @@ def with_auth yield rescue UnauthorizedAccess => e raise if retried || auth_type != :digest - @response_auth_header = e.response['WWW-Authenticate'] + @response_auth_header = e.response["WWW-Authenticate"] retried = true retry end @@ -241,12 +228,12 @@ def with_auth def authorization_header(http_method, uri) if @user || @password if auth_type == :digest - { 'Authorization' => digest_auth_header(http_method, uri) } + { "Authorization" => digest_auth_header(http_method, uri) } else - { 'Authorization' => 'Basic ' + ["#{@user}:#{@password}"].pack('m').delete("\r\n") } + { "Authorization" => "Basic " + ["#{@user}:#{@password}"].pack("m").delete("\r\n") } end elsif @bearer_token - { 'Authorization' => "Bearer #{@bearer_token}" } + { "Authorization" => "Bearer #{@bearer_token}" } else {} end @@ -261,8 +248,8 @@ def digest_auth_header(http_method, uri) ha1 = Digest::MD5.hexdigest("#{@user}:#{params['realm']}:#{@password}") ha2 = Digest::MD5.hexdigest("#{http_method.to_s.upcase}:#{request_uri}") - params.merge!('cnonce' => client_nonce) - request_digest = Digest::MD5.hexdigest([ha1, params['nonce'], "0", params['cnonce'], params['qop'], ha2].join(":")) + params["cnonce"] = client_nonce + request_digest = Digest::MD5.hexdigest([ha1, params["nonce"], "0", params["cnonce"], params["qop"], ha2].join(":")) "Digest #{auth_attributes_for(uri, request_digest, params)}" end @@ -286,16 +273,16 @@ def auth_attributes_for(uri, request_digest, params) %Q(qop="#{params['qop']}"), %Q(uri="#{uri.path}"), %Q(nonce="#{params['nonce']}"), - %Q(nc="0"), + 'nc="0"', %Q(cnonce="#{params['cnonce']}"), %Q(response="#{request_digest}")] - auth_attrs << %Q(opaque="#{params['opaque']}") unless params['opaque'].blank? + auth_attrs << %Q(opaque="#{params['opaque']}") unless params["opaque"].blank? auth_attrs.join(", ") end def http_format_header(http_method) - {HTTP_FORMAT_HEADER_NAMES[http_method] => format.mime_type} + { HTTP_FORMAT_HEADER_NAMES[http_method] => format.mime_type } end def legitimize_auth_type(auth_type) diff --git a/lib/active_resource/custom_methods.rb b/lib/active_resource/custom_methods.rb index e0bd1cc7e9..3a3f67b5b9 100644 --- a/lib/active_resource/custom_methods.rb +++ b/lib/active_resource/custom_methods.rb @@ -1,4 +1,6 @@ -require 'active_support/core_ext/object/blank' +# frozen_string_literal: true + +require "active_support/core_ext/object/blank" module ActiveResource # A module to support custom REST methods and sub-resources, allowing you to break out @@ -59,15 +61,15 @@ def get(custom_method_name, options = {}) derooted.is_a?(Array) ? derooted.map { |e| Formats.remove_root(e) } : derooted end - def post(custom_method_name, options = {}, body = '') + def post(custom_method_name, options = {}, body = "") connection.post(custom_method_collection_url(custom_method_name, options), body, headers) end - def patch(custom_method_name, options = {}, body = '') + def patch(custom_method_name, options = {}, body = "") connection.patch(custom_method_collection_url(custom_method_name, options), body, headers) end - def put(custom_method_name, options = {}, body = '') + def put(custom_method_name, options = {}, body = "") connection.put(custom_method_collection_url(custom_method_name, options), body, headers) end @@ -102,11 +104,11 @@ def post(method_name, options = {}, body = nil) end end - def patch(method_name, options = {}, body = '') + def patch(method_name, options = {}, body = "") connection.patch(custom_method_element_url(method_name, options), body, self.class.headers) end - def put(method_name, options = {}, body = '') + def put(method_name, options = {}, body = "") connection.put(custom_method_element_url(method_name, options), body, self.class.headers) end diff --git a/lib/active_resource/exceptions.rb b/lib/active_resource/exceptions.rb index 51bede3bd0..3ce5e033e2 100644 --- a/lib/active_resource/exceptions.rb +++ b/lib/active_resource/exceptions.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ActiveResource class ConnectionError < StandardError # :nodoc: attr_reader :response @@ -8,7 +10,7 @@ def initialize(response, message = nil) end def to_s - message = "Failed." + message = "Failed.".dup message << " Response code = #{response.code}." if response.respond_to?(:code) message << " Response message = #{response.message}." if response.respond_to?(:message) message @@ -34,7 +36,7 @@ def to_s; @message ;end # 3xx Redirection class Redirection < ConnectionError # :nodoc: def to_s - response['Location'] ? "#{super} => #{response['Location']}" : super + response["Location"] ? "#{super} => #{response['Location']}" : super end end @@ -76,7 +78,7 @@ class ServerError < ConnectionError # :nodoc: # 405 Method Not Allowed class MethodNotAllowed < ClientError # :nodoc: def allowed_methods - @response['Allow'].split(',').map { |verb| verb.strip.downcase.to_sym } + @response["Allow"].split(",").map { |verb| verb.strip.downcase.to_sym } end end end diff --git a/lib/active_resource/formats.rb b/lib/active_resource/formats.rb index 49c3e700d4..fbfaa183f1 100644 --- a/lib/active_resource/formats.rb +++ b/lib/active_resource/formats.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + module ActiveResource module Formats - autoload :XmlFormat, 'active_resource/formats/xml_format' - autoload :JsonFormat, 'active_resource/formats/json_format' + autoload :XmlFormat, "active_resource/formats/xml_format" + autoload :JsonFormat, "active_resource/formats/json_format" # Lookup the format class from a mime type reference symbol. Example: # diff --git a/lib/active_resource/formats/json_format.rb b/lib/active_resource/formats/json_format.rb index b92ecc6ff8..67795f95e3 100644 --- a/lib/active_resource/formats/json_format.rb +++ b/lib/active_resource/formats/json_format.rb @@ -1,4 +1,6 @@ -require 'active_support/json' +# frozen_string_literal: true + +require "active_support/json" module ActiveResource module Formats diff --git a/lib/active_resource/formats/xml_format.rb b/lib/active_resource/formats/xml_format.rb index 49cb9aa1ac..5fbf967e08 100644 --- a/lib/active_resource/formats/xml_format.rb +++ b/lib/active_resource/formats/xml_format.rb @@ -1,4 +1,6 @@ -require 'active_support/core_ext/hash/conversions' +# frozen_string_literal: true + +require "active_support/core_ext/hash/conversions" module ActiveResource module Formats @@ -13,7 +15,7 @@ def mime_type "application/xml" end - def encode(hash, options={}) + def encode(hash, options = {}) hash.to_xml(options) end diff --git a/lib/active_resource/http_mock.rb b/lib/active_resource/http_mock.rb index df5489dd86..5e793791dc 100644 --- a/lib/active_resource/http_mock.rb +++ b/lib/active_resource/http_mock.rb @@ -1,5 +1,7 @@ -require 'active_support/core_ext/kernel/reporting' -require 'active_support/core_ext/object/inclusion' +# frozen_string_literal: true + +require "active_support/core_ext/kernel/reporting" +require "active_support/core_ext/object/inclusion" module ActiveResource class InvalidRequestError < StandardError; end #:nodoc: @@ -74,12 +76,11 @@ def #{method}(path, request_headers = {}, body = nil, status = 200, response_hea private def delete_duplicate_responses(request) - @responses.delete_if {|r| r[0] == request } + @responses.delete_if { |r| r[0] == request } end end class << self - # Returns an array of all request objects that have been sent to the mock. You can use this to check # if your model actually sent an HTTP request. # @@ -203,9 +204,9 @@ def respond_to(*args) #:yields: mock end def delete_responses_to_replace(new_responses) - new_responses.each{|nr| + new_responses.each { |nr| request_to_remove = nr[0] - @@responses = responses.delete_if{|r| r[0] == request_to_remove} + @@responses = responses.delete_if { |r| r[0] == request_to_remove } } end @@ -238,7 +239,6 @@ def net_connection_enabled? def net_connection_disabled? !net_connection_enabled? end - end # body? methods @@ -294,15 +294,15 @@ def to_s private - def headers_match?(req) - # Ignore format header on equality if it's not defined - format_header = ActiveResource::Connection::HTTP_FORMAT_HEADER_NAMES[method] - if headers[format_header].present? || req.headers[format_header].blank? - headers == req.headers - else - headers.dup.merge(format_header => req.headers[format_header]) == req.headers + def headers_match?(req) + # Ignore format header on equality if it's not defined + format_header = ActiveResource::Connection::HTTP_FORMAT_HEADER_NAMES[method] + if headers[format_header].present? || req.headers[format_header].blank? + headers == req.headers + else + headers.dup.merge(format_header => req.headers[format_header]) == req.headers + end end - end end class Response @@ -310,15 +310,14 @@ class Response def initialize(body, message = 200, headers = {}) @body, @message, @headers = body, message.to_s, headers - @code = @message[0,3].to_i + @code = @message[0, 3].to_i resp_cls = Net::HTTPResponse::CODE_TO_OBJ[@code.to_s] if resp_cls && !resp_cls.body_permitted? @body = nil end - self['Content-Length'] = @body.nil? ? "0" : body.size.to_s - + self["Content-Length"] = @body.nil? ? "0" : body.size.to_s end # Returns true if code is 2xx, @@ -338,7 +337,7 @@ def []=(key, value) # Returns true if the other is a Response with an equal body, equal message # and equal headers. Otherwise it returns false. def ==(other) - if (other.is_a?(Response)) + if other.is_a?(Response) other.body == body && other.message == message && other.headers == headers else false @@ -369,7 +368,6 @@ def unstub_http? def stub_http? HttpMock.net_connection_disabled? && defined?(@http) && @http.kind_of?(Net::HTTP) end - end end end diff --git a/lib/active_resource/log_subscriber.rb b/lib/active_resource/log_subscriber.rb index 1616818922..25a90e6475 100644 --- a/lib/active_resource/log_subscriber.rb +++ b/lib/active_resource/log_subscriber.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ActiveResource class LogSubscriber < ActiveSupport::LogSubscriber def request(event) diff --git a/lib/active_resource/railtie.rb b/lib/active_resource/railtie.rb index 26250c60d4..b30bb06148 100644 --- a/lib/active_resource/railtie.rb +++ b/lib/active_resource/railtie.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "active_resource" require "rails" @@ -7,7 +9,7 @@ class Railtie < Rails::Railtie initializer "active_resource.set_configs" do |app| ActiveSupport.on_load(:active_resource) do - app.config.active_resource.each do |k,v| + app.config.active_resource.each do |k, v| send "#{k}=", v end end diff --git a/lib/active_resource/reflection.rb b/lib/active_resource/reflection.rb index caf778621b..db13b0e8a8 100644 --- a/lib/active_resource/reflection.rb +++ b/lib/active_resource/reflection.rb @@ -1,5 +1,7 @@ -require 'active_support/core_ext/class/attribute' -require 'active_support/core_ext/module/deprecation' +# frozen_string_literal: true + +require "active_support/core_ext/class/attribute" +require "active_support/core_ext/module/deprecation" module ActiveResource # = Active Resource reflection @@ -25,7 +27,6 @@ def create_reflection(macro, name, options) class AssociationReflection - def initialize(macro, name, options) @macro, @name, @options = macro, name, options end @@ -65,13 +66,13 @@ def foreign_key end private - def derive_class_name - return (options[:class_name] ? options[:class_name].to_s.camelize : name.to_s.classify) - end + def derive_class_name + (options[:class_name] ? options[:class_name].to_s.camelize : name.to_s.classify) + end - def derive_foreign_key - return options[:foreign_key] ? options[:foreign_key].to_s : "#{name.to_s.downcase}_id" - end + def derive_foreign_key + options[:foreign_key] ? options[:foreign_key].to_s : "#{name.to_s.downcase}_id" + end end end end diff --git a/lib/active_resource/schema.rb b/lib/active_resource/schema.rb index 7fe9e1a52b..5c421b1d7c 100644 --- a/lib/active_resource/schema.rb +++ b/lib/active_resource/schema.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ActiveResource # :nodoc: class Schema # :nodoc: # attributes can be known to be one of these types. They are easy to @@ -29,8 +31,8 @@ def attribute(name, type, options = {}) the_type = type.to_s # TODO: add defaults - #the_attr = [type.to_s] - #the_attr << options[:default] if options.has_key? :default + # the_attr = [type.to_s] + # the_attr << options[:default] if options.has_key? :default @attrs[name.to_s] = the_type self end @@ -45,7 +47,7 @@ def attribute(name, type, options = {}) # attr_names.each { |name| attribute(name, 'string', options) } # end class_eval <<-EOV, __FILE__, __LINE__ + 1 - def #{attr_type.to_s}(*args) + def #{attr_type}(*args) options = args.extract_options! attr_names = args diff --git a/lib/active_resource/singleton.rb b/lib/active_resource/singleton.rb index 6ed83b294d..a83b4fceb4 100644 --- a/lib/active_resource/singleton.rb +++ b/lib/active_resource/singleton.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ActiveResource module Singleton extend ActiveSupport::Concern @@ -60,20 +62,19 @@ def singleton_path(prefix_options = {}, query_options = nil) # # Inventory.find # # => raises ResourceNotFound - def find(options={}) + def find(options = {}) find_singleton(options) end private - # Find singleton resource - def find_singleton(options) - prefix_options, query_options = split_options(options[:params]) - - path = singleton_path(prefix_options, query_options) - resp = self.format.decode(self.connection.get(path, self.headers).body) - instantiate_record(resp, prefix_options) - end - + # Find singleton resource + def find_singleton(options) + prefix_options, query_options = split_options(options[:params]) + + path = singleton_path(prefix_options, query_options) + resp = self.format.decode(self.connection.get(path, self.headers).body) + instantiate_record(resp, prefix_options) + end end # Deletes the resource from the remote service. # @@ -88,27 +89,25 @@ def destroy protected - # Update the resource on the remote service - def update - connection.put(singleton_path(prefix_options), encode, self.class.headers).tap do |response| - load_attributes_from_response(response) + # Update the resource on the remote service + def update + connection.put(singleton_path(prefix_options), encode, self.class.headers).tap do |response| + load_attributes_from_response(response) + end end - end - # Create (i.e. \save to the remote service) the \new resource. - def create - connection.post(singleton_path, encode, self.class.headers).tap do |response| - self.id = id_from_response(response) - load_attributes_from_response(response) + # Create (i.e. \save to the remote service) the \new resource. + def create + connection.post(singleton_path, encode, self.class.headers).tap do |response| + self.id = id_from_response(response) + load_attributes_from_response(response) + end end - end private - def singleton_path(options = nil) - self.class.singleton_path(options || prefix_options) - end - + def singleton_path(options = nil) + self.class.singleton_path(options || prefix_options) + end end - end diff --git a/lib/active_resource/threadsafe_attributes.rb b/lib/active_resource/threadsafe_attributes.rb index f60acb0fc0..5a3a055e56 100644 --- a/lib/active_resource/threadsafe_attributes.rb +++ b/lib/active_resource/threadsafe_attributes.rb @@ -1,4 +1,6 @@ -require 'active_support/core_ext/object/duplicable' +# frozen_string_literal: true + +require "active_support/core_ext/object/duplicable" module ThreadsafeAttributes def self.included(klass) @@ -27,38 +29,38 @@ def threadsafe_attribute(*attrs) private - def get_threadsafe_attribute(name, main_thread) - if threadsafe_attribute_defined_by_thread?(name, Thread.current) - get_threadsafe_attribute_by_thread(name, Thread.current) - elsif threadsafe_attribute_defined_by_thread?(name, main_thread) - value = get_threadsafe_attribute_by_thread(name, main_thread) - value = value.dup if value.duplicable? - set_threadsafe_attribute_by_thread(name, value, Thread.current) - value + def get_threadsafe_attribute(name, main_thread) + if threadsafe_attribute_defined_by_thread?(name, Thread.current) + get_threadsafe_attribute_by_thread(name, Thread.current) + elsif threadsafe_attribute_defined_by_thread?(name, main_thread) + value = get_threadsafe_attribute_by_thread(name, main_thread) + value = value.dup if value.duplicable? + set_threadsafe_attribute_by_thread(name, value, Thread.current) + value + end end - end - def set_threadsafe_attribute(name, value, main_thread) - set_threadsafe_attribute_by_thread(name, value, Thread.current) - unless threadsafe_attribute_defined_by_thread?(name, main_thread) - set_threadsafe_attribute_by_thread(name, value, main_thread) + def set_threadsafe_attribute(name, value, main_thread) + set_threadsafe_attribute_by_thread(name, value, Thread.current) + unless threadsafe_attribute_defined_by_thread?(name, main_thread) + set_threadsafe_attribute_by_thread(name, value, main_thread) + end end - end - def threadsafe_attribute_defined?(name, main_thread) - threadsafe_attribute_defined_by_thread?(name, Thread.current) || ((Thread.current != main_thread) && threadsafe_attribute_defined_by_thread?(name, main_thread)) - end + def threadsafe_attribute_defined?(name, main_thread) + threadsafe_attribute_defined_by_thread?(name, Thread.current) || ((Thread.current != main_thread) && threadsafe_attribute_defined_by_thread?(name, main_thread)) + end - def get_threadsafe_attribute_by_thread(name, thread) - thread.thread_variable_get "active.resource.#{name}.#{self.object_id}" - end + def get_threadsafe_attribute_by_thread(name, thread) + thread.thread_variable_get "active.resource.#{name}.#{self.object_id}" + end - def set_threadsafe_attribute_by_thread(name, value, thread) - thread.thread_variable_set "active.resource.#{name}.#{self.object_id}.defined", true - thread.thread_variable_set "active.resource.#{name}.#{self.object_id}", value - end + def set_threadsafe_attribute_by_thread(name, value, thread) + thread.thread_variable_set "active.resource.#{name}.#{self.object_id}.defined", true + thread.thread_variable_set "active.resource.#{name}.#{self.object_id}", value + end - def threadsafe_attribute_defined_by_thread?(name, thread) - thread.thread_variable_get "active.resource.#{name}.#{self.object_id}.defined" - end + def threadsafe_attribute_defined_by_thread?(name, thread) + thread.thread_variable_get "active.resource.#{name}.#{self.object_id}.defined" + end end diff --git a/lib/active_resource/validations.rb b/lib/active_resource/validations.rb index 0116261a58..5c8d2e8e38 100644 --- a/lib/active_resource/validations.rb +++ b/lib/active_resource/validations.rb @@ -1,5 +1,7 @@ -require 'active_support/core_ext/array/wrap' -require 'active_support/core_ext/object/blank' +# frozen_string_literal: true + +require "active_support/core_ext/array/wrap" +require "active_support/core_ext/object/blank" module ActiveResource class ResourceInvalid < ClientError #:nodoc: @@ -33,11 +35,11 @@ def from_array(messages, save_cache = false) def from_hash(messages, save_cache = false) clear unless save_cache - messages.each do |(key,errors)| + messages.each do |(key, errors)| errors.each do |error| if @base.known_attributes.include?(key) add key, error - elsif key == 'base' + elsif key == "base" self[:base] << error else # reporting an error on an attribute not in attributes @@ -51,11 +53,11 @@ def from_hash(messages, save_cache = false) # Grabs errors from a json response. def from_json(json, save_cache = false) decoded = ActiveSupport::JSON.decode(json) || {} rescue {} - if decoded.kind_of?(Hash) && (decoded.has_key?('errors') || decoded.empty?) - errors = decoded['errors'] || {} + if decoded.kind_of?(Hash) && (decoded.has_key?("errors") || decoded.empty?) + errors = decoded["errors"] || {} if errors.kind_of?(Array) # 3.2.1-style with array of strings - ActiveSupport::Deprecation.warn('Returning errors as an array of strings is deprecated.') + ActiveSupport::Deprecation.warn("Returning errors as an array of strings is deprecated.") from_array errors, save_cache else # 3.2.2+ style @@ -70,7 +72,7 @@ def from_json(json, save_cache = false) # Grabs errors from an XML response. def from_xml(xml, save_cache = false) - array = Array.wrap(Hash.from_xml(xml)['errors']['error']) rescue [] + array = Array.wrap(Hash.from_xml(xml)["errors"]["error"]) rescue [] from_array array, save_cache end end @@ -106,7 +108,7 @@ module Validations # Validate a resource and save (POST) it to the remote web service. # If any local validations fail - the save (POST) will not be attempted. - def save_with_validation(options={}) + def save_with_validation(options = {}) perform_validation = options[:validate] != false # clear the remote validations so they don't interfere with the local @@ -131,7 +133,7 @@ def save_with_validation(options={}) # Loads the set of remote errors into the object's Errors based on the # content-type of the error-block received. - def load_remote_errors(remote_errors, save_cache = false ) #:nodoc: + def load_remote_errors(remote_errors, save_cache = false) #:nodoc: case self.class.format when ActiveResource::Formats[:xml] errors.from_xml(remote_errors.response.body, save_cache) diff --git a/lib/active_resource/version.rb b/lib/active_resource/version.rb index 1f89f1c5dd..90d379364b 100644 --- a/lib/active_resource/version.rb +++ b/lib/active_resource/version.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ActiveResource module VERSION #:nodoc: MAJOR = 5 @@ -5,6 +7,6 @@ module VERSION #:nodoc: TINY = 0 PRE = nil - STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.') + STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") end end diff --git a/lib/activeresource.rb b/lib/activeresource.rb index e076455b16..7233460c33 100644 --- a/lib/activeresource.rb +++ b/lib/activeresource.rb @@ -1 +1,3 @@ -require 'active_resource' +# frozen_string_literal: true + +require "active_resource" diff --git a/test/abstract_unit.rb b/test/abstract_unit.rb index ec6f4e43e4..7d6a9c277f 100644 --- a/test/abstract_unit.rb +++ b/test/abstract_unit.rb @@ -1,15 +1,17 @@ -require 'rubygems' unless defined? Gem -require 'bundler/setup' +# frozen_string_literal: true + +require "rubygems" unless defined? Gem +require "bundler/setup" lib = File.expand_path("#{File.dirname(__FILE__)}/../lib") -$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib) +$:.unshift(lib) unless $:.include?("lib") || $:.include?(lib) -require 'minitest/autorun' -require 'active_resource' -require 'active_support' -require 'active_support/test_case' -require 'setter_trap' -require 'active_support/logger' +require "minitest/autorun" +require "active_resource" +require "active_support" +require "active_support/test_case" +require "setter_trap" +require "active_support/logger" ActiveSupport::TestCase.test_order = :random if ActiveSupport::TestCase.respond_to?(:test_order=) ActiveResource::Base.logger = ActiveSupport::Logger.new("#{File.dirname(__FILE__)}/debug.log") @@ -22,22 +24,22 @@ def self.rails_5_1? end def setup_response - matz_hash = { 'person' => { :id => 1, :name => 'Matz' } } + 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 - @post = {:id => 1, :title => 'Hello World', :body => 'Lorem Ipsum'}.to_json - @posts = [{:id => 1, :title => 'Hello World', :body => 'Lorem Ipsum'},{:id => 2, :title => 'Second Post', :body => 'Lorem Ipsum'}].to_json - @comments = [{:id => 1, :post_id => 1, :content => 'Interesting post'},{:id => 2, :post_id => 1, :content => 'I agree'}].to_json + @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 + @post = { id: 1, title: "Hello World", body: "Lorem Ipsum" }.to_json + @posts = [{ id: 1, title: "Hello World", body: "Lorem Ipsum" }, { id: 2, title: "Second Post", body: "Lorem Ipsum" }].to_json + @comments = [{ id: 1, post_id: 1, content: "Interesting post" }, { id: 2, post_id: 1, content: "I agree" }].to_json # - deep nested resource - # - Luis (Customer) @@ -57,48 +59,48 @@ def setup_response # - Milena (Customer::Friend::Brother) # @luis = { - :customer => { - :id => 1, - :name => 'Luis', - :friends => [{ - :name => 'JK', - :brothers => [ + customer: { + id: 1, + name: "Luis", + friends: [{ + name: "JK", + brothers: [ { - :name => 'Mateo', - :children => [{ :name => 'Edith' },{ :name => 'Martha' }] + name: "Mateo", + children: [{ name: "Edith" }, { name: "Martha" }] }, { - :name => 'Felipe', - :children => [{ :name => 'Bryan' },{ :name => 'Luke' }] + name: "Felipe", + children: [{ name: "Bryan" }, { name: "Luke" }] } ] }, { - :name => 'Eduardo', - :brothers => [ + name: "Eduardo", + brothers: [ { - :name => 'Sebas', - :children => [{ :name => 'Andres' },{ :name => 'Jorge' }] + name: "Sebas", + children: [{ name: "Andres" }, { name: "Jorge" }] }, { - :name => 'Elsa', - :children => [{ :name => 'Natacha' }] + name: "Elsa", + children: [{ name: "Natacha" }] }, { - :name => 'Milena', - :children => [] + name: "Milena", + children: [] } ] }], - :enemies => [{:name => 'Joker'}], - :mother => {:name => 'Ingeborg'} + enemies: [{ name: "Joker" }], + mother: { name: "Ingeborg" } } }.to_json @startup_sound = { - :sound => { - :name => "Mac Startup Sound", :author => { :name => "Jim Reekes" } + sound: { + name: "Mac Startup Sound", author: { name: "Jim Reekes" } } }.to_json - @product = {id: 1, name: 'Rails book'}.to_json - @inventory = {status: 'Sold Out', total: 10, used: 10}.to_json + @product = { id: 1, name: "Rails book" }.to_json + @inventory = { status: "Sold Out", total: 10, used: 10 }.to_json ActiveResource::HttpMock.respond_to do |mock| mock.get "/people/1.json", {}, @matz @@ -106,12 +108,12 @@ def setup_response mock.get "/people/2.xml", {}, @david mock.get "/people/Greg.json", {}, @greg mock.get "/people/6.json", {}, @joe - mock.get "/people/4.json", { 'key' => 'value' }, nil, 404 + 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.json", {}, nil, 404 - mock.post "/people.json", {}, @rick, 201, 'Location' => '/people/5.xml' + 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 @@ -121,7 +123,7 @@ def setup_response 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.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 @@ -144,8 +146,8 @@ def setup_response mock.get "/posts/1.json", {}, @post mock.get "/posts/1/comments.json", {}, @comments # products - mock.get '/products/1.json', {}, @product - mock.get '/products/1/inventory.json', {}, @inventory + mock.get "/products/1.json", {}, @product + mock.get "/products/1/inventory.json", {}, @inventory end Person.user = nil diff --git a/test/cases/active_job_serializer_test.rb b/test/cases/active_job_serializer_test.rb index 8083f936d8..4b9dda7cef 100644 --- a/test/cases/active_job_serializer_test.rb +++ b/test/cases/active_job_serializer_test.rb @@ -1,20 +1,21 @@ -require 'abstract_unit' +# frozen_string_literal: true -require 'fixtures/project' -require 'fixtures/person' -require 'fixtures/product' -require 'active_job' -require 'active_job/arguments' -require 'active_resource/active_job_serializer' if ActiveJob::VERSION::MAJOR >= 6 +require "abstract_unit" -class ActiveJobSerializerTest < ActiveSupport::TestCase +require "fixtures/project" +require "fixtures/person" +require "fixtures/product" +require "active_job" +require "active_job/arguments" +require "active_resource/active_job_serializer" if ActiveJob::VERSION::MAJOR >= 6 +class ActiveJobSerializerTest < ActiveSupport::TestCase setup do @klass = ActiveResource::ActiveJobSerializer end def test_serialize - project = Project.new(id: 1, name: 'Ruby on Rails') + project = Project.new(id: 1, name: "Ruby on Rails") project.prefix_options[:person_id] = 1 project_json = { _aj_serialized: @klass.name, @@ -29,7 +30,7 @@ def test_serialize end def test_deserialize - person = Person.new(id: 2, name: 'David') + person = Person.new(id: 2, name: "David") person.persisted = true person_json = { _aj_serialized: @klass.name, @@ -44,9 +45,9 @@ def test_deserialize end def test_serialize? - product = Product.new(id: 3, name: 'Chunky Bacon') + product = Product.new(id: 3, name: "Chunky Bacon") assert @klass.serialize?(product) - refute @klass.serialize?('not a resource') + assert_not @klass.serialize?("not a resource") end end if ActiveJob::VERSION::MAJOR >= 6 diff --git a/test/cases/association_test.rb b/test/cases/association_test.rb index d0e6236d58..f612fc5af7 100644 --- a/test/cases/association_test.rb +++ b/test/cases/association_test.rb @@ -1,8 +1,10 @@ -require 'abstract_unit' +# frozen_string_literal: true -require 'fixtures/person' -require 'fixtures/beast' -require 'fixtures/customer' +require "abstract_unit" + +require "fixtures/person" +require "fixtures/beast" +require "fixtures/customer" class AssociationTest < ActiveSupport::TestCase @@ -23,10 +25,10 @@ def test_instance_build end def test_valid_options - assert @klass.build(Person, :customers, {:class_name => 'Client'}) + assert @klass.build(Person, :customers, class_name: "Client") assert_raise ArgumentError do - @klass.build(Person, :customers, {:soo_invalid => true}) + @klass.build(Person, :customers, soo_invalid: true) end end @@ -36,7 +38,7 @@ def test_association_class_build def test_has_many External::Person.send(:has_many, :people) - assert_equal 1, External::Person.reflections.select{|name, reflection| reflection.macro.eql?(:has_many)}.count + assert_equal 1, External::Person.reflections.select { |name, reflection| reflection.macro.eql?(:has_many) }.count end def test_has_many_on_new_record @@ -47,22 +49,22 @@ def test_has_many_on_new_record def test_has_one External::Person.send(:has_one, :customer) - assert_equal 1, External::Person.reflections.select{|name, reflection| reflection.macro.eql?(:has_one)}.count + assert_equal 1, External::Person.reflections.select { |name, reflection| reflection.macro.eql?(:has_one) }.count end def test_belongs_to External::Person.belongs_to(:Customer) - assert_equal 1, External::Person.reflections.select{|name, reflection| reflection.macro.eql?(:belongs_to)}.count + assert_equal 1, External::Person.reflections.select { |name, reflection| reflection.macro.eql?(:belongs_to) }.count end def test_defines_belongs_to_finder_method_with_instance_variable_cache Person.defines_belongs_to_finder_method(@reflection) person = Person.new - assert !person.instance_variable_defined?(:@customer) + assert_not person.instance_variable_defined?(:@customer) person.stubs(:customer_id).returns(2) Customer.expects(:find).with(2).once() - 2.times{person.customer} + 2.times { person.customer } assert person.instance_variable_defined?(:@customer) end diff --git a/test/cases/associations/builder/belongs_to_test.rb b/test/cases/associations/builder/belongs_to_test.rb index 37ebb66ca1..7aa11ec371 100644 --- a/test/cases/associations/builder/belongs_to_test.rb +++ b/test/cases/associations/builder/belongs_to_test.rb @@ -1,9 +1,10 @@ +# frozen_string_literal: true -require 'abstract_unit' +require "abstract_unit" -require 'fixtures/person' -require 'fixtures/beast' -require 'fixtures/customer' +require "fixtures/person" +require "fixtures/beast" +require "fixtures/customer" class ActiveResource::Associations::Builder::BelongsToTest < ActiveSupport::TestCase @@ -26,16 +27,16 @@ def test_instance_build assert_kind_of ActiveResource::Reflection::AssociationReflection, reflection assert_equal :customer, reflection.name assert_equal Customer, reflection.klass - assert_equal 'customer_id', reflection.foreign_key + assert_equal "customer_id", reflection.foreign_key end def test_valid_options - assert @klass.build(Person, :customer, {:class_name => 'Person'}) - assert @klass.build(Person, :customer, {:foreign_key => 'person_id'}) + assert @klass.build(Person, :customer, class_name: "Person") + assert @klass.build(Person, :customer, foreign_key: "person_id") assert_raise ArgumentError do - @klass.build(Person, :customer, {:soo_invalid => true}) + @klass.build(Person, :customer, soo_invalid: true) end end end diff --git a/test/cases/associations/builder/has_many_test.rb b/test/cases/associations/builder/has_many_test.rb index 4e612713b6..e7b85c8726 100644 --- a/test/cases/associations/builder/has_many_test.rb +++ b/test/cases/associations/builder/has_many_test.rb @@ -1,7 +1,9 @@ -require 'abstract_unit' +# frozen_string_literal: true -require 'fixtures/person' -require 'fixtures/street_address' +require "abstract_unit" + +require "fixtures/person" +require "fixtures/street_address" class ActiveResource::Associations::Builder::HasManyTest < ActiveSupport::TestCase def setup @@ -23,5 +25,4 @@ def test_instance_build assert_equal :street_address, reflection.name assert_equal StreetAddress, reflection.klass end - end diff --git a/test/cases/associations/builder/has_one_test.rb b/test/cases/associations/builder/has_one_test.rb index 14780a71ff..d128e5cc52 100644 --- a/test/cases/associations/builder/has_one_test.rb +++ b/test/cases/associations/builder/has_one_test.rb @@ -1,7 +1,9 @@ -require 'abstract_unit' +# frozen_string_literal: true -require 'fixtures/product' -require 'fixtures/inventory' +require "abstract_unit" + +require "fixtures/product" +require "fixtures/inventory" class ActiveResource::Associations::Builder::HasOneTest < ActiveSupport::TestCase def setup @@ -23,5 +25,4 @@ def test_instance_build assert_equal :inventory, reflection.name assert_equal Inventory, reflection.klass end - end diff --git a/test/cases/authorization_test.rb b/test/cases/authorization_test.rb index 829ba1c87b..7004128ad7 100644 --- a/test/cases/authorization_test.rb +++ b/test/cases/authorization_test.rb @@ -1,16 +1,18 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" class AuthorizationTest < ActiveSupport::TestCase Response = Struct.new(:code) def setup - @conn = ActiveResource::Connection.new('http://localhost') - @matz = { :person => { :id => 1, :name => 'Matz' } }.to_json - @david = { :person => { :id => 2, :name => 'David' } }.to_json + @conn = ActiveResource::Connection.new("http://localhost") + @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==' } - @jwt = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c' - @bearer_token_authorization_request_header = { 'Authorization' => "Bearer #{@jwt}" } + @basic_authorization_request_header = { "Authorization" => "Basic ZGF2aWQ6dGVzdDEyMw==" } + @jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" + @bearer_token_authorization_request_header = { "Authorization" => "Bearer #{@jwt}" } end private @@ -26,11 +28,11 @@ def setup ActiveResource::HttpMock.respond_to do |mock| 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.get "/people/1.json", @basic_authorization_request_header, nil, 401, "WWW-Authenticate" => "i_should_be_ignored" mock.get "/people/3.json", @bearer_token_authorization_request_header, @david 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.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 end end @@ -75,8 +77,8 @@ def test_raises_invalid_request_on_unauthorized_requests def test_authorization_header - authorization_header = @authenticated_conn.__send__(:authorization_header, :get, URI.parse('/people/2.json')) - assert_equal @basic_authorization_request_header['Authorization'], authorization_header['Authorization'] + 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 assert_equal "Basic", authorization[0] @@ -85,7 +87,7 @@ def test_authorization_header 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.json')) + authorization_header = @conn.__send__(:authorization_header, :get, URI.parse("/people/2.json")) authorization = authorization_header["Authorization"].to_s.split assert_equal "Basic", authorization[0] @@ -94,7 +96,7 @@ def test_authorization_header_with_username_but_no_password 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.json')) + authorization_header = @conn.__send__(:authorization_header, :get, URI.parse("/people/2.json")) authorization = authorization_header["Authorization"].to_s.split assert_equal "Basic", authorization[0] @@ -103,7 +105,7 @@ def test_authorization_header_with_password_but_no_username 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.json')) + authorization_header = @conn.__send__(:authorization_header, :get, URI.parse("/people/2.json")) authorization = authorization_header["Authorization"].to_s.split assert_equal "Basic", authorization[0] @@ -112,10 +114,10 @@ def test_authorization_header_with_decoded_credentials_from_url def test_authorization_header_explicitly_setting_username_and_password @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.json')) - assert_equal @basic_authorization_request_header['Authorization'], authorization_header['Authorization'] + @authenticated_conn.user = "david" + @authenticated_conn.password = "test123" + 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 assert_equal "Basic", authorization[0] @@ -125,7 +127,7 @@ def test_authorization_header_explicitly_setting_username_and_password 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.json')) + authorization_header = @conn.__send__(:authorization_header, :get, URI.parse("/people/2.json")) authorization = authorization_header["Authorization"].to_s.split assert_equal "Basic", authorization[0] @@ -135,7 +137,7 @@ def test_authorization_header_explicitly_setting_username_but_no_password 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.json')) + authorization_header = @conn.__send__(:authorization_header, :get, URI.parse("/people/2.json")) authorization = authorization_header["Authorization"].to_s.split assert_equal "Basic", authorization[0] @@ -143,8 +145,8 @@ def test_authorization_header_explicitly_setting_password_but_no_username end def test_authorization_header_if_credentials_supplied_and_auth_type_is_basic - authorization_header = @authenticated_conn.__send__(:authorization_header, :get, URI.parse('/people/2.json')) - assert_equal @basic_authorization_request_header['Authorization'], authorization_header['Authorization'] + 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 assert_equal "Basic", authorization[0] @@ -155,8 +157,8 @@ def test_authorization_header_explicitly_setting_jwt_and_auth_type_is_bearer @conn = ActiveResource::Connection.new("http://localhost") @conn.auth_type = :bearer @conn.bearer_token = @jwt - authorization_header = @conn.__send__(:authorization_header, :get, URI.parse('/people/3.json')) - assert_equal @bearer_token_authorization_request_header['Authorization'], authorization_header['Authorization'] + authorization_header = @conn.__send__(:authorization_header, :get, URI.parse("/people/3.json")) + assert_equal @bearer_token_authorization_request_header["Authorization"], authorization_header["Authorization"] authorization = authorization_header["Authorization"].to_s.split assert_equal "Bearer", authorization[0] @@ -166,8 +168,8 @@ def test_authorization_header_explicitly_setting_jwt_and_auth_type_is_bearer def test_authorization_header_if_no_jwt_and_auth_type_is_bearer @conn = ActiveResource::Connection.new("http://localhost") @conn.auth_type = :bearer - authorization_header = @conn.__send__(:authorization_header, :get, URI.parse('/people/3.json')) - assert_nil authorization_header['Authorization'] + authorization_header = @conn.__send__(:authorization_header, :get, URI.parse("/people/3.json")) + assert_nil authorization_header["Authorization"] end def test_client_nonce_is_not_nil @@ -181,37 +183,37 @@ def setup @authenticated_conn.auth_type = :digest # Make client nonce deterministic - def @authenticated_conn.client_nonce; 'i-am-a-client-nonce' end + def @authenticated_conn.client_nonce; "i-am-a-client-nonce" end @nonce = "MTI0OTUxMzc4NzpjYWI3NDM3NDNmY2JmODU4ZjQ2ZjcwNGZkMTJiMjE0NA==" ActiveResource::HttpMock.respond_to do |mock| - 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.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.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.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.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.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.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.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.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 + 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 end def test_authorization_header_if_credentials_supplied_and_auth_type_is_digest - 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'] + 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_authorization_header_with_query_string_if_auth_type_is_digest - authorization_header = @authenticated_conn.__send__(:authorization_header, :get, URI.parse('/people/2.json?only=name')) - assert_equal blank_digest_auth_header("/people/2.json?only=name", "f8457b0b5d21b6b80737a386217afb24"), authorization_header['Authorization'] + authorization_header = @authenticated_conn.__send__(:authorization_header, :get, URI.parse("/people/2.json?only=name")) + assert_equal blank_digest_auth_header("/people/2.json?only=name", "f8457b0b5d21b6b80737a386217afb24"), authorization_header["Authorization"] end def test_get_with_digest_auth_handles_initial_401_response_and_retries diff --git a/test/cases/base/custom_methods_test.rb b/test/cases/base/custom_methods_test.rb index 8da5d24eb6..2c137249e3 100644 --- a/test/cases/base/custom_methods_test.rb +++ b/test/cases/base/custom_methods_test.rb @@ -1,16 +1,18 @@ -require 'abstract_unit' -require 'fixtures/person' -require 'fixtures/street_address' -require 'active_support/core_ext/hash/conversions' +# frozen_string_literal: true + +require "abstract_unit" +require "fixtures/person" +require "fixtures/street_address" +require "active_support/core_ext/hash/conversions" class CustomMethodsTest < ActiveSupport::TestCase def setup - @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 + @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.json", {}, @matz @@ -24,13 +26,13 @@ def setup 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/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' + 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 @@ -43,52 +45,52 @@ def teardown def test_custom_collection_method # GET - assert_equal([{ "id" => 1, "name" => 'Matz' }], Person.get(:retrieve, :name => 'Matz')) + assert_equal([{ "id" => 1, "name" => "Matz" }], Person.get(:retrieve, name: "Matz")) # POST - assert_equal(ActiveResource::Response.new("", 201, {}), Person.post(:hire, :name => 'Matz')) + assert_equal(ActiveResource::Response.new("", 201, {}), Person.post(:hire, name: "Matz")) # PUT assert_equal ActiveResource::Response.new("", 204, {}), - Person.put(:promote, {:name => 'Matz'}, 'atestbody') - assert_equal ActiveResource::Response.new("", 204, {}), Person.put(:sort, :by => 'name') + Person.put(:promote, { name: "Matz" }, "atestbody") + assert_equal ActiveResource::Response.new("", 204, {}), Person.put(:sort, by: "name") # DELETE - Person.delete :deactivate, :name => 'Matz' + Person.delete :deactivate, name: "Matz" # Nested resource - assert_equal ActiveResource::Response.new("", 204, {}), StreetAddress.put(:sort, :person_id => 1, :by => 'name') + assert_equal ActiveResource::Response.new("", 204, {}), StreetAddress.put(:sort, person_id: 1, by: "name") end def test_custom_element_method # Test GET against an element URL - assert_equal Person.find(1).get(:shallow), {"id" => 1, "name" => 'Matz'} - assert_equal Person.find(1).get(:deep), {"id" => 1, "name" => 'Matz', "other" => 'other'} + assert_equal Person.find(1).get(:shallow), "id" => 1, "name" => "Matz" + assert_equal Person.find(1).get(:deep), "id" => 1, "name" => "Matz", "other" => "other" # Test PUT against an element URL - assert_equal ActiveResource::Response.new("", 204, {}), Person.find(1).put(:promote, {:position => 'Manager'}, 'body') + assert_equal ActiveResource::Response.new("", 204, {}), Person.find(1).put(:promote, { position: "Manager" }, "body") # Test DELETE against an element URL assert_equal ActiveResource::Response.new("", 200, {}), Person.find(1).delete(:deactivate) # With nested resources - assert_equal StreetAddress.find(1, :params => { :person_id => 1 }).get(:deep), - { "id" => 1, "street" => '12345 Street', "zip" => "27519" } + assert_equal StreetAddress.find(1, params: { person_id: 1 }).get(:deep), + "id" => 1, "street" => "12345 Street", "zip" => "27519" assert_equal ActiveResource::Response.new("", 204, {}), - StreetAddress.find(1, :params => { :person_id => 1 }).put(:normalize_phone, :locale => 'US') + StreetAddress.find(1, params: { person_id: 1 }).put(:normalize_phone, locale: "US") end 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.json' }), ryan.post(:register) - expected_request = ActiveResource::Request.new(:post, '/people/new/register.json', @ryan) + ryan = Person.new(name: "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({ :address => { :street => '12345 Street' } }.to_json, - 201, { 'Location' => '/people/1/addresses/2.json' }), + addy = StreetAddress.new(street: "123 Test Dr.", person_id: 1) + 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) @@ -96,7 +98,7 @@ def test_custom_new_element_method end def test_find_custom_resources - assert_equal 'Matz', Person.find(:all, :from => :managers).first.name + assert_equal "Matz", Person.find(:all, from: :managers).first.name end def test_paths_with_format diff --git a/test/cases/base/equality_test.rb b/test/cases/base/equality_test.rb index fffd8b75c3..3775e23577 100644 --- a/test/cases/base/equality_test.rb +++ b/test/cases/base/equality_test.rb @@ -1,28 +1,30 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" require "fixtures/person" require "fixtures/street_address" class BaseEqualityTest < ActiveSupport::TestCase def setup @new = Person.new - @one = Person.new(:id => 1) - @two = Person.new(:id => 2) - @street = StreetAddress.new(:id => 2) + @one = Person.new(id: 1) + @two = Person.new(id: 2) + @street = StreetAddress.new(id: 2) end def test_should_equal_self - assert @new == @new, '@new == @new' - assert @one == @one, '@one == @one' + assert @new == @new, "@new == @new" + assert @one == @one, "@one == @one" end def test_shouldnt_equal_new_resource - assert @new != @one, '@new != @one' - assert @one != @new, '@one != @new' + assert @new != @one, "@new != @one" + assert @one != @new, "@one != @new" end def test_shouldnt_equal_different_class - assert @two != @street, 'person != street_address with same id' - assert @street != @two, 'street_address != person with same id' + assert @two != @street, "person != street_address with same id" + assert @street != @two, "street_address != person with same id" end def test_eql_should_alias_equals_operator @@ -41,12 +43,11 @@ def test_hash_should_be_id_hash end end - def test_with_prefix_options + def test_with_prefix_options assert_equal @one == @one, @one.eql?(@one) assert_equal @one == @one.dup, @one.eql?(@one.dup) new_one = @one.dup - new_one.prefix_options = {:foo => 'bar'} + new_one.prefix_options = { foo: "bar" } assert_not_equal @one, new_one - end - + end end diff --git a/test/cases/base/load_test.rb b/test/cases/base/load_test.rb index 5005fbb3a0..daac61bbc7 100644 --- a/test/cases/base/load_test.rb +++ b/test/cases/base/load_test.rb @@ -1,7 +1,9 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" require "fixtures/person" require "fixtures/street_address" -require 'active_support/core_ext/hash/conversions' +require "active_support/core_ext/hash/conversions" module Highrise class Note < ActiveResource::Base @@ -44,44 +46,44 @@ def to_hash end def setup - @matz = { :id => 1, :name => 'Matz' } + @matz = { id: 1, name: "Matz" } - @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 ] } + @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', - :notable_rivers => [ - { :id => 1, :name => 'Willamette' }, - { :id => 2, :name => 'Columbia', :rafted_by => @matz }], - :postal_codes => [ 97018, 1234567890 ], - :dates => [ Time.now ], - :votes => [ true, false, true ], - :places => [ "Columbia City", "Unknown" ]}}} + @deep = { id: 1, street: { + id: 1, state: { id: 1, name: "Oregon", + notable_rivers: [ + { id: 1, name: "Willamette" }, + { id: 2, name: "Columbia", rafted_by: @matz }], + postal_codes: [ 97018, 1234567890 ], + dates: [ Time.now ], + votes: [ true, false, true ], + places: [ "Columbia City", "Unknown" ] } } } # List of books formated as [{timestamp_of_publication => name}, ...] - @books = {:books => [ - {1009839600 => "Ruby in a Nutshell"}, - {1199142000 => "The Ruby Programming Language"} - ]} + @books = { books: [ + { 1009839600 => "Ruby in a Nutshell" }, + { 1199142000 => "The Ruby Programming Language" } + ] } - @books_date = {:books => [ - {Time.at(1009839600) => "Ruby in a Nutshell"}, - {Time.at(1199142000) => "The Ruby Programming Language"} - ]} + @books_date = { books: [ + { Time.at(1009839600) => "Ruby in a Nutshell" }, + { Time.at(1199142000) => "The Ruby Programming Language" } + ] } @complex_books = { books: { "Complex.String&-Character*|=_+()!~": { isbn: 1009839690, - author: 'Frank Smith' + author: "Frank Smith" }, "16Candles": { isbn: 1199142400, - author: 'John Hughes' + author: "John Hughes" } } } @@ -91,22 +93,22 @@ def setup def test_load_hash_with_integers_as_keys_creates_stringified_attributes Person.__send__(:remove_const, :Book) if Person.const_defined?(:Book) - assert !Person.const_defined?(:Book), "Books shouldn't exist until autocreated" - assert_nothing_raised{ @person.load(@books) } - assert_equal @books[:books].map{ |book| book.stringify_keys }, @person.books.map(&:attributes) + assert_not Person.const_defined?(:Book), "Books shouldn't exist until autocreated" + assert_nothing_raised { @person.load(@books) } + assert_equal @books[:books].map { |book| book.stringify_keys }, @person.books.map(&:attributes) end def test_load_hash_with_dates_as_keys_creates_stringified_attributes Person.__send__(:remove_const, :Book) if Person.const_defined?(:Book) - assert !Person.const_defined?(:Book), "Books shouldn't exist until autocreated" - assert_nothing_raised{@person.load(@books_date)} - assert_equal @books_date[:books].map{ |book| book.stringify_keys }, @person.books.map(&:attributes) + assert_not Person.const_defined?(:Book), "Books shouldn't exist until autocreated" + assert_nothing_raised { @person.load(@books_date) } + assert_equal @books_date[:books].map { |book| book.stringify_keys }, @person.books.map(&:attributes) end def test_load_hash_with_unacceptable_constant_characters_creates_unknown_resource Person.__send__(:remove_const, :Books) if Person.const_defined?(:Books) - assert !Person.const_defined?(:Books), "Books shouldn't exist until autocreated" - assert_nothing_raised{@person.load(@complex_books)} + assert_not Person.const_defined?(:Books), "Books shouldn't exist until autocreated" + assert_nothing_raised { @person.load(@complex_books) } assert Person::Books.const_defined?(:UnnamedResource), "UnnamedResource should have been autocreated" @person.books.attributes.keys.each { |key| assert_kind_of Person::Books::UnnamedResource, @person.books.attributes[key] } end @@ -128,18 +130,18 @@ def test_load_object_with_implict_conversion_to_hash def test_after_load_attributes_are_accessible assert_equal Hash.new, @person.attributes 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_after_load_attributes_are_accessible_via_indifferent_access assert_equal Hash.new, @person.attributes assert_equal @matz.stringify_keys, @person.load(@matz).attributes - assert_equal @matz[:name], @person.attributes['name'] + 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.values.first).street_address + address = @person.load(street_address: @first_address.values.first).street_address assert_kind_of StreetAddress, address assert_equal @first_address.values.first.stringify_keys, address.attributes end @@ -151,7 +153,7 @@ def test_load_one_with_unknown_resource end def test_load_one_with_unknown_resource_from_anonymous_subclass - subclass = Class.new(Person).tap { |c| c.element_name = 'person' } + subclass = Class.new(Person).tap { |c| c.element_name = "person" } address = silence_warnings { subclass.new.load(@first_address).address } assert_kind_of subclass::Address, address end @@ -165,8 +167,8 @@ def test_load_collection_with_existing_resource def test_load_collection_with_unknown_resource Person.__send__(:remove_const, :Address) if Person.const_defined?(:Address) - assert !Person.const_defined?(:Address), "Address shouldn't exist until autocreated" - addresses = silence_warnings { @person.load(:addresses => @addresses).addresses } + assert_not Person.const_defined?(:Address), "Address shouldn't exist until autocreated" + 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 { |a| a[:address].stringify_keys }, addresses.map(&:attributes) @@ -181,8 +183,8 @@ def test_load_collection_with_single_existing_resource def test_load_collection_with_single_unknown_resource Person.__send__(:remove_const, :Address) if Person.const_defined?(:Address) - assert !Person.const_defined?(:Address), "Address shouldn't exist until autocreated" - addresses = silence_warnings { @person.load(:addresses => [ @first_address ]).addresses } + assert_not Person.const_defined?(:Address), "Address shouldn't exist until autocreated" + 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.values.first ].map(&:stringify_keys), addresses.map(&:attributes) @@ -231,17 +233,17 @@ def test_recursively_loaded_collections end def test_nested_collections_within_the_same_namespace - n = Highrise::Note.new(:comments => [{ :comment => { :name => "1" } }]) + n = Highrise::Note.new(comments: [{ comment: { name: "1" } }]) assert_kind_of Highrise::Comment, n.comments.first end def test_nested_collections_within_deeply_nested_namespace - n = Highrise::Deeply::Nested::Note.new(:comments => [{ :name => "1" }]) + n = Highrise::Deeply::Nested::Note.new(comments: [{ name: "1" }]) assert_kind_of Highrise::Deeply::Nested::Comment, n.comments.first end def test_nested_collections_in_different_levels_of_namespaces - n = Highrise::Deeply::Nested::TestDifferentLevels::Note.new(:comments => [{ :name => "1" }]) + n = Highrise::Deeply::Nested::TestDifferentLevels::Note.new(comments: [{ name: "1" }]) assert_kind_of Highrise::Deeply::Nested::Comment, n.comments.first end end diff --git a/test/cases/base/schema_test.rb b/test/cases/base/schema_test.rb index 5666d231ea..5b9de29b5e 100644 --- a/test/cases/base/schema_test.rb +++ b/test/cases/base/schema_test.rb @@ -1,5 +1,7 @@ -require 'abstract_unit' -require 'active_support/core_ext/hash/conversions' +# frozen_string_literal: true + +require "abstract_unit" +require "active_support/core_ext/hash/conversions" require "fixtures/person" require "fixtures/street_address" @@ -26,30 +28,30 @@ def teardown end test "schema should only accept a hash" do - ["blahblah", ['one','two'], [:age, :name], Person.new].each do |bad_schema| - assert_raises(ArgumentError,"should only accept a hash (or nil), but accepted: #{bad_schema.inspect}") do + ["blahblah", ["one", "two"], [:age, :name], Person.new].each do |bad_schema| + assert_raises(ArgumentError, "should only accept a hash (or nil), but accepted: #{bad_schema.inspect}") do Person.schema = bad_schema end end end test "schema should accept a simple hash" do - new_schema = {'age' => 'integer', 'name' => 'string', - 'height' => 'float', 'bio' => 'text', - 'weight' => 'decimal', 'photo' => 'binary', - 'alive' => 'boolean', 'created_at' => 'timestamp', - 'thetime' => 'time', 'thedate' => 'date', 'mydatetime' => 'datetime'} + new_schema = { "age" => "integer", "name" => "string", + "height" => "float", "bio" => "text", + "weight" => "decimal", "photo" => "binary", + "alive" => "boolean", "created_at" => "timestamp", + "thetime" => "time", "thedate" => "date", "mydatetime" => "datetime" } assert_nothing_raised { Person.schema = new_schema } assert_equal new_schema, Person.schema end test "schema should accept a hash with simple values" do - new_schema = {'age' => 'integer', 'name' => 'string', - 'height' => 'float', 'bio' => 'text', - 'weight' => 'decimal', 'photo' => 'binary', - 'alive' => 'boolean', 'created_at' => 'timestamp', - 'thetime' => 'time', 'thedate' => 'date', 'mydatetime' => 'datetime'} + new_schema = { "age" => "integer", "name" => "string", + "height" => "float", "bio" => "text", + "weight" => "decimal", "photo" => "binary", + "alive" => "boolean", "created_at" => "timestamp", + "thetime" => "time", "thedate" => "date", "mydatetime" => "datetime" } assert_nothing_raised { Person.schema = new_schema } assert_equal new_schema, Person.schema @@ -57,26 +59,26 @@ def teardown test "schema should accept all known attribute types as values" do ActiveResource::Schema::KNOWN_ATTRIBUTE_TYPES.each do |the_type| - assert_nothing_raised { Person.schema = {'my_key' => the_type } } + assert_nothing_raised { Person.schema = { "my_key" => the_type } } end end test "schema should not accept unknown values" do - bad_values = [ :oogle, :blob, 'thing'] + bad_values = [ :oogle, :blob, "thing"] bad_values.each do |bad_value| - assert_raises(ArgumentError,"should only accept a known attribute type, but accepted: #{bad_value.inspect}") do - Person.schema = {'key' => bad_value} + assert_raises(ArgumentError, "should only accept a known attribute type, but accepted: #{bad_value.inspect}") do + Person.schema = { "key" => bad_value } end end end test "schema should accept nil and remove the schema" do - new_schema = {'age' => 'integer', 'name' => 'string', - 'height' => 'float', 'bio' => 'text', - 'weight' => 'decimal', 'photo' => 'binary', - 'alive' => 'boolean', 'created_at' => 'timestamp', - 'thetime' => 'time', 'thedate' => 'date', 'mydatetime' => 'datetime'} + new_schema = { "age" => "integer", "name" => "string", + "height" => "float", "bio" => "text", + "weight" => "decimal", "photo" => "binary", + "alive" => "boolean", "created_at" => "timestamp", + "thetime" => "time", "thedate" => "date", "mydatetime" => "datetime" } assert_nothing_raised { Person.schema = new_schema } assert_equal new_schema, Person.schema # sanity check @@ -86,17 +88,17 @@ def teardown end test "schema should be with indifferent access" do - new_schema = {'age' => 'integer', 'name' => 'string', - 'height' => 'float', 'bio' => 'text', - 'weight' => 'decimal', 'photo' => 'binary', - 'alive' => 'boolean', 'created_at' => 'timestamp', - 'thetime' => 'time', 'thedate' => 'date', 'mydatetime' => 'datetime'} + new_schema = { "age" => "integer", "name" => "string", + "height" => "float", "bio" => "text", + "weight" => "decimal", "photo" => "binary", + "alive" => "boolean", "created_at" => "timestamp", + "thetime" => "time", "thedate" => "date", "mydatetime" => "datetime" } new_schema_syms = new_schema.keys assert_nothing_raised { Person.schema = new_schema } new_schema_syms.each do |col| - assert Person.new.respond_to?(col.to_s), "should respond to the schema's string key, but failed on: #{col.to_s}" + assert Person.new.respond_to?(col.to_s), "should respond to the schema's string key, but failed on: #{col}" assert Person.new.respond_to?(col.to_sym), "should respond to the schema's symbol key, but failed on: #{col.to_sym}" end end @@ -126,11 +128,11 @@ def teardown test "defining a schema should return it when asked" do assert Person.schema.blank?, "should have a blank class schema" - new_schema = {'age' => 'integer', 'name' => 'string', - 'height' => 'float', 'bio' => 'text', - 'weight' => 'decimal', 'photo' => 'binary', - 'alive' => 'boolean', 'created_at' => 'timestamp', - 'thetime' => 'time', 'thedate' => 'date', 'mydatetime' => 'datetime'} + new_schema = { "age" => "integer", "name" => "string", + "height" => "float", "bio" => "text", + "weight" => "decimal", "photo" => "binary", + "alive" => "boolean", "created_at" => "timestamp", + "thetime" => "time", "thedate" => "date", "mydatetime" => "datetime" } assert_nothing_raised { Person.schema = new_schema @@ -142,14 +144,14 @@ def teardown test "defining a schema, then fetching a model should still match the defined schema" do # sanity checks assert Person.schema.blank?, "should have a blank class schema" - new_schema = {'age' => 'integer', 'name' => 'string', - 'height' => 'float', 'bio' => 'text', - 'weight' => 'decimal', 'photo' => 'binary', - 'alive' => 'boolean', 'created_at' => 'timestamp', - 'thetime' => 'time', 'thedate' => 'date', 'mydatetime' => 'datetime'} + new_schema = { "age" => "integer", "name" => "string", + "height" => "float", "bio" => "text", + "weight" => "decimal", "photo" => "binary", + "alive" => "boolean", "created_at" => "timestamp", + "thetime" => "time", "thedate" => "date", "mydatetime" => "datetime" } matz = Person.find(1) - assert !matz.schema.blank?, "should have some sort of schema on an instance variable" + assert_not matz.schema.blank?, "should have some sort of schema on an instance variable" assert_not_equal new_schema, matz.schema, "should not have the class-level schema until it's been added to the class!" assert_nothing_raised { @@ -179,7 +181,7 @@ def teardown attribute :foo, :string end assert_respond_to s, :attrs, "should return attributes in theory" - assert_equal({'foo' => 'string' }, s.attrs, "should return attributes in practice") + assert_equal({ "foo" => "string" }, s.attrs, "should return attributes in practice") end end @@ -188,10 +190,10 @@ def teardown s = nil Person.schema do s = self - attribute('foo', 'string') + attribute("foo", "string") end - assert s.attrs.has_key?('foo'), "should have saved the attribute name" - assert_equal 'string', s.attrs['foo'], "should have saved the attribute type" + assert s.attrs.has_key?("foo"), "should have saved the attribute name" + assert_equal "string", s.attrs["foo"], "should have saved the attribute type" end end @@ -203,8 +205,8 @@ def teardown attribute(:foo, :integer) end - assert s.attrs.has_key?('foo'), "should have saved the attribute name as a string" - assert_equal 'integer', s.attrs['foo'], "should have saved the attribute type as a string" + assert s.attrs.has_key?("foo"), "should have saved the attribute name as a string" + assert_equal "integer", s.attrs["foo"], "should have saved the attribute type as a string" end end @@ -214,27 +216,27 @@ def teardown s = nil Person.schema do s = self - attribute('foo', the_type) + attribute("foo", the_type) end - assert s.attrs.has_key?('foo'), "should have saved the attribute name" - assert_equal the_type.to_s, s.attrs['foo'], "should have saved the attribute type of: #{the_type}" + assert s.attrs.has_key?("foo"), "should have saved the attribute name" + assert_equal the_type.to_s, s.attrs["foo"], "should have saved the attribute type of: #{the_type}" end end end test "attributes should not accept unknown values" do - bad_values = [ :oogle, :blob, 'thing'] + bad_values = [ :oogle, :blob, "thing"] bad_values.each do |bad_value| - assert_raises(ArgumentError,"should only accept a known attribute type, but accepted: #{bad_value.inspect}") do + assert_raises(ArgumentError, "should only accept a known attribute type, but accepted: #{bad_value.inspect}") do Person.schema do - attribute 'key', bad_value + attribute "key", bad_value end end - assert !self.respond_to?(bad_value), "should only respond to a known attribute type, but accepted: #{bad_value.inspect}" - assert_raises(NoMethodError,"should only have methods for known attribute types, but accepted: #{bad_value.inspect}") do + assert_not self.respond_to?(bad_value), "should only respond to a known attribute type, but accepted: #{bad_value.inspect}" + assert_raises(NoMethodError, "should only have methods for known attribute types, but accepted: #{bad_value.inspect}") do Person.schema do - send bad_value, 'key' + send bad_value, "key" end end end @@ -245,15 +247,15 @@ def teardown s = nil Person.schema do s = self - send(the_type,'foo') + send(the_type, "foo") end - assert s.attrs.has_key?('foo'), "should now have saved the attribute name" - assert_equal the_type.to_s, s.attrs['foo'], "should have saved the attribute type of: #{the_type}" + assert s.attrs.has_key?("foo"), "should now have saved the attribute name" + assert_equal the_type.to_s, s.attrs["foo"], "should have saved the attribute type of: #{the_type}" end end test "should accept multiple attribute names for an attribute method" do - names = ['foo','bar','baz'] + names = ["foo", "bar", "baz"] s = nil Person.schema do s = self @@ -261,7 +263,7 @@ def teardown end names.each do |the_name| assert s.attrs.has_key?(the_name), "should now have saved the attribute name: #{the_name}" - assert_equal 'string', s.attrs[the_name], "should have saved the attribute as a string" + assert_equal "string", s.attrs[the_name], "should have saved the attribute as a string" end end @@ -277,11 +279,11 @@ def teardown new_attr_name_two = :another_new_schema_attribute assert Person.schema.blank?, "sanity check - should have a blank class schema" - assert !Person.new.respond_to?(new_attr_name), "sanity check - should not respond to the brand-new attribute yet" - assert !Person.new.respond_to?(new_attr_name_two), "sanity check - should not respond to the brand-new attribute yet" + assert_not Person.new.respond_to?(new_attr_name), "sanity check - should not respond to the brand-new attribute yet" + assert_not Person.new.respond_to?(new_attr_name_two), "sanity check - should not respond to the brand-new attribute yet" assert_nothing_raised do - Person.schema = {new_attr_name.to_s => 'string'} + Person.schema = { new_attr_name.to_s => "string" } Person.schema { string new_attr_name_two } end @@ -295,28 +297,28 @@ def teardown assert Person.schema.blank?, "sanity check - should have a blank class schema" - assert !Person.new.respond_to?(new_attr_name), "sanity check - should not respond to the brand-new attribute yet" - assert !Person.new.respond_to?(new_attr_name_two), "sanity check - should not respond to the brand-new attribute yet" + assert_not Person.new.respond_to?(new_attr_name), "sanity check - should not respond to the brand-new attribute yet" + assert_not Person.new.respond_to?(new_attr_name_two), "sanity check - should not respond to the brand-new attribute yet" assert_nothing_raised do Person.schema { string new_attr_name_two } - Person.schema = {new_attr_name.to_s => 'string'} + Person.schema = { new_attr_name.to_s => "string" } end assert_respond_to Person.new, new_attr_name, "should respond to the attribute in a passed-in schema, but failed on: #{new_attr_name}" assert_respond_to Person.new, new_attr_name_two, "should respond to the attribute from the schema, but failed on: #{new_attr_name_two}" end - test 'should retrieve the `Method` object' do + test "should retrieve the `Method` object" do new_attr_name = :my_new_schema_attribute new_attr_name_two = :another_new_schema_attribute assert Person.schema.blank?, "sanity check - should have a blank class schema" - assert !Person.new.respond_to?(new_attr_name), "sanity check - should not respond to the brand-new attribute yet" - assert !Person.new.respond_to?(new_attr_name_two), "sanity check - should not respond to the brand-new attribute yet" + assert_not Person.new.respond_to?(new_attr_name), "sanity check - should not respond to the brand-new attribute yet" + assert_not Person.new.respond_to?(new_attr_name_two), "sanity check - should not respond to the brand-new attribute yet" assert_nothing_raised do - Person.schema = {new_attr_name.to_s => 'string'} + Person.schema = { new_attr_name.to_s => "string" } Person.schema { string new_attr_name_two } end @@ -339,7 +341,7 @@ def teardown Person.new.send(new_attr_name_two) end - Person.schema = {new_attr_name.to_s => :float} + Person.schema = { new_attr_name.to_s => :float } Person.schema { string new_attr_name_two } assert_nothing_raised do @@ -362,11 +364,11 @@ def teardown end test "setting schema should set known attributes on class and instance" do - new_schema = {'age' => 'integer', 'name' => 'string', - 'height' => 'float', 'bio' => 'text', - 'weight' => 'decimal', 'photo' => 'binary', - 'alive' => 'boolean', 'created_at' => 'timestamp', - 'thetime' => 'time', 'thedate' => 'date', 'mydatetime' => 'datetime'} + new_schema = { "age" => "integer", "name" => "string", + "height" => "float", "bio" => "text", + "weight" => "decimal", "photo" => "binary", + "alive" => "boolean", "created_at" => "timestamp", + "thetime" => "time", "thedate" => "date", "mydatetime" => "datetime" } assert_nothing_raised { Person.schema = new_schema } @@ -399,11 +401,11 @@ def teardown test "setting schema then fetching should add schema attributes to the instance attributes" do # an attribute in common with fetched instance and one that isn't - new_schema = {'age' => 'integer', 'name' => 'string', - 'height' => 'float', 'bio' => 'text', - 'weight' => 'decimal', 'photo' => 'binary', - 'alive' => 'boolean', 'created_at' => 'timestamp', - 'thetime' => 'time', 'thedate' => 'date', 'mydatetime' => 'datetime'} + new_schema = { "age" => "integer", "name" => "string", + "height" => "float", "bio" => "text", + "weight" => "decimal", "photo" => "binary", + "alive" => "boolean", "created_at" => "timestamp", + "thetime" => "time", "thedate" => "date", "mydatetime" => "datetime" } assert_nothing_raised { Person.schema = new_schema } @@ -418,9 +420,9 @@ def teardown end end - test 'known attributes should be unique' do - new_schema = {'age' => 'integer', 'name' => 'string'} + test "known attributes should be unique" do + new_schema = { "age" => "integer", "name" => "string" } Person.schema = new_schema - assert_equal Person.new(:age => 20, :name => 'Matz').known_attributes, ['age', 'name'] + assert_equal Person.new(age: 20, name: "Matz").known_attributes, ["age", "name"] end end diff --git a/test/cases/base_errors_test.rb b/test/cases/base_errors_test.rb index f05e913396..6f098811f5 100644 --- a/test/cases/base_errors_test.rb +++ b/test/cases/base_errors_test.rb @@ -1,18 +1,20 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" require "fixtures/person" class BaseErrorsTest < ActiveSupport::TestCase def setup ActiveResource::HttpMock.respond_to do |mock| - mock.post "/people.xml", {}, %q(Age can't be blankKnown attribute can't be blankName can't be blankName must start with a letterPerson quota full for today.Phone work can't be blankPhone is not valid), 422, {'Content-Type' => 'application/xml; charset=utf-8'} - mock.post "/people.json", {}, %q({"errors":{"age":["can't be blank"],"known_attribute":["can't be blank"],"name":["can't be blank", "must start with a letter"],"person":["quota full for today."],"phone_work":["can't be blank"],"phone":["is not valid"]}}), 422, {'Content-Type' => 'application/json; charset=utf-8'} + mock.post "/people.xml", {}, %q(Age can't be blankKnown attribute can't be blankName can't be blankName must start with a letterPerson quota full for today.Phone work can't be blankPhone is not valid), 422, "Content-Type" => "application/xml; charset=utf-8" + mock.post "/people.json", {}, %q({"errors":{"age":["can't be blank"],"known_attribute":["can't be blank"],"name":["can't be blank", "must start with a letter"],"person":["quota full for today."],"phone_work":["can't be blank"],"phone":["is not valid"]}}), 422, "Content-Type" => "application/json; charset=utf-8" end end def test_should_mark_as_invalid [ :json, :xml ].each do |format| invalid_user_using_format(format) do - assert !@person.valid? + assert_not @person.valid? end end end @@ -28,7 +30,7 @@ def test_should_parse_json_and_xml_errors def test_should_parse_json_errors_when_no_errors_key ActiveResource::HttpMock.respond_to do |mock| - mock.post "/people.json", {}, '{}', 422, {'Content-Type' => 'application/json; charset=utf-8'} + mock.post "/people.json", {}, "{}", 422, "Content-Type" => "application/json; charset=utf-8" end invalid_user_using_format(:json) do @@ -100,14 +102,14 @@ def test_should_mark_as_invalid_when_content_type_is_unavailable_in_response_hea [ :json, :xml ].each do |format| invalid_user_using_format(format) do - assert !@person.valid? + assert_not @person.valid? end end end def test_should_parse_json_string_errors_with_an_errors_key ActiveResource::HttpMock.respond_to do |mock| - mock.post "/people.json", {}, %q({"errors":["Age can't be blank", "Name can't be blank", "Name must start with a letter", "Person quota full for today.", "Phone work can't be blank", "Phone is not valid"]}), 422, {'Content-Type' => 'application/json; charset=utf-8'} + mock.post "/people.json", {}, %q({"errors":["Age can't be blank", "Name can't be blank", "Name must start with a letter", "Person quota full for today.", "Phone work can't be blank", "Phone is not valid"]}), 422, "Content-Type" => "application/json; charset=utf-8" end assert_deprecated(/as an array/) do @@ -124,7 +126,7 @@ def test_should_parse_json_string_errors_with_an_errors_key def test_should_parse_3_1_style_json_errors ActiveResource::HttpMock.respond_to do |mock| - mock.post "/people.json", {}, %q({"age":["can't be blank"],"name":["can't be blank", "must start with a letter"],"person":["quota full for today."],"phone_work":["can't be blank"],"phone":["is not valid"]}), 422, {'Content-Type' => 'application/json; charset=utf-8'} + mock.post "/people.json", {}, %q({"age":["can't be blank"],"name":["can't be blank", "must start with a letter"],"person":["quota full for today."],"phone_work":["can't be blank"],"phone":["is not valid"]}), 422, "Content-Type" => "application/json; charset=utf-8" end assert_deprecated(/without a root/) do @@ -140,18 +142,18 @@ def test_should_parse_3_1_style_json_errors end private - def invalid_user_using_format(mime_type_reference) - previous_format = Person.format - previous_schema = Person.schema - - Person.format = mime_type_reference - Person.schema = { 'known_attribute' => 'string' } - @person = Person.new(:name => '', :age => '', :phone => '', :phone_work => '') - assert_equal false, @person.save - - yield - ensure - Person.format = previous_format - Person.schema = previous_schema - end + def invalid_user_using_format(mime_type_reference) + previous_format = Person.format + previous_schema = Person.schema + + Person.format = mime_type_reference + Person.schema = { "known_attribute" => "string" } + @person = Person.new(name: "", age: "", phone: "", phone_work: "") + assert_equal false, @person.save + + yield + ensure + Person.format = previous_format + Person.schema = previous_schema + end end diff --git a/test/cases/base_test.rb b/test/cases/base_test.rb index 45da517a9f..3872e715d5 100644 --- a/test/cases/base_test.rb +++ b/test/cases/base_test.rb @@ -1,4 +1,6 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" require "fixtures/person" require "fixtures/customer" require "fixtures/street_address" @@ -11,9 +13,9 @@ require "fixtures/comment" require "fixtures/product" require "fixtures/inventory" -require 'active_support/json' -require 'active_support/core_ext/hash/conversions' -require 'mocha/setup' +require "active_support/json" +require "active_support/core_ext/hash/conversions" +require "mocha/setup" class BaseTest < ActiveSupport::TestCase def setup @@ -32,9 +34,9 @@ def teardown ######################################################################## def test_site_accessor_accepts_uri_or_string_argument - site = URI.parse('http://localhost') + site = URI.parse("http://localhost") - assert_nothing_raised { Person.site = 'http://localhost' } + assert_nothing_raised { Person.site = "http://localhost" } assert_equal site, Person.site assert_nothing_raised { Person.site = site } @@ -42,22 +44,22 @@ def test_site_accessor_accepts_uri_or_string_argument end def test_should_use_site_prefix_and_credentials - assert_equal 'http://foo:bar@beast.caboo.se', Forum.site.to_s - assert_equal 'http://foo:bar@beast.caboo.se/forums/:forum_id', Topic.site.to_s + assert_equal "http://foo:bar@beast.caboo.se", Forum.site.to_s + assert_equal "http://foo:bar@beast.caboo.se/forums/:forum_id", Topic.site.to_s end def test_site_variable_can_be_reset actor = Class.new(ActiveResource::Base) assert_nil actor.site - actor.site = 'http://localhost:31337' + actor.site = "http://localhost:31337" actor.site = nil assert_nil actor.site end def test_proxy_accessor_accepts_uri_or_string_argument - proxy = URI.parse('http://localhost') + proxy = URI.parse("http://localhost") - assert_nothing_raised { Person.proxy = 'http://localhost' } + assert_nothing_raised { Person.proxy = "http://localhost" } assert_equal proxy, Person.proxy assert_nothing_raised { Person.proxy = proxy } @@ -65,27 +67,27 @@ def test_proxy_accessor_accepts_uri_or_string_argument end def test_should_use_proxy_prefix_and_credentials - assert_equal 'http://user:password@proxy.local:3000', ProxyResource.proxy.to_s + assert_equal "http://user:password@proxy.local:3000", ProxyResource.proxy.to_s end def test_proxy_variable_can_be_reset actor = Class.new(ActiveResource::Base) assert_nil actor.site - actor.proxy = 'http://localhost:31337' + actor.proxy = "http://localhost:31337" actor.proxy = nil assert_nil actor.site end def test_should_accept_setting_user - Forum.user = 'david' - assert_equal('david', Forum.user) - assert_equal('david', Forum.connection.user) + Forum.user = "david" + assert_equal("david", Forum.user) + assert_equal("david", Forum.connection.user) end def test_should_accept_setting_password - Forum.password = 'test123' - assert_equal('test123', Forum.password) - assert_equal('test123', Forum.connection.password) + Forum.password = "test123" + assert_equal("test123", Forum.password) + assert_equal("test123", Forum.connection.password) end def test_should_accept_setting_auth_type @@ -113,17 +115,17 @@ def test_should_accept_setting_read_timeout end def test_should_accept_setting_ssl_options - expected = {:verify => 1} - Forum.ssl_options= expected + expected = { verify: 1 } + Forum.ssl_options = expected assert_equal(expected, Forum.ssl_options) assert_equal(expected, Forum.connection.ssl_options) end def test_user_variable_can_be_reset actor = Class.new(ActiveResource::Base) - actor.site = 'http://cinema' + actor.site = "http://cinema" assert_nil actor.user - actor.user = 'username' + actor.user = "username" actor.user = nil assert_nil actor.user assert_nil actor.connection.user @@ -131,9 +133,9 @@ def test_user_variable_can_be_reset def test_password_variable_can_be_reset actor = Class.new(ActiveResource::Base) - actor.site = 'http://cinema' + actor.site = "http://cinema" assert_nil actor.password - actor.password = 'username' + actor.password = "username" actor.password = nil assert_nil actor.password assert_nil actor.connection.password @@ -141,7 +143,7 @@ def test_password_variable_can_be_reset def test_timeout_variable_can_be_reset actor = Class.new(ActiveResource::Base) - actor.site = 'http://cinema' + actor.site = "http://cinema" assert_nil actor.timeout actor.timeout = 5 actor.timeout = nil @@ -151,7 +153,7 @@ def test_timeout_variable_can_be_reset def test_open_timeout_variable_can_be_reset actor = Class.new(ActiveResource::Base) - actor.site = 'http://cinema' + actor.site = "http://cinema" assert_nil actor.open_timeout actor.open_timeout = 5 actor.open_timeout = nil @@ -161,7 +163,7 @@ def test_open_timeout_variable_can_be_reset def test_read_timeout_variable_can_be_reset actor = Class.new(ActiveResource::Base) - actor.site = 'http://cinema' + actor.site = "http://cinema" assert_nil actor.read_timeout actor.read_timeout = 5 actor.read_timeout = nil @@ -172,13 +174,13 @@ def test_read_timeout_variable_can_be_reset def test_ssl_options_hash_can_be_reset # SSL options are nil, resulting in an empty hash on the connection. actor = Class.new(ActiveResource::Base) - actor.site = 'https://cinema' + actor.site = "https://cinema" assert_nil actor.ssl_options connection = actor.connection assert_equal Hash.new, connection.ssl_options # Setting SSL options wipes the connection. - actor.ssl_options = { :foo => 5 } + actor.ssl_options = { foo: 5 } assert_not_equal connection, actor.connection connection = actor.connection assert_equal 5, connection.ssl_options[:foo] @@ -191,7 +193,7 @@ def test_ssl_options_hash_can_be_reset def test_credentials_from_site_are_decoded actor = Class.new(ActiveResource::Base) - actor.site = 'http://my%40email.com:%31%32%33@cinema' + actor.site = "http://my%40email.com:%31%32%33@cinema" assert_equal("my@email.com", actor.user) assert_equal("123", actor.password) end @@ -206,23 +208,23 @@ def test_site_reader_uses_superclass_site_until_written assert_equal Person.site, actor.site # Subclass returns frozen superclass copy. - assert !Person.site.frozen? + assert_not Person.site.frozen? assert actor.site.frozen? # Changing subclass site doesn't change superclass site. - actor.site = 'http://localhost:31337' + actor.site = "http://localhost:31337" assert_not_equal Person.site, actor.site # Changed subclass site is not frozen. - assert !actor.site.frozen? + assert_not actor.site.frozen? # Changing superclass site doesn't overwrite subclass site. - Person.site = 'http://somewhere.else' + Person.site = "http://somewhere.else" assert_not_equal Person.site, actor.site # Changing superclass site after subclassing changes subclass site. jester = Class.new(actor) - actor.site = 'http://nomad' + actor.site = "http://nomad" assert_equal actor.site, jester.site assert jester.site.frozen? @@ -230,11 +232,11 @@ def test_site_reader_uses_superclass_site_until_written fruit = Class.new(ActiveResource::Base) apple = Class.new(fruit) - fruit.site = 'http://market' - assert_equal fruit.site, apple.site, 'subclass did not adopt changes from parent class' + fruit.site = "http://market" + assert_equal fruit.site, apple.site, "subclass did not adopt changes from parent class" - fruit.site = 'http://supermarket' - assert_equal fruit.site, apple.site, 'subclass did not adopt changes from parent class' + fruit.site = "http://supermarket" + assert_equal fruit.site, apple.site, "subclass did not adopt changes from parent class" end def test_proxy_reader_uses_superclass_site_until_written @@ -242,30 +244,30 @@ def test_proxy_reader_uses_superclass_site_until_written assert_nil ActiveResource::Base.proxy assert_nil Class.new(ActiveResource::Base).proxy - Person.proxy = 'http://proxy.local' + Person.proxy = "http://proxy.local" # Subclass uses superclass proxy. actor = Class.new(Person) assert_equal Person.proxy, actor.proxy # Subclass returns frozen superclass copy. - assert !Person.proxy.frozen? + assert_not Person.proxy.frozen? assert actor.proxy.frozen? # Changing subclass proxy doesn't change superclass site. - actor.proxy = 'http://localhost:31337' + actor.proxy = "http://localhost:31337" assert_not_equal Person.proxy, actor.proxy # Changed subclass proxy is not frozen. - assert !actor.proxy.frozen? + assert_not actor.proxy.frozen? # Changing superclass proxy doesn't overwrite subclass site. - Person.proxy = 'http://somewhere.else' + Person.proxy = "http://somewhere.else" assert_not_equal Person.proxy, actor.proxy # Changing superclass proxy after subclassing changes subclass site. jester = Class.new(actor) - actor.proxy = 'http://nomad' + actor.proxy = "http://nomad" assert_equal actor.proxy, jester.proxy assert jester.proxy.frozen? @@ -273,87 +275,87 @@ def test_proxy_reader_uses_superclass_site_until_written fruit = Class.new(ActiveResource::Base) apple = Class.new(fruit) - fruit.proxy = 'http://market' - assert_equal fruit.proxy, apple.proxy, 'subclass did not adopt changes from parent class' + fruit.proxy = "http://market" + assert_equal fruit.proxy, apple.proxy, "subclass did not adopt changes from parent class" - fruit.proxy = 'http://supermarket' - assert_equal fruit.proxy, apple.proxy, 'subclass did not adopt changes from parent class' + fruit.proxy = "http://supermarket" + assert_equal fruit.proxy, apple.proxy, "subclass did not adopt changes from parent class" end def test_user_reader_uses_superclass_user_until_written # Superclass is Object so returns nil. assert_nil ActiveResource::Base.user assert_nil Class.new(ActiveResource::Base).user - Person.user = 'anonymous' + Person.user = "anonymous".dup # Subclass uses superclass user. actor = Class.new(Person) assert_equal Person.user, actor.user # Subclass returns frozen superclass copy. - assert !Person.user.frozen? + assert_not Person.user.frozen? assert actor.user.frozen? # Changing subclass user doesn't change superclass user. - actor.user = 'david' + actor.user = "david" assert_not_equal Person.user, actor.user # Changing superclass user doesn't overwrite subclass user. - Person.user = 'john' + Person.user = "john" assert_not_equal Person.user, actor.user # Changing superclass user after subclassing changes subclass user. jester = Class.new(actor) - actor.user = 'john.doe' + actor.user = "john.doe" assert_equal actor.user, jester.user # Subclasses are always equal to superclass user when not overridden fruit = Class.new(ActiveResource::Base) apple = Class.new(fruit) - fruit.user = 'manager' - assert_equal fruit.user, apple.user, 'subclass did not adopt changes from parent class' + fruit.user = "manager" + assert_equal fruit.user, apple.user, "subclass did not adopt changes from parent class" - fruit.user = 'client' - assert_equal fruit.user, apple.user, 'subclass did not adopt changes from parent class' + fruit.user = "client" + assert_equal fruit.user, apple.user, "subclass did not adopt changes from parent class" end def test_password_reader_uses_superclass_password_until_written # Superclass is Object so returns nil. assert_nil ActiveResource::Base.password assert_nil Class.new(ActiveResource::Base).password - Person.password = 'my-password' + Person.password = "my-password".dup # Subclass uses superclass password. actor = Class.new(Person) assert_equal Person.password, actor.password # Subclass returns frozen superclass copy. - assert !Person.password.frozen? + assert_not Person.password.frozen? assert actor.password.frozen? # Changing subclass password doesn't change superclass password. - actor.password = 'secret' + actor.password = "secret" assert_not_equal Person.password, actor.password # Changing superclass password doesn't overwrite subclass password. - Person.password = 'super-secret' + Person.password = "super-secret" assert_not_equal Person.password, actor.password # Changing superclass password after subclassing changes subclass password. jester = Class.new(actor) - actor.password = 'even-more-secret' + actor.password = "even-more-secret" assert_equal actor.password, jester.password # Subclasses are always equal to superclass password when not overridden fruit = Class.new(ActiveResource::Base) apple = Class.new(fruit) - fruit.password = 'mega-secret' - assert_equal fruit.password, apple.password, 'subclass did not adopt changes from parent class' + fruit.password = "mega-secret" + assert_equal fruit.password, apple.password, "subclass did not adopt changes from parent class" - fruit.password = 'ok-password' - assert_equal fruit.password, apple.password, 'subclass did not adopt changes from parent class' + fruit.password = "ok-password" + assert_equal fruit.password, apple.password, "subclass did not adopt changes from parent class" end def test_timeout_reader_uses_superclass_timeout_until_written @@ -384,10 +386,10 @@ def test_timeout_reader_uses_superclass_timeout_until_written apple = Class.new(fruit) fruit.timeout = 25 - assert_equal fruit.timeout, apple.timeout, 'subclass did not adopt changes from parent class' + assert_equal fruit.timeout, apple.timeout, "subclass did not adopt changes from parent class" fruit.timeout = 30 - assert_equal fruit.timeout, apple.timeout, 'subclass did not adopt changes from parent class' + assert_equal fruit.timeout, apple.timeout, "subclass did not adopt changes from parent class" end def test_open_and_read_timeout_readers_uses_superclass_timeout_until_written @@ -429,19 +431,19 @@ def test_open_and_read_timeout_readers_uses_superclass_timeout_until_written fruit.open_timeout = 25 fruit.read_timeout = 25 - assert_equal fruit.open_timeout, apple.open_timeout, 'subclass did not adopt changes from parent class' - assert_equal fruit.read_timeout, apple.read_timeout, 'subclass did not adopt changes from parent class' + assert_equal fruit.open_timeout, apple.open_timeout, "subclass did not adopt changes from parent class" + assert_equal fruit.read_timeout, apple.read_timeout, "subclass did not adopt changes from parent class" fruit.open_timeout = 30 fruit.read_timeout = 30 - assert_equal fruit.open_timeout, apple.open_timeout, 'subclass did not adopt changes from parent class' - assert_equal fruit.read_timeout, apple.read_timeout, 'subclass did not adopt changes from parent class' + assert_equal fruit.open_timeout, apple.open_timeout, "subclass did not adopt changes from parent class" + assert_equal fruit.read_timeout, apple.read_timeout, "subclass did not adopt changes from parent class" end def test_primary_key_uses_superclass_primary_key_until_written # Superclass is Object so defaults to 'id' - assert_equal 'id', ActiveResource::Base.primary_key - assert_equal 'id', Class.new(ActiveResource::Base).primary_key + assert_equal "id", ActiveResource::Base.primary_key + assert_equal "id", Class.new(ActiveResource::Base).primary_key Person.primary_key = :first # Subclass uses superclass primary_key @@ -466,47 +468,47 @@ def test_primary_key_uses_superclass_primary_key_until_written apple = Class.new(fruit) fruit.primary_key = :fifth - assert_equal fruit.primary_key, apple.primary_key, 'subclass did not adopt changes from parent class' + assert_equal fruit.primary_key, apple.primary_key, "subclass did not adopt changes from parent class" fruit.primary_key = :sixth - assert_equal fruit.primary_key, apple.primary_key, 'subclass did not adopt changes from parent class' + assert_equal fruit.primary_key, apple.primary_key, "subclass did not adopt changes from parent class" # Reset the primary key for subsequent tests - Person.primary_key = 'id' + Person.primary_key = "id" end def test_ssl_options_reader_uses_superclass_ssl_options_until_written # Superclass is Object so returns nil. assert_nil ActiveResource::Base.ssl_options assert_nil Class.new(ActiveResource::Base).ssl_options - Person.ssl_options = {:foo => 'bar'} + Person.ssl_options = { foo: "bar" } # Subclass uses superclass ssl_options. actor = Class.new(Person) assert_equal Person.ssl_options, actor.ssl_options # Changing subclass ssl_options doesn't change superclass ssl_options. - actor.ssl_options = {:baz => ''} + actor.ssl_options = { baz: "" } assert_not_equal Person.ssl_options, actor.ssl_options # Changing superclass ssl_options doesn't overwrite subclass ssl_options. - Person.ssl_options = {:color => 'blue'} + Person.ssl_options = { color: "blue" } assert_not_equal Person.ssl_options, actor.ssl_options # Changing superclass ssl_options after subclassing changes subclass ssl_options. jester = Class.new(actor) - actor.ssl_options = {:color => 'red'} + actor.ssl_options = { color: "red" } assert_equal actor.ssl_options, jester.ssl_options # Subclasses are always equal to superclass ssl_options when not overridden. fruit = Class.new(ActiveResource::Base) apple = Class.new(fruit) - fruit.ssl_options = {:alpha => 'betas'} - assert_equal fruit.ssl_options, apple.ssl_options, 'subclass did not adopt changes from parent class' + fruit.ssl_options = { alpha: "betas" } + assert_equal fruit.ssl_options, apple.ssl_options, "subclass did not adopt changes from parent class" - fruit.ssl_options = {:omega => 'moos'} - assert_equal fruit.ssl_options, apple.ssl_options, 'subclass did not adopt changes from parent class' + fruit.ssl_options = { omega: "moos" } + assert_equal fruit.ssl_options, apple.ssl_options, "subclass did not adopt changes from parent class" end def test_updating_baseclass_site_object_wipes_descendent_cached_connection_objects @@ -514,53 +516,53 @@ def test_updating_baseclass_site_object_wipes_descendent_cached_connection_objec fruit = Class.new(ActiveResource::Base) apple = Class.new(fruit) - fruit.site = 'http://market' + fruit.site = "http://market" assert_equal fruit.connection.site, apple.connection.site first_connection = apple.connection.object_id - fruit.site = 'http://supermarket' + fruit.site = "http://supermarket" assert_equal fruit.connection.site, apple.connection.site second_connection = apple.connection.object_id - assert_not_equal(first_connection, second_connection, 'Connection should be re-created') + assert_not_equal(first_connection, second_connection, "Connection should be re-created") end def test_updating_baseclass_user_wipes_descendent_cached_connection_objects # Subclasses are always equal to superclass user when not overridden fruit = Class.new(ActiveResource::Base) apple = Class.new(fruit) - fruit.site = 'http://market' + fruit.site = "http://market" - fruit.user = 'david' + fruit.user = "david" assert_equal fruit.connection.user, apple.connection.user first_connection = apple.connection.object_id - fruit.user = 'john' + fruit.user = "john" assert_equal fruit.connection.user, apple.connection.user second_connection = apple.connection.object_id - assert_not_equal(first_connection, second_connection, 'Connection should be re-created') + assert_not_equal(first_connection, second_connection, "Connection should be re-created") end def test_updating_baseclass_password_wipes_descendent_cached_connection_objects # Subclasses are always equal to superclass password when not overridden fruit = Class.new(ActiveResource::Base) apple = Class.new(fruit) - fruit.site = 'http://market' + fruit.site = "http://market" - fruit.password = 'secret' + fruit.password = "secret" assert_equal fruit.connection.password, apple.connection.password first_connection = apple.connection.object_id - fruit.password = 'supersecret' + fruit.password = "supersecret" assert_equal fruit.connection.password, apple.connection.password second_connection = apple.connection.object_id - assert_not_equal(first_connection, second_connection, 'Connection should be re-created') + assert_not_equal(first_connection, second_connection, "Connection should be re-created") end def test_updating_baseclass_timeout_wipes_descendent_cached_connection_objects # Subclasses are always equal to superclass timeout when not overridden fruit = Class.new(ActiveResource::Base) apple = Class.new(fruit) - fruit.site = 'http://market' + fruit.site = "http://market" fruit.timeout = 5 assert_equal fruit.connection.timeout, apple.connection.timeout @@ -569,14 +571,14 @@ def test_updating_baseclass_timeout_wipes_descendent_cached_connection_objects fruit.timeout = 10 assert_equal fruit.connection.timeout, apple.connection.timeout second_connection = apple.connection.object_id - assert_not_equal(first_connection, second_connection, 'Connection should be re-created') + assert_not_equal(first_connection, second_connection, "Connection should be re-created") end def test_updating_baseclass_read_and_open_timeouts_wipes_descendent_cached_connection_objects # Subclasses are always equal to superclass timeout when not overridden fruit = Class.new(ActiveResource::Base) apple = Class.new(fruit) - fruit.site = 'http://market' + fruit.site = "http://market" fruit.open_timeout = 1 fruit.read_timeout = 5 @@ -589,58 +591,58 @@ def test_updating_baseclass_read_and_open_timeouts_wipes_descendent_cached_conne assert_equal fruit.connection.open_timeout, apple.connection.open_timeout assert_equal fruit.connection.read_timeout, apple.connection.read_timeout second_connection = apple.connection.object_id - assert_not_equal(first_connection, second_connection, 'Connection should be re-created') + assert_not_equal(first_connection, second_connection, "Connection should be re-created") end def test_header_inheritance fruit = Class.new(ActiveResource::Base) apple = Class.new(fruit) - fruit.site = 'http://market' + fruit.site = "http://market" - fruit.headers['key'] = 'value' - assert_equal 'value', apple.headers['key'] + fruit.headers["key"] = "value" + assert_equal "value", apple.headers["key"] end def test_header_inheritance_set_at_multiple_points fruit = Class.new(ActiveResource::Base) apple = Class.new(fruit) - fruit.site = 'http://market' + fruit.site = "http://market" - fruit.headers['key'] = 'value' - assert_equal 'value', apple.headers['key'] + fruit.headers["key"] = "value" + assert_equal "value", apple.headers["key"] - apple.headers['key2'] = 'value2' - fruit.headers['key3'] = 'value3' + apple.headers["key2"] = "value2" + fruit.headers["key3"] = "value3" - assert_equal 'value', apple.headers['key'] - assert_equal 'value2', apple.headers['key2'] - assert_equal 'value3', apple.headers['key3'] + assert_equal "value", apple.headers["key"] + assert_equal "value2", apple.headers["key2"] + assert_equal "value3", apple.headers["key3"] end def test_header_inheritance_should_not_leak_upstream fruit = Class.new(ActiveResource::Base) apple = Class.new(fruit) - fruit.site = 'http://market' + fruit.site = "http://market" - fruit.headers['key'] = 'value' + fruit.headers["key"] = "value" - apple.headers['key2'] = 'value2' - assert_nil fruit.headers['key2'] + apple.headers["key2"] = "value2" + assert_nil fruit.headers["key2"] end def test_header_should_be_copied_to_main_thread_if_not_defined fruit = Class.new(ActiveResource::Base) Thread.new do - fruit.site = 'http://market' - assert_equal 'http://market', fruit.site.to_s + fruit.site = "http://market" + assert_equal "http://market", fruit.site.to_s - fruit.headers['key'] = 'value' - assert_equal 'value', fruit.headers['key'] + fruit.headers["key"] = "value" + assert_equal "value", fruit.headers["key"] end.join - assert_equal 'http://market', fruit.site.to_s - assert_equal 'value', fruit.headers['key'] + assert_equal "http://market", fruit.site.to_s + assert_equal "value", fruit.headers["key"] end def test_connection_should_use_connection_class @@ -663,30 +665,30 @@ def test_collection_name end def test_collection_path - assert_equal '/people.json', Person.collection_path + assert_equal "/people.json", Person.collection_path end def test_collection_path_with_parameters - 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.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.json?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.json?') - assert Person.collection_path(:gender => 'male', :student => true).include?('gender=male') - assert Person.collection_path(:gender => 'male', :student => true).include?('student=true') + 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.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.json?struct%5Ba%5D%5B%5D=2&struct%5Ba%5D%5B%5D=1&struct%5Bb%5D=fred', Person.collection_path(:struct => {:a => [2,1], 'b' => 'fred'}) + 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.json?struct%5Ba%5D%5B%5D=2&struct%5Ba%5D%5B%5D=1&struct%5Bb%5D=fred", Person.collection_path(struct: { :a => [2, 1], "b" => "fred" }) end def test_custom_element_path - 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') + 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 @@ -696,26 +698,26 @@ def test_custom_element_path_without_required_prefix_param end def test_module_element_path - assert_equal '/sounds/1.json', Asset::Sound.element_path(1) + assert_equal "/sounds/1.json", Asset::Sound.element_path(1) end def test_module_element_url - assert_equal 'http://37s.sunrise.i:3000/sounds/1.json', Asset::Sound.element_url(1) + assert_equal "http://37s.sunrise.i:3000/sounds/1.json", Asset::Sound.element_url(1) end def test_custom_element_path_with_redefined_to_param Person.module_eval do alias_method :original_to_param_element_path, :to_param - def to_param - name - end + def to_param + name + end end # Class method. - assert_equal '/people/Greg.json', Person.element_path('Greg') + assert_equal "/people/Greg.json", Person.element_path("Greg") # Protected Instance method. - assert_equal '/people/Greg.json', Person.find('Greg').send(:element_path) + assert_equal "/people/Greg.json", Person.find("Greg").send(:element_path) ensure # revert back to original @@ -727,14 +729,14 @@ def to_param end def test_custom_element_path_with_parameters - 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']) + 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.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" }) end def test_custom_collection_path_without_required_prefix_param @@ -744,25 +746,25 @@ def test_custom_collection_path_without_required_prefix_param end def test_custom_collection_path - assert_equal '/people/1/addresses.json', 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) + 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.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') + 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.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_element_name - assert_equal 'address', StreetAddress.element_name + assert_equal "address", StreetAddress.element_name end def test_custom_collection_name - assert_equal 'addresses', StreetAddress.collection_name + assert_equal "addresses", StreetAddress.collection_name end def test_prefix @@ -780,7 +782,7 @@ def test_set_prefix def test_set_prefix_with_inline_keys SetterTrap.rollback_sets(Person) do |person_class| person_class.prefix = "the_prefix:the_param" - assert_equal "the_prefixthe_param_value", person_class.prefix(:the_param => "the_param_value") + assert_equal "the_prefixthe_param_value", person_class.prefix(the_param: "the_param_value") end end @@ -803,8 +805,8 @@ def test_set_prefix_with_default_value end def test_custom_prefix - assert_equal '/people//', StreetAddress.prefix - assert_equal '/people/1/', StreetAddress.prefix(:person_id => 1) + assert_equal "/people//", StreetAddress.prefix + assert_equal "/people/1/", StreetAddress.prefix(person_id: 1) assert_equal [:person_id].to_set, StreetAddress.__send__(:prefix_parameters) end @@ -817,25 +819,25 @@ def test_respond_to assert_respond_to matz, :name assert_respond_to matz, :name= assert_respond_to matz, :name? - assert !matz.respond_to?(:super_scalable_stuff) + assert_not matz.respond_to?(:super_scalable_stuff) end def test_custom_header - Person.headers['key'] = 'value' + Person.headers["key"] = "value" assert_raise(ActiveResource::ResourceNotFound) { Person.find(4) } ensure - Person.headers.delete('key') + Person.headers.delete("key") end def test_build_with_custom_header - Person.headers['key'] = 'value' + Person.headers["key"] = "value" ActiveResource::HttpMock.respond_to do |mock| mock.get "/people/new.json", {}, Person.new.to_json - mock.get "/people/new.json", { 'key' => 'value' }, Person.new.to_json, 404 + mock.get "/people/new.json", { "key" => "value" }, Person.new.to_json, 404 end assert_raise(ActiveResource::ResourceNotFound) { Person.build } ensure - Person.headers.delete('key') + Person.headers.delete("key") end def test_build_without_attributes_for_prefix_call @@ -865,22 +867,22 @@ def test_build_with_non_prefix_attributes def test_save rick = Person.new assert rick.save - assert_equal '5', rick.id + assert_equal "5", rick.id end def test_save! rick = Person.new assert rick.save! - assert_equal '5', rick.id + assert_equal "5", rick.id end def test_id_from_response p = Person.new - resp = {'Location' => '/foo/bar/1'} - assert_equal '1', p.__send__(:id_from_response, resp) + resp = { "Location" => "/foo/bar/1" } + assert_equal "1", p.__send__(:id_from_response, resp) - resp['Location'] << '.json' - assert_equal '1', p.__send__(:id_from_response, resp) + resp["Location"] += ".json" + assert_equal "1", p.__send__(:id_from_response, resp) end def test_id_from_response_without_location @@ -891,24 +893,24 @@ def test_id_from_response_without_location def test_not_persisted_with_no_body_and_positive_content_length resp = ActiveResource::Response.new(nil) - resp['Content-Length'] = "100" + resp["Content-Length"] = "100" Person.connection.expects(:post).returns(resp) - assert !Person.create.persisted? + assert_not Person.create.persisted? end def test_not_persisted_with_body_and_zero_content_length resp = ActiveResource::Response.new(@rick) - resp['Content-Length'] = "0" + resp["Content-Length"] = "0" Person.connection.expects(:post).returns(resp) - assert !Person.create.persisted? + assert_not Person.create.persisted? end # These response codes aren't allowed to have bodies per HTTP spec def test_not_persisted_with_empty_response_codes - [100,101,204,304].each do |status_code| + [100, 101, 204, 304].each do |status_code| resp = ActiveResource::Response.new(@rick, status_code) Person.connection.expects(:post).returns(resp) - assert !Person.create.persisted? + assert_not Person.create.persisted? end end @@ -916,38 +918,38 @@ def test_not_persisted_with_empty_response_codes # the body anyway in its absence. def test_persisted_with_no_content_length resp = ActiveResource::Response.new(@rick) - resp['Content-Length'] = nil + resp["Content-Length"] = nil Person.connection.expects(:post).returns(resp) assert Person.create.persisted? end def test_create_with_custom_prefix - matzs_house = StreetAddress.new(:person_id => 1) + matzs_house = StreetAddress.new(person_id: 1) matzs_house.save - assert_equal '5', matzs_house.id + assert_equal "5", matzs_house.id end # Test that loading a resource preserves its prefix_options. def test_load_preserves_prefix_options - address = StreetAddress.find(1, :params => { :person_id => 1 }) - ryan = Person.new(:id => 1, :name => 'Ryan', :address => address) + address = StreetAddress.find(1, params: { person_id: 1 }) + ryan = Person.new(id: 1, name: "Ryan", address: address) assert_equal address.prefix_options, ryan.address.prefix_options end def test_reload_works_with_prefix_options - address = StreetAddress.find(1, :params => { :person_id => 1 }) + address = StreetAddress.find(1, params: { person_id: 1 }) assert_equal address, address.reload end def test_reload_with_redefined_to_param Person.module_eval do alias_method :original_to_param_reload, :to_param - def to_param - name - end + def to_param + name + end end - person = Person.find('Greg') + person = Person.find("Greg") assert_equal person, person.reload ensure @@ -965,10 +967,10 @@ def test_reload_works_without_prefix_options end def test_create - rick = Person.create(:name => 'Rick') + rick = Person.create(name: "Rick") assert rick.valid? - assert !rick.new? - assert_equal '5', rick.id + assert_not rick.new? + assert_equal "5", rick.id # test additional attribute returned on create assert_equal 25, rick.age @@ -977,20 +979,20 @@ def test_create ActiveResource::HttpMock.respond_to do |mock| mock.post "/people.json", {}, nil, 409 end - assert_raise(ActiveResource::ResourceConflict) { Person.create(:name => 'Rick') } + assert_raise(ActiveResource::ResourceConflict) { Person.create(name: "Rick") } end def test_create_without_location ActiveResource::HttpMock.respond_to do |mock| mock.post "/people.json", {}, nil, 201 end - person = Person.create(:name => 'Rick') + person = Person.create(name: "Rick") assert_nil person.id end def test_create! - rick = Person.create(:name => 'Rick') - rick_bang = Person.create!(:name => 'Rick') + rick = Person.create(name: "Rick") + rick_bang = Person.create!(name: "Rick") assert_equal rick.id, rick_bang.id assert_equal rick.age, rick_bang.age @@ -998,7 +1000,7 @@ def test_create! ActiveResource::HttpMock.respond_to do |mock| mock.post "/people.json", {}, nil, 422 end - assert_raise(ActiveResource::ResourceInvalid) { Person.create!(:name => 'Rick') } + assert_raise(ActiveResource::ResourceInvalid) { Person.create!(name: "Rick") } end def test_clone @@ -1011,7 +1013,7 @@ def test_clone end def test_nested_clone - addy = StreetAddress.find(1, :params => {:person_id => 1}) + addy = StreetAddress.find(1, params: { person_id: 1 }) addy_c = addy.clone assert addy_c.new? addy.attributes.each do |k, v| @@ -1022,12 +1024,12 @@ def test_nested_clone def test_complex_clone matz = Person.find(1) - matz.address = StreetAddress.find(1, :params => {:person_id => matz.id}) - matz.non_ar_hash = {:not => "an ARes instance"} + matz.address = StreetAddress.find(1, params: { person_id: matz.id }) + matz.non_ar_hash = { not: "an ARes instance" } matz.non_ar_arr = ["not", "ARes"] matz_c = matz.clone assert matz_c.new? - assert_raise(NoMethodError) {matz_c.address} + assert_raise(NoMethodError) { matz_c.address } assert_equal matz.non_ar_hash, matz_c.non_ar_hash assert_equal matz.non_ar_arr, matz_c.non_ar_arr @@ -1045,7 +1047,7 @@ def test_update end def test_update_with_custom_prefix_with_specific_id - addy = StreetAddress.find(1, :params => { :person_id => 1 }) + addy = StreetAddress.find(1, params: { person_id: 1 }) addy.street = "54321 Street" assert_kind_of StreetAddress, addy assert_equal "54321 Street", addy.street @@ -1053,7 +1055,7 @@ def test_update_with_custom_prefix_with_specific_id end def test_update_with_custom_prefix_without_specific_id - addy = StreetAddress.find(:first, :params => { :person_id => 1 }) + addy = StreetAddress.find(:first, params: { person_id: 1 }) addy.street = "54321 Lane" assert_kind_of StreetAddress, addy assert_equal "54321 Lane", addy.street @@ -1086,29 +1088,29 @@ def test_update_attribute_as_string matz.expects(:save).returns(true) assert_equal "Matz", matz.name - assert matz.update_attribute('name', "David") + assert matz.update_attribute("name", "David") assert_equal "David", matz.name end def test_update_attributes_as_symbols - addy = StreetAddress.first(:params => {:person_id => 1}) + addy = StreetAddress.first(params: { person_id: 1 }) addy.expects(:save).returns(true) assert_equal "12345 Street", addy.street assert_equal "Australia", addy.country - assert addy.update_attributes(:street => '54321 Street', :country => 'USA') + assert addy.update_attributes(street: "54321 Street", country: "USA") assert_equal "54321 Street", addy.street assert_equal "USA", addy.country end def test_update_attributes_as_strings - addy = StreetAddress.first(:params => {:person_id => 1}) + addy = StreetAddress.first(params: { person_id: 1 }) addy.expects(:save).returns(true) assert_equal "12345 Street", addy.street assert_equal "Australia", addy.country - assert addy.update_attributes('street' => '54321 Street', 'country' => 'USA') + assert addy.update_attributes("street" => "54321 Street", "country" => "USA") assert_equal "54321 Street", addy.street assert_equal "USA", addy.country end @@ -1126,11 +1128,11 @@ def test_destroy end def test_destroy_with_custom_prefix - assert StreetAddress.find(1, :params => { :person_id => 1 }).destroy + assert StreetAddress.find(1, params: { person_id: 1 }).destroy ActiveResource::HttpMock.respond_to do |mock| mock.get "/people/1/addresses/1.json", {}, nil, 404 end - assert_raise(ActiveResource::ResourceNotFound) { StreetAddress.find(1, :params => { :person_id => 1 }) } + assert_raise(ActiveResource::ResourceNotFound) { StreetAddress.find(1, params: { person_id: 1 }) } end def test_destroy_with_410_gone @@ -1150,11 +1152,11 @@ def test_delete end def test_delete_with_custom_prefix - assert StreetAddress.delete(1, :person_id => 1) + assert StreetAddress.delete(1, person_id: 1) ActiveResource::HttpMock.respond_to do |mock| mock.get "/people/1/addresses/1.json", {}, nil, 404 end - assert_raise(ActiveResource::ResourceNotFound) { StreetAddress.find(1, :params => { :person_id => 1 }) } + assert_raise(ActiveResource::ResourceNotFound) { StreetAddress.find(1, params: { person_id: 1 }) } end def test_delete_with_410_gone @@ -1166,14 +1168,14 @@ def test_delete_with_410_gone end def test_delete_with_custom_header - Person.headers['key'] = 'value' + Person.headers["key"] = "value" ActiveResource::HttpMock.respond_to do |mock| mock.delete "/people/1.json", {}, nil, 200 - mock.delete "/people/1.json", { 'key' => 'value' }, nil, 404 + mock.delete "/people/1.json", { "key" => "value" }, nil, 404 end assert_raise(ActiveResource::ResourceNotFound) { Person.delete(1) } ensure - Person.headers.delete('key') + Person.headers.delete("key") end ######################################################################## @@ -1181,24 +1183,24 @@ def test_delete_with_custom_header ######################################################################## def test_exists # Class method. - assert !Person.exists?(nil) + assert_not Person.exists?(nil) assert Person.exists?(1) - assert !Person.exists?(99) + assert_not Person.exists?(99) # Instance method. - assert !Person.new.exists? + assert_not Person.new.exists? assert Person.find(1).exists? - assert !Person.new(:id => 99).exists? + assert_not Person.new(id: 99).exists? # Nested class method. - assert StreetAddress.exists?(1, :params => { :person_id => 1 }) - assert !StreetAddress.exists?(1, :params => { :person_id => 2 }) - assert !StreetAddress.exists?(2, :params => { :person_id => 1 }) + assert StreetAddress.exists?(1, params: { person_id: 1 }) + assert_not StreetAddress.exists?(1, params: { person_id: 2 }) + assert_not StreetAddress.exists?(2, params: { person_id: 1 }) # Nested instance method. - assert StreetAddress.find(1, :params => { :person_id => 1 }).exists? - assert !StreetAddress.new({:id => 1, :person_id => 2}).exists? - assert !StreetAddress.new({:id => 2, :person_id => 1}).exists? + assert StreetAddress.find(1, params: { person_id: 1 }).exists? + assert_not StreetAddress.new(id: 1, person_id: 2).exists? + assert_not StreetAddress.new(id: 2, person_id: 1).exists? end def test_exists_with_redefined_to_param @@ -1210,16 +1212,16 @@ def to_param end # Class method. - assert Person.exists?('Greg') + assert Person.exists?("Greg") # Instance method. - assert Person.find('Greg').exists? + assert Person.find("Greg").exists? # Nested class method. - assert StreetAddress.exists?(1, :params => { :person_id => Person.find('Greg').to_param }) + assert StreetAddress.exists?(1, params: { person_id: Person.find("Greg").to_param }) # Nested instance method. - assert StreetAddress.find(1, :params => { :person_id => Person.find('Greg').to_param }).exists? + assert StreetAddress.find(1, params: { person_id: Person.find("Greg").to_param }).exists? ensure # revert back to original @@ -1235,7 +1237,7 @@ def test_exists_without_http_mock ActiveResource::Connection.any_instance.expects(:http).returns(http) http.expects(:request).returns(ActiveResource::Response.new("")) - assert Person.exists?('not-mocked') + assert Person.exists?("not-mocked") end def test_exists_with_410_gone @@ -1243,7 +1245,7 @@ def test_exists_with_410_gone mock.head "/people/1.json", {}, nil, 410 end - assert !Person.exists?(1) + assert_not Person.exists?(1) end def test_exists_with_204_no_content @@ -1258,18 +1260,18 @@ def test_read_attribute_for_serialization joe = Person.find(6) joe.singleton_class.class_eval do def non_attribute_field - 'foo' + "foo" end def id - 'bar' + "bar" end end assert_equal joe.read_attribute_for_serialization(:id), 6 - assert_equal joe.read_attribute_for_serialization(:name), 'Joe' + assert_equal joe.read_attribute_for_serialization(:name), "Joe" assert_equal joe.read_attribute_for_serialization(:likes_hats), true - assert_equal joe.read_attribute_for_serialization(:non_attribute_field), 'foo' + assert_equal joe.read_attribute_for_serialization(:non_attribute_field), "foo" end def test_to_xml @@ -1280,7 +1282,7 @@ def test_to_xml assert_equal encode, xml assert xml.include?('') - assert xml.include?('Matz') + assert xml.include?("Matz") assert xml.include?('1') ensure Person.format = :json @@ -1290,16 +1292,16 @@ 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' + Person.element_name = "ruby_creator" encode = matz.encode xml = matz.to_xml assert_equal encode, xml assert xml.include?('') - assert xml.include?('') - assert xml.include?('Matz') + assert xml.include?("") + assert xml.include?("Matz") assert xml.include?('1') - assert xml.include?('') + assert xml.include?("") ensure Person.format = :json Person.element_name = old_elem_name @@ -1308,7 +1310,7 @@ def test_to_xml_with_element_name def test_to_xml_with_private_method_name_as_attribute Person.format = :xml - customer = Customer.new(:foo => "foo") + customer = Customer.new(foo: "foo") customer.singleton_class.class_eval do def foo "bar" @@ -1316,7 +1318,7 @@ def foo private :foo end - assert !customer.to_xml.include?("bar") + assert_not customer.to_xml.include?("bar") assert customer.to_xml.include?("foo") ensure Person.format = :json @@ -1351,7 +1353,7 @@ def test_to_json_without_root def test_to_json_with_element_name old_elem_name = Person.element_name joe = Person.find(6) - Person.element_name = 'ruby_creator' + Person.element_name = "ruby_creator" encode = joe.encode json = joe.to_json @@ -1368,7 +1370,7 @@ def test_to_param_quacks_like_active_record new_person = Person.new assert_nil new_person.to_param matz = Person.find(1) - assert_equal '1', matz.to_param + assert_equal "1", matz.to_param end def test_to_key_quacks_like_active_record @@ -1395,24 +1397,24 @@ def test_parse_deep_nested_resources def test_persisted_nested_resources_from_response luis = Customer.find(1) luis.friends.each do |friend| - assert !friend.new? + assert_not friend.new? friend.brothers.each do |brother| - assert !brother.new? + assert_not brother.new? brother.children.each do |child| - assert !child.new? + assert_not child.new? end end end end def test_parse_resource_with_given_has_one_resources - Customer.send(:has_one, :mother, :class_name => "external/person") + Customer.send(:has_one, :mother, class_name: "external/person") luis = Customer.find(1) assert_kind_of External::Person, luis.mother end def test_parse_resources_with_given_has_many_resources - Customer.send(:has_many, :enemies, :class_name => "external/person") + Customer.send(:has_many, :enemies, class_name: "external/person") luis = Customer.find(1) luis.enemies.each do |enemy| assert_kind_of External::Person, enemy @@ -1430,23 +1432,23 @@ def test_parse_resources_with_has_many_makes_get_request_on_nested_route def test_parse_resource_with_has_one_makes_get_request_on_child_route Product.send(:has_one, :inventory) product = Product.find(1) - assert product.inventory.status == ActiveSupport::JSON.decode(@inventory)['status'] + assert product.inventory.status == ActiveSupport::JSON.decode(@inventory)["status"] end def test_parse_non_singleton_resource_with_has_one_makes_get_request_on_child_route - accepts = { 'Accept' => 'application/json' } + accepts = { "Accept" => "application/json" } ActiveResource::HttpMock.respond_to do |mock| - mock.get '/posts/1.json', accepts, @post - mock.get '/posts/1/author.json', accepts, @matz + mock.get "/posts/1.json", accepts, @post + mock.get "/posts/1/author.json", accepts, @matz end - Post.send(:has_one, :author, class_name: 'Person') + Post.send(:has_one, :author, class_name: "Person") post = Post.find(1) - assert post.author.name == ActiveSupport::JSON.decode(@matz)['person']['name'] + assert post.author.name == ActiveSupport::JSON.decode(@matz)["person"]["name"] 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 @@ -1460,30 +1462,30 @@ def test_with_custom_formatter end def test_create_with_custom_primary_key - silver_plan = { :plan => { :code => "silver", :price => 5.00 } }.to_json + silver_plan = { plan: { code: "silver", price: 5.00 } }.to_json ActiveResource::HttpMock.respond_to do |mock| - mock.post "/plans.json", {}, silver_plan, 201, 'Location' => '/plans/silver.json' + mock.post "/plans.json", {}, silver_plan, 201, "Location" => "/plans/silver.json" end - plan = SubscriptionPlan.new(:code => "silver", :price => 5.00) + plan = SubscriptionPlan.new(code: "silver", price: 5.00) assert plan.new? plan.save! - assert !plan.new? + assert_not plan.new? end def test_update_with_custom_primary_key - silver_plan = { :plan => { :code => "silver", :price => 5.00 } }.to_json - silver_plan_updated = { :plan => { :code => "silver", :price => 10.00 } }.to_json + 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.json", {}, silver_plan - mock.put "/plans/silver.json", {}, silver_plan_updated, 201, 'Location' => '/plans/silver.json' + mock.put "/plans/silver.json", {}, silver_plan_updated, 201, "Location" => "/plans/silver.json" end plan = SubscriptionPlan.find("silver") - assert !plan.new? + assert_not plan.new? assert_equal 5.00, plan.price # update price diff --git a/test/cases/callbacks_test.rb b/test/cases/callbacks_test.rb index a4393580d4..9c225e8bf3 100644 --- a/test/cases/callbacks_test.rb +++ b/test/cases/callbacks_test.rb @@ -1,8 +1,10 @@ -require 'abstract_unit' -require 'active_support/core_ext/hash/conversions' +# frozen_string_literal: true + +require "abstract_unit" +require "active_support/core_ext/hash/conversions" class Developer < ActiveResource::Base - self.site = 'http://37s.sunrise.i:3000' + self.site = "http://37s.sunrise.i:3000" class << self def callback_string(callback_method) @@ -47,13 +49,13 @@ def history class CallbacksTest < ActiveSupport::TestCase def setup - @developer_attrs = {:id => 1, :name => "Guillermo", :salary => 100_000} - @developer = {"developer" => @developer_attrs}.to_json + @developer_attrs = { id: 1, name: "Guillermo", salary: 100_000 } + @developer = { "developer" => @developer_attrs }.to_json ActiveResource::HttpMock.respond_to do |mock| - mock.post '/developers.json', {}, @developer, 201, 'Location' => '/developers/1.json' - mock.get '/developers/1.json', {}, @developer - mock.put '/developers/1.json', {}, nil, 204 - mock.delete '/developers/1.json', {}, nil, 200 + mock.post "/developers.json", {}, @developer, 201, "Location" => "/developers/1.json" + mock.get "/developers/1.json", {}, @developer + mock.put "/developers/1.json", {}, nil, 204 + mock.delete "/developers/1.json", {}, nil, 200 end end diff --git a/test/cases/collection_test.rb b/test/cases/collection_test.rb index 9722375626..d89a16ef08 100644 --- a/test/cases/collection_test.rb +++ b/test/cases/collection_test.rb @@ -1,9 +1,11 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" class CollectionTest < ActiveSupport::TestCase def setup @collection = ActiveResource::Collection.new - end + end end class BasicCollectionTest < CollectionTest @@ -30,14 +32,14 @@ def test_first_or_create_without_resource_class_raises_error def test_first_or_initialize_without_resource_class_raises_error assert_raise(RuntimeError) { @collection.first_or_initialize } end - + def test_collect_bang_modifies_elements elements = %w(a b c) @collection.elements = elements results = @collection.collect! { |i| i + "!" } assert_equal results.to_a, elements.collect! { |i| i + "!" } end - + def test_collect_bang_returns_collection @collection.elements = %w(a) results = @collection.collect! { |i| i + "!" } @@ -47,77 +49,75 @@ def test_collect_bang_returns_collection def respond_to_where assert @collection.respond_to?(:where) end - end class PaginatedCollection < ActiveResource::Collection attr_accessor :next_page def initialize(parsed = {}) - @elements = parsed['results'] - @next_page = parsed['next_page'] + @elements = parsed["results"] + @next_page = parsed["next_page"] end end class PaginatedPost < ActiveResource::Base - self.site = 'http://37s.sunrise.i:3000' - self.collection_parser = 'PaginatedCollection' + self.site = "http://37s.sunrise.i:3000" + self.collection_parser = "PaginatedCollection" end class ReduxCollection < ActiveResource::Base - self.site = 'http://37s.sunrise.i:3000' + self.site = "http://37s.sunrise.i:3000" self.collection_parser = PaginatedCollection end class CollectionInheretanceTest < ActiveSupport::TestCase def setup - @post = {:id => 1, :title => "Awesome"} - @posts_hash = {"results" => [@post], :next_page => '/paginated_posts.json?page=2'} + @post = { id: 1, title: "Awesome" } + @posts_hash = { "results" => [@post], :next_page => "/paginated_posts.json?page=2" } @posts = @posts_hash.to_json - @posts2 = {"results" => [@post.merge({:id => 2})], :next_page => nil}.to_json + @posts2 = { "results" => [@post.merge(id: 2)], :next_page => nil }.to_json @empty_posts = { "results" => [], :next_page => nil }.to_json - @new_post = { :id => nil, :title => nil }.to_json + @new_post = { id: nil, title: nil }.to_json ActiveResource::HttpMock.respond_to do |mock| - mock.get '/paginated_posts.json', {}, @posts - mock.get '/paginated_posts/new.json', {}, @new_post - mock.get '/paginated_posts.json?page=2', {}, @posts - mock.get '/paginated_posts.json?title=test', {}, @empty_posts - mock.get '/paginated_posts.json?page=2&title=Awesome', {}, @posts - mock.post '/paginated_posts.json', {}, nil + mock.get "/paginated_posts.json", {}, @posts + mock.get "/paginated_posts/new.json", {}, @new_post + mock.get "/paginated_posts.json?page=2", {}, @posts + mock.get "/paginated_posts.json?title=test", {}, @empty_posts + mock.get "/paginated_posts.json?page=2&title=Awesome", {}, @posts + mock.post "/paginated_posts.json", {}, nil end end - + def test_setting_collection_parser assert_kind_of PaginatedCollection, PaginatedPost.find(:all) end def test_setting_collection_parser_resource_class - assert_equal PaginatedPost, PaginatedPost.where(:page => 2).resource_class + assert_equal PaginatedPost, PaginatedPost.where(page: 2).resource_class end def test_setting_collection_parser_original_params - assert_equal({:page => 2}, PaginatedPost.where(:page => 2).original_params) + assert_equal({ page: 2 }, PaginatedPost.where(page: 2).original_params) end - + def test_custom_accessor assert_equal PaginatedPost.find(:all).next_page, @posts_hash[:next_page] end def test_first_or_create - post = PaginatedPost.where(:title => 'test').first_or_create + post = PaginatedPost.where(title: "test").first_or_create assert post.valid? end def test_first_or_initialize - post = PaginatedPost.where(:title => 'test').first_or_initialize + post = PaginatedPost.where(title: "test").first_or_initialize assert post.valid? end def test_where - posts = PaginatedPost.where(:page => 2) - next_posts = posts.where(:title => 'Awesome') + posts = PaginatedPost.where(page: 2) + next_posts = posts.where(title: "Awesome") assert_kind_of PaginatedCollection, next_posts end - end diff --git a/test/cases/connection_test.rb b/test/cases/connection_test.rb index 57d6c497b4..bd6766de78 100644 --- a/test/cases/connection_test.rb +++ b/test/cases/connection_test.rb @@ -1,21 +1,23 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" class ConnectionTest < ActiveSupport::TestCase ResponseCodeStub = Struct.new(:code) RedirectResponseStub = Struct.new(:code, :Location) def setup - @conn = ActiveResource::Connection.new('http://localhost') - 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 + @conn = ActiveResource::Connection.new("http://localhost") + 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 + @header = { "key" => "value" }.freeze - @default_request_headers = { 'Content-Type' => 'application/json' } + @default_request_headers = { "Content-Type" => "application/json" } ActiveResource::HttpMock.respond_to do |mock| mock.get "/people/2.json", @header, @david mock.get "/people.json", {}, @people @@ -26,8 +28,8 @@ def setup 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.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 @@ -37,7 +39,7 @@ def test_same_logger_as_base ActiveResource::Base.logger = original_logger = Object.new old_site = ActiveResource::Base.site - ActiveResource::Base.site = 'http://localhost' + ActiveResource::Base.site = "http://localhost" assert_equal original_logger, ActiveResource::Base.connection.logger ActiveResource::Base.logger = Logger.new(STDOUT) @@ -106,7 +108,7 @@ def test_handle_response end end - ResponseHeaderStub = Struct.new(:code, :message, 'Allow') + ResponseHeaderStub = Struct.new(:code, :message, "Allow") def test_should_return_allowed_methods_for_method_no_allowed_exception begin handle_response ResponseHeaderStub.new(405, "HTTP Failed...", "GET, POST") @@ -228,14 +230,14 @@ def test_delete_with_header end def test_timeout - @http = mock('new Net::HTTP') + @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.json') } + @http.expects(:get).raises(Timeout::Error, "execution expired") + assert_raise(ActiveResource::TimeoutError) { @conn.get("/people_timeout.json") } end def test_setting_timeout - http = Net::HTTP.new('') + http = Net::HTTP.new("") [10, 20].each do |timeout| @conn.timeout = timeout @@ -246,17 +248,17 @@ def test_setting_timeout end def test_accept_http_header - @http = mock('new Net::HTTP') + @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 { @conn.get(path, { 'Accept' => 'application/xhtml+xml' }) } + 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 { @conn.get(path, "Accept" => "application/xhtml+xml") } end def test_ssl_options_get_applied_to_http - http = Net::HTTP.new('') - @conn.site = 'https://secure' - @conn.ssl_options = { :verify_mode => OpenSSL::SSL::VERIFY_PEER } + http = Net::HTTP.new("") + @conn.site = "https://secure" + @conn.ssl_options = { verify_mode: OpenSSL::SSL::VERIFY_PEER } @conn.send(:configure_http, http) assert http.use_ssl? @@ -264,20 +266,20 @@ def test_ssl_options_get_applied_to_http end def test_ssl_options_get_applied_to_https_urls_without_explicitly_setting_ssl_options - http = Net::HTTP.new('') - @conn.site = 'https://secure' + http = Net::HTTP.new("") + @conn.site = "https://secure" assert @conn.send(:configure_http, http).use_ssl? end def test_ssl_error - http = Net::HTTP.new('') + 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.json') } + http.expects(:get).raises(OpenSSL::SSL::SSLError, "Expired certificate") + assert_raise(ActiveResource::SSLError) { @conn.get("/people/1.json") } end def test_auth_type_can_be_string - @conn.auth_type = 'digest' + @conn.auth_type = "digest" assert_equal(:digest, @conn.auth_type) end @@ -326,7 +328,7 @@ def keep_net_connection_status end def new_connection - ActiveResource::Connection.new('http://localhost') + ActiveResource::Connection.new("http://localhost") end protected @@ -338,7 +340,7 @@ def assert_response_raises(klass, code) def assert_redirect_raises(code) assert_raise(ActiveResource::Redirection, "Expected response code #{code} to raise ActiveResource::Redirection") do - handle_response RedirectResponseStub.new(code, 'http://example.com/') + handle_response RedirectResponseStub.new(code, "http://example.com/") end end diff --git a/test/cases/finder_test.rb b/test/cases/finder_test.rb index 63a979f8db..cc49cd4051 100644 --- a/test/cases/finder_test.rb +++ b/test/cases/finder_test.rb @@ -1,10 +1,12 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" require "fixtures/person" require "fixtures/customer" require "fixtures/street_address" require "fixtures/beast" require "fixtures/proxy" -require 'active_support/core_ext/hash/conversions' +require "active_support/core_ext/hash/conversions" class FinderTest < ActiveSupport::TestCase def setup @@ -19,9 +21,9 @@ def test_find_by_id end def test_find_by_id_with_custom_prefix - addy = StreetAddress.find(1, :params => { :person_id => 1 }) + addy = StreetAddress.find(1, params: { person_id: 1 }) assert_kind_of StreetAddress, addy - assert_equal '12345 Street', addy.street + assert_equal "12345 Street", addy.street end def test_find_all @@ -41,7 +43,7 @@ def test_all end def test_all_with_params - all = StreetAddress.all(:params => { :person_id => 1 }) + all = StreetAddress.all(params: { person_id: 1 }) assert_equal 1, all.size assert_kind_of StreetAddress, all.first end @@ -50,27 +52,27 @@ def test_where people = Person.where assert_equal 2, people.size assert_kind_of Person, people.first - assert_equal 'Matz', people.first.name - assert_equal 'David', people.last.name + assert_equal "Matz", people.first.name + assert_equal "David", people.last.name end def test_where_with_clauses - addresses = StreetAddress.where(:person_id => 1) + addresses = StreetAddress.where(person_id: 1) assert_equal 1, addresses.size assert_kind_of StreetAddress, addresses.first end def test_where_with_clause_in ActiveResource::HttpMock.respond_to { |m| m.get "/people.json?id%5B%5D=2", {}, @people_david } - people = Person.where(:id => [2]) + people = Person.where(id: [2]) assert_equal 1, people.size assert_kind_of Person, people.first - assert_equal 'David', people.first.name + assert_equal "David", people.first.name end def test_where_with_invalid_clauses error = assert_raise(ArgumentError) { Person.where(nil) } - assert_equal 'expected a clauses Hash, got nil', error.message + assert_equal "expected a clauses Hash, got nil", error.message end def test_find_first @@ -86,50 +88,50 @@ def test_first end def test_first_with_params - addy = StreetAddress.first(:params => { :person_id => 1 }) + addy = StreetAddress.first(params: { person_id: 1 }) assert_kind_of StreetAddress, addy - assert_equal '12345 Street', addy.street + assert_equal "12345 Street", addy.street end def test_find_last david = Person.find(:last) assert_kind_of Person, david - assert_equal 'David', david.name + assert_equal "David", david.name end def test_last david = Person.last assert_kind_of Person, david - assert_equal 'David', david.name + assert_equal "David", david.name end def test_last_with_params - addy = StreetAddress.last(:params => { :person_id => 1 }) + addy = StreetAddress.last(params: { person_id: 1 }) assert_kind_of StreetAddress, addy - assert_equal '12345 Street', addy.street + assert_equal "12345 Street", addy.street end def test_find_by_id_not_found assert_raise(ActiveResource::ResourceNotFound) { Person.find(99) } - assert_raise(ActiveResource::ResourceNotFound) { StreetAddress.find(99, :params => {:person_id => 1}) } + assert_raise(ActiveResource::ResourceNotFound) { StreetAddress.find(99, params: { person_id: 1 }) } end def test_find_all_sub_objects - all = StreetAddress.find(:all, :params => { :person_id => 1 }) + all = StreetAddress.find(:all, params: { person_id: 1 }) assert_equal 1, all.size assert_kind_of StreetAddress, all.first end def test_find_all_sub_objects_not_found assert_nothing_raised do - StreetAddress.find(:all, :params => { :person_id => 2 }) + StreetAddress.find(:all, params: { person_id: 2 }) end end def test_find_all_by_from ActiveResource::HttpMock.respond_to { |m| m.get "/companies/1/people.json", {}, @people_david } - people = Person.find(:all, :from => "/companies/1/people.json") + people = Person.find(:all, from: "/companies/1/people.json") assert_equal 1, people.size assert_equal "David", people.first.name end @@ -137,7 +139,7 @@ def test_find_all_by_from def test_find_all_by_from_with_options ActiveResource::HttpMock.respond_to { |m| m.get "/companies/1/people.json", {}, @people_david } - people = Person.find(:all, :from => "/companies/1/people.json") + people = Person.find(:all, from: "/companies/1/people.json") assert_equal 1, people.size assert_equal "David", people.first.name end @@ -145,7 +147,7 @@ def test_find_all_by_from_with_options def test_find_all_by_symbol_from ActiveResource::HttpMock.respond_to { |m| m.get "/people/managers.json", {}, @people_david } - people = Person.find(:all, :from => :managers) + people = Person.find(:all, from: :managers) assert_equal 1, people.size assert_equal "David", people.first.name end @@ -160,14 +162,14 @@ def test_find_first_or_last_not_found def test_find_single_by_from ActiveResource::HttpMock.respond_to { |m| m.get "/companies/1/manager.json", {}, @david } - david = Person.find(:one, :from => "/companies/1/manager.json") + 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.json", {}, @david } - david = Person.find(:one, :from => :leader) + david = Person.find(:one, from: :leader) assert_equal "David", david.name end end diff --git a/test/cases/format_test.rb b/test/cases/format_test.rb index 86f610ac8f..744ad170ac 100644 --- a/test/cases/format_test.rb +++ b/test/cases/format_test.rb @@ -1,11 +1,13 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" require "fixtures/person" require "fixtures/street_address" class FormatTest < ActiveSupport::TestCase def setup - @matz = { :id => 1, :name => 'Matz' } - @david = { :id => 2, :name => 'David' } + @matz = { id: 1, name: "Matz" } + @david = { id: 2, name: "David" } @programmers = [ @matz, @david ] end @@ -13,19 +15,19 @@ def setup def test_http_format_header_name [:get, :head].each do |verb| header_name = ActiveResource::Connection::HTTP_FORMAT_HEADER_NAMES[verb] - assert_equal 'Accept', header_name + assert_equal "Accept", header_name end [:patch, :put, :post].each do |verb| header_name = ActiveResource::Connection::HTTP_FORMAT_HEADER_NAMES[verb] - assert_equal 'Content-Type', header_name + assert_equal "Content-Type", header_name end end def test_formats_on_single_element [ :json, :xml ].each do |format| using_format(Person, format) do - ActiveResource::HttpMock.respond_to.get "/people/1.#{format}", {'Accept' => ActiveResource::Formats[format].mime_type}, ActiveResource::Formats[format].encode(@david) + ActiveResource::HttpMock.respond_to.get "/people/1.#{format}", { "Accept" => ActiveResource::Formats[format].mime_type }, ActiveResource::Formats[format].encode(@david) assert_equal @david[:name], Person.find(1).name end end @@ -34,10 +36,10 @@ def test_formats_on_single_element def test_formats_on_collection [ :json, :xml ].each do |format| using_format(Person, format) do - ActiveResource::HttpMock.respond_to.get "/people.#{format}", {'Accept' => ActiveResource::Formats[format].mime_type}, ActiveResource::Formats[format].encode(@programmers) + ActiveResource::HttpMock.respond_to.get "/people.#{format}", { "Accept" => ActiveResource::Formats[format].mime_type }, ActiveResource::Formats[format].encode(@programmers) remote_programmers = Person.find(:all) assert_equal 2, remote_programmers.size - assert remote_programmers.find { |p| p.name == 'David' } + assert remote_programmers.find { |p| p.name == "David" } end end end @@ -45,11 +47,11 @@ def test_formats_on_collection def test_formats_on_custom_collection_method [ :json, :xml ].each do |format| using_format(Person, format) do - ActiveResource::HttpMock.respond_to.get "/people/retrieve.#{format}?name=David", {'Accept' => ActiveResource::Formats[format].mime_type}, ActiveResource::Formats[format].encode([@david]) - remote_programmers = Person.get(:retrieve, :name => 'David') + ActiveResource::HttpMock.respond_to.get "/people/retrieve.#{format}?name=David", { "Accept" => ActiveResource::Formats[format].mime_type }, ActiveResource::Formats[format].encode([@david]) + remote_programmers = Person.get(:retrieve, name: "David") assert_equal 1, remote_programmers.size - assert_equal @david[:id], remote_programmers[0]['id'] - assert_equal @david[:name], remote_programmers[0]['name'] + assert_equal @david[:id], remote_programmers[0]["id"] + assert_equal @david[:name], remote_programmers[0]["name"] end end end @@ -57,28 +59,28 @@ def test_formats_on_custom_collection_method def test_formats_on_custom_element_method [:json, :xml].each do |format| using_format(Person, format) do - david = (format == :json ? { :person => @david } : @david) + 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'] + assert_equal @david[:id], remote_programmer["id"] + assert_equal @david[:name], remote_programmer["name"] end - ryan_hash = { :name => 'Ryan' } - ryan_hash = (format == :json ? { :person => ryan_hash } : ryan_hash) + 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}" } + 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}" 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) + 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) end end end @@ -86,29 +88,29 @@ def test_formats_on_custom_element_method def test_setting_format_before_site resource = Class.new(ActiveResource::Base) resource.format = :json - resource.site = 'http://37s.sunrise.i:3000' + resource.site = "http://37s.sunrise.i:3000" assert_equal ActiveResource::Formats[:json], resource.connection.format end def test_serialization_of_nested_resource - address = { :street => '12345 Street' } - person = { :name => 'Rus', :address => address} + address = { street: "12345 Street" } + person = { name: "Rus", address: address } [:json, :xml].each do |format| encoded_person = ActiveResource::Formats[format].encode(person) assert_match(/12345 Street/, encoded_person) - remote_person = Person.new(person.update({:address => StreetAddress.new(address)})) + remote_person = Person.new(person.update(address: StreetAddress.new(address))) assert_kind_of StreetAddress, remote_person.address using_format(Person, format) do - ActiveResource::HttpMock.respond_to.post "/people.#{format}", {'Content-Type' => ActiveResource::Formats[format].mime_type}, encoded_person, 201, {'Location' => "/people/5.#{format}"} + ActiveResource::HttpMock.respond_to.post "/people.#{format}", { "Content-Type" => ActiveResource::Formats[format].mime_type }, encoded_person, 201, "Location" => "/people/5.#{format}" remote_person.save end end end def test_removing_root - matz = { :name => 'Matz' } - matz_with_root = { :person => matz } + matz = { name: "Matz" } + matz_with_root = { person: matz } # On Array people = [ matz ] diff --git a/test/cases/http_mock_test.rb b/test/cases/http_mock_test.rb index d13d9258ce..4f2b5a7561 100644 --- a/test/cases/http_mock_test.rb +++ b/test/cases/http_mock_test.rb @@ -1,5 +1,7 @@ -require 'abstract_unit' -require 'active_support/core_ext/object/inclusion' +# frozen_string_literal: true + +require "abstract_unit" +require "active_support/core_ext/object/inclusion" class HttpMockTest < ActiveSupport::TestCase setup do @@ -27,7 +29,7 @@ class HttpMockTest < ActiveSupport::TestCase test "respond only when headers match header by default to #{method} request" do ActiveResource::HttpMock.respond_to do |mock| - mock.send(method, "/people/1", {"X-Header" => "X"}, "Response") + mock.send(method, "/people/1", { "X-Header" => "X" }, "Response") end assert_equal "Response", request(method, "/people/1", "X-Header" => "X").body @@ -36,7 +38,7 @@ class HttpMockTest < ActiveSupport::TestCase test "does not overwrite format header to #{method} request" do ActiveResource::HttpMock.respond_to do |mock| - mock.send(method, "/people/1", {FORMAT_HEADER[method] => "application/json"}, "Response") + mock.send(method, "/people/1", { FORMAT_HEADER[method] => "application/json" }, "Response") end assert_equal "Response", request(method, "/people/1", FORMAT_HEADER[method] => "application/json").body @@ -70,18 +72,17 @@ class HttpMockTest < ActiveSupport::TestCase 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 = { :person => { :id => 1, :name => "Matz" } }.to_json + matz = { person: { id: 1, name: "Matz" } }.to_json - 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) + 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} + pairs = { create_matz => created_response, get_matz => ok_response } ActiveResource::HttpMock.respond_to(pairs) assert_equal 2, ActiveResource::HttpMock.responses.length @@ -107,10 +108,10 @@ class HttpMockTest < ActiveSupport::TestCase end assert_equal 1, ActiveResource::HttpMock.responses.length - matz = { :person => { :id => 1, :name => "Matz" } }.to_json - get_matz = ActiveResource::Request.new(:get, '/people/1.json', 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}) + ActiveResource::HttpMock.respond_to(get_matz => ok_response) assert_equal 1, ActiveResource::HttpMock.responses.length end @@ -133,10 +134,10 @@ class HttpMockTest < ActiveSupport::TestCase end assert_equal 1, ActiveResource::HttpMock.responses.length - matz = { :person => { :id => 1, :name => "Matz" } }.to_json - get_matz = ActiveResource::Request.new(:get, '/people/1.json', 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) + ActiveResource::HttpMock.respond_to({ get_matz => ok_response }, false) assert_equal 2, ActiveResource::HttpMock.responses.length end @@ -159,11 +160,11 @@ class HttpMockTest < ActiveSupport::TestCase end assert_equal 1, ActiveResource::HttpMock.responses.length - matz = { :person => { :id => 1, :name => "Matz" } }.to_json - get_matz = ActiveResource::Request.new(:get, '/people/1', nil) + matz = { person: { id: 1, name: "Matz" } }.to_json + get_matz = ActiveResource::Request.new(:get, "/people/1", nil) ok_response = ActiveResource::Response.new(matz, 200, {}) - ActiveResource::HttpMock.respond_to({get_matz => ok_response}, false) + ActiveResource::HttpMock.respond_to({ get_matz => ok_response }, false) assert_equal 1, ActiveResource::HttpMock.responses.length end @@ -185,10 +186,10 @@ class HttpMockTest < ActiveSupport::TestCase end assert_equal 1, ActiveResource::HttpMock.responses.length - put_matz = ActiveResource::Request.new(:put, '/people/1', nil) + put_matz = ActiveResource::Request.new(:put, "/people/1", nil) ok_response = ActiveResource::Response.new("", 200, {}) - ActiveResource::HttpMock.respond_to({put_matz => ok_response}, false) + ActiveResource::HttpMock.respond_to({ put_matz => ok_response }, false) assert_equal 2, ActiveResource::HttpMock.responses.length end diff --git a/test/cases/log_subscriber_test.rb b/test/cases/log_subscriber_test.rb index 459bdcd903..162d040c66 100644 --- a/test/cases/log_subscriber_test.rb +++ b/test/cases/log_subscriber_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "abstract_unit" require "fixtures/person" require "active_support/log_subscriber/test_helper" @@ -10,7 +12,7 @@ class LogSubscriberTest < ActiveSupport::TestCase def setup super - @matz = { :person => { :id => 1, :name => 'Matz' } }.to_json + @matz = { person: { id: 1, name: "Matz" } }.to_json ActiveResource::HttpMock.respond_to do |mock| mock.get "/people/1.json", {}, @matz mock.get "/people/2.json", {}, nil, 404 @@ -37,7 +39,7 @@ def test_failure_error_log rescue wait assert_equal 2, @logger.logged(:error).size - assert_equal 'GET http://37s.sunrise.i:3000/people/2.json', @logger.logged(:error)[0] + assert_equal "GET http://37s.sunrise.i:3000/people/2.json", @logger.logged(:error)[0] assert_match(/\-\-\> 404 404 0/, @logger.logged(:error)[1]) end @@ -46,7 +48,7 @@ def test_server_error_log rescue wait assert_equal 2, @logger.logged(:error).size - assert_equal 'GET http://37s.sunrise.i:3000/people/3.json', @logger.logged(:error)[0] + assert_equal "GET http://37s.sunrise.i:3000/people/3.json", @logger.logged(:error)[0] assert_match(/\-\-\> 502 502 0/, @logger.logged(:error)[1]) end @@ -55,7 +57,7 @@ def test_connection_failure rescue wait assert_equal 2, @logger.logged(:error).size - assert_equal 'GET http://37s.sunrise.i:3000/people/99.json', @logger.logged(:error)[0] + assert_equal "GET http://37s.sunrise.i:3000/people/99.json", @logger.logged(:error)[0] assert_match(/\-\-\> 523 ActiveResource connection error 0/, @logger.logged(:error)[1]) end end diff --git a/test/cases/reflection_test.rb b/test/cases/reflection_test.rb index d0ff00d5f3..7ac913179d 100644 --- a/test/cases/reflection_test.rb +++ b/test/cases/reflection_test.rb @@ -1,12 +1,13 @@ -require 'abstract_unit' +# frozen_string_literal: true -require 'fixtures/person' -require 'fixtures/customer' +require "abstract_unit" +require "fixtures/person" +require "fixtures/customer" -class ReflectionTest < ActiveSupport::TestCase +class ReflectionTest < ActiveSupport::TestCase def test_correct_class_attributes object = ActiveResource::Reflection::AssociationReflection.new(:test, :people, {}) assert_equal :people, object.name @@ -20,38 +21,38 @@ def test_correct_class_name_matching_without_class_name end def test_correct_class_name_matching_as_string - object = ActiveResource::Reflection::AssociationReflection.new(:test, :people, {:class_name => 'Person'}) + object = ActiveResource::Reflection::AssociationReflection.new(:test, :people, class_name: "Person") assert_equal Person, object.klass end def test_correct_class_name_matching_as_symbol - object = ActiveResource::Reflection::AssociationReflection.new(:test, :people, {:class_name => :person}) + object = ActiveResource::Reflection::AssociationReflection.new(:test, :people, class_name: :person) assert_equal Person, object.klass end def test_correct_class_name_matching_as_class - object = ActiveResource::Reflection::AssociationReflection.new(:test, :people, {:class_name => Person}) + object = ActiveResource::Reflection::AssociationReflection.new(:test, :people, class_name: Person) assert_equal Person, object.klass end def test_correct_class_name_matching_as_string_with_namespace - object = ActiveResource::Reflection::AssociationReflection.new(:test, :people, {:class_name => 'external/person'}) + object = ActiveResource::Reflection::AssociationReflection.new(:test, :people, class_name: "external/person") assert_equal External::Person, object.klass end def test_correct_class_name_matching_as_plural_string_with_namespace - object = ActiveResource::Reflection::AssociationReflection.new(:test, :people, {:class_name => 'external/profile_data'}) + object = ActiveResource::Reflection::AssociationReflection.new(:test, :people, class_name: "external/profile_data") assert_equal External::ProfileData, object.klass end def test_foreign_key_method_with_no_foreign_key_option object = ActiveResource::Reflection::AssociationReflection.new(:test, :person, {}) - assert_equal 'person_id', object.foreign_key + assert_equal "person_id", object.foreign_key end def test_foreign_key_method_with_with_foreign_key_option - object = ActiveResource::Reflection::AssociationReflection.new(:test, :people, {:foreign_key => 'client_id'}) - assert_equal 'client_id', object.foreign_key + object = ActiveResource::Reflection::AssociationReflection.new(:test, :people, foreign_key: "client_id") + assert_equal "client_id", object.foreign_key end def test_creation_of_reflection @@ -61,5 +62,4 @@ def test_creation_of_reflection assert_equal 1, Person.reflections.count assert_equal Person, Person.reflections[:people].klass end - end diff --git a/test/cases/validations_test.rb b/test/cases/validations_test.rb index 9c8f6132e7..6a1aa6909a 100644 --- a/test/cases/validations_test.rb +++ b/test/cases/validations_test.rb @@ -1,23 +1,25 @@ -require 'abstract_unit' -require 'fixtures/project' -require 'active_support/core_ext/hash/conversions' +# frozen_string_literal: true + +require "abstract_unit" +require "fixtures/project" +require "active_support/core_ext/hash/conversions" # The validations are tested thoroughly under ActiveModel::Validations # This test case simply makes sure that they are all accessible by # Active Resource objects. class ValidationsTest < ActiveSupport::TestCase - VALID_PROJECT_HASH = { :name => "My Project", :description => "A project" } + VALID_PROJECT_HASH = { name: "My Project", description: "A project" } def setup @my_proj = { "person" => VALID_PROJECT_HASH }.to_json ActiveResource::HttpMock.respond_to do |mock| - mock.post "/projects.json", {}, @my_proj, 201, 'Location' => '/projects/5.json' + mock.post "/projects.json", {}, @my_proj, 201, "Location" => "/projects/5.json" end end def test_validates_presence_of - p = new_project(:name => nil) - assert !p.valid?, "should not be a valid record without name" - assert !p.save, "should not have saved an invalid record" + p = new_project(name: nil) + assert_not p.valid?, "should not be a valid record without name" + assert_not p.save, "should not have saved an invalid record" assert_equal ["can't be blank"], p.errors[:name], "should have an error on name" p.name = "something" @@ -26,42 +28,40 @@ def test_validates_presence_of end def test_fails_save! - p = new_project(:name => nil) + p = new_project(name: nil) assert_raise(ActiveResource::ResourceInvalid) { p.save! } end def test_save_without_validation - p = new_project(:name => nil) - assert !p.save - assert p.save(:validate => false) + p = new_project(name: nil) + assert_not p.save + assert p.save(validate: false) end def test_validate_callback # we have a callback ensuring the description is longer than three letters - p = new_project(:description => 'a') - assert !p.valid?, "should not be a valid record when it fails a validation callback" - assert !p.save, "should not have saved an invalid record" + p = new_project(description: "a") + assert_not p.valid?, "should not be a valid record when it fails a validation callback" + assert_not p.save, "should not have saved an invalid record" assert_equal ["must be greater than three letters long"], p.errors[:description], "should be an error on description" # should now allow this description - p.description = 'abcd' + p.description = "abcd" assert p.save, "should have saved after fixing the validation, but had: #{p.errors.inspect}" end def test_client_side_validation_maximum - project = Project.new(:description => '123456789012345') - assert ! project.valid? - assert_equal ['is too long (maximum is 10 characters)'], project.errors[:description] + project = Project.new(description: "123456789012345") + assert_not project.valid? + assert_equal ["is too long (maximum is 10 characters)"], project.errors[:description] end protected - # quickie helper to create a new project with all the required - # attributes. - # Pass in any params you specifically want to override - def new_project(opts = {}) - Project.new(VALID_PROJECT_HASH.merge(opts)) - end - + # quickie helper to create a new project with all the required + # attributes. + # Pass in any params you specifically want to override + def new_project(opts = {}) + Project.new(VALID_PROJECT_HASH.merge(opts)) + end end - diff --git a/test/fixtures/address.rb b/test/fixtures/address.rb index 7a73ecb52a..742a335600 100644 --- a/test/fixtures/address.rb +++ b/test/fixtures/address.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # turns everything into the same object class AddressXMLFormatter include ActiveResource::Formats::XmlFormat @@ -6,14 +8,13 @@ def decode(xml) data = ActiveResource::Formats::XmlFormat.decode(xml) # process address fields data.each do |address| - address['city_state'] = "#{address['city']}, #{address['state']}" + address["city_state"] = "#{address['city']}, #{address['state']}" end data end - end class AddressResource < ActiveResource::Base self.element_name = "address" self.format = AddressXMLFormatter.new -end \ No newline at end of file +end diff --git a/test/fixtures/beast.rb b/test/fixtures/beast.rb index e31ec58346..52a8ae34b8 100644 --- a/test/fixtures/beast.rb +++ b/test/fixtures/beast.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + class BeastResource < ActiveResource::Base - self.site = 'http://beast.caboo.se' - site.user = 'foo' - site.password = 'bar' + self.site = "http://beast.caboo.se" + site.user = "foo" + site.password = "bar" end class Forum < BeastResource @@ -10,5 +12,5 @@ class Forum < BeastResource end class Topic < BeastResource - self.site += '/forums/:forum_id' + self.site += "/forums/:forum_id" end diff --git a/test/fixtures/comment.rb b/test/fixtures/comment.rb index af5f8883e6..6b94449f0f 100644 --- a/test/fixtures/comment.rb +++ b/test/fixtures/comment.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class Comment < ActiveResource::Base self.site = "http://37s.sunrise.i:3000/posts/:post_id" end diff --git a/test/fixtures/customer.rb b/test/fixtures/customer.rb index 845d5d11cb..45534d5591 100644 --- a/test/fixtures/customer.rb +++ b/test/fixtures/customer.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class Customer < ActiveResource::Base self.site = "http://37s.sunrise.i:3000" end diff --git a/test/fixtures/inventory.rb b/test/fixtures/inventory.rb index 4df01f419d..0da20a32f3 100644 --- a/test/fixtures/inventory.rb +++ b/test/fixtures/inventory.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + class Inventory < ActiveResource::Base include ActiveResource::Singleton - self.site = 'http://37s.sunrise.i:3000' - self.prefix = '/products/:product_id/' + self.site = "http://37s.sunrise.i:3000" + self.prefix = "/products/:product_id/" schema do integer :total @@ -10,4 +12,3 @@ class Inventory < ActiveResource::Base string :status end end - diff --git a/test/fixtures/person.rb b/test/fixtures/person.rb index a082bc236f..ad0c20ada8 100644 --- a/test/fixtures/person.rb +++ b/test/fixtures/person.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class Person < ActiveResource::Base self.site = "http://37s.sunrise.i:3000" end @@ -11,4 +13,3 @@ class ProfileData < ActiveResource::Base self.site = "http://external.profile.data.nl" end end - diff --git a/test/fixtures/post.rb b/test/fixtures/post.rb index cfb99d9fce..bb60086150 100644 --- a/test/fixtures/post.rb +++ b/test/fixtures/post.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class Post < ActiveResource::Base self.site = "http://37s.sunrise.i:3000" end diff --git a/test/fixtures/product.rb b/test/fixtures/product.rb index 6784cfb52a..44fc0d50ac 100644 --- a/test/fixtures/product.rb +++ b/test/fixtures/product.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class Product < ActiveResource::Base - self.site = 'http://37s.sunrise.i:3000' + self.site = "http://37s.sunrise.i:3000" end diff --git a/test/fixtures/project.rb b/test/fixtures/project.rb index 53de666601..e9f41f0672 100644 --- a/test/fixtures/project.rb +++ b/test/fixtures/project.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # used to test validations class Project < ActiveResource::Base self.site = "http://37s.sunrise.i:3000" @@ -6,13 +8,12 @@ class Project < ActiveResource::Base string :name end - validates :name, :presence => true - validates :description, :presence => false, :length => {:maximum => 10} + validates :name, presence: true + validates :description, presence: false, length: { maximum: 10 } validate :description_greater_than_three_letters # to test the validate *callback* works def description_greater_than_three_letters - errors.add :description, 'must be greater than three letters long' if description.length < 3 unless description.blank? + errors.add :description, "must be greater than three letters long" if description.length < 3 unless description.blank? end end - diff --git a/test/fixtures/proxy.rb b/test/fixtures/proxy.rb index bb8e015df0..062a01a4cb 100644 --- a/test/fixtures/proxy.rb +++ b/test/fixtures/proxy.rb @@ -1,4 +1,6 @@ +# frozen_string_literal: true + class ProxyResource < ActiveResource::Base self.site = "http://localhost" self.proxy = "http://user:password@proxy.local:3000" -end \ No newline at end of file +end diff --git a/test/fixtures/sound.rb b/test/fixtures/sound.rb index d9d2b99fcd..0397465196 100644 --- a/test/fixtures/sound.rb +++ b/test/fixtures/sound.rb @@ -1,4 +1,6 @@ -module Asset +# frozen_string_literal: true + +module Asset class Sound < ActiveResource::Base self.site = "http://37s.sunrise.i:3000" end @@ -6,4 +8,4 @@ class Sound < ActiveResource::Base # to test namespacing in a module class Author -end \ No newline at end of file +end diff --git a/test/fixtures/street_address.rb b/test/fixtures/street_address.rb index 6a8adb98b5..55cb9139b5 100644 --- a/test/fixtures/street_address.rb +++ b/test/fixtures/street_address.rb @@ -1,4 +1,6 @@ +# frozen_string_literal: true + class StreetAddress < ActiveResource::Base self.site = "http://37s.sunrise.i:3000/people/:person_id" - self.element_name = 'address' + self.element_name = "address" end diff --git a/test/fixtures/subscription_plan.rb b/test/fixtures/subscription_plan.rb index e3c2dd9a74..5d2cebe8f7 100644 --- a/test/fixtures/subscription_plan.rb +++ b/test/fixtures/subscription_plan.rb @@ -1,5 +1,7 @@ +# frozen_string_literal: true + class SubscriptionPlan < ActiveResource::Base self.site = "http://37s.sunrise.i:3000" - self.element_name = 'plan' + self.element_name = "plan" self.primary_key = :code end diff --git a/test/fixtures/weather.rb b/test/fixtures/weather.rb index d0fc1c34e3..4785289879 100644 --- a/test/fixtures/weather.rb +++ b/test/fixtures/weather.rb @@ -1,6 +1,8 @@ +# frozen_string_literal: true + class Weather < ActiveResource::Base include ActiveResource::Singleton - self.site = 'http://37s.sunrise.i:3000' + self.site = "http://37s.sunrise.i:3000" schema do string :status @@ -10,8 +12,8 @@ class Weather < ActiveResource::Base class WeatherDashboard < ActiveResource::Base include ActiveResource::Singleton - self.site = 'http://37s.sunrise.i:3000' - self.singleton_name = 'dashboard' + self.site = "http://37s.sunrise.i:3000" + self.singleton_name = "dashboard" schema do string :status diff --git a/test/setter_trap.rb b/test/setter_trap.rb index 81a1ddb1c2..cccbf3c8a5 100644 --- a/test/setter_trap.rb +++ b/test/setter_trap.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class SetterTrap < ActiveSupport::ProxyObject class << self def rollback_sets(obj) diff --git a/test/singleton_test.rb b/test/singleton_test.rb index 1c75ffdb64..fd8a3bbaee 100644 --- a/test/singleton_test.rb +++ b/test/singleton_test.rb @@ -1,69 +1,71 @@ -require 'abstract_unit' -require 'fixtures/weather' -require 'fixtures/inventory' +# frozen_string_literal: true + +require "abstract_unit" +require "fixtures/weather" +require "fixtures/inventory" class SingletonTest < ActiveSupport::TestCase def setup_weather - weather = { :status => 'Sunny', :temperature => 67 } + weather = { status: "Sunny", temperature: 67 } ActiveResource::HttpMock.respond_to do |mock| - mock.get '/weather.json', {}, weather.to_json - mock.get '/weather.json?degrees=fahrenheit', {}, weather.merge(:temperature => 100).to_json - mock.post '/weather.json', {}, weather.to_json, 201, 'Location' => '/weather.json' - mock.delete '/weather.json', {}, nil - mock.put '/weather.json', {}, nil, 204 + mock.get "/weather.json", {}, weather.to_json + mock.get "/weather.json?degrees=fahrenheit", {}, weather.merge(temperature: 100).to_json + mock.post "/weather.json", {}, weather.to_json, 201, "Location" => "/weather.json" + mock.delete "/weather.json", {}, nil + mock.put "/weather.json", {}, nil, 204 end end def setup_weather_not_found ActiveResource::HttpMock.respond_to do |mock| - mock.get '/weather.json', {}, nil, 404 + mock.get "/weather.json", {}, nil, 404 end end def setup_inventory - inventory = {:status => 'Sold Out', :total => 10, :used => 10}.to_json + inventory = { status: "Sold Out", total: 10, used: 10 }.to_json ActiveResource::HttpMock.respond_to do |mock| - mock.get '/products/5/inventory.json', {}, inventory + mock.get "/products/5/inventory.json", {}, inventory end end def test_custom_singleton_name - assert_equal 'dashboard', WeatherDashboard.singleton_name + assert_equal "dashboard", WeatherDashboard.singleton_name end def test_singleton_path - assert_equal '/weather.json', Weather.singleton_path + assert_equal "/weather.json", Weather.singleton_path end def test_singleton_path_with_parameters - assert_equal '/weather.json?degrees=fahrenheit', Weather.singleton_path(:degrees => 'fahrenheit') - assert_equal '/weather.json?degrees=false', Weather.singleton_path(:degrees => false) - assert_equal '/weather.json?degrees=', Weather.singleton_path(:degrees => nil) + assert_equal "/weather.json?degrees=fahrenheit", Weather.singleton_path(degrees: "fahrenheit") + assert_equal "/weather.json?degrees=false", Weather.singleton_path(degrees: false) + assert_equal "/weather.json?degrees=", Weather.singleton_path(degrees: nil) - assert_equal '/weather.json?degrees=fahrenheit', Weather.singleton_path('degrees' => 'fahrenheit') + assert_equal "/weather.json?degrees=fahrenheit", Weather.singleton_path("degrees" => "fahrenheit") # Use include? because ordering of param hash is not guaranteed - path = Weather.singleton_path(:degrees => 'fahrenheit', :lunar => true) - assert path.include?('weather.json') - assert path.include?('degrees=fahrenheit') - assert path.include?('lunar=true') + path = Weather.singleton_path(degrees: "fahrenheit", lunar: true) + assert path.include?("weather.json") + assert path.include?("degrees=fahrenheit") + assert path.include?("lunar=true") - path = Weather.singleton_path(:days => ['monday', 'saturday and sunday', nil, false]) - assert_equal '/weather.json?days%5B%5D=monday&days%5B%5D=saturday+and+sunday&days%5B%5D=&days%5B%5D=false', path + path = Weather.singleton_path(days: ["monday", "saturday and sunday", nil, false]) + assert_equal "/weather.json?days%5B%5D=monday&days%5B%5D=saturday+and+sunday&days%5B%5D=&days%5B%5D=false", path - path = Inventory.singleton_path(:product_id => 5) - assert_equal '/products/5/inventory.json', path + path = Inventory.singleton_path(product_id: 5) + assert_equal "/products/5/inventory.json", path - path = Inventory.singleton_path({:product_id =>5}, {:sold => true}) - assert_equal '/products/5/inventory.json?sold=true', path + path = Inventory.singleton_path({ product_id: 5 }, { sold: true }) + assert_equal "/products/5/inventory.json?sold=true", path end def test_find_singleton setup_weather weather = Weather.send(:find_singleton, Hash.new) assert_not_nil weather - assert_equal 'Sunny', weather.status + assert_equal "Sunny", weather.status assert_equal 67, weather.temperature end @@ -71,27 +73,27 @@ def test_find setup_weather weather = Weather.find assert_not_nil weather - assert_equal 'Sunny', weather.status + assert_equal "Sunny", weather.status assert_equal 67, weather.temperature end def test_find_with_param_options setup_inventory - inventory = Inventory.find(:params => {:product_id => 5}) + inventory = Inventory.find(params: { product_id: 5 }) assert_not_nil inventory - assert_equal 'Sold Out', inventory.status + assert_equal "Sold Out", inventory.status assert_equal 10, inventory.used assert_equal 10, inventory.total - assert_equal({:product_id => 5}, inventory.prefix_options) + assert_equal({ product_id: 5 }, inventory.prefix_options) end def test_find_with_query_options setup_weather - weather = Weather.find(:params => {:degrees => 'fahrenheit'}) + weather = Weather.find(params: { degrees: "fahrenheit" }) assert_not_nil weather - assert_equal 'Sunny', weather.status + assert_equal "Sunny", weather.status assert_equal 100, weather.temperature end @@ -105,9 +107,9 @@ def test_not_found def test_create_singleton setup_weather - weather = Weather.create(:status => 'Sunny', :temperature => 67) + weather = Weather.create(status: "Sunny", temperature: 67) assert_not_nil weather - assert_equal 'Sunny', weather.status + assert_equal "Sunny", weather.status assert_equal 67, weather.temperature end @@ -115,7 +117,7 @@ def test_destroy setup_weather # First Create the Weather - weather = Weather.create(:status => 'Sunny', :temperature => 67) + weather = Weather.create(status: "Sunny", temperature: 67) assert_not_nil weather # Now Destroy it @@ -126,12 +128,11 @@ def test_update setup_weather # First Create the Weather - weather = Weather.create(:status => 'Sunny', :temperature => 67) + weather = Weather.create(status: "Sunny", temperature: 67) assert_not_nil weather # Then update it - weather.status = 'Rainy' + weather.status = "Rainy" weather.save end end - diff --git a/test/threadsafe_attributes_test.rb b/test/threadsafe_attributes_test.rb index e2459c78d0..9c69f36fbf 100644 --- a/test/threadsafe_attributes_test.rb +++ b/test/threadsafe_attributes_test.rb @@ -1,7 +1,8 @@ -require 'abstract_unit' +# frozen_string_literal: true -class ThreadsafeAttributesTest < ActiveSupport::TestCase +require "abstract_unit" +class ThreadsafeAttributesTest < ActiveSupport::TestCase class TestClass include ThreadsafeAttributes threadsafe_attribute :safeattr @@ -12,7 +13,7 @@ class TestClass end test "#threadsafe attributes work in a single thread" do - refute @tester.safeattr_defined? + assert_not @tester.safeattr_defined? assert_nil @tester.safeattr @tester.safeattr = "a value" assert @tester.safeattr_defined? @@ -47,7 +48,7 @@ class TestClass end test "#changing a threadsafe attribute in a thread sets an equal value for the main thread, if no value has been set" do - refute @tester.safeattr_defined? + assert_not @tester.safeattr_defined? assert_nil @tester.safeattr Thread.new do @tester.safeattr = "value from child" @@ -71,7 +72,7 @@ class TestClass end.resume end - unless RUBY_PLATFORM == 'java' + unless RUBY_PLATFORM == "java" test "threadsafe attributes can be accessed after forking within a thread" do reader, writer = IO.pipe @tester.safeattr = "a value"