aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/test/json
diff options
context:
space:
mode:
authorJeremy Kemper <jeremy@bitsweat.net>2010-04-26 19:32:23 -0700
committerJeremy Kemper <jeremy@bitsweat.net>2010-04-26 19:55:39 -0700
commitc1d73270717f30498f8f4d55d6695509107c2834 (patch)
tree88529812e5afe3cb15e60da2bc3fa67d3f4b09e4 /activesupport/test/json
parent43e2fd93b4fa92ca23d8bc8e68e1bf5a94038461 (diff)
downloadrails-c1d73270717f30498f8f4d55d6695509107c2834.tar.gz
rails-c1d73270717f30498f8f4d55d6695509107c2834.tar.bz2
rails-c1d73270717f30498f8f4d55d6695509107c2834.zip
JSON: encode objects that don't have a native JSON representation using to_hash, if available, instead of instance_values (the old fallback) or to_s (other encoders' default). Encode BigDecimal and Regexp encode as strings to conform with other encoders. Try to transcode non-UTF-8 strings.
Diffstat (limited to 'activesupport/test/json')
-rw-r--r--activesupport/test/json/encoding_test.rb21
1 files changed, 19 insertions, 2 deletions
diff --git a/activesupport/test/json/encoding_test.rb b/activesupport/test/json/encoding_test.rb
index 188b799f3f..ff95c0ca18 100644
--- a/activesupport/test/json/encoding_test.rb
+++ b/activesupport/test/json/encoding_test.rb
@@ -9,6 +9,12 @@ class TestJSONEncoding < Test::Unit::TestCase
end
end
+ class Hashlike
+ def to_hash
+ { :a => 1 }
+ end
+ end
+
class Custom
def as_json(options)
'custom'
@@ -19,7 +25,8 @@ class TestJSONEncoding < Test::Unit::TestCase
FalseTests = [[ false, %(false) ]]
NilTests = [[ nil, %(null) ]]
NumericTests = [[ 1, %(1) ],
- [ 2.5, %(2.5) ]]
+ [ 2.5, %(2.5) ],
+ [ BigDecimal('2.5'), %("#{BigDecimal('2.5').to_s}") ]]
StringTests = [[ 'this is the <string>', %("this is the \\u003Cstring\\u003E")],
[ 'a "string" with quotes & an ampersand', %("a \\"string\\" with quotes \\u0026 an ampersand") ],
@@ -35,11 +42,12 @@ class TestJSONEncoding < Test::Unit::TestCase
[ :"a b", %("a b") ]]
ObjectTests = [[ Foo.new(1, 2), %({\"a\":1,\"b\":2}) ]]
+ HashlikeTests = [[ Hashlike.new, %({\"a\":1}) ]]
CustomTests = [[ Custom.new, '"custom"' ]]
VariableTests = [[ ActiveSupport::JSON::Variable.new('foo'), 'foo'],
[ ActiveSupport::JSON::Variable.new('alert("foo")'), 'alert("foo")']]
- RegexpTests = [[ /^a/, '/^a/' ], [/^\w{1,2}[a-z]+/ix, '/^\\w{1,2}[a-z]+/ix']]
+ RegexpTests = [[ /^a/, '"(?-mix:^a)"' ], [/^\w{1,2}[a-z]+/ix, '"(?ix-m:^\\\\w{1,2}[a-z]+)"']]
DateTests = [[ Date.new(2005,2,1), %("2005/02/01") ]]
TimeTests = [[ Time.utc(2005,2,1,15,15,10), %("2005/02/01 15:15:10 +0000") ]]
@@ -91,6 +99,15 @@ class TestJSONEncoding < Test::Unit::TestCase
end
end
+ if '1.9'.respond_to?(:force_encoding)
+ def test_non_utf8_string_transcodes
+ s = '二'.encode('Shift_JIS')
+ result = ActiveSupport::JSON.encode(s)
+ assert_equal '"\\u4e8c"', result
+ assert_equal Encoding::UTF_8, result.encoding
+ end
+ end
+
def test_exception_raised_when_encoding_circular_reference
a = [1]
a << a