PageRenderTime 54ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/activesupport/test/core_ext/hash_ext_test.rb

https://github.com/phallstrom/rails
Ruby | 1084 lines | 926 code | 142 blank | 16 comment | 2 complexity | 5b506d16de849261aa97ef6da2e4a61a MD5 | raw file
  1. require 'abstract_unit'
  2. require 'active_support/core_ext/hash'
  3. require 'bigdecimal'
  4. require 'active_support/core_ext/string/access'
  5. require 'active_support/ordered_hash'
  6. require 'active_support/core_ext/object/conversions'
  7. require 'active_support/inflections'
  8. class HashExtTest < Test::Unit::TestCase
  9. class IndifferentHash < HashWithIndifferentAccess
  10. end
  11. class SubclassingArray < Array
  12. end
  13. class SubclassingHash < Hash
  14. end
  15. def setup
  16. @strings = { 'a' => 1, 'b' => 2 }
  17. @symbols = { :a => 1, :b => 2 }
  18. @mixed = { :a => 1, 'b' => 2 }
  19. @fixnums = { 0 => 1, 1 => 2 }
  20. if RUBY_VERSION < '1.9.0'
  21. @illegal_symbols = { "\0" => 1, "" => 2, [] => 3 }
  22. else
  23. @illegal_symbols = { [] => 3 }
  24. end
  25. end
  26. def test_methods
  27. h = {}
  28. assert_respond_to h, :symbolize_keys
  29. assert_respond_to h, :symbolize_keys!
  30. assert_respond_to h, :stringify_keys
  31. assert_respond_to h, :stringify_keys!
  32. assert_respond_to h, :to_options
  33. assert_respond_to h, :to_options!
  34. end
  35. def test_symbolize_keys
  36. assert_equal @symbols, @symbols.symbolize_keys
  37. assert_equal @symbols, @strings.symbolize_keys
  38. assert_equal @symbols, @mixed.symbolize_keys
  39. end
  40. def test_symbolize_keys!
  41. assert_equal @symbols, @symbols.dup.symbolize_keys!
  42. assert_equal @symbols, @strings.dup.symbolize_keys!
  43. assert_equal @symbols, @mixed.dup.symbolize_keys!
  44. end
  45. def test_symbolize_keys_preserves_keys_that_cant_be_symbolized
  46. assert_equal @illegal_symbols, @illegal_symbols.symbolize_keys
  47. assert_equal @illegal_symbols, @illegal_symbols.dup.symbolize_keys!
  48. end
  49. def test_symbolize_keys_preserves_fixnum_keys
  50. assert_equal @fixnums, @fixnums.symbolize_keys
  51. assert_equal @fixnums, @fixnums.dup.symbolize_keys!
  52. end
  53. def test_stringify_keys
  54. assert_equal @strings, @symbols.stringify_keys
  55. assert_equal @strings, @strings.stringify_keys
  56. assert_equal @strings, @mixed.stringify_keys
  57. end
  58. def test_stringify_keys!
  59. assert_equal @strings, @symbols.dup.stringify_keys!
  60. assert_equal @strings, @strings.dup.stringify_keys!
  61. assert_equal @strings, @mixed.dup.stringify_keys!
  62. end
  63. def test_symbolize_keys_for_hash_with_indifferent_access
  64. assert_instance_of Hash, @symbols.with_indifferent_access.symbolize_keys
  65. assert_equal @symbols, @symbols.with_indifferent_access.symbolize_keys
  66. assert_equal @symbols, @strings.with_indifferent_access.symbolize_keys
  67. assert_equal @symbols, @mixed.with_indifferent_access.symbolize_keys
  68. end
  69. def test_symbolize_keys_bang_for_hash_with_indifferent_access
  70. assert_raise(NoMethodError) { @symbols.with_indifferent_access.dup.symbolize_keys! }
  71. assert_raise(NoMethodError) { @strings.with_indifferent_access.dup.symbolize_keys! }
  72. assert_raise(NoMethodError) { @mixed.with_indifferent_access.dup.symbolize_keys! }
  73. end
  74. def test_symbolize_keys_preserves_keys_that_cant_be_symbolized_for_hash_with_indifferent_access
  75. assert_equal @illegal_symbols, @illegal_symbols.with_indifferent_access.symbolize_keys
  76. assert_raise(NoMethodError) { @illegal_symbols.with_indifferent_access.dup.symbolize_keys! }
  77. end
  78. def test_symbolize_keys_preserves_fixnum_keys_for_hash_with_indifferent_access
  79. assert_equal @fixnums, @fixnums.with_indifferent_access.symbolize_keys
  80. assert_raise(NoMethodError) { @fixnums.with_indifferent_access.dup.symbolize_keys! }
  81. end
  82. def test_stringify_keys_for_hash_with_indifferent_access
  83. assert_instance_of ActiveSupport::HashWithIndifferentAccess, @symbols.with_indifferent_access.stringify_keys
  84. assert_equal @strings, @symbols.with_indifferent_access.stringify_keys
  85. assert_equal @strings, @strings.with_indifferent_access.stringify_keys
  86. assert_equal @strings, @mixed.with_indifferent_access.stringify_keys
  87. end
  88. def test_stringify_keys_bang_for_hash_with_indifferent_access
  89. assert_instance_of ActiveSupport::HashWithIndifferentAccess, @symbols.with_indifferent_access.dup.stringify_keys!
  90. assert_equal @strings, @symbols.with_indifferent_access.dup.stringify_keys!
  91. assert_equal @strings, @strings.with_indifferent_access.dup.stringify_keys!
  92. assert_equal @strings, @mixed.with_indifferent_access.dup.stringify_keys!
  93. end
  94. def test_hash_subclass
  95. flash = { "foo" => SubclassingHash.new.tap { |h| h["bar"] = "baz" } }.with_indifferent_access
  96. assert_kind_of SubclassingHash, flash["foo"]
  97. end
  98. def test_indifferent_assorted
  99. @strings = @strings.with_indifferent_access
  100. @symbols = @symbols.with_indifferent_access
  101. @mixed = @mixed.with_indifferent_access
  102. assert_equal 'a', @strings.__send__(:convert_key, :a)
  103. assert_equal 1, @strings.fetch('a')
  104. assert_equal 1, @strings.fetch(:a.to_s)
  105. assert_equal 1, @strings.fetch(:a)
  106. hashes = { :@strings => @strings, :@symbols => @symbols, :@mixed => @mixed }
  107. method_map = { :'[]' => 1, :fetch => 1, :values_at => [1],
  108. :has_key? => true, :include? => true, :key? => true,
  109. :member? => true }
  110. hashes.each do |name, hash|
  111. method_map.sort_by { |m| m.to_s }.each do |meth, expected|
  112. assert_equal(expected, hash.__send__(meth, 'a'),
  113. "Calling #{name}.#{meth} 'a'")
  114. assert_equal(expected, hash.__send__(meth, :a),
  115. "Calling #{name}.#{meth} :a")
  116. end
  117. end
  118. assert_equal [1, 2], @strings.values_at('a', 'b')
  119. assert_equal [1, 2], @strings.values_at(:a, :b)
  120. assert_equal [1, 2], @symbols.values_at('a', 'b')
  121. assert_equal [1, 2], @symbols.values_at(:a, :b)
  122. assert_equal [1, 2], @mixed.values_at('a', 'b')
  123. assert_equal [1, 2], @mixed.values_at(:a, :b)
  124. end
  125. def test_indifferent_reading
  126. hash = HashWithIndifferentAccess.new
  127. hash["a"] = 1
  128. hash["b"] = true
  129. hash["c"] = false
  130. hash["d"] = nil
  131. assert_equal 1, hash[:a]
  132. assert_equal true, hash[:b]
  133. assert_equal false, hash[:c]
  134. assert_equal nil, hash[:d]
  135. assert_equal nil, hash[:e]
  136. end
  137. def test_indifferent_reading_with_nonnil_default
  138. hash = HashWithIndifferentAccess.new(1)
  139. hash["a"] = 1
  140. hash["b"] = true
  141. hash["c"] = false
  142. hash["d"] = nil
  143. assert_equal 1, hash[:a]
  144. assert_equal true, hash[:b]
  145. assert_equal false, hash[:c]
  146. assert_equal nil, hash[:d]
  147. assert_equal 1, hash[:e]
  148. end
  149. def test_indifferent_writing
  150. hash = HashWithIndifferentAccess.new
  151. hash[:a] = 1
  152. hash['b'] = 2
  153. hash[3] = 3
  154. assert_equal hash['a'], 1
  155. assert_equal hash['b'], 2
  156. assert_equal hash[:a], 1
  157. assert_equal hash[:b], 2
  158. assert_equal hash[3], 3
  159. end
  160. def test_indifferent_update
  161. hash = HashWithIndifferentAccess.new
  162. hash[:a] = 'a'
  163. hash['b'] = 'b'
  164. updated_with_strings = hash.update(@strings)
  165. updated_with_symbols = hash.update(@symbols)
  166. updated_with_mixed = hash.update(@mixed)
  167. assert_equal updated_with_strings[:a], 1
  168. assert_equal updated_with_strings['a'], 1
  169. assert_equal updated_with_strings['b'], 2
  170. assert_equal updated_with_symbols[:a], 1
  171. assert_equal updated_with_symbols['b'], 2
  172. assert_equal updated_with_symbols[:b], 2
  173. assert_equal updated_with_mixed[:a], 1
  174. assert_equal updated_with_mixed['b'], 2
  175. assert [updated_with_strings, updated_with_symbols, updated_with_mixed].all? { |h| h.keys.size == 2 }
  176. end
  177. def test_indifferent_merging
  178. hash = HashWithIndifferentAccess.new
  179. hash[:a] = 'failure'
  180. hash['b'] = 'failure'
  181. other = { 'a' => 1, :b => 2 }
  182. merged = hash.merge(other)
  183. assert_equal HashWithIndifferentAccess, merged.class
  184. assert_equal 1, merged[:a]
  185. assert_equal 2, merged['b']
  186. hash.update(other)
  187. assert_equal 1, hash[:a]
  188. assert_equal 2, hash['b']
  189. end
  190. def test_indifferent_reverse_merging
  191. hash = HashWithIndifferentAccess.new('some' => 'value', 'other' => 'value')
  192. hash.reverse_merge!(:some => 'noclobber', :another => 'clobber')
  193. assert_equal 'value', hash[:some]
  194. assert_equal 'clobber', hash[:another]
  195. end
  196. def test_indifferent_deleting
  197. get_hash = proc{ { :a => 'foo' }.with_indifferent_access }
  198. hash = get_hash.call
  199. assert_equal hash.delete(:a), 'foo'
  200. assert_equal hash.delete(:a), nil
  201. hash = get_hash.call
  202. assert_equal hash.delete('a'), 'foo'
  203. assert_equal hash.delete('a'), nil
  204. end
  205. def test_indifferent_to_hash
  206. # Should convert to a Hash with String keys.
  207. assert_equal @strings, @mixed.with_indifferent_access.to_hash
  208. # Should preserve the default value.
  209. mixed_with_default = @mixed.dup
  210. mixed_with_default.default = '1234'
  211. roundtrip = mixed_with_default.with_indifferent_access.to_hash
  212. assert_equal @strings, roundtrip
  213. assert_equal '1234', roundtrip.default
  214. end
  215. def test_indifferent_hash_with_array_of_hashes
  216. hash = { "urls" => { "url" => [ { "address" => "1" }, { "address" => "2" } ] }}.with_indifferent_access
  217. assert_equal "1", hash[:urls][:url].first[:address]
  218. end
  219. def test_should_preserve_array_subclass_when_value_is_array
  220. array = SubclassingArray.new
  221. array << { "address" => "1" }
  222. hash = { "urls" => { "url" => array }}.with_indifferent_access
  223. assert_equal SubclassingArray, hash[:urls][:url].class
  224. end
  225. def test_should_preserve_array_class_when_hash_value_is_frozen_array
  226. array = SubclassingArray.new
  227. array << { "address" => "1" }
  228. hash = { "urls" => { "url" => array.freeze }}.with_indifferent_access
  229. assert_equal SubclassingArray, hash[:urls][:url].class
  230. end
  231. def test_stringify_and_symbolize_keys_on_indifferent_preserves_hash
  232. h = HashWithIndifferentAccess.new
  233. h[:first] = 1
  234. h = h.stringify_keys
  235. assert_equal 1, h['first']
  236. h = HashWithIndifferentAccess.new
  237. h['first'] = 1
  238. h = h.symbolize_keys
  239. assert_equal 1, h[:first]
  240. end
  241. def test_to_options_on_indifferent_preserves_hash
  242. h = HashWithIndifferentAccess.new
  243. h['first'] = 1
  244. h.to_options!
  245. assert_equal 1, h['first']
  246. end
  247. def test_indifferent_subhashes
  248. h = {'user' => {'id' => 5}}.with_indifferent_access
  249. ['user', :user].each {|user| [:id, 'id'].each {|id| assert_equal 5, h[user][id], "h[#{user.inspect}][#{id.inspect}] should be 5"}}
  250. h = {:user => {:id => 5}}.with_indifferent_access
  251. ['user', :user].each {|user| [:id, 'id'].each {|id| assert_equal 5, h[user][id], "h[#{user.inspect}][#{id.inspect}] should be 5"}}
  252. end
  253. def test_indifferent_duplication
  254. # Should preserve default value
  255. h = HashWithIndifferentAccess.new
  256. h.default = '1234'
  257. assert_equal h.default, h.dup.default
  258. # Should preserve class for subclasses
  259. h = IndifferentHash.new
  260. assert_equal h.class, h.dup.class
  261. end
  262. def test_assert_valid_keys
  263. assert_nothing_raised do
  264. { :failure => "stuff", :funny => "business" }.assert_valid_keys([ :failure, :funny ])
  265. { :failure => "stuff", :funny => "business" }.assert_valid_keys(:failure, :funny)
  266. end
  267. assert_raise(ArgumentError, "Unknown key: failore") do
  268. { :failore => "stuff", :funny => "business" }.assert_valid_keys([ :failure, :funny ])
  269. { :failore => "stuff", :funny => "business" }.assert_valid_keys(:failure, :funny)
  270. end
  271. end
  272. def test_assorted_keys_not_stringified
  273. original = {Object.new => 2, 1 => 2, [] => true}
  274. indiff = original.with_indifferent_access
  275. assert(!indiff.keys.any? {|k| k.kind_of? String}, "A key was converted to a string!")
  276. end
  277. def test_deep_merge
  278. hash_1 = { :a => "a", :b => "b", :c => { :c1 => "c1", :c2 => "c2", :c3 => { :d1 => "d1" } } }
  279. hash_2 = { :a => 1, :c => { :c1 => 2, :c3 => { :d2 => "d2" } } }
  280. expected = { :a => 1, :b => "b", :c => { :c1 => 2, :c2 => "c2", :c3 => { :d1 => "d1", :d2 => "d2" } } }
  281. assert_equal expected, hash_1.deep_merge(hash_2)
  282. hash_1.deep_merge!(hash_2)
  283. assert_equal expected, hash_1
  284. end
  285. def test_deep_merge_on_indifferent_access
  286. hash_1 = HashWithIndifferentAccess.new({ :a => "a", :b => "b", :c => { :c1 => "c1", :c2 => "c2", :c3 => { :d1 => "d1" } } })
  287. hash_2 = HashWithIndifferentAccess.new({ :a => 1, :c => { :c1 => 2, :c3 => { :d2 => "d2" } } })
  288. hash_3 = { :a => 1, :c => { :c1 => 2, :c3 => { :d2 => "d2" } } }
  289. expected = { "a" => 1, "b" => "b", "c" => { "c1" => 2, "c2" => "c2", "c3" => { "d1" => "d1", "d2" => "d2" } } }
  290. assert_equal expected, hash_1.deep_merge(hash_2)
  291. assert_equal expected, hash_1.deep_merge(hash_3)
  292. hash_1.deep_merge!(hash_2)
  293. assert_equal expected, hash_1
  294. end
  295. def test_deep_dup
  296. hash = { :a => { :b => 'b' } }
  297. dup = hash.deep_dup
  298. dup[:a][:c] = 'c'
  299. assert_equal nil, hash[:a][:c]
  300. assert_equal 'c', dup[:a][:c]
  301. end
  302. def test_deep_dup_initialize
  303. zero_hash = Hash.new 0
  304. hash = { :a => zero_hash }
  305. dup = hash.deep_dup
  306. assert_equal 0, dup[:a][44]
  307. end
  308. def test_store_on_indifferent_access
  309. hash = HashWithIndifferentAccess.new
  310. hash.store(:test1, 1)
  311. hash.store('test1', 11)
  312. hash[:test2] = 2
  313. hash['test2'] = 22
  314. expected = { "test1" => 11, "test2" => 22 }
  315. assert_equal expected, hash
  316. end
  317. def test_reverse_merge
  318. defaults = { :a => "x", :b => "y", :c => 10 }.freeze
  319. options = { :a => 1, :b => 2 }
  320. expected = { :a => 1, :b => 2, :c => 10 }
  321. # Should merge defaults into options, creating a new hash.
  322. assert_equal expected, options.reverse_merge(defaults)
  323. assert_not_equal expected, options
  324. # Should merge! defaults into options, replacing options.
  325. merged = options.dup
  326. assert_equal expected, merged.reverse_merge!(defaults)
  327. assert_equal expected, merged
  328. # Should be an alias for reverse_merge!
  329. merged = options.dup
  330. assert_equal expected, merged.reverse_update(defaults)
  331. assert_equal expected, merged
  332. end
  333. def test_diff
  334. assert_equal({ :a => 2 }, { :a => 2, :b => 5 }.diff({ :a => 1, :b => 5 }))
  335. end
  336. def test_slice
  337. original = { :a => 'x', :b => 'y', :c => 10 }
  338. expected = { :a => 'x', :b => 'y' }
  339. # Should return a new hash with only the given keys.
  340. assert_equal expected, original.slice(:a, :b)
  341. assert_not_equal expected, original
  342. end
  343. def test_slice_inplace
  344. original = { :a => 'x', :b => 'y', :c => 10 }
  345. expected = { :c => 10 }
  346. # Should replace the hash with only the given keys.
  347. assert_equal expected, original.slice!(:a, :b)
  348. end
  349. def test_slice_with_an_array_key
  350. original = { :a => 'x', :b => 'y', :c => 10, [:a, :b] => "an array key" }
  351. expected = { [:a, :b] => "an array key", :c => 10 }
  352. # Should return a new hash with only the given keys when given an array key.
  353. assert_equal expected, original.slice([:a, :b], :c)
  354. assert_not_equal expected, original
  355. end
  356. def test_slice_inplace_with_an_array_key
  357. original = { :a => 'x', :b => 'y', :c => 10, [:a, :b] => "an array key" }
  358. expected = { :a => 'x', :b => 'y' }
  359. # Should replace the hash with only the given keys when given an array key.
  360. assert_equal expected, original.slice!([:a, :b], :c)
  361. end
  362. def test_slice_with_splatted_keys
  363. original = { :a => 'x', :b => 'y', :c => 10, [:a, :b] => "an array key" }
  364. expected = { :a => 'x', :b => "y" }
  365. # Should grab each of the splatted keys.
  366. assert_equal expected, original.slice(*[:a, :b])
  367. end
  368. def test_indifferent_slice
  369. original = { :a => 'x', :b => 'y', :c => 10 }.with_indifferent_access
  370. expected = { :a => 'x', :b => 'y' }.with_indifferent_access
  371. [['a', 'b'], [:a, :b]].each do |keys|
  372. # Should return a new hash with only the given keys.
  373. assert_equal expected, original.slice(*keys), keys.inspect
  374. assert_not_equal expected, original
  375. end
  376. end
  377. def test_indifferent_slice_inplace
  378. original = { :a => 'x', :b => 'y', :c => 10 }.with_indifferent_access
  379. expected = { :c => 10 }.with_indifferent_access
  380. [['a', 'b'], [:a, :b]].each do |keys|
  381. # Should replace the hash with only the given keys.
  382. copy = original.dup
  383. assert_equal expected, copy.slice!(*keys)
  384. end
  385. end
  386. def test_indifferent_slice_access_with_symbols
  387. original = {'login' => 'bender', 'password' => 'shiny', 'stuff' => 'foo'}
  388. original = original.with_indifferent_access
  389. slice = original.slice(:login, :password)
  390. assert_equal 'bender', slice[:login]
  391. assert_equal 'bender', slice['login']
  392. end
  393. def test_except
  394. original = { :a => 'x', :b => 'y', :c => 10 }
  395. expected = { :a => 'x', :b => 'y' }
  396. # Should return a new hash with only the given keys.
  397. assert_equal expected, original.except(:c)
  398. assert_not_equal expected, original
  399. # Should replace the hash with only the given keys.
  400. assert_equal expected, original.except!(:c)
  401. assert_equal expected, original
  402. end
  403. def test_except_with_original_frozen
  404. original = { :a => 'x', :b => 'y' }
  405. original.freeze
  406. assert_nothing_raised { original.except(:a) }
  407. end
  408. def test_except_with_mocha_expectation_on_original
  409. original = { :a => 'x', :b => 'y' }
  410. original.expects(:delete).never
  411. original.except(:a)
  412. end
  413. end
  414. class IWriteMyOwnXML
  415. def to_xml(options = {})
  416. options[:indent] ||= 2
  417. xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent])
  418. xml.instruct! unless options[:skip_instruct]
  419. xml.level_one do
  420. xml.tag!(:second_level, 'content')
  421. end
  422. end
  423. end
  424. class HashExtToParamTests < Test::Unit::TestCase
  425. class ToParam < String
  426. def to_param
  427. "#{self}-1"
  428. end
  429. end
  430. def test_string_hash
  431. assert_equal '', {}.to_param
  432. assert_equal 'hello=world', { :hello => "world" }.to_param
  433. assert_equal 'hello=10', { "hello" => 10 }.to_param
  434. assert_equal 'hello=world&say_bye=true', {:hello => "world", "say_bye" => true}.to_param
  435. end
  436. def test_number_hash
  437. assert_equal '10=20&30=40&50=60', {10 => 20, 30 => 40, 50 => 60}.to_param
  438. end
  439. def test_to_param_hash
  440. assert_equal 'custom2=param2-1&custom=param-1', {ToParam.new('custom') => ToParam.new('param'), ToParam.new('custom2') => ToParam.new('param2')}.to_param
  441. end
  442. def test_to_param_hash_escapes_its_keys_and_values
  443. assert_equal 'param+1=A+string+with+%2F+characters+%26+that+should+be+%3F+escaped', { 'param 1' => 'A string with / characters & that should be ? escaped' }.to_param
  444. end
  445. def test_to_param_orders_by_key_in_ascending_order
  446. assert_equal 'a=2&b=1&c=0', ActiveSupport::OrderedHash[*%w(b 1 c 0 a 2)].to_param
  447. end
  448. end
  449. class HashToXmlTest < Test::Unit::TestCase
  450. def setup
  451. @xml_options = { :root => :person, :skip_instruct => true, :indent => 0 }
  452. end
  453. def test_one_level
  454. xml = { :name => "David", :street => "Paulina" }.to_xml(@xml_options)
  455. assert_equal "<person>", xml.first(8)
  456. assert xml.include?(%(<street>Paulina</street>))
  457. assert xml.include?(%(<name>David</name>))
  458. end
  459. def test_one_level_dasherize_false
  460. xml = { :name => "David", :street_name => "Paulina" }.to_xml(@xml_options.merge(:dasherize => false))
  461. assert_equal "<person>", xml.first(8)
  462. assert xml.include?(%(<street_name>Paulina</street_name>))
  463. assert xml.include?(%(<name>David</name>))
  464. end
  465. def test_one_level_dasherize_true
  466. xml = { :name => "David", :street_name => "Paulina" }.to_xml(@xml_options.merge(:dasherize => true))
  467. assert_equal "<person>", xml.first(8)
  468. assert xml.include?(%(<street-name>Paulina</street-name>))
  469. assert xml.include?(%(<name>David</name>))
  470. end
  471. def test_one_level_camelize_true
  472. xml = { :name => "David", :street_name => "Paulina" }.to_xml(@xml_options.merge(:camelize => true))
  473. assert_equal "<Person>", xml.first(8)
  474. assert xml.include?(%(<StreetName>Paulina</StreetName>))
  475. assert xml.include?(%(<Name>David</Name>))
  476. end
  477. def test_one_level_camelize_lower
  478. xml = { :name => "David", :street_name => "Paulina" }.to_xml(@xml_options.merge(:camelize => :lower))
  479. assert_equal "<person>", xml.first(8)
  480. assert xml.include?(%(<streetName>Paulina</streetName>))
  481. assert xml.include?(%(<name>David</name>))
  482. end
  483. def test_one_level_with_types
  484. xml = { :name => "David", :street => "Paulina", :age => 26, :age_in_millis => 820497600000, :moved_on => Date.new(2005, 11, 15), :resident => :yes }.to_xml(@xml_options)
  485. assert_equal "<person>", xml.first(8)
  486. assert xml.include?(%(<street>Paulina</street>))
  487. assert xml.include?(%(<name>David</name>))
  488. assert xml.include?(%(<age type="integer">26</age>))
  489. assert xml.include?(%(<age-in-millis type="integer">820497600000</age-in-millis>))
  490. assert xml.include?(%(<moved-on type="date">2005-11-15</moved-on>))
  491. assert xml.include?(%(<resident type="symbol">yes</resident>))
  492. end
  493. def test_one_level_with_nils
  494. xml = { :name => "David", :street => "Paulina", :age => nil }.to_xml(@xml_options)
  495. assert_equal "<person>", xml.first(8)
  496. assert xml.include?(%(<street>Paulina</street>))
  497. assert xml.include?(%(<name>David</name>))
  498. assert xml.include?(%(<age nil="true"></age>))
  499. end
  500. def test_one_level_with_skipping_types
  501. xml = { :name => "David", :street => "Paulina", :age => nil }.to_xml(@xml_options.merge(:skip_types => true))
  502. assert_equal "<person>", xml.first(8)
  503. assert xml.include?(%(<street>Paulina</street>))
  504. assert xml.include?(%(<name>David</name>))
  505. assert xml.include?(%(<age nil="true"></age>))
  506. end
  507. def test_one_level_with_yielding
  508. xml = { :name => "David", :street => "Paulina" }.to_xml(@xml_options) do |x|
  509. x.creator("Rails")
  510. end
  511. assert_equal "<person>", xml.first(8)
  512. assert xml.include?(%(<street>Paulina</street>))
  513. assert xml.include?(%(<name>David</name>))
  514. assert xml.include?(%(<creator>Rails</creator>))
  515. end
  516. def test_two_levels
  517. xml = { :name => "David", :address => { :street => "Paulina" } }.to_xml(@xml_options)
  518. assert_equal "<person>", xml.first(8)
  519. assert xml.include?(%(<address><street>Paulina</street></address>))
  520. assert xml.include?(%(<name>David</name>))
  521. end
  522. def test_two_levels_with_second_level_overriding_to_xml
  523. xml = { :name => "David", :address => { :street => "Paulina" }, :child => IWriteMyOwnXML.new }.to_xml(@xml_options)
  524. assert_equal "<person>", xml.first(8)
  525. assert xml.include?(%(<address><street>Paulina</street></address>))
  526. assert xml.include?(%(<level_one><second_level>content</second_level></level_one>))
  527. end
  528. def test_two_levels_with_array
  529. xml = { :name => "David", :addresses => [{ :street => "Paulina" }, { :street => "Evergreen" }] }.to_xml(@xml_options)
  530. assert_equal "<person>", xml.first(8)
  531. assert xml.include?(%(<addresses type="array"><address>))
  532. assert xml.include?(%(<address><street>Paulina</street></address>))
  533. assert xml.include?(%(<address><street>Evergreen</street></address>))
  534. assert xml.include?(%(<name>David</name>))
  535. end
  536. def test_three_levels_with_array
  537. xml = { :name => "David", :addresses => [{ :streets => [ { :name => "Paulina" }, { :name => "Paulina" } ] } ] }.to_xml(@xml_options)
  538. assert xml.include?(%(<addresses type="array"><address><streets type="array"><street><name>))
  539. end
  540. def test_timezoned_attributes
  541. xml = {
  542. :created_at => Time.utc(1999,2,2),
  543. :local_created_at => Time.utc(1999,2,2).in_time_zone('Eastern Time (US & Canada)')
  544. }.to_xml(@xml_options)
  545. assert_match %r{<created-at type=\"datetime\">1999-02-02T00:00:00Z</created-at>}, xml
  546. assert_match %r{<local-created-at type=\"datetime\">1999-02-01T19:00:00-05:00</local-created-at>}, xml
  547. end
  548. def test_single_record_from_xml
  549. topic_xml = <<-EOT
  550. <topic>
  551. <title>The First Topic</title>
  552. <author-name>David</author-name>
  553. <id type="integer">1</id>
  554. <approved type="boolean"> true </approved>
  555. <replies-count type="integer">0</replies-count>
  556. <replies-close-in type="integer">2592000000</replies-close-in>
  557. <written-on type="date">2003-07-16</written-on>
  558. <viewed-at type="datetime">2003-07-16T09:28:00+0000</viewed-at>
  559. <content type="yaml">--- \n1: should be an integer\n:message: Have a nice day\narray: \n- should-have-dashes: true\n should_have_underscores: true\n</content>
  560. <author-email-address>david@loudthinking.com</author-email-address>
  561. <parent-id></parent-id>
  562. <ad-revenue type="decimal">1.5</ad-revenue>
  563. <optimum-viewing-angle type="float">135</optimum-viewing-angle>
  564. <resident type="symbol">yes</resident>
  565. </topic>
  566. EOT
  567. expected_topic_hash = {
  568. :title => "The First Topic",
  569. :author_name => "David",
  570. :id => 1,
  571. :approved => true,
  572. :replies_count => 0,
  573. :replies_close_in => 2592000000,
  574. :written_on => Date.new(2003, 7, 16),
  575. :viewed_at => Time.utc(2003, 7, 16, 9, 28),
  576. :content => { :message => "Have a nice day", 1 => "should be an integer", "array" => [{ "should-have-dashes" => true, "should_have_underscores" => true }] },
  577. :author_email_address => "david@loudthinking.com",
  578. :parent_id => nil,
  579. :ad_revenue => BigDecimal("1.50"),
  580. :optimum_viewing_angle => 135.0,
  581. :resident => :yes
  582. }.stringify_keys
  583. assert_equal expected_topic_hash, Hash.from_xml(topic_xml)["topic"]
  584. end
  585. def test_single_record_from_xml_with_nil_values
  586. topic_xml = <<-EOT
  587. <topic>
  588. <title></title>
  589. <id type="integer"></id>
  590. <approved type="boolean"></approved>
  591. <written-on type="date"></written-on>
  592. <viewed-at type="datetime"></viewed-at>
  593. <content type="yaml"></content>
  594. <parent-id></parent-id>
  595. </topic>
  596. EOT
  597. expected_topic_hash = {
  598. :title => nil,
  599. :id => nil,
  600. :approved => nil,
  601. :written_on => nil,
  602. :viewed_at => nil,
  603. :content => nil,
  604. :parent_id => nil
  605. }.stringify_keys
  606. assert_equal expected_topic_hash, Hash.from_xml(topic_xml)["topic"]
  607. end
  608. def test_multiple_records_from_xml
  609. topics_xml = <<-EOT
  610. <topics type="array">
  611. <topic>
  612. <title>The First Topic</title>
  613. <author-name>David</author-name>
  614. <id type="integer">1</id>
  615. <approved type="boolean">false</approved>
  616. <replies-count type="integer">0</replies-count>
  617. <replies-close-in type="integer">2592000000</replies-close-in>
  618. <written-on type="date">2003-07-16</written-on>
  619. <viewed-at type="datetime">2003-07-16T09:28:00+0000</viewed-at>
  620. <content>Have a nice day</content>
  621. <author-email-address>david@loudthinking.com</author-email-address>
  622. <parent-id nil="true"></parent-id>
  623. </topic>
  624. <topic>
  625. <title>The Second Topic</title>
  626. <author-name>Jason</author-name>
  627. <id type="integer">1</id>
  628. <approved type="boolean">false</approved>
  629. <replies-count type="integer">0</replies-count>
  630. <replies-close-in type="integer">2592000000</replies-close-in>
  631. <written-on type="date">2003-07-16</written-on>
  632. <viewed-at type="datetime">2003-07-16T09:28:00+0000</viewed-at>
  633. <content>Have a nice day</content>
  634. <author-email-address>david@loudthinking.com</author-email-address>
  635. <parent-id></parent-id>
  636. </topic>
  637. </topics>
  638. EOT
  639. expected_topic_hash = {
  640. :title => "The First Topic",
  641. :author_name => "David",
  642. :id => 1,
  643. :approved => false,
  644. :replies_count => 0,
  645. :replies_close_in => 2592000000,
  646. :written_on => Date.new(2003, 7, 16),
  647. :viewed_at => Time.utc(2003, 7, 16, 9, 28),
  648. :content => "Have a nice day",
  649. :author_email_address => "david@loudthinking.com",
  650. :parent_id => nil
  651. }.stringify_keys
  652. assert_equal expected_topic_hash, Hash.from_xml(topics_xml)["topics"].first
  653. end
  654. def test_single_record_from_xml_with_attributes_other_than_type
  655. topic_xml = <<-EOT
  656. <rsp stat="ok">
  657. <photos page="1" pages="1" perpage="100" total="16">
  658. <photo id="175756086" owner="55569174@N00" secret="0279bf37a1" server="76" title="Colored Pencil PhotoBooth Fun" ispublic="1" isfriend="0" isfamily="0"/>
  659. </photos>
  660. </rsp>
  661. EOT
  662. expected_topic_hash = {
  663. :id => "175756086",
  664. :owner => "55569174@N00",
  665. :secret => "0279bf37a1",
  666. :server => "76",
  667. :title => "Colored Pencil PhotoBooth Fun",
  668. :ispublic => "1",
  669. :isfriend => "0",
  670. :isfamily => "0",
  671. }.stringify_keys
  672. assert_equal expected_topic_hash, Hash.from_xml(topic_xml)["rsp"]["photos"]["photo"]
  673. end
  674. def test_all_caps_key_from_xml
  675. test_xml = <<-EOT
  676. <ABC3XYZ>
  677. <TEST>Lorem Ipsum</TEST>
  678. </ABC3XYZ>
  679. EOT
  680. expected_hash = {
  681. "ABC3XYZ" => {
  682. "TEST" => "Lorem Ipsum"
  683. }
  684. }
  685. assert_equal expected_hash, Hash.from_xml(test_xml)
  686. end
  687. def test_empty_array_from_xml
  688. blog_xml = <<-XML
  689. <blog>
  690. <posts type="array"></posts>
  691. </blog>
  692. XML
  693. expected_blog_hash = {"blog" => {"posts" => []}}
  694. assert_equal expected_blog_hash, Hash.from_xml(blog_xml)
  695. end
  696. def test_empty_array_with_whitespace_from_xml
  697. blog_xml = <<-XML
  698. <blog>
  699. <posts type="array">
  700. </posts>
  701. </blog>
  702. XML
  703. expected_blog_hash = {"blog" => {"posts" => []}}
  704. assert_equal expected_blog_hash, Hash.from_xml(blog_xml)
  705. end
  706. def test_array_with_one_entry_from_xml
  707. blog_xml = <<-XML
  708. <blog>
  709. <posts type="array">
  710. <post>a post</post>
  711. </posts>
  712. </blog>
  713. XML
  714. expected_blog_hash = {"blog" => {"posts" => ["a post"]}}
  715. assert_equal expected_blog_hash, Hash.from_xml(blog_xml)
  716. end
  717. def test_array_with_multiple_entries_from_xml
  718. blog_xml = <<-XML
  719. <blog>
  720. <posts type="array">
  721. <post>a post</post>
  722. <post>another post</post>
  723. </posts>
  724. </blog>
  725. XML
  726. expected_blog_hash = {"blog" => {"posts" => ["a post", "another post"]}}
  727. assert_equal expected_blog_hash, Hash.from_xml(blog_xml)
  728. end
  729. def test_file_from_xml
  730. blog_xml = <<-XML
  731. <blog>
  732. <logo type="file" name="logo.png" content_type="image/png">
  733. </logo>
  734. </blog>
  735. XML
  736. hash = Hash.from_xml(blog_xml)
  737. assert hash.has_key?('blog')
  738. assert hash['blog'].has_key?('logo')
  739. file = hash['blog']['logo']
  740. assert_equal 'logo.png', file.original_filename
  741. assert_equal 'image/png', file.content_type
  742. end
  743. def test_file_from_xml_with_defaults
  744. blog_xml = <<-XML
  745. <blog>
  746. <logo type="file">
  747. </logo>
  748. </blog>
  749. XML
  750. file = Hash.from_xml(blog_xml)['blog']['logo']
  751. assert_equal 'untitled', file.original_filename
  752. assert_equal 'application/octet-stream', file.content_type
  753. end
  754. def test_tag_with_attrs_and_whitespace
  755. xml = <<-XML
  756. <blog name="bacon is the best">
  757. </blog>
  758. XML
  759. hash = Hash.from_xml(xml)
  760. assert_equal "bacon is the best", hash['blog']['name']
  761. end
  762. def test_xsd_like_types_from_xml
  763. bacon_xml = <<-EOT
  764. <bacon>
  765. <weight type="double">0.5</weight>
  766. <price type="decimal">12.50</price>
  767. <chunky type="boolean"> 1 </chunky>
  768. <expires-at type="dateTime">2007-12-25T12:34:56+0000</expires-at>
  769. <notes type="string"></notes>
  770. <illustration type="base64Binary">YmFiZS5wbmc=</illustration>
  771. <caption type="binary" encoding="base64">VGhhdCdsbCBkbywgcGlnLg==</caption>
  772. </bacon>
  773. EOT
  774. expected_bacon_hash = {
  775. :weight => 0.5,
  776. :chunky => true,
  777. :price => BigDecimal("12.50"),
  778. :expires_at => Time.utc(2007,12,25,12,34,56),
  779. :notes => "",
  780. :illustration => "babe.png",
  781. :caption => "That'll do, pig."
  782. }.stringify_keys
  783. assert_equal expected_bacon_hash, Hash.from_xml(bacon_xml)["bacon"]
  784. end
  785. def test_type_trickles_through_when_unknown
  786. product_xml = <<-EOT
  787. <product>
  788. <weight type="double">0.5</weight>
  789. <image type="ProductImage"><filename>image.gif</filename></image>
  790. </product>
  791. EOT
  792. expected_product_hash = {
  793. :weight => 0.5,
  794. :image => {'type' => 'ProductImage', 'filename' => 'image.gif' },
  795. }.stringify_keys
  796. assert_equal expected_product_hash, Hash.from_xml(product_xml)["product"]
  797. end
  798. def test_should_use_default_value_for_unknown_key
  799. hash_wia = HashWithIndifferentAccess.new(3)
  800. assert_equal 3, hash_wia[:new_key]
  801. end
  802. def test_should_use_default_value_if_no_key_is_supplied
  803. hash_wia = HashWithIndifferentAccess.new(3)
  804. assert_equal 3, hash_wia.default
  805. end
  806. def test_should_nil_if_no_default_value_is_supplied
  807. hash_wia = HashWithIndifferentAccess.new
  808. assert_nil hash_wia.default
  809. end
  810. def test_should_copy_the_default_value_when_converting_to_hash_with_indifferent_access
  811. hash = Hash.new(3)
  812. hash_wia = hash.with_indifferent_access
  813. assert_equal 3, hash_wia.default
  814. end
  815. # The XML builder seems to fail miserably when trying to tag something
  816. # with the same name as a Kernel method (throw, test, loop, select ...)
  817. def test_kernel_method_names_to_xml
  818. hash = { :throw => { :ball => 'red' } }
  819. expected = '<person><throw><ball>red</ball></throw></person>'
  820. assert_nothing_raised do
  821. assert_equal expected, hash.to_xml(@xml_options)
  822. end
  823. end
  824. def test_empty_string_works_for_typecast_xml_value
  825. assert_nothing_raised do
  826. Hash.__send__(:typecast_xml_value, "")
  827. end
  828. end
  829. def test_escaping_to_xml
  830. hash = {
  831. :bare_string => 'First & Last Name',
  832. :pre_escaped_string => 'First &amp; Last Name'
  833. }.stringify_keys
  834. expected_xml = '<person><bare-string>First &amp; Last Name</bare-string><pre-escaped-string>First &amp;amp; Last Name</pre-escaped-string></person>'
  835. assert_equal expected_xml, hash.to_xml(@xml_options)
  836. end
  837. def test_unescaping_from_xml
  838. xml_string = '<person><bare-string>First &amp; Last Name</bare-string><pre-escaped-string>First &amp;amp; Last Name</pre-escaped-string></person>'
  839. expected_hash = {
  840. :bare_string => 'First & Last Name',
  841. :pre_escaped_string => 'First &amp; Last Name'
  842. }.stringify_keys
  843. assert_equal expected_hash, Hash.from_xml(xml_string)['person']
  844. end
  845. def test_roundtrip_to_xml_from_xml
  846. hash = {
  847. :bare_string => 'First & Last Name',
  848. :pre_escaped_string => 'First &amp; Last Name'
  849. }.stringify_keys
  850. assert_equal hash, Hash.from_xml(hash.to_xml(@xml_options))['person']
  851. end
  852. def test_datetime_xml_type_with_utc_time
  853. alert_xml = <<-XML
  854. <alert>
  855. <alert_at type="datetime">2008-02-10T15:30:45Z</alert_at>
  856. </alert>
  857. XML
  858. alert_at = Hash.from_xml(alert_xml)['alert']['alert_at']
  859. assert alert_at.utc?
  860. assert_equal Time.utc(2008, 2, 10, 15, 30, 45), alert_at
  861. end
  862. def test_datetime_xml_type_with_non_utc_time
  863. alert_xml = <<-XML
  864. <alert>
  865. <alert_at type="datetime">2008-02-10T10:30:45-05:00</alert_at>
  866. </alert>
  867. XML
  868. alert_at = Hash.from_xml(alert_xml)['alert']['alert_at']
  869. assert alert_at.utc?
  870. assert_equal Time.utc(2008, 2, 10, 15, 30, 45), alert_at
  871. end
  872. def test_datetime_xml_type_with_far_future_date
  873. alert_xml = <<-XML
  874. <alert>
  875. <alert_at type="datetime">2050-02-10T15:30:45Z</alert_at>
  876. </alert>
  877. XML
  878. alert_at = Hash.from_xml(alert_xml)['alert']['alert_at']
  879. assert alert_at.utc?
  880. assert_equal 2050, alert_at.year
  881. assert_equal 2, alert_at.month
  882. assert_equal 10, alert_at.day
  883. assert_equal 15, alert_at.hour
  884. assert_equal 30, alert_at.min
  885. assert_equal 45, alert_at.sec
  886. end
  887. def test_to_xml_dups_options
  888. options = {:skip_instruct => true}
  889. {}.to_xml(options)
  890. # :builder, etc, shouldn't be added to options
  891. assert_equal({:skip_instruct => true}, options)
  892. end
  893. def test_expansion_count_is_limited
  894. expected =
  895. case ActiveSupport::XmlMini.backend.name
  896. when 'ActiveSupport::XmlMini_REXML'; RuntimeError
  897. when 'ActiveSupport::XmlMini_Nokogiri'; Nokogiri::XML::SyntaxError
  898. when 'ActiveSupport::XmlMini_NokogiriSAX'; RuntimeError
  899. when 'ActiveSupport::XmlMini_LibXML'; LibXML::XML::Error
  900. when 'ActiveSupport::XmlMini_LibXMLSAX'; LibXML::XML::Error
  901. end
  902. assert_raise expected do
  903. attack_xml = <<-EOT
  904. <?xml version="1.0" encoding="UTF-8"?>
  905. <!DOCTYPE member [
  906. <!ENTITY a "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;">
  907. <!ENTITY b "&c;&c;&c;&c;&c;&c;&c;&c;&c;&c;">
  908. <!ENTITY c "&d;&d;&d;&d;&d;&d;&d;&d;&d;&d;">
  909. <!ENTITY d "&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;">
  910. <!ENTITY e "&f;&f;&f;&f;&f;&f;&f;&f;&f;&f;">
  911. <!ENTITY f "&g;&g;&g;&g;&g;&g;&g;&g;&g;&g;">
  912. <!ENTITY g "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx">
  913. ]>
  914. <member>
  915. &a;
  916. </member>
  917. EOT
  918. Hash.from_xml(attack_xml)
  919. end
  920. end
  921. end