diff options
Diffstat (limited to 'actionpack/test/controller/parameters')
-rw-r--r-- | actionpack/test/controller/parameters/accessors_test.rb | 96 | ||||
-rw-r--r-- | actionpack/test/controller/parameters/always_permitted_parameters_test.rb | 11 | ||||
-rw-r--r-- | actionpack/test/controller/parameters/dup_test.rb | 67 | ||||
-rw-r--r-- | actionpack/test/controller/parameters/log_on_unpermitted_params_test.rb | 56 | ||||
-rw-r--r-- | actionpack/test/controller/parameters/multi_parameter_attributes_test.rb | 11 | ||||
-rw-r--r-- | actionpack/test/controller/parameters/mutators_test.rb | 41 | ||||
-rw-r--r-- | actionpack/test/controller/parameters/nested_parameters_permit_test.rb (renamed from actionpack/test/controller/parameters/nested_parameters_test.rb) | 131 | ||||
-rw-r--r-- | actionpack/test/controller/parameters/parameters_permit_test.rb | 303 | ||||
-rw-r--r-- | actionpack/test/controller/parameters/raise_on_unpermitted_params_test.rb | 16 | ||||
-rw-r--r-- | actionpack/test/controller/parameters/serialization_test.rb | 55 |
10 files changed, 566 insertions, 221 deletions
diff --git a/actionpack/test/controller/parameters/accessors_test.rb b/actionpack/test/controller/parameters/accessors_test.rb index 17c62dc3fe..43cabae7d2 100644 --- a/actionpack/test/controller/parameters/accessors_test.rb +++ b/actionpack/test/controller/parameters/accessors_test.rb @@ -1,6 +1,8 @@ -require 'abstract_unit' -require 'action_controller/metal/strong_parameters' -require 'active_support/core_ext/hash/transform_values' +# frozen_string_literal: true + +require "abstract_unit" +require "action_controller/metal/strong_parameters" +require "active_support/core_ext/hash/transform_values" class ParametersAccessorsTest < ActiveSupport::TestCase setup do @@ -8,12 +10,12 @@ class ParametersAccessorsTest < ActiveSupport::TestCase @params = ActionController::Parameters.new( person: { - age: '32', + age: "32", name: { - first: 'David', - last: 'Heinemeier Hansson' + first: "David", + last: "Heinemeier Hansson" }, - addresses: [{city: 'Chicago', state: 'Illinois'}] + addresses: [{ city: "Chicago", state: "Illinois" }] } ) end @@ -35,6 +37,11 @@ class ParametersAccessorsTest < ActiveSupport::TestCase assert @params.as_json.key? "person" end + test "to_s returns the string representation of the parameters hash" do + assert_equal '{"person"=>{"age"=>"32", "name"=>{"first"=>"David", "last"=>"Heinemeier Hansson"}, ' \ + '"addresses"=>[{"city"=>"Chicago", "state"=>"Illinois"}]}}', @params.to_s + end + test "each carries permitted status" do @params.permit! @params.each { |key, value| assert(value.permitted?) if key == "person" } @@ -53,6 +60,15 @@ class ParametersAccessorsTest < ActiveSupport::TestCase @params.each_pair { |key, value| assert_not(value.permitted?) if key == "person" } end + test "empty? returns true when params contains no key/value pairs" do + params = ActionController::Parameters.new + assert params.empty? + end + + test "empty? returns false when any params are present" do + refute @params.empty? + end + test "except retains permitted status" do @params.permit! assert @params.except(:person).permitted? @@ -75,6 +91,45 @@ class ParametersAccessorsTest < ActiveSupport::TestCase assert_not @params[:person].fetch(:name).permitted? end + test "has_key? returns true if the given key is present in the params" do + assert @params.has_key?(:person) + end + + test "has_key? returns false if the given key is not present in the params" do + refute @params.has_key?(:address) + end + + test "has_value? returns true if the given value is present in the params" do + params = ActionController::Parameters.new(city: "Chicago", state: "Illinois") + assert params.has_value?("Chicago") + end + + test "has_value? returns false if the given value is not present in the params" do + params = ActionController::Parameters.new(city: "Chicago", state: "Illinois") + refute params.has_value?("New York") + end + + test "include? returns true if the given key is present in the params" do + assert @params.include?(:person) + end + + test "include? returns false if the given key is not present in the params" do + refute @params.include?(:address) + end + + test "key? returns true if the given key is present in the params" do + assert @params.key?(:person) + end + + test "key? returns false if the given key is not present in the params" do + refute @params.key?(:address) + end + + test "keys returns an array of the keys of the params" do + assert_equal ["person"], @params.keys + assert_equal ["age", "name", "addresses"], @params[:person].keys + end + test "reject retains permitted status" do assert_not @params.reject { |k| k == "person" }.permitted? end @@ -120,6 +175,21 @@ class ParametersAccessorsTest < ActiveSupport::TestCase assert_not @params.transform_values { |v| v }.permitted? end + test "value? returns true if the given value is present in the params" do + params = ActionController::Parameters.new(city: "Chicago", state: "Illinois") + assert params.value?("Chicago") + end + + test "value? returns false if the given value is not present in the params" do + params = ActionController::Parameters.new(city: "Chicago", state: "Illinois") + refute params.value?("New York") + end + + test "values returns an array of the values of the params" do + params = ActionController::Parameters.new(city: "Chicago", state: "Illinois") + assert_equal ["Chicago", "Illinois"], params.values + end + test "values_at retains permitted status" do @params.permit! assert @params.values_at(:person).first.permitted? @@ -131,14 +201,6 @@ class ParametersAccessorsTest < ActiveSupport::TestCase assert_not @params[:person].values_at(:name).first.permitted? end - test "equality with a hash is deprecated" do - hash1 = { foo: :bar } - params1 = ActionController::Parameters.new(hash1) - assert_deprecated("will be removed in Rails 5.1") do - assert(params1 == hash1) - end - end - test "is equal to Parameters instance with same params" do params1 = ActionController::Parameters.new(a: 1, b: 2) params2 = ActionController::Parameters.new(a: 1, b: 2) @@ -158,7 +220,7 @@ class ParametersAccessorsTest < ActiveSupport::TestCase assert(params2 == params1) end - test 'is not equal to an unpermitted Parameters instance with same params' do + test "is not equal to an unpermitted Parameters instance with same params" do params1 = ActionController::Parameters.new(a: 1).permit(:a) params2 = ActionController::Parameters.new(a: 1) assert(params1 != params2) @@ -173,7 +235,7 @@ class ParametersAccessorsTest < ActiveSupport::TestCase end test "equality with simple types works" do - assert(@params != 'Hello') + assert(@params != "Hello") assert(@params != 42) assert(@params != false) end diff --git a/actionpack/test/controller/parameters/always_permitted_parameters_test.rb b/actionpack/test/controller/parameters/always_permitted_parameters_test.rb index c5bfb10b53..1e8b71d789 100644 --- a/actionpack/test/controller/parameters/always_permitted_parameters_test.rb +++ b/actionpack/test/controller/parameters/always_permitted_parameters_test.rb @@ -1,5 +1,7 @@ -require 'abstract_unit' -require 'action_controller/metal/strong_parameters' +# frozen_string_literal: true + +require "abstract_unit" +require "action_controller/metal/strong_parameters" class AlwaysPermittedParametersTest < ActiveSupport::TestCase def setup @@ -19,10 +21,9 @@ class AlwaysPermittedParametersTest < ActiveSupport::TestCase end test "permits parameters that are whitelisted" do - params = ActionController::Parameters.new({ + params = ActionController::Parameters.new( book: { pages: 65 }, - format: "json" - }) + format: "json") permitted = params.permit book: [:pages] assert permitted.permitted? end diff --git a/actionpack/test/controller/parameters/dup_test.rb b/actionpack/test/controller/parameters/dup_test.rb new file mode 100644 index 0000000000..f5833aff46 --- /dev/null +++ b/actionpack/test/controller/parameters/dup_test.rb @@ -0,0 +1,67 @@ +# frozen_string_literal: true + +require "abstract_unit" +require "action_controller/metal/strong_parameters" +require "active_support/core_ext/object/deep_dup" + +class ParametersDupTest < ActiveSupport::TestCase + setup do + ActionController::Parameters.permit_all_parameters = false + + @params = ActionController::Parameters.new( + person: { + age: "32", + name: { + first: "David", + last: "Heinemeier Hansson" + }, + addresses: [{ city: "Chicago", state: "Illinois" }] + } + ) + end + + test "a duplicate maintains the original's permitted status" do + @params.permit! + dupped_params = @params.dup + assert dupped_params.permitted? + end + + test "a duplicate maintains the original's parameters" do + @params.permit! + dupped_params = @params.dup + assert_equal @params.to_h, dupped_params.to_h + end + + test "changes to a duplicate's parameters do not affect the original" do + dupped_params = @params.dup + dupped_params.delete(:person) + assert_not_equal @params, dupped_params + end + + test "changes to a duplicate's permitted status do not affect the original" do + dupped_params = @params.dup + dupped_params.permit! + assert_not_equal @params, dupped_params + end + + test "deep_dup content" do + dupped_params = @params.deep_dup + dupped_params[:person][:age] = "45" + dupped_params[:person][:addresses].clear + + assert_not_equal @params[:person][:age], dupped_params[:person][:age] + assert_not_equal @params[:person][:addresses], dupped_params[:person][:addresses] + end + + test "deep_dup @permitted" do + dupped_params = @params.deep_dup + dupped_params.permit! + + assert_not @params.permitted? + end + + test "deep_dup @permitted is being copied" do + @params.permit! + assert @params.deep_dup.permitted? + end +end diff --git a/actionpack/test/controller/parameters/log_on_unpermitted_params_test.rb b/actionpack/test/controller/parameters/log_on_unpermitted_params_test.rb index 9ce04b9aeb..fc9229ca1d 100644 --- a/actionpack/test/controller/parameters/log_on_unpermitted_params_test.rb +++ b/actionpack/test/controller/parameters/log_on_unpermitted_params_test.rb @@ -1,5 +1,7 @@ -require 'abstract_unit' -require 'action_controller/metal/strong_parameters' +# frozen_string_literal: true + +require "abstract_unit" +require "action_controller/metal/strong_parameters" class LogOnUnpermittedParamsTest < ActiveSupport::TestCase def setup @@ -11,62 +13,58 @@ class LogOnUnpermittedParamsTest < ActiveSupport::TestCase end test "logs on unexpected param" do - params = ActionController::Parameters.new({ + params = ActionController::Parameters.new( book: { pages: 65 }, - fishing: "Turnips" - }) + fishing: "Turnips") - assert_logged("Unpermitted parameter: fishing") do + assert_logged("Unpermitted parameter: :fishing") do params.permit(book: [:pages]) end end test "logs on unexpected params" do - params = ActionController::Parameters.new({ + params = ActionController::Parameters.new( book: { pages: 65 }, fishing: "Turnips", - car: "Mersedes" - }) + car: "Mersedes") - assert_logged("Unpermitted parameters: fishing, car") do + assert_logged("Unpermitted parameters: :fishing, :car") do params.permit(book: [:pages]) end end test "logs on unexpected nested param" do - params = ActionController::Parameters.new({ - book: { pages: 65, title: "Green Cats and where to find then." } - }) + params = ActionController::Parameters.new( + book: { pages: 65, title: "Green Cats and where to find then." }) - assert_logged("Unpermitted parameter: title") do + assert_logged("Unpermitted parameter: :title") do params.permit(book: [:pages]) end end test "logs on unexpected nested params" do - params = ActionController::Parameters.new({ - book: { pages: 65, title: "Green Cats and where to find then.", author: "G. A. Dog" } - }) + params = ActionController::Parameters.new( + book: { pages: 65, title: "Green Cats and where to find then.", author: "G. A. Dog" }) - assert_logged("Unpermitted parameters: title, author") do + assert_logged("Unpermitted parameters: :title, :author") do params.permit(book: [:pages]) end end private - def assert_logged(message) - old_logger = ActionController::Base.logger - log = StringIO.new - ActionController::Base.logger = Logger.new(log) + def assert_logged(message) + old_logger = ActionController::Base.logger + log = StringIO.new + ActionController::Base.logger = Logger.new(log) - begin - yield + begin + yield - log.rewind - assert_match message, log.read - ensure - ActionController::Base.logger = old_logger + log.rewind + assert_match message, log.read + ensure + ActionController::Base.logger = old_logger + end end - end end diff --git a/actionpack/test/controller/parameters/multi_parameter_attributes_test.rb b/actionpack/test/controller/parameters/multi_parameter_attributes_test.rb index 15338059bc..dcf848a620 100644 --- a/actionpack/test/controller/parameters/multi_parameter_attributes_test.rb +++ b/actionpack/test/controller/parameters/multi_parameter_attributes_test.rb @@ -1,9 +1,11 @@ -require 'abstract_unit' -require 'action_controller/metal/strong_parameters' +# frozen_string_literal: true + +require "abstract_unit" +require "action_controller/metal/strong_parameters" class MultiParameterAttributesTest < ActiveSupport::TestCase test "permitted multi-parameter attribute keys" do - params = ActionController::Parameters.new({ + params = ActionController::Parameters.new( book: { "shipped_at(1i)" => "2012", "shipped_at(2i)" => "3", @@ -15,8 +17,7 @@ class MultiParameterAttributesTest < ActiveSupport::TestCase "published_at(3i)" => "5", "price(1)" => "R$", "price(2f)" => "2.02" - } - }) + }) permitted = params.permit book: [ :shipped_at, :price ] diff --git a/actionpack/test/controller/parameters/mutators_test.rb b/actionpack/test/controller/parameters/mutators_test.rb index 744d8664be..49dede03c2 100644 --- a/actionpack/test/controller/parameters/mutators_test.rb +++ b/actionpack/test/controller/parameters/mutators_test.rb @@ -1,17 +1,19 @@ -require 'abstract_unit' -require 'action_controller/metal/strong_parameters' -require 'active_support/core_ext/hash/transform_values' +# frozen_string_literal: true + +require "abstract_unit" +require "action_controller/metal/strong_parameters" +require "active_support/core_ext/hash/transform_values" class ParametersMutatorsTest < ActiveSupport::TestCase setup do @params = ActionController::Parameters.new( person: { - age: '32', + age: "32", name: { - first: 'David', - last: 'Heinemeier Hansson' + first: "David", + last: "Heinemeier Hansson" }, - addresses: [{city: 'Chicago', state: 'Illinois'}] + addresses: [{ city: "Chicago", state: "Illinois" }] } ) end @@ -25,6 +27,27 @@ class ParametersMutatorsTest < ActiveSupport::TestCase assert_not @params.delete(:person).permitted? end + test "delete returns the value when the key is present" do + assert_equal "32", @params[:person].delete(:age) + end + + test "delete removes the entry when the key present" do + @params[:person].delete(:age) + assert_not @params[:person].key?(:age) + end + + test "delete returns nil when the key is not present" do + assert_nil @params[:person].delete(:first_name) + end + + test "delete returns the value of the given block when the key is not present" do + assert_equal "David", @params[:person].delete(:first_name) { "David" } + end + + test "delete yields the key to the given block when the key is not present" do + assert_equal "first_name: David", @params[:person].delete(:first_name) { |k| "#{k}: David" } + end + test "delete_if retains permitted status" do @params.permit! assert @params.delete_if { |k| k == "person" }.permitted? @@ -45,11 +68,11 @@ class ParametersMutatorsTest < ActiveSupport::TestCase test "keep_if retains permitted status" do @params.permit! - assert @params.keep_if { |k,v| k == "person" }.permitted? + assert @params.keep_if { |k, v| k == "person" }.permitted? end test "keep_if retains unpermitted status" do - assert_not @params.keep_if { |k,v| k == "person" }.permitted? + assert_not @params.keep_if { |k, v| k == "person" }.permitted? end test "reject! retains permitted status" do diff --git a/actionpack/test/controller/parameters/nested_parameters_test.rb b/actionpack/test/controller/parameters/nested_parameters_permit_test.rb index 7151a8567c..c9fcc483ee 100644 --- a/actionpack/test/controller/parameters/nested_parameters_test.rb +++ b/actionpack/test/controller/parameters/nested_parameters_permit_test.rb @@ -1,13 +1,15 @@ -require 'abstract_unit' -require 'action_controller/metal/strong_parameters' +# frozen_string_literal: true -class NestedParametersTest < ActiveSupport::TestCase +require "abstract_unit" +require "action_controller/metal/strong_parameters" + +class NestedParametersPermitTest < ActiveSupport::TestCase def assert_filtered_out(params, key) assert !params.has_key?(key), "key #{key.inspect} has not been filtered out" end test "permitted nested parameters" do - params = ActionController::Parameters.new({ + params = ActionController::Parameters.new( book: { title: "Romeo and Juliet", authors: [{ @@ -23,11 +25,10 @@ class NestedParametersTest < ActiveSupport::TestCase genre: "Tragedy" }, id: { - isbn: 'x' + isbn: "x" } }, - magazine: "Mjallo!" - }) + magazine: "Mjallo!") permitted = params.permit book: [ :title, { authors: [ :name ] }, { details: :pages }, :id ] @@ -45,74 +46,69 @@ class NestedParametersTest < ActiveSupport::TestCase end test "permitted nested parameters with a string or a symbol as a key" do - params = ActionController::Parameters.new({ + params = ActionController::Parameters.new( book: { - 'authors' => [ - { name: 'William Shakespeare', born: '1564-04-26' }, - { name: 'Christopher Marlowe' } + "authors" => [ + { name: "William Shakespeare", born: "1564-04-26" }, + { name: "Christopher Marlowe" } ] - } - }) + }) - permitted = params.permit book: [ { 'authors' => [ :name ] } ] + permitted = params.permit book: [ { "authors" => [ :name ] } ] - assert_equal 'William Shakespeare', permitted[:book]['authors'][0][:name] - assert_equal 'William Shakespeare', permitted[:book][:authors][0][:name] - assert_equal 'Christopher Marlowe', permitted[:book]['authors'][1][:name] - assert_equal 'Christopher Marlowe', permitted[:book][:authors][1][:name] + assert_equal "William Shakespeare", permitted[:book]["authors"][0][:name] + assert_equal "William Shakespeare", permitted[:book][:authors][0][:name] + assert_equal "Christopher Marlowe", permitted[:book]["authors"][1][:name] + assert_equal "Christopher Marlowe", permitted[:book][:authors][1][:name] permitted = params.permit book: [ { authors: [ :name ] } ] - assert_equal 'William Shakespeare', permitted[:book]['authors'][0][:name] - assert_equal 'William Shakespeare', permitted[:book][:authors][0][:name] - assert_equal 'Christopher Marlowe', permitted[:book]['authors'][1][:name] - assert_equal 'Christopher Marlowe', permitted[:book][:authors][1][:name] + assert_equal "William Shakespeare", permitted[:book]["authors"][0][:name] + assert_equal "William Shakespeare", permitted[:book][:authors][0][:name] + assert_equal "Christopher Marlowe", permitted[:book]["authors"][1][:name] + assert_equal "Christopher Marlowe", permitted[:book][:authors][1][:name] end test "nested arrays with strings" do - params = ActionController::Parameters.new({ + params = ActionController::Parameters.new( book: { genres: ["Tragedy"] - } - }) + }) - permitted = params.permit book: {genres: []} + permitted = params.permit book: { genres: [] } assert_equal ["Tragedy"], permitted[:book][:genres] end test "permit may specify symbols or strings" do - params = ActionController::Parameters.new({ + params = ActionController::Parameters.new( book: { title: "Romeo and Juliet", author: "William Shakespeare" }, - magazine: "Shakespeare Today" - }) + magazine: "Shakespeare Today") - permitted = params.permit({book: ["title", :author]}, "magazine") + permitted = params.permit({ book: ["title", :author] }, "magazine") assert_equal "Romeo and Juliet", permitted[:book][:title] assert_equal "William Shakespeare", permitted[:book][:author] assert_equal "Shakespeare Today", permitted[:magazine] end test "nested array with strings that should be hashes" do - params = ActionController::Parameters.new({ + params = ActionController::Parameters.new( book: { genres: ["Tragedy"] - } - }) + }) permitted = params.permit book: { genres: :type } assert_empty permitted[:book][:genres] end test "nested array with strings that should be hashes and additional values" do - params = ActionController::Parameters.new({ + params = ActionController::Parameters.new( book: { title: "Romeo and Juliet", genres: ["Tragedy"] - } - }) + }) permitted = params.permit book: [ :title, { genres: :type } ] assert_equal "Romeo and Juliet", permitted[:book][:title] @@ -120,66 +116,67 @@ class NestedParametersTest < ActiveSupport::TestCase end test "nested string that should be a hash" do - params = ActionController::Parameters.new({ + params = ActionController::Parameters.new( book: { genre: "Tragedy" - } - }) + }) permitted = params.permit book: { genre: :type } assert_nil permitted[:book][:genre] end test "fields_for-style nested params" do - params = ActionController::Parameters.new({ + params = ActionController::Parameters.new( book: { authors_attributes: { - :'0' => { name: 'William Shakespeare', age_of_death: '52' }, - :'1' => { name: 'Unattributed Assistant' }, - :'2' => { name: %w(injected names) } + '0': { name: "William Shakespeare", age_of_death: "52" }, + '1': { name: "Unattributed Assistant" }, + '2': { name: %w(injected names) } } - } - }) + }) permitted = params.permit book: { authors_attributes: [ :name ] } - assert_not_nil permitted[:book][:authors_attributes]['0'] - assert_not_nil permitted[:book][:authors_attributes]['1'] - assert_empty permitted[:book][:authors_attributes]['2'] - assert_equal 'William Shakespeare', permitted[:book][:authors_attributes]['0'][:name] - assert_equal 'Unattributed Assistant', permitted[:book][:authors_attributes]['1'][:name] + assert_not_nil permitted[:book][:authors_attributes]["0"] + assert_not_nil permitted[:book][:authors_attributes]["1"] + assert_empty permitted[:book][:authors_attributes]["2"] + assert_equal "William Shakespeare", permitted[:book][:authors_attributes]["0"][:name] + assert_equal "Unattributed Assistant", permitted[:book][:authors_attributes]["1"][:name] + + assert_equal( + { "book" => { "authors_attributes" => { "0" => { "name" => "William Shakespeare" }, "1" => { "name" => "Unattributed Assistant" }, "2" => {} } } }, + permitted.to_h + ) - assert_filtered_out permitted[:book][:authors_attributes]['0'], :age_of_death + assert_filtered_out permitted[:book][:authors_attributes]["0"], :age_of_death end test "fields_for-style nested params with negative numbers" do - params = ActionController::Parameters.new({ + params = ActionController::Parameters.new( book: { authors_attributes: { - :'-1' => { name: 'William Shakespeare', age_of_death: '52' }, - :'-2' => { name: 'Unattributed Assistant' } + '-1': { name: "William Shakespeare", age_of_death: "52" }, + '-2': { name: "Unattributed Assistant" } } - } - }) + }) permitted = params.permit book: { authors_attributes: [:name] } - assert_not_nil permitted[:book][:authors_attributes]['-1'] - assert_not_nil permitted[:book][:authors_attributes]['-2'] - assert_equal 'William Shakespeare', permitted[:book][:authors_attributes]['-1'][:name] - assert_equal 'Unattributed Assistant', permitted[:book][:authors_attributes]['-2'][:name] + assert_not_nil permitted[:book][:authors_attributes]["-1"] + assert_not_nil permitted[:book][:authors_attributes]["-2"] + assert_equal "William Shakespeare", permitted[:book][:authors_attributes]["-1"][:name] + assert_equal "Unattributed Assistant", permitted[:book][:authors_attributes]["-2"][:name] - assert_filtered_out permitted[:book][:authors_attributes]['-1'], :age_of_death + assert_filtered_out permitted[:book][:authors_attributes]["-1"], :age_of_death end test "nested number as key" do - params = ActionController::Parameters.new({ + params = ActionController::Parameters.new( product: { properties: { - '0' => "prop0", - '1' => "prop1" + "0" => "prop0", + "1" => "prop1" } - } - }) - params = params.require(:product).permit(:properties => ["0"]) + }) + params = params.require(:product).permit(properties: ["0"]) assert_not_nil params[:properties]["0"] assert_nil params[:properties]["1"] assert_equal "prop0", params[:properties]["0"] diff --git a/actionpack/test/controller/parameters/parameters_permit_test.rb b/actionpack/test/controller/parameters/parameters_permit_test.rb index b75eb0e3bf..ebdaca0162 100644 --- a/actionpack/test/controller/parameters/parameters_permit_test.rb +++ b/actionpack/test/controller/parameters/parameters_permit_test.rb @@ -1,6 +1,8 @@ -require 'abstract_unit' -require 'action_dispatch/http/upload' -require 'action_controller/metal/strong_parameters' +# frozen_string_literal: true + +require "abstract_unit" +require "action_dispatch/http/upload" +require "action_controller/metal/strong_parameters" class ParametersPermitTest < ActiveSupport::TestCase def assert_filtered_out(params, key) @@ -10,25 +12,25 @@ class ParametersPermitTest < ActiveSupport::TestCase setup do @params = ActionController::Parameters.new( person: { - age: '32', + age: "32", name: { - first: 'David', - last: 'Heinemeier Hansson' + first: "David", + last: "Heinemeier Hansson" }, - addresses: [{city: 'Chicago', state: 'Illinois'}] + addresses: [{ city: "Chicago", state: "Illinois" }] } ) @struct_fields = [] %w(0 1 12).each do |number| - ['', 'i', 'f'].each do |suffix| + ["", "i", "f"].each do |suffix| @struct_fields << "sf(#{number}#{suffix})" end end end - def walk_permitted params - params.each do |k,v| + def walk_permitted(params) + params.each do |k, v| case v when ActionController::Parameters walk_permitted v @@ -38,25 +40,25 @@ class ParametersPermitTest < ActiveSupport::TestCase end end - test 'iteration should not impact permit' do - hash = {"foo"=>{"bar"=>{"0"=>{"baz"=>"hello", "zot"=>"1"}}}} + test "iteration should not impact permit" do + hash = { "foo" => { "bar" => { "0" => { "baz" => "hello", "zot" => "1" } } } } params = ActionController::Parameters.new(hash) walk_permitted params sanitized = params[:foo].permit(bar: [:baz]) - assert_equal({"0"=>{"baz"=>"hello"}}, sanitized[:bar].to_unsafe_h) + assert_equal({ "0" => { "baz" => "hello" } }, sanitized[:bar].to_unsafe_h) end - test 'if nothing is permitted, the hash becomes empty' do - params = ActionController::Parameters.new(id: '1234') + test "if nothing is permitted, the hash becomes empty" do + params = ActionController::Parameters.new(id: "1234") permitted = params.permit assert permitted.permitted? assert permitted.empty? end - test 'key: permitted scalar values' do - values = ['a', :a, nil] + test "key: permitted scalar values" do + values = ["a", :a, nil] values += [0, 1.0, 2**128, BigDecimal.new(1)] values += [true, false] values += [Date.today, Time.now, DateTime.now] @@ -66,25 +68,33 @@ class ParametersPermitTest < ActiveSupport::TestCase values.each do |value| params = ActionController::Parameters.new(id: value) permitted = params.permit(:id) - assert_equal value, permitted[:id] + if value.nil? + assert_nil permitted[:id] + else + assert_equal value, permitted[:id] + end @struct_fields.each do |sf| params = ActionController::Parameters.new(sf => value) permitted = params.permit(:sf) - assert_equal value, permitted[sf] + if value.nil? + assert_nil permitted[sf] + else + assert_equal value, permitted[sf] + end end end end - test 'key: unknown keys are filtered out' do - params = ActionController::Parameters.new(id: '1234', injected: 'injected') + test "key: unknown keys are filtered out" do + params = ActionController::Parameters.new(id: "1234", injected: "injected") permitted = params.permit(:id) - assert_equal '1234', permitted[:id] + assert_equal "1234", permitted[:id] assert_filtered_out permitted, :injected end - test 'key: arrays are filtered out' do - [[], [1], ['1']].each do |array| + test "key: arrays are filtered out" do + [[], [1], ["1"]].each do |array| params = ActionController::Parameters.new(id: array) permitted = params.permit(:id) assert_filtered_out permitted, :id @@ -97,8 +107,8 @@ class ParametersPermitTest < ActiveSupport::TestCase end end - test 'key: hashes are filtered out' do - [{}, {foo: 1}, {foo: 'bar'}].each do |hash| + test "key: hashes are filtered out" do + [{}, { foo: 1 }, { foo: "bar" }].each do |hash| params = ActionController::Parameters.new(id: hash) permitted = params.permit(:id) assert_filtered_out permitted, :id @@ -111,7 +121,7 @@ class ParametersPermitTest < ActiveSupport::TestCase end end - test 'key: non-permitted scalar values are filtered out' do + test "key: non-permitted scalar values are filtered out" do params = ActionController::Parameters.new(id: Object.new) permitted = params.permit(:id) assert_filtered_out permitted, :id @@ -123,51 +133,84 @@ class ParametersPermitTest < ActiveSupport::TestCase end end - test 'key: it is not assigned if not present in params' do - params = ActionController::Parameters.new(name: 'Joe') + test "key: it is not assigned if not present in params" do + params = ActionController::Parameters.new(name: "Joe") permitted = params.permit(:id) assert !permitted.has_key?(:id) end - test 'key to empty array: empty arrays pass' do + test "key to empty array: empty arrays pass" do params = ActionController::Parameters.new(id: []) permitted = params.permit(id: []) assert_equal [], permitted[:id] end - test 'do not break params filtering on nil values' do + test "do not break params filtering on nil values" do params = ActionController::Parameters.new(a: 1, b: [1, 2, 3], c: nil) permitted = params.permit(:a, c: [], b: []) assert_equal 1, permitted[:a] assert_equal [1, 2, 3], permitted[:b] - assert_equal nil, permitted[:c] + assert_nil permitted[:c] end - test 'key to empty array: arrays of permitted scalars pass' do - [['foo'], [1], ['foo', 'bar'], [1, 2, 3]].each do |array| + test "key to empty array: arrays of permitted scalars pass" do + [["foo"], [1], ["foo", "bar"], [1, 2, 3]].each do |array| params = ActionController::Parameters.new(id: array) permitted = params.permit(id: []) assert_equal array, permitted[:id] end end - test 'key to empty array: permitted scalar values do not pass' do - ['foo', 1].each do |permitted_scalar| + test "key to empty array: permitted scalar values do not pass" do + ["foo", 1].each do |permitted_scalar| params = ActionController::Parameters.new(id: permitted_scalar) permitted = params.permit(id: []) assert_filtered_out permitted, :id end end - test 'key to empty array: arrays of non-permitted scalar do not pass' do - [[Object.new], [[]], [[1]], [{}], [{id: '1'}]].each do |non_permitted_scalar| + test "key to empty array: arrays of non-permitted scalar do not pass" do + [[Object.new], [[]], [[1]], [{}], [{ id: "1" }]].each do |non_permitted_scalar| params = ActionController::Parameters.new(id: non_permitted_scalar) permitted = params.permit(id: []) assert_filtered_out permitted, :id end end + test "key to empty hash: arbitrary hashes are permitted" do + params = ActionController::Parameters.new( + username: "fxn", + preferences: { + scheme: "Marazul", + font: { + name: "Source Code Pro", + size: 12 + }, + tabstops: [4, 8, 12, 16], + suspicious: [true, Object.new, false, /yo!/], + dubious: [{ a: :a, b: /wtf!/ }, { c: :c }], + injected: Object.new + }, + hacked: 1 # not a hash + ) + + permitted = params.permit(:username, preferences: {}, hacked: {}) + + assert_equal "fxn", permitted[:username] + assert_equal "Marazul", permitted[:preferences][:scheme] + assert_equal "Source Code Pro", permitted[:preferences][:font][:name] + assert_equal 12, permitted[:preferences][:font][:size] + assert_equal [4, 8, 12, 16], permitted[:preferences][:tabstops] + assert_equal [true, false], permitted[:preferences][:suspicious] + assert_equal :a, permitted[:preferences][:dubious][0][:a] + assert_equal :c, permitted[:preferences][:dubious][1][:c] + + assert_filtered_out permitted[:preferences][:dubious][0], :b + assert_filtered_out permitted[:preferences], :injected + assert_filtered_out permitted, :hacked + end + test "fetch raises ParameterMissing exception" do e = assert_raises(ActionController::ParameterMissing) do @params.fetch :foo @@ -178,10 +221,10 @@ class ParametersPermitTest < ActiveSupport::TestCase test "fetch with a default value of a hash does not mutate the object" do params = ActionController::Parameters.new({}) params.fetch :foo, {} - assert_equal nil, params[:foo] + assert_nil params[:foo] end - test 'hashes in array values get wrapped' do + test "hashes in array values get wrapped" do params = ActionController::Parameters.new(foo: [{}, {}]) params[:foo].each do |hash| assert !hash.permitted? @@ -191,7 +234,7 @@ class ParametersPermitTest < ActiveSupport::TestCase # Strong params has an optimization to avoid looping every time you read # a key whose value is an array and building a new object. We check that # optimization here. - test 'arrays are converted at most once' do + test "arrays are converted at most once" do params = ActionController::Parameters.new(foo: [{}]) assert_same params[:foo], params[:foo] end @@ -202,11 +245,11 @@ class ParametersPermitTest < ActiveSupport::TestCase # This test checks that if we push a hash to an array (in-place modification) # the cache does not get fooled, the hash is still wrapped as strong params, # and not permitted. - test 'mutated arrays are detected' do - params = ActionController::Parameters.new(users: [{id: 1}]) + test "mutated arrays are detected" do + params = ActionController::Parameters.new(users: [{ id: 1 }]) permitted = params.permit(users: [:id]) - permitted[:users] << {injected: 1} + permitted[:users] << { injected: 1 } assert_not permitted[:users].last.permitted? end @@ -216,11 +259,11 @@ class ParametersPermitTest < ActiveSupport::TestCase end test "fetch doesnt raise ParameterMissing exception if there is a default that is nil" do - assert_equal nil, @params.fetch(:foo, nil) - assert_equal nil, @params.fetch(:foo) { nil } + assert_nil @params.fetch(:foo, nil) + assert_nil @params.fetch(:foo) { nil } end - test 'KeyError in fetch block should not be covered up' do + test "KeyError in fetch block should not be covered up" do params = ActionController::Parameters.new e = assert_raises(KeyError) do params.fetch(:missing_key) { {}.fetch(:also_missing) } @@ -237,6 +280,71 @@ class ParametersPermitTest < ActiveSupport::TestCase assert @params.merge(a: "b").permitted? end + test "merge with parameters" do + other_params = ActionController::Parameters.new(id: "1234").permit! + merged_params = @params.merge(other_params) + + assert merged_params[:id] + end + + test "not permitted is sticky beyond merge!" do + assert_not @params.merge!(a: "b").permitted? + end + + test "permitted is sticky beyond merge!" do + @params.permit! + assert @params.merge!(a: "b").permitted? + end + + test "merge! with parameters" do + other_params = ActionController::Parameters.new(id: "1234").permit! + @params.merge!(other_params) + + assert_equal "1234", @params[:id] + assert_equal "32", @params[:person][:age] + end + + test "#reverse_merge with parameters" do + default_params = ActionController::Parameters.new(id: "1234", person: {}).permit! + merged_params = @params.reverse_merge(default_params) + + assert_equal "1234", merged_params[:id] + refute_predicate merged_params[:person], :empty? + end + + test "#with_defaults is an alias of reverse_merge" do + default_params = ActionController::Parameters.new(id: "1234", person: {}).permit! + merged_params = @params.with_defaults(default_params) + + assert_equal "1234", merged_params[:id] + refute_predicate merged_params[:person], :empty? + end + + test "not permitted is sticky beyond reverse_merge" do + refute_predicate @params.reverse_merge(a: "b"), :permitted? + end + + test "permitted is sticky beyond reverse_merge" do + @params.permit! + assert_predicate @params.reverse_merge(a: "b"), :permitted? + end + + test "#reverse_merge! with parameters" do + default_params = ActionController::Parameters.new(id: "1234", person: {}).permit! + @params.reverse_merge!(default_params) + + assert_equal "1234", @params[:id] + refute_predicate @params[:person], :empty? + end + + test "#with_defaults! is an alias of reverse_merge!" do + default_params = ActionController::Parameters.new(id: "1234", person: {}).permit! + @params.with_defaults!(default_params) + + assert_equal "1234", @params[:id] + refute_predicate @params[:person], :empty? + end + test "modifying the parameters" do @params[:person][:hometown] = "Chicago" @params[:person][:family] = { brother: "Jonas" } @@ -245,11 +353,6 @@ class ParametersPermitTest < ActiveSupport::TestCase assert_equal "Jonas", @params[:person][:family][:brother] end - test "permit state is kept on a dup" do - @params.permit! - assert_equal @params.permitted?, @params.dup.permitted? - end - test "permit is recursive" do @params.permit! assert @params.permitted? @@ -261,9 +364,9 @@ class ParametersPermitTest < ActiveSupport::TestCase test "permitted takes a default value when Parameters.permit_all_parameters is set" do begin ActionController::Parameters.permit_all_parameters = true - params = ActionController::Parameters.new({ person: { + params = ActionController::Parameters.new(person: { age: "32", name: { first: "David", last: "Heinemeier Hansson" } - }}) + }) assert params.slice(:person).permitted? assert params[:person][:name].permitted? @@ -276,17 +379,17 @@ class ParametersPermitTest < ActiveSupport::TestCase assert_equal "32", @params[:person].permit([ :age ])[:age] end - test "to_h returns empty hash on unpermitted params" do - assert @params.to_h.is_a? ActiveSupport::HashWithIndifferentAccess - assert_not @params.to_h.is_a? ActionController::Parameters - assert @params.to_h.empty? + test "to_h raises UnfilteredParameters on unfiltered params" do + assert_raises(ActionController::UnfilteredParameters) do + @params.to_h + end end test "to_h returns converted hash on permitted params" do @params.permit! - assert @params.to_h.is_a? ActiveSupport::HashWithIndifferentAccess - assert_not @params.to_h.is_a? ActionController::Parameters + assert_instance_of ActiveSupport::HashWithIndifferentAccess, @params.to_h + assert_not_kind_of ActionController::Parameters, @params.to_h end test "to_h returns converted hash when .permit_all_parameters is set" do @@ -294,39 +397,71 @@ class ParametersPermitTest < ActiveSupport::TestCase ActionController::Parameters.permit_all_parameters = true params = ActionController::Parameters.new(crab: "Senjougahara Hitagi") - assert params.to_h.is_a? ActiveSupport::HashWithIndifferentAccess - assert_not @params.to_h.is_a? ActionController::Parameters + assert_instance_of ActiveSupport::HashWithIndifferentAccess, params.to_h + assert_not_kind_of ActionController::Parameters, params.to_h assert_equal({ "crab" => "Senjougahara Hitagi" }, params.to_h) ensure ActionController::Parameters.permit_all_parameters = false end end - test "to_h returns always permitted parameter on unpermitted params" do - params = ActionController::Parameters.new( - controller: "users", - action: "create", - user: { - name: "Sengoku Nadeko" - } - ) + test "to_hash raises UnfilteredParameters on unfiltered params" do + assert_raises(ActionController::UnfilteredParameters) do + @params.to_hash + end + end + + test "to_hash returns converted hash on permitted params" do + @params.permit! + + assert_instance_of Hash, @params.to_hash + assert_not_kind_of ActionController::Parameters, @params.to_hash + end + + test "parameters can be implicit converted to Hash" do + params = ActionController::Parameters.new + params.permit! - assert_equal({ "controller" => "users", "action" => "create" }, params.to_h) + assert_equal({ a: 1 }, { a: 1 }.merge!(params)) + end + + test "to_hash returns converted hash when .permit_all_parameters is set" do + begin + ActionController::Parameters.permit_all_parameters = true + params = ActionController::Parameters.new(crab: "Senjougahara Hitagi") + + assert_instance_of Hash, params.to_hash + assert_not_kind_of ActionController::Parameters, params.to_hash + assert_equal({ "crab" => "Senjougahara Hitagi" }, params.to_hash) + assert_equal({ "crab" => "Senjougahara Hitagi" }, params) + ensure + ActionController::Parameters.permit_all_parameters = false + end end test "to_unsafe_h returns unfiltered params" do - assert @params.to_unsafe_h.is_a? ActiveSupport::HashWithIndifferentAccess - assert_not @params.to_unsafe_h.is_a? ActionController::Parameters + assert_instance_of ActiveSupport::HashWithIndifferentAccess, @params.to_unsafe_h + assert_not_kind_of ActionController::Parameters, @params.to_unsafe_h end test "to_unsafe_h returns unfiltered params even after accessing few keys" do - params = ActionController::Parameters.new("f"=>{"language_facet"=>["Tibetan"]}) - expected = {"f"=>{"language_facet"=>["Tibetan"]}} + params = ActionController::Parameters.new("f" => { "language_facet" => ["Tibetan"] }) + expected = { "f" => { "language_facet" => ["Tibetan"] } } - assert params['f'].is_a? ActionController::Parameters + assert_instance_of ActionController::Parameters, params["f"] assert_equal expected, params.to_unsafe_h end + test "to_unsafe_h does not mutate the parameters" do + params = ActionController::Parameters.new("f" => { "language_facet" => ["Tibetan"] }) + params[:f] + + params.to_unsafe_h + + assert_not_predicate params, :permitted? + assert_not_predicate params[:f], :permitted? + end + test "to_h only deep dups Ruby collections" do company = Class.new do attr_reader :dupped @@ -334,10 +469,10 @@ class ParametersPermitTest < ActiveSupport::TestCase end.new params = ActionController::Parameters.new(prem: { likes: %i( dancing ) }) - assert_equal({ 'prem' => { 'likes' => %i( dancing ) } }, params.permit!.to_h) + assert_equal({ "prem" => { "likes" => %i( dancing ) } }, params.permit!.to_h) params = ActionController::Parameters.new(companies: [ company, :acme ]) - assert_equal({ 'companies' => [ company, :acme ] }, params.permit!.to_h) + assert_equal({ "companies" => [ company, :acme ] }, params.permit!.to_h) assert_not company.dupped end @@ -348,16 +483,16 @@ class ParametersPermitTest < ActiveSupport::TestCase end.new params = ActionController::Parameters.new(prem: { likes: %i( dancing ) }) - assert_equal({ 'prem' => { 'likes' => %i( dancing ) } }, params.to_unsafe_h) + assert_equal({ "prem" => { "likes" => %i( dancing ) } }, params.to_unsafe_h) params = ActionController::Parameters.new(companies: [ company, :acme ]) - assert_equal({ 'companies' => [ company, :acme ] }, params.to_unsafe_h) + assert_equal({ "companies" => [ company, :acme ] }, params.to_unsafe_h) assert_not company.dupped end test "include? returns true when the key is present" do assert @params.include? :person - assert @params.include? 'person' + assert @params.include? "person" assert_not @params.include? :gorilla end @@ -369,4 +504,10 @@ class ParametersPermitTest < ActiveSupport::TestCase refute params.permit(foo: [:bar]).has_key?(:foo) refute params.permit(foo: :bar).has_key?(:foo) end + + test "#permitted? is false by default" do + params = ActionController::Parameters.new + + assert_equal false, params.permitted? + end end diff --git a/actionpack/test/controller/parameters/raise_on_unpermitted_params_test.rb b/actionpack/test/controller/parameters/raise_on_unpermitted_params_test.rb index f9cc9f96f1..4afd3da593 100644 --- a/actionpack/test/controller/parameters/raise_on_unpermitted_params_test.rb +++ b/actionpack/test/controller/parameters/raise_on_unpermitted_params_test.rb @@ -1,5 +1,7 @@ -require 'abstract_unit' -require 'action_controller/metal/strong_parameters' +# frozen_string_literal: true + +require "abstract_unit" +require "action_controller/metal/strong_parameters" class RaiseOnUnpermittedParamsTest < ActiveSupport::TestCase def setup @@ -11,10 +13,9 @@ class RaiseOnUnpermittedParamsTest < ActiveSupport::TestCase end test "raises on unexpected params" do - params = ActionController::Parameters.new({ + params = ActionController::Parameters.new( book: { pages: 65 }, - fishing: "Turnips" - }) + fishing: "Turnips") assert_raises(ActionController::UnpermittedParameters) do params.permit(book: [:pages]) @@ -22,9 +23,8 @@ class RaiseOnUnpermittedParamsTest < ActiveSupport::TestCase end test "raises on unexpected nested params" do - params = ActionController::Parameters.new({ - book: { pages: 65, title: "Green Cats and where to find then." } - }) + params = ActionController::Parameters.new( + book: { pages: 65, title: "Green Cats and where to find then." }) assert_raises(ActionController::UnpermittedParameters) do params.permit(book: [:pages]) diff --git a/actionpack/test/controller/parameters/serialization_test.rb b/actionpack/test/controller/parameters/serialization_test.rb new file mode 100644 index 0000000000..823f01d82a --- /dev/null +++ b/actionpack/test/controller/parameters/serialization_test.rb @@ -0,0 +1,55 @@ +# frozen_string_literal: true + +require "abstract_unit" +require "action_controller/metal/strong_parameters" +require "active_support/core_ext/string/strip" + +class ParametersSerializationTest < ActiveSupport::TestCase + setup do + @old_permitted_parameters = ActionController::Parameters.permit_all_parameters + ActionController::Parameters.permit_all_parameters = false + end + + teardown do + ActionController::Parameters.permit_all_parameters = @old_permitted_parameters + end + + test "yaml serialization" do + params = ActionController::Parameters.new(key: :value) + yaml_dump = YAML.dump(params) + assert_match("--- !ruby/object:ActionController::Parameters", yaml_dump) + assert_match(/parameters: !ruby\/hash:ActiveSupport::HashWithIndifferentAccess\n\s+key: :value/, yaml_dump) + assert_match("permitted: false", yaml_dump) + end + + test "yaml deserialization" do + params = ActionController::Parameters.new(key: :value) + roundtripped = YAML.load(YAML.dump(params)) + + assert_equal params, roundtripped + assert_not roundtripped.permitted? + end + + test "yaml backwardscompatible with psych 2.0.8 format" do + params = YAML.load <<-end_of_yaml.strip_heredoc + --- !ruby/hash:ActionController::Parameters + key: :value + end_of_yaml + + assert_equal :value, params[:key] + assert_not params.permitted? + end + + test "yaml backwardscompatible with psych 2.0.9+ format" do + params = YAML.load(<<-end_of_yaml.strip_heredoc) + --- !ruby/hash-with-ivars:ActionController::Parameters + elements: + key: :value + ivars: + :@permitted: false + end_of_yaml + + assert_equal :value, params[:key] + assert_not params.permitted? + end +end |