aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/test/json.rb
blob: c5b597abd7c82407dc86da9900ad3ecb7c7aee7a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
$:.unshift File.dirname(__FILE__) + '/../lib'
require 'active_support'
require 'test/unit'

class Foo
  def initialize(a, b)
    @a, @b = a, b
  end
end

class TestJSONEmitters < Test::Unit::TestCase
  TrueTests    = [[ true,  %(true)  ]]
  FalseTests   = [[ false, %(false) ]]
  NilTests     = [[ nil,   %(null)  ]]
  NumericTests = [[ 1,     %(1)     ],
                  [ 2.5,   %(2.5)   ]]
                    
  StringTests  = [[ 'this is the string',     %("this is the string")         ],
                  [ 'a "string" with quotes', %("a \\"string\\" with quotes") ]]
                 
  ArrayTests   = [[ ['a', 'b', 'c'],          %([\"a\", \"b\", \"c\"])          ],
                  [ [1, 'a', :b, nil, false], %([1, \"a\", \"b\", null, false]) ]]
  
  HashTests    = [[ {:a => :b, :c => :d}, %({\"c\": \"d\", \"a\": \"b\"}) ]]
                  
  SymbolTests  = [[ :a,     %("a")    ],
                  [ :this,  %("this") ],
                  [ :"a b", %("a b")  ]]

  ObjectTests  = [[ Foo.new(1, 2), %({\"a\": 1, \"b\": 2}) ]]
  
  constants.grep(/Tests$/).each do |class_tests|
    define_method("test_#{class_tests[0..-6].downcase}") do
      self.class.const_get(class_tests).each do |pair|
        assert_equal pair.last, pair.first.to_json
      end
    end
  end
  
  def test_utf8_string_encoded_properly_when_kcode_is_utf8
    old_kcode, $KCODE = $KCODE, 'UTF8'
    assert_equal '"\\u20ac2.99"', '€2.99'.to_json
    assert_equal '"\\u270e\\u263a"', '✎☺'.to_json
  ensure
    $KCODE = old_kcode
  end
  
  def test_exception_raised_when_encoding_circular_reference
    a = [1]
    a << a
    assert_raises(ActiveSupport::JSON::CircularReferenceError) { a.to_json }
  end
end