basic.rb 43.6 KB
Newer Older
Chris Fallin's avatar
Chris Fallin committed
1 2
#!/usr/bin/ruby

3
require 'google/protobuf'
4
require 'json'
Chris Fallin's avatar
Chris Fallin committed
5 6 7 8 9 10 11
require 'test/unit'

# ------------- generated code --------------

module BasicTest
  pool = Google::Protobuf::DescriptorPool.new
  pool.build do
12 13 14 15 16 17 18 19 20 21 22 23 24
    add_message "Foo" do
      optional :bar, :message, 1, "Bar"
      repeated :baz, :message, 2, "Baz"
    end

    add_message "Bar" do
      optional :msg, :string, 1
    end

    add_message "Baz" do
      optional :msg, :string, 1
    end

Chris Fallin's avatar
Chris Fallin committed
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
    add_message "TestMessage" do
      optional :optional_int32,  :int32,        1
      optional :optional_int64,  :int64,        2
      optional :optional_uint32, :uint32,       3
      optional :optional_uint64, :uint64,       4
      optional :optional_bool,   :bool,         5
      optional :optional_float,  :float,        6
      optional :optional_double, :double,       7
      optional :optional_string, :string,       8
      optional :optional_bytes,  :bytes,        9
      optional :optional_msg,    :message,      10, "TestMessage2"
      optional :optional_enum,   :enum,         11, "TestEnum"

      repeated :repeated_int32,  :int32,        12
      repeated :repeated_int64,  :int64,        13
      repeated :repeated_uint32, :uint32,       14
      repeated :repeated_uint64, :uint64,       15
      repeated :repeated_bool,   :bool,         16
      repeated :repeated_float,  :float,        17
      repeated :repeated_double, :double,       18
      repeated :repeated_string, :string,       19
      repeated :repeated_bytes,  :bytes,        20
      repeated :repeated_msg,    :message,      21, "TestMessage2"
      repeated :repeated_enum,   :enum,         22, "TestEnum"
    end
    add_message "TestMessage2" do
      optional :foo, :int32, 1
    end
53

54 55 56 57 58 59 60 61 62 63 64
    add_message "TestEmbeddedMessageParent" do
      optional :child_msg, :message, 1, "TestEmbeddedMessageChild"
      optional :number, :int32, 2

      repeated :repeated_msg, :message, 3, "TestEmbeddedMessageChild"
      repeated :repeated_number, :int32, 4
    end
    add_message "TestEmbeddedMessageChild" do
      optional :sub_child, :message, 1, "TestMessage"
    end

Chris Fallin's avatar
Chris Fallin committed
65 66 67 68 69 70
    add_message "Recursive1" do
      optional :foo, :message, 1, "Recursive2"
    end
    add_message "Recursive2" do
      optional :foo, :message, 1, "Recursive1"
    end
71

Chris Fallin's avatar
Chris Fallin committed
72 73 74 75 76 77
    add_enum "TestEnum" do
      value :Default, 0
      value :A, 1
      value :B, 2
      value :C, 3
    end
78

Chris Fallin's avatar
Chris Fallin committed
79 80 81 82 83
    add_message "BadFieldNames" do
      optional :dup, :int32, 1
      optional :class, :int32, 2
      optional :"a.b", :int32, 3
    end
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

    add_message "MapMessage" do
      map :map_string_int32, :string, :int32, 1
      map :map_string_msg, :string, :message, 2, "TestMessage2"
    end
    add_message "MapMessageWireEquiv" do
      repeated :map_string_int32, :message, 1, "MapMessageWireEquiv_entry1"
      repeated :map_string_msg, :message, 2, "MapMessageWireEquiv_entry2"
    end
    add_message "MapMessageWireEquiv_entry1" do
      optional :key, :string, 1
      optional :value, :int32, 2
    end
    add_message "MapMessageWireEquiv_entry2" do
      optional :key, :string, 1
      optional :value, :message, 2, "TestMessage2"
    end
101 102 103 104 105 106 107 108 109

    add_message "OneofMessage" do
      oneof :my_oneof do
        optional :a, :string, 1
        optional :b, :int32, 2
        optional :c, :message, 3, "TestMessage2"
        optional :d, :enum, 4, "TestEnum"
      end
    end
110 111 112 113 114 115 116

    add_message "repro.Outer" do
      map :items, :int32, :message, 1, "repro.Inner"
    end

    add_message "repro.Inner" do
    end
Chris Fallin's avatar
Chris Fallin committed
117 118
  end

119 120 121

  Outer = pool.lookup("repro.Outer").msgclass
  Inner = pool.lookup("repro.Inner").msgclass
122 123 124
  Foo = pool.lookup("Foo").msgclass
  Bar = pool.lookup("Bar").msgclass
  Baz = pool.lookup("Baz").msgclass
Chris Fallin's avatar
Chris Fallin committed
125 126
  TestMessage = pool.lookup("TestMessage").msgclass
  TestMessage2 = pool.lookup("TestMessage2").msgclass
127 128
  TestEmbeddedMessageParent = pool.lookup("TestEmbeddedMessageParent").msgclass
  TestEmbeddedMessageChild = pool.lookup("TestEmbeddedMessageChild").msgclass
Chris Fallin's avatar
Chris Fallin committed
129 130 131 132
  Recursive1 = pool.lookup("Recursive1").msgclass
  Recursive2 = pool.lookup("Recursive2").msgclass
  TestEnum = pool.lookup("TestEnum").enummodule
  BadFieldNames = pool.lookup("BadFieldNames").msgclass
133 134 135 136 137 138
  MapMessage = pool.lookup("MapMessage").msgclass
  MapMessageWireEquiv = pool.lookup("MapMessageWireEquiv").msgclass
  MapMessageWireEquiv_entry1 =
    pool.lookup("MapMessageWireEquiv_entry1").msgclass
  MapMessageWireEquiv_entry2 =
    pool.lookup("MapMessageWireEquiv_entry2").msgclass
139
  OneofMessage = pool.lookup("OneofMessage").msgclass
Chris Fallin's avatar
Chris Fallin committed
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176

# ------------ test cases ---------------

  class MessageContainerTest < Test::Unit::TestCase

    def test_defaults
      m = TestMessage.new
      assert m.optional_int32 == 0
      assert m.optional_int64 == 0
      assert m.optional_uint32 == 0
      assert m.optional_uint64 == 0
      assert m.optional_bool == false
      assert m.optional_float == 0.0
      assert m.optional_double == 0.0
      assert m.optional_string == ""
      assert m.optional_bytes == ""
      assert m.optional_msg == nil
      assert m.optional_enum == :Default
    end

    def test_setters
      m = TestMessage.new
      m.optional_int32 = -42
      assert m.optional_int32 == -42
      m.optional_int64 = -0x1_0000_0000
      assert m.optional_int64 == -0x1_0000_0000
      m.optional_uint32 = 0x9000_0000
      assert m.optional_uint32 == 0x9000_0000
      m.optional_uint64 = 0x9000_0000_0000_0000
      assert m.optional_uint64 == 0x9000_0000_0000_0000
      m.optional_bool = true
      assert m.optional_bool == true
      m.optional_float = 0.5
      assert m.optional_float == 0.5
      m.optional_double = 0.5
      m.optional_string = "hello"
      assert m.optional_string == "hello"
177 178
      m.optional_string = :hello
      assert m.optional_string == "hello"
Chris Fallin's avatar
Chris Fallin committed
179 180 181 182
      m.optional_bytes = "world".encode!('ASCII-8BIT')
      assert m.optional_bytes == "world"
      m.optional_msg = TestMessage2.new(:foo => 42)
      assert m.optional_msg == TestMessage2.new(:foo => 42)
183 184
      m.optional_msg = nil
      assert m.optional_msg == nil
185 186 187 188
      m.optional_enum = :C
      assert m.optional_enum == :C
      m.optional_enum = 'C'
      assert m.optional_enum == :C
Chris Fallin's avatar
Chris Fallin committed
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
    end

    def test_ctor_args
      m = TestMessage.new(:optional_int32 => -42,
                          :optional_msg => TestMessage2.new,
                          :optional_enum => :C,
                          :repeated_string => ["hello", "there", "world"])
      assert m.optional_int32 == -42
      assert m.optional_msg.class == TestMessage2
      assert m.repeated_string.length == 3
      assert m.optional_enum == :C
      assert m.repeated_string[0] == "hello"
      assert m.repeated_string[1] == "there"
      assert m.repeated_string[2] == "world"
    end

205 206 207 208 209 210 211 212 213 214
    def test_ctor_string_symbol_args
      m = TestMessage.new(:optional_enum => 'C', :repeated_enum => ['A', 'B'])
      assert_equal :C, m.optional_enum
      assert_equal [:A, :B], m.repeated_enum

      m = TestMessage.new(:optional_string => :foo, :repeated_string => [:foo, :bar])
      assert_equal 'foo', m.optional_string
      assert_equal ['foo', 'bar'], m.repeated_string
    end

215 216 217 218 219 220 221 222 223
    def test_ctor_nil_args
      m = TestMessage.new(:optional_enum => nil, :optional_int32 => nil, :optional_string => nil, :optional_msg => nil)

      assert_equal :Default, m.optional_enum
      assert_equal 0, m.optional_int32
      assert_equal "", m.optional_string
      assert_nil m.optional_msg
    end

224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
    def test_embeddedmsg_hash_init
      m = TestEmbeddedMessageParent.new(:child_msg => {sub_child: {optional_int32: 1}},
                                        :number => 2,
                                        :repeated_msg => [{sub_child: {optional_int32: 3}}],
                                        :repeated_number => [10, 20, 30])

      assert_equal 2, m.number
      assert_equal [10, 20, 30], m.repeated_number

      assert_not_nil m.child_msg
      assert_not_nil m.child_msg.sub_child
      assert_equal m.child_msg.sub_child.optional_int32, 1

      assert_not_nil m.repeated_msg
      assert_equal 1, m.repeated_msg.length
      assert_equal 3, m.repeated_msg.first.sub_child.optional_int32
    end

Chris Fallin's avatar
Chris Fallin committed
242 243 244 245 246 247
    def test_inspect
      m = TestMessage.new(:optional_int32 => -42,
                          :optional_enum => :A,
                          :optional_msg => TestMessage2.new,
                          :repeated_string => ["hello", "there", "world"])
      expected = '<BasicTest::TestMessage: optional_int32: -42, optional_int64: 0, optional_uint32: 0, optional_uint64: 0, optional_bool: false, optional_float: 0.0, optional_double: 0.0, optional_string: "", optional_bytes: "", optional_msg: <BasicTest::TestMessage2: foo: 0>, optional_enum: :A, repeated_int32: [], repeated_int64: [], repeated_uint32: [], repeated_uint64: [], repeated_bool: [], repeated_float: [], repeated_double: [], repeated_string: ["hello", "there", "world"], repeated_bytes: [], repeated_msg: [], repeated_enum: []>'
248
      assert_equal expected, m.inspect
Chris Fallin's avatar
Chris Fallin committed
249 250 251 252
    end

    def test_hash
      m1 = TestMessage.new(:optional_int32 => 42)
253 254
      m2 = TestMessage.new(:optional_int32 => 102, repeated_string: ['please', 'work', 'ok?'])
      m3 = TestMessage.new(:optional_int32 => 102, repeated_string: ['please', 'work', 'ok?'])
Chris Fallin's avatar
Chris Fallin committed
255 256
      assert m1.hash != 0
      assert m2.hash != 0
257
      assert m3.hash != 0
Chris Fallin's avatar
Chris Fallin committed
258 259 260
      # relying on the randomness here -- if hash function changes and we are
      # unlucky enough to get a collision, then change the values above.
      assert m1.hash != m2.hash
261
      assert_equal m2.hash, m3.hash
Chris Fallin's avatar
Chris Fallin committed
262 263
    end

264 265 266 267 268 269 270 271 272 273 274 275
    def test_unknown_field_errors
      e = assert_raise NoMethodError do
        TestMessage.new.hello
      end
      assert_match(/hello/, e.message)

      e = assert_raise NoMethodError do
        TestMessage.new.hello = "world"
      end
      assert_match(/hello/, e.message)
    end

276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
    def test_initialization_map_errors
      e = assert_raise ArgumentError do
        TestMessage.new(:hello => "world")
      end
      assert_match(/hello/, e.message)

      e = assert_raise ArgumentError do
        MapMessage.new(:map_string_int32 => "hello")
      end
      assert_equal e.message, "Expected Hash object as initializer value for map field 'map_string_int32'."

      e = assert_raise ArgumentError do
        TestMessage.new(:repeated_uint32 => "hello")
      end
      assert_equal e.message, "Expected array as initializer value for repeated field 'repeated_uint32'."
    end

Chris Fallin's avatar
Chris Fallin committed
293 294
    def test_type_errors
      m = TestMessage.new
295
      e = assert_raise Google::Protobuf::TypeError do
Chris Fallin's avatar
Chris Fallin committed
296 297
        m.optional_int32 = "hello"
      end
298 299 300 301 302 303

      # Google::Protobuf::TypeError should inherit from TypeError for backwards compatibility
      # TODO: This can be removed when we can safely migrate to Google::Protobuf::TypeError
      assert_true e.is_a?(::TypeError)

      assert_raise Google::Protobuf::TypeError do
Chris Fallin's avatar
Chris Fallin committed
304 305
        m.optional_string = 42
      end
306
      assert_raise Google::Protobuf::TypeError do
Chris Fallin's avatar
Chris Fallin committed
307 308
        m.optional_string = nil
      end
309
      assert_raise Google::Protobuf::TypeError do
Chris Fallin's avatar
Chris Fallin committed
310 311
        m.optional_bool = 42
      end
312
      assert_raise Google::Protobuf::TypeError do
Chris Fallin's avatar
Chris Fallin committed
313 314 315
        m.optional_msg = TestMessage.new  # expects TestMessage2
      end

316
      assert_raise Google::Protobuf::TypeError do
Chris Fallin's avatar
Chris Fallin committed
317 318 319
        m.repeated_int32 = []  # needs RepeatedField
      end

320
      assert_raise Google::Protobuf::TypeError do
Chris Fallin's avatar
Chris Fallin committed
321 322 323
        m.repeated_int32.push "hello"
      end

324
      assert_raise Google::Protobuf::TypeError do
Chris Fallin's avatar
Chris Fallin committed
325 326 327 328 329 330 331 332
        m.repeated_msg.push TestMessage.new
      end
    end

    def test_string_encoding
      m = TestMessage.new

      # Assigning a normal (ASCII or UTF8) string to a bytes field, or
333 334 335 336 337 338 339
      # ASCII-8BIT to a string field will convert to the proper encoding.
      m.optional_bytes = "Test string ASCII".encode!('ASCII')
      assert m.optional_bytes.frozen?
      assert_equal Encoding::ASCII_8BIT, m.optional_bytes.encoding
      assert_equal "Test string ASCII", m.optional_bytes

      assert_raise Encoding::UndefinedConversionError do
Chris Fallin's avatar
Chris Fallin committed
340 341
        m.optional_bytes = "Test string UTF-8 \u0100".encode!('UTF-8')
      end
342 343

      assert_raise Encoding::UndefinedConversionError do
Chris Fallin's avatar
Chris Fallin committed
344 345 346 347 348 349 350
        m.optional_string = ["FFFF"].pack('H*')
      end

      # "Ordinary" use case.
      m.optional_bytes = ["FFFF"].pack('H*')
      m.optional_string = "\u0100"

351
      # strings are immutable so we can't do this, but serialize should catch it.
Chris Fallin's avatar
Chris Fallin committed
352
      m.optional_string = "asdf".encode!('UTF-8')
353 354 355
      # Ruby 2.5 changed to raise FrozenError. However, assert_raise don't
      # accept subclass. Don't specify type here.
      assert_raise do
356
        m.optional_string.encode!('ASCII-8BIT')
Chris Fallin's avatar
Chris Fallin committed
357 358 359 360 361 362 363 364
      end
    end

    def test_rptfield_int32
      l = Google::Protobuf::RepeatedField.new(:int32)
      assert l.count == 0
      l = Google::Protobuf::RepeatedField.new(:int32, [1, 2, 3])
      assert l.count == 3
365 366
      assert_equal [1, 2, 3], l
      assert_equal l, [1, 2, 3]
Chris Fallin's avatar
Chris Fallin committed
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
      l.push 4
      assert l == [1, 2, 3, 4]
      dst_list = []
      l.each { |val| dst_list.push val }
      assert dst_list == [1, 2, 3, 4]
      assert l.to_a == [1, 2, 3, 4]
      assert l[0] == 1
      assert l[3] == 4
      l[0] = 5
      assert l == [5, 2, 3, 4]

      l2 = l.dup
      assert l == l2
      assert l.object_id != l2.object_id
      l2.push 6
      assert l.count == 4
      assert l2.count == 5

      assert l.inspect == '[5, 2, 3, 4]'

387
      l.concat([7, 8, 9])
Chris Fallin's avatar
Chris Fallin committed
388 389 390 391
      assert l == [5, 2, 3, 4, 7, 8, 9]
      assert l.pop == 9
      assert l == [5, 2, 3, 4, 7, 8]

392
      assert_raise Google::Protobuf::TypeError do
Chris Fallin's avatar
Chris Fallin committed
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
        m = TestMessage.new
        l.push m
      end

      m = TestMessage.new
      m.repeated_int32 = l
      assert m.repeated_int32 == [5, 2, 3, 4, 7, 8]
      assert m.repeated_int32.object_id == l.object_id
      l.push 42
      assert m.repeated_int32.pop == 42

      l3 = l + l.dup
      assert l3.count == l.count * 2
      l.count.times do |i|
        assert l3[i] == l[i]
        assert l3[l.count + i] == l[i]
      end

      l.clear
      assert l.count == 0
      l += [1, 2, 3, 4]
      l.replace([5, 6, 7, 8])
      assert l == [5, 6, 7, 8]

      l4 = Google::Protobuf::RepeatedField.new(:int32)
      l4[5] = 42
      assert l4 == [0, 0, 0, 0, 0, 42]

      l4 << 100
      assert l4 == [0, 0, 0, 0, 0, 42, 100]
      l4 << 101 << 102
      assert l4 == [0, 0, 0, 0, 0, 42, 100, 101, 102]
    end

427 428 429 430 431 432 433 434 435 436 437
    def test_parent_rptfield
      #make sure we set the RepeatedField and can add to it
      m = TestMessage.new
      assert m.repeated_string == []
      m.repeated_string << 'ok'
      m.repeated_string.push('ok2')
      assert m.repeated_string == ['ok', 'ok2']
      m.repeated_string += ['ok3']
      assert m.repeated_string == ['ok', 'ok2', 'ok3']
    end

Chris Fallin's avatar
Chris Fallin committed
438 439 440 441
    def test_rptfield_msg
      l = Google::Protobuf::RepeatedField.new(:message, TestMessage)
      l.push TestMessage.new
      assert l.count == 1
442
      assert_raise Google::Protobuf::TypeError do
Chris Fallin's avatar
Chris Fallin committed
443 444
        l.push TestMessage2.new
      end
445
      assert_raise Google::Protobuf::TypeError do
Chris Fallin's avatar
Chris Fallin committed
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
        l.push 42
      end

      l2 = l.dup
      assert l2[0] == l[0]
      assert l2[0].object_id == l[0].object_id

      l2 = Google::Protobuf.deep_copy(l)
      assert l2[0] == l[0]
      assert l2[0].object_id != l[0].object_id

      l3 = l + l2
      assert l3.count == 2
      assert l3[0] == l[0]
      assert l3[1] == l2[0]
      l3[0].optional_int32 = 1000
      assert l[0].optional_int32 == 1000

      new_msg = TestMessage.new(:optional_int32 => 200)
      l4 = l + [new_msg]
      assert l4.count == 2
      new_msg.optional_int32 = 1000
      assert l4[1].optional_int32 == 1000
    end

    def test_rptfield_enum
      l = Google::Protobuf::RepeatedField.new(:enum, TestEnum)
      l.push :A
      l.push :B
      l.push :C
      assert l.count == 3
477
      assert_raise RangeError do
Chris Fallin's avatar
Chris Fallin committed
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
        l.push :D
      end
      assert l[0] == :A

      l.push 4
      assert l[3] == 4
    end

    def test_rptfield_initialize
      assert_raise ArgumentError do
        l = Google::Protobuf::RepeatedField.new
      end
      assert_raise ArgumentError do
        l = Google::Protobuf::RepeatedField.new(:message)
      end
      assert_raise ArgumentError do
        l = Google::Protobuf::RepeatedField.new([1, 2, 3])
      end
      assert_raise ArgumentError do
        l = Google::Protobuf::RepeatedField.new(:message, [TestMessage2.new])
      end
    end

501 502 503 504 505 506
    def test_rptfield_array_ducktyping
      l = Google::Protobuf::RepeatedField.new(:int32)
      length_methods = %w(count length size)
      length_methods.each do |lm|
        assert l.send(lm)  == 0
      end
507 508 509 510
      # out of bounds returns a nil
      assert l[0] == nil
      assert l[1] == nil
      assert l[-1] == nil
511 512
      l.push 4
      length_methods.each do |lm|
513 514 515 516 517 518 519 520 521 522
        assert l.send(lm) == 1
      end
      assert l[0] == 4
      assert l[1] == nil
      assert l[-1] == 4
      assert l[-2] == nil

      l.push 2
      length_methods.each do |lm|
        assert l.send(lm) == 2
523
      end
524 525 526 527 528 529 530 531
      assert l[0] == 4
      assert l[1] == 2
      assert l[2] == nil
      assert l[-1] == 2
      assert l[-2] == 4
      assert l[-3] == nil

      #adding out of scope will backfill with empty objects
532 533
    end

534 535 536 537 538 539 540 541 542 543 544 545 546 547
    def test_map_basic
      # allowed key types:
      # :int32, :int64, :uint32, :uint64, :bool, :string, :bytes.

      m = Google::Protobuf::Map.new(:string, :int32)
      m["asdf"] = 1
      assert m["asdf"] == 1
      m["jkl;"] = 42
      assert m == { "jkl;" => 42, "asdf" => 1 }
      assert m.has_key?("asdf")
      assert !m.has_key?("qwerty")
      assert m.length == 2

      m2 = m.dup
548
      assert_equal m, m2
549
      assert m.hash != 0
550
      assert_equal m.hash, m2.hash
551 552 553 554 555 556 557 558 559 560 561 562 563

      collected = {}
      m.each { |k,v| collected[v] = k }
      assert collected == { 42 => "jkl;", 1 => "asdf" }

      assert m.delete("asdf") == 1
      assert !m.has_key?("asdf")
      assert m["asdf"] == nil
      assert !m.has_key?("asdf")

      # We only assert on inspect value when there is one map entry because the
      # order in which elements appear is unspecified (depends on the internal
      # hash function). We don't want a brittle test.
564
      assert m.inspect == "{\"jkl;\"=>42}"
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593

      assert m.keys == ["jkl;"]
      assert m.values == [42]

      m.clear
      assert m.length == 0
      assert m == {}

      assert_raise TypeError do
        m[1] = 1
      end
      assert_raise RangeError do
        m["asdf"] = 0x1_0000_0000
      end
    end

    def test_map_ctor
      m = Google::Protobuf::Map.new(:string, :int32,
                                    {"a" => 1, "b" => 2, "c" => 3})
      assert m == {"a" => 1, "c" => 3, "b" => 2}
    end

    def test_map_keytypes
      m = Google::Protobuf::Map.new(:int32, :int32)
      m[1] = 42
      m[-1] = 42
      assert_raise RangeError do
        m[0x8000_0000] = 1
      end
594
      assert_raise Google::Protobuf::TypeError do
595 596 597 598 599 600 601 602
        m["asdf"] = 1
      end

      m = Google::Protobuf::Map.new(:int64, :int32)
      m[0x1000_0000_0000_0000] = 1
      assert_raise RangeError do
        m[0x1_0000_0000_0000_0000] = 1
      end
603
      assert_raise Google::Protobuf::TypeError do
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
        m["asdf"] = 1
      end

      m = Google::Protobuf::Map.new(:uint32, :int32)
      m[0x8000_0000] = 1
      assert_raise RangeError do
        m[0x1_0000_0000] = 1
      end
      assert_raise RangeError do
        m[-1] = 1
      end

      m = Google::Protobuf::Map.new(:uint64, :int32)
      m[0x8000_0000_0000_0000] = 1
      assert_raise RangeError do
        m[0x1_0000_0000_0000_0000] = 1
      end
      assert_raise RangeError do
        m[-1] = 1
      end

      m = Google::Protobuf::Map.new(:bool, :int32)
      m[true] = 1
      m[false] = 2
628
      assert_raise Google::Protobuf::TypeError do
629 630
        m[1] = 1
      end
631
      assert_raise Google::Protobuf::TypeError do
632 633 634 635 636 637 638 639
        m["asdf"] = 1
      end

      m = Google::Protobuf::Map.new(:string, :int32)
      m["asdf"] = 1
      assert_raise TypeError do
        m[1] = 1
      end
640
      assert_raise Encoding::UndefinedConversionError do
641 642 643 644 645 646 647
        bytestring = ["FFFF"].pack("H*")
        m[bytestring] = 1
      end

      m = Google::Protobuf::Map.new(:bytes, :int32)
      bytestring = ["FFFF"].pack("H*")
      m[bytestring] = 1
648 649
      # Allowed -- we will automatically convert to ASCII-8BIT.
      m["asdf"] = 1
650 651 652 653 654 655 656 657
      assert_raise TypeError do
        m[1] = 1
      end
    end

    def test_map_msg_enum_valuetypes
      m = Google::Protobuf::Map.new(:string, :message, TestMessage)
      m["asdf"] = TestMessage.new
658
      assert_raise Google::Protobuf::TypeError do
659 660 661
        m["jkl;"] = TestMessage2.new
      end

Chris Fallin's avatar
Chris Fallin committed
662 663 664 665
      m = Google::Protobuf::Map.new(
        :string, :message, TestMessage,
        { "a" => TestMessage.new(:optional_int32 => 42),
          "b" => TestMessage.new(:optional_int32 => 84) })
666 667 668 669 670 671 672 673 674 675 676 677 678 679
      assert m.length == 2
      assert m.values.map{|msg| msg.optional_int32}.sort == [42, 84]

      m = Google::Protobuf::Map.new(:string, :enum, TestEnum,
                                    { "x" => :A, "y" => :B, "z" => :C })
      assert m.length == 3
      assert m["z"] == :C
      m["z"] = 2
      assert m["z"] == :B
      m["z"] = 4
      assert m["z"] == 4
      assert_raise RangeError do
        m["z"] = :Z
      end
680
      assert_raise RangeError do
681 682 683 684 685
        m["z"] = "z"
      end
    end

    def test_map_dup_deep_copy
Chris Fallin's avatar
Chris Fallin committed
686 687 688 689
      m = Google::Protobuf::Map.new(
        :string, :message, TestMessage,
        { "a" => TestMessage.new(:optional_int32 => 42),
          "b" => TestMessage.new(:optional_int32 => 84) })
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708

      m2 = m.dup
      assert m == m2
      assert m.object_id != m2.object_id
      assert m["a"].object_id == m2["a"].object_id
      assert m["b"].object_id == m2["b"].object_id

      m2 = Google::Protobuf.deep_copy(m)
      assert m == m2
      assert m.object_id != m2.object_id
      assert m["a"].object_id != m2["a"].object_id
      assert m["b"].object_id != m2["b"].object_id
    end

    def test_map_field
      m = MapMessage.new
      assert m.map_string_int32 == {}
      assert m.map_string_msg == {}

Chris Fallin's avatar
Chris Fallin committed
709 710 711 712
      m = MapMessage.new(
        :map_string_int32 => {"a" => 1, "b" => 2},
        :map_string_msg => {"a" => TestMessage2.new(:foo => 1),
                            "b" => TestMessage2.new(:foo => 2)})
713 714 715 716 717 718 719 720 721 722 723 724
      assert m.map_string_int32.keys.sort == ["a", "b"]
      assert m.map_string_int32["a"] == 1
      assert m.map_string_msg["b"].foo == 2

      m.map_string_int32["c"] = 3
      assert m.map_string_int32["c"] == 3
      m.map_string_msg["c"] = TestMessage2.new(:foo => 3)
      assert m.map_string_msg["c"] == TestMessage2.new(:foo => 3)
      m.map_string_msg.delete("b")
      m.map_string_msg.delete("c")
      assert m.map_string_msg == { "a" => TestMessage2.new(:foo => 1) }

725
      assert_raise Google::Protobuf::TypeError do
726 727 728 729 730 731
        m.map_string_msg["e"] = TestMessage.new # wrong value type
      end
      # ensure nothing was added by the above
      assert m.map_string_msg == { "a" => TestMessage2.new(:foo => 1) }

      m.map_string_int32 = Google::Protobuf::Map.new(:string, :int32)
732
      assert_raise Google::Protobuf::TypeError do
733 734
        m.map_string_int32 = Google::Protobuf::Map.new(:string, :int64)
      end
735
      assert_raise Google::Protobuf::TypeError do
736 737 738 739 740 741 742 743
        m.map_string_int32 = {}
      end

      assert_raise TypeError do
        m = MapMessage.new(:map_string_int32 => { 1 => "I am not a number" })
      end
    end

744 745 746 747 748 749 750
    def test_map_corruption
      # This pattern led to a crash in a previous version of upb/protobuf.
      m = MapMessage.new(map_string_int32: { "aaa" => 1 })
      m.map_string_int32['podid'] = 2
      m.map_string_int32['aaa'] = 3
    end

751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
    def test_concurrent_decoding
      o = Outer.new
      o.items[0] = Inner.new
      raw = Outer.encode(o)

      thds = 2.times.map do
        Thread.new do
          100000.times do
            assert_equal o, Outer.decode(raw)
          end
        end
      end
      thds.map(&:join)
    end

766
    def test_map_encode_decode
Chris Fallin's avatar
Chris Fallin committed
767 768 769 770
      m = MapMessage.new(
        :map_string_int32 => {"a" => 1, "b" => 2},
        :map_string_msg => {"a" => TestMessage2.new(:foo => 1),
                            "b" => TestMessage2.new(:foo => 2)})
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
      m2 = MapMessage.decode(MapMessage.encode(m))
      assert m == m2

      m3 = MapMessageWireEquiv.decode(MapMessage.encode(m))
      assert m3.map_string_int32.length == 2

      kv = {}
      m3.map_string_int32.map { |msg| kv[msg.key] = msg.value }
      assert kv == {"a" => 1, "b" => 2}

      kv = {}
      m3.map_string_msg.map { |msg| kv[msg.key] = msg.value }
      assert kv == {"a" => TestMessage2.new(:foo => 1),
                    "b" => TestMessage2.new(:foo => 2)}
    end

787 788 789 790 791 792
    def test_oneof_descriptors
      d = OneofMessage.descriptor
      o = d.lookup_oneof("my_oneof")
      assert o != nil
      assert o.class == Google::Protobuf::OneofDescriptor
      assert o.name == "my_oneof"
793 794 795 796 797 798
      oneof_count = 0
      d.each_oneof{ |oneof|
        oneof_count += 1
        assert oneof == o
      }
      assert oneof_count == 1
799 800 801 802 803 804 805
      assert o.count == 4
      field_names = o.map{|f| f.name}.sort
      assert field_names == ["a", "b", "c", "d"]
    end

    def test_oneof
      d = OneofMessage.new
806 807
      assert d.a == ""
      assert d.b == 0
808
      assert d.c == nil
809
      assert d.d == :Default
810
      assert d.my_oneof == nil
811 812 813

      d.a = "hi"
      assert d.a == "hi"
814
      assert d.b == 0
815
      assert d.c == nil
816
      assert d.d == :Default
817
      assert d.my_oneof == :a
818 819

      d.b = 42
820
      assert d.a == ""
821 822
      assert d.b == 42
      assert d.c == nil
823
      assert d.d == :Default
824
      assert d.my_oneof == :b
825 826

      d.c = TestMessage2.new(:foo => 100)
827 828
      assert d.a == ""
      assert d.b == 0
829
      assert d.c.foo == 100
830
      assert d.d == :Default
831
      assert d.my_oneof == :c
832 833

      d.d = :C
834 835
      assert d.a == ""
      assert d.b == 0
836 837
      assert d.c == nil
      assert d.d == :C
838
      assert d.my_oneof == :d
839 840 841 842 843 844 845 846 847 848 849 850

      d2 = OneofMessage.decode(OneofMessage.encode(d))
      assert d2 == d

      encoded_field_a = OneofMessage.encode(OneofMessage.new(:a => "string"))
      encoded_field_b = OneofMessage.encode(OneofMessage.new(:b => 1000))
      encoded_field_c = OneofMessage.encode(
        OneofMessage.new(:c => TestMessage2.new(:foo => 1)))
      encoded_field_d = OneofMessage.encode(OneofMessage.new(:d => :B))

      d3 = OneofMessage.decode(
        encoded_field_c + encoded_field_a + encoded_field_d)
851 852
      assert d3.a == ""
      assert d3.b == 0
853 854 855 856 857 858
      assert d3.c == nil
      assert d3.d == :B

      d4 = OneofMessage.decode(
        encoded_field_c + encoded_field_a + encoded_field_d +
        encoded_field_c)
859 860
      assert d4.a == ""
      assert d4.b == 0
861
      assert d4.c.foo == 1
862
      assert d4.d == :Default
863 864

      d5 = OneofMessage.new(:a => "hello")
865
      assert d5.a == "hello"
866
      d5.a = nil
867
      assert d5.a == ""
868
      assert OneofMessage.encode(d5) == ''
869
      assert d5.my_oneof == nil
870 871
    end

Chris Fallin's avatar
Chris Fallin committed
872 873 874 875 876
    def test_enum_field
      m = TestMessage.new
      assert m.optional_enum == :Default
      m.optional_enum = :A
      assert m.optional_enum == :A
877
      assert_raise RangeError do
Chris Fallin's avatar
Chris Fallin committed
878 879 880 881 882 883 884 885 886 887 888 889
        m.optional_enum = :ASDF
      end
      m.optional_enum = 1
      assert m.optional_enum == :A
      m.optional_enum = 100
      assert m.optional_enum == 100
    end

    def test_dup
      m = TestMessage.new
      m.optional_string = "hello"
      m.optional_int32 = 42
890 891 892 893 894 895
      tm1 = TestMessage2.new(:foo => 100)
      tm2 = TestMessage2.new(:foo => 200)
      m.repeated_msg.push tm1
      assert m.repeated_msg[-1] == tm1
      m.repeated_msg.push tm2
      assert m.repeated_msg[-1] == tm2
Chris Fallin's avatar
Chris Fallin committed
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
      m2 = m.dup
      assert m == m2
      m.optional_int32 += 1
      assert m != m2
      assert m.repeated_msg[0] == m2.repeated_msg[0]
      assert m.repeated_msg[0].object_id == m2.repeated_msg[0].object_id
    end

    def test_deep_copy
      m = TestMessage.new(:optional_int32 => 42,
                          :repeated_msg => [TestMessage2.new(:foo => 100)])
      m2 = Google::Protobuf.deep_copy(m)
      assert m == m2
      assert m.repeated_msg == m2.repeated_msg
      assert m.repeated_msg.object_id != m2.repeated_msg.object_id
      assert m.repeated_msg[0].object_id != m2.repeated_msg[0].object_id
    end

914 915 916 917 918 919 920 921
    def test_eq
      m = TestMessage.new(:optional_int32 => 42,
                          :repeated_int32 => [1, 2, 3])
      m2 = TestMessage.new(:optional_int32 => 43,
                           :repeated_int32 => [1, 2, 3])
      assert m != m2
    end

Chris Fallin's avatar
Chris Fallin committed
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
    def test_enum_lookup
      assert TestEnum::A == 1
      assert TestEnum::B == 2
      assert TestEnum::C == 3

      assert TestEnum::lookup(1) == :A
      assert TestEnum::lookup(2) == :B
      assert TestEnum::lookup(3) == :C

      assert TestEnum::resolve(:A) == 1
      assert TestEnum::resolve(:B) == 2
      assert TestEnum::resolve(:C) == 3
    end

    def test_parse_serialize
      m = TestMessage.new(:optional_int32 => 42,
                          :optional_string => "hello world",
                          :optional_enum => :B,
                          :repeated_string => ["a", "b", "c"],
                          :repeated_int32 => [42, 43, 44],
                          :repeated_enum => [:A, :B, :C, 100],
Chris Fallin's avatar
Chris Fallin committed
943 944
                          :repeated_msg => [TestMessage2.new(:foo => 1),
                                            TestMessage2.new(:foo => 2)])
Chris Fallin's avatar
Chris Fallin committed
945 946 947 948 949 950 951 952 953
      data = TestMessage.encode m
      m2 = TestMessage.decode data
      assert m == m2

      data = Google::Protobuf.encode m
      m2 = Google::Protobuf.decode(TestMessage, data)
      assert m == m2
    end

954 955
    def test_encode_decode_helpers
      m = TestMessage.new(:optional_string => 'foo', :repeated_string => ['bar1', 'bar2'])
956 957 958
      assert_equal 'foo', m.optional_string
      assert_equal ['bar1', 'bar2'], m.repeated_string

959 960
      json = m.to_json
      m2 = TestMessage.decode_json(json)
961 962
      assert_equal 'foo', m2.optional_string
      assert_equal ['bar1', 'bar2'], m2.repeated_string
963 964 965 966
      if RUBY_PLATFORM != "java"
        assert m2.optional_string.frozen?
        assert m2.repeated_string[0].frozen?
      end
967 968 969

      proto = m.to_proto
      m2 = TestMessage.decode(proto)
970 971
      assert_equal 'foo', m2.optional_string
      assert_equal ['bar1', 'bar2'], m2.repeated_string
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
    end

    def test_protobuf_encode_decode_helpers
      m = TestMessage.new(:optional_string => 'foo', :repeated_string => ['bar1', 'bar2'])
      encoded_msg = Google::Protobuf.encode(m)
      assert_equal m.to_proto, encoded_msg

      decoded_msg = Google::Protobuf.decode(TestMessage, encoded_msg)
      assert_equal TestMessage.decode(m.to_proto), decoded_msg
    end

    def test_protobuf_encode_decode_json_helpers
      m = TestMessage.new(:optional_string => 'foo', :repeated_string => ['bar1', 'bar2'])
      encoded_msg = Google::Protobuf.encode_json(m)
      assert_equal m.to_json, encoded_msg

      decoded_msg = Google::Protobuf.decode_json(TestMessage, encoded_msg)
      assert_equal TestMessage.decode_json(m.to_json), decoded_msg
    end

    def test_to_h
993
      m = TestMessage.new(:optional_bool => true, :optional_double => -10.100001, :optional_string => 'foo', :repeated_string => ['bar1', 'bar2'], :repeated_msg => [TestMessage2.new(:foo => 100)])
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
      expected_result = {
        :optional_bool=>true,
        :optional_bytes=>"",
        :optional_double=>-10.100001,
        :optional_enum=>:Default,
        :optional_float=>0.0,
        :optional_int32=>0,
        :optional_int64=>0,
        :optional_msg=>nil,
        :optional_string=>"foo",
        :optional_uint32=>0,
        :optional_uint64=>0,
        :repeated_bool=>[],
        :repeated_bytes=>[],
        :repeated_double=>[],
        :repeated_enum=>[],
        :repeated_float=>[],
        :repeated_int32=>[],
        :repeated_int64=>[],
1013
        :repeated_msg=>[{:foo => 100}],
1014 1015 1016 1017 1018
        :repeated_string=>["bar1", "bar2"],
        :repeated_uint32=>[],
        :repeated_uint64=>[]
      }
      assert_equal expected_result, m.to_h
1019 1020 1021 1022 1023 1024

      m = MapMessage.new(
        :map_string_int32 => {"a" => 1, "b" => 2},
        :map_string_msg => {"a" => TestMessage2.new(:foo => 1),
                            "b" => TestMessage2.new(:foo => 2)})
      expected_result = {
1025 1026
        :map_string_int32 => {"a" => 1, "b" => 2},
        :map_string_msg => {"a" => {:foo => 1}, "b" => {:foo => 2}}
1027 1028
      }
      assert_equal expected_result, m.to_h
1029 1030 1031
    end


Chris Fallin's avatar
Chris Fallin committed
1032 1033
    def test_def_errors
      s = Google::Protobuf::DescriptorPool.new
1034
      assert_raise Google::Protobuf::TypeError do
Chris Fallin's avatar
Chris Fallin committed
1035 1036 1037 1038 1039 1040 1041
        s.build do
          # enum with no default (integer value 0)
          add_enum "MyEnum" do
            value :A, 1
          end
        end
      end
1042
      assert_raise Google::Protobuf::TypeError do
Chris Fallin's avatar
Chris Fallin committed
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
        s.build do
          # message with required field (unsupported in proto3)
          add_message "MyMessage" do
            required :foo, :int32, 1
          end
        end
      end
    end

    def test_corecursive
      # just be sure that we can instantiate types with corecursive field-type
      # references.
      m = Recursive1.new(:foo => Recursive2.new(:foo => Recursive1.new))
      assert Recursive1.descriptor.lookup("foo").subtype ==
        Recursive2.descriptor
      assert Recursive2.descriptor.lookup("foo").subtype ==
        Recursive1.descriptor

      serialized = Recursive1.encode(m)
      m2 = Recursive1.decode(serialized)
      assert m == m2
    end

    def test_serialize_cycle
      m = Recursive1.new(:foo => Recursive2.new)
      m.foo.foo = m
      assert_raise RuntimeError do
        serialized = Recursive1.encode(m)
      end
    end

    def test_bad_field_names
      m = BadFieldNames.new(:dup => 1, :class => 2)
      m2 = m.dup
      assert m == m2
      assert m['dup'] == 1
      assert m['class'] == 2
      m['dup'] = 3
      assert m['dup'] == 3
      m['a.b'] = 4
      assert m['a.b'] == 4
    end

    def test_int_ranges
      m = TestMessage.new

      m.optional_int32 = 0
      m.optional_int32 = -0x8000_0000
      m.optional_int32 = +0x7fff_ffff
      m.optional_int32 = 1.0
      m.optional_int32 = -1.0
      m.optional_int32 = 2e9
      assert_raise RangeError do
        m.optional_int32 = -0x8000_0001
      end
      assert_raise RangeError do
        m.optional_int32 = +0x8000_0000
      end
      assert_raise RangeError do
        m.optional_int32 = +0x1000_0000_0000_0000_0000_0000 # force Bignum
      end
      assert_raise RangeError do
        m.optional_int32 = 1e12
      end
      assert_raise RangeError do
        m.optional_int32 = 1.5
      end

      m.optional_uint32 = 0
      m.optional_uint32 = +0xffff_ffff
      m.optional_uint32 = 1.0
      m.optional_uint32 = 4e9
      assert_raise RangeError do
        m.optional_uint32 = -1
      end
      assert_raise RangeError do
        m.optional_uint32 = -1.5
      end
      assert_raise RangeError do
        m.optional_uint32 = -1.5e12
      end
      assert_raise RangeError do
        m.optional_uint32 = -0x1000_0000_0000_0000
      end
      assert_raise RangeError do
        m.optional_uint32 = +0x1_0000_0000
      end
      assert_raise RangeError do
        m.optional_uint32 = +0x1000_0000_0000_0000_0000_0000 # force Bignum
      end
      assert_raise RangeError do
        m.optional_uint32 = 1e12
      end
      assert_raise RangeError do
        m.optional_uint32 = 1.5
      end

      m.optional_int64 = 0
      m.optional_int64 = -0x8000_0000_0000_0000
      m.optional_int64 = +0x7fff_ffff_ffff_ffff
      m.optional_int64 = 1.0
      m.optional_int64 = -1.0
      m.optional_int64 = 8e18
      m.optional_int64 = -8e18
      assert_raise RangeError do
        m.optional_int64 = -0x8000_0000_0000_0001
      end
      assert_raise RangeError do
        m.optional_int64 = +0x8000_0000_0000_0000
      end
      assert_raise RangeError do
        m.optional_int64 = +0x1000_0000_0000_0000_0000_0000 # force Bignum
      end
      assert_raise RangeError do
        m.optional_int64 = 1e50
      end
      assert_raise RangeError do
        m.optional_int64 = 1.5
      end

      m.optional_uint64 = 0
      m.optional_uint64 = +0xffff_ffff_ffff_ffff
      m.optional_uint64 = 1.0
      m.optional_uint64 = 16e18
      assert_raise RangeError do
        m.optional_uint64 = -1
      end
      assert_raise RangeError do
        m.optional_uint64 = -1.5
      end
      assert_raise RangeError do
        m.optional_uint64 = -1.5e12
      end
      assert_raise RangeError do
        m.optional_uint64 = -0x1_0000_0000_0000_0000
      end
      assert_raise RangeError do
        m.optional_uint64 = +0x1_0000_0000_0000_0000
      end
      assert_raise RangeError do
        m.optional_uint64 = +0x1000_0000_0000_0000_0000_0000 # force Bignum
      end
      assert_raise RangeError do
        m.optional_uint64 = 1e50
      end
      assert_raise RangeError do
        m.optional_uint64 = 1.5
      end
    end

    def test_stress_test
      m = TestMessage.new
      m.optional_int32 = 42
      m.optional_int64 = 0x100000000
      m.optional_string = "hello world"
      10.times do m.repeated_msg.push TestMessage2.new(:foo => 42) end
      10.times do m.repeated_string.push "hello world" end

      data = TestMessage.encode(m)

      l = 0
      10_000.times do
        m = TestMessage.decode(data)
        data_new = TestMessage.encode(m)
        assert data_new == data
        data = data_new
      end
    end

    def test_reflection
      m = TestMessage.new(:optional_int32 => 1234)
      msgdef = m.class.descriptor
      assert msgdef.class == Google::Protobuf::Descriptor
      assert msgdef.any? {|field| field.name == "optional_int32"}
      optional_int32 = msgdef.lookup "optional_int32"
      assert optional_int32.class == Google::Protobuf::FieldDescriptor
      assert optional_int32 != nil
      assert optional_int32.name == "optional_int32"
      assert optional_int32.type == :int32
      optional_int32.set(m, 5678)
      assert m.optional_int32 == 5678
      m.optional_int32 = 1000
      assert optional_int32.get(m) == 1000

      optional_msg = msgdef.lookup "optional_msg"
      assert optional_msg.subtype == TestMessage2.descriptor

      optional_msg.set(m, optional_msg.subtype.msgclass.new)

      assert msgdef.msgclass == TestMessage

      optional_enum = msgdef.lookup "optional_enum"
      assert optional_enum.subtype == TestEnum.descriptor
      assert optional_enum.subtype.class == Google::Protobuf::EnumDescriptor
      optional_enum.subtype.each do |k, v|
        # set with integer, check resolution to symbolic name
        optional_enum.set(m, v)
        assert optional_enum.get(m) == k
      end
    end

    def test_json
1245 1246
      # TODO: Fix JSON in JRuby version.
      return if RUBY_PLATFORM == "java"
Chris Fallin's avatar
Chris Fallin committed
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
      m = TestMessage.new(:optional_int32 => 1234,
                          :optional_int64 => -0x1_0000_0000,
                          :optional_uint32 => 0x8000_0000,
                          :optional_uint64 => 0xffff_ffff_ffff_ffff,
                          :optional_bool => true,
                          :optional_float => 1.0,
                          :optional_double => -1e100,
                          :optional_string => "Test string",
                          :optional_bytes => ["FFFFFFFF"].pack('H*'),
                          :optional_msg => TestMessage2.new(:foo => 42),
                          :repeated_int32 => [1, 2, 3, 4],
                          :repeated_string => ["a", "b", "c"],
                          :repeated_bool => [true, false, true, false],
                          :repeated_msg => [TestMessage2.new(:foo => 1),
                                            TestMessage2.new(:foo => 2)])

      json_text = TestMessage.encode_json(m)
      m2 = TestMessage.decode_json(json_text)
1265 1266
      puts m.inspect
      puts m2.inspect
Chris Fallin's avatar
Chris Fallin committed
1267
      assert m == m2
1268 1269 1270 1271 1272 1273 1274 1275

      # Crash case from GitHub issue 283.
      bar = Bar.new(msg: "bar")
      baz1 = Baz.new(msg: "baz")
      baz2 = Baz.new(msg: "quux")
      Foo.encode_json(Foo.new)
      Foo.encode_json(Foo.new(bar: bar))
      Foo.encode_json(Foo.new(bar: bar, baz: [baz1, baz2]))
Chris Fallin's avatar
Chris Fallin committed
1276
    end
1277

1278 1279 1280 1281
    def test_json_empty
      assert TestMessage.encode_json(TestMessage.new) == '{}'
    end

1282 1283 1284 1285 1286
    def test_json_emit_defaults
      # TODO: Fix JSON in JRuby version.
      return if RUBY_PLATFORM == "java"
      m = TestMessage.new

1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
      expected = {
        optionalInt32: 0,
        optionalInt64: 0,
        optionalUint32: 0,
        optionalUint64: 0,
        optionalBool: false,
        optionalFloat: 0,
        optionalDouble: 0,
        optionalString: "",
        optionalBytes: "",
        optionalEnum: "Default",
        repeatedInt32: [],
        repeatedInt64: [],
        repeatedUint32: [],
        repeatedUint64: [],
        repeatedBool: [],
        repeatedFloat: [],
        repeatedDouble: [],
        repeatedString: [],
        repeatedBytes: [],
        repeatedMsg: [],
        repeatedEnum: []
      }

      actual = TestMessage.encode_json(m, :emit_defaults => true)
1312

1313
      assert JSON.parse(actual, :symbolize_names => true) == expected
1314 1315 1316 1317 1318 1319 1320
    end

    def test_json_emit_defaults_submsg
      # TODO: Fix JSON in JRuby version.
      return if RUBY_PLATFORM == "java"
      m = TestMessage.new(optional_msg: TestMessage2.new)

1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
      expected = {
        optionalInt32: 0,
        optionalInt64: 0,
        optionalUint32: 0,
        optionalUint64: 0,
        optionalBool: false,
        optionalFloat: 0,
        optionalDouble: 0,
        optionalString: "",
        optionalBytes: "",
        optionalMsg: {foo: 0},
        optionalEnum: "Default",
        repeatedInt32: [],
        repeatedInt64: [],
        repeatedUint32: [],
        repeatedUint64: [],
        repeatedBool: [],
        repeatedFloat: [],
        repeatedDouble: [],
        repeatedString: [],
        repeatedBytes: [],
        repeatedMsg: [],
        repeatedEnum: []
      }

      actual = TestMessage.encode_json(m, :emit_defaults => true)
1347

1348
      assert JSON.parse(actual, :symbolize_names => true) == expected
1349 1350 1351 1352 1353 1354 1355
    end

    def test_json_emit_defaults_repeated_submsg
      # TODO: Fix JSON in JRuby version.
      return if RUBY_PLATFORM == "java"
      m = TestMessage.new(repeated_msg: [TestMessage2.new])

1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
      expected = {
        optionalInt32: 0,
        optionalInt64: 0,
        optionalUint32: 0,
        optionalUint64: 0,
        optionalBool: false,
        optionalFloat: 0,
        optionalDouble: 0,
        optionalString: "",
        optionalBytes: "",
        optionalEnum: "Default",
        repeatedInt32: [],
        repeatedInt64: [],
        repeatedUint32: [],
        repeatedUint64: [],
        repeatedBool: [],
        repeatedFloat: [],
        repeatedDouble: [],
        repeatedString: [],
        repeatedBytes: [],
        repeatedMsg: [{foo: 0}],
        repeatedEnum: []
      }

      actual = TestMessage.encode_json(m, :emit_defaults => true)
1381

1382
      assert JSON.parse(actual, :symbolize_names => true) == expected
1383 1384
    end

1385
    def test_json_maps
1386 1387
      # TODO: Fix JSON in JRuby version.
      return if RUBY_PLATFORM == "java"
1388
      m = MapMessage.new(:map_string_int32 => {"a" => 1})
1389 1390 1391
      expected = {mapStringInt32: {a: 1}, mapStringMsg: {}}
      expected_preserve = {map_string_int32: {a: 1}, map_string_msg: {}}
      assert JSON.parse(MapMessage.encode_json(m), :symbolize_names => true) == expected
1392 1393

      json = MapMessage.encode_json(m, :preserve_proto_fieldnames => true)
1394
      assert JSON.parse(json, :symbolize_names => true) == expected_preserve
1395

1396 1397 1398
      m2 = MapMessage.decode_json(MapMessage.encode_json(m))
      assert m == m2
    end
1399

1400 1401 1402 1403
    def test_json_maps_emit_defaults_submsg
      # TODO: Fix JSON in JRuby version.
      return if RUBY_PLATFORM == "java"
      m = MapMessage.new(:map_string_msg => {"a" => TestMessage2.new})
1404 1405 1406 1407 1408
      expected = {mapStringInt32: {}, mapStringMsg: {a: {foo: 0}}}

      actual = MapMessage.encode_json(m, :emit_defaults => true)

      assert JSON.parse(actual, :symbolize_names => true) == expected
1409 1410
    end

1411
    def test_comparison_with_arbitrary_object
1412
      assert MapMessage.new != nil
1413 1414 1415
    end

    def test_respond_to
1416 1417
      # This test fails with JRuby 1.7.23, likely because of an old JRuby bug.
      return if RUBY_PLATFORM == "java"
1418 1419
      msg = MapMessage.new
      assert msg.respond_to?(:map_string_int32)
1420
      assert !msg.respond_to?(:bacon)
1421
    end
Chris Fallin's avatar
Chris Fallin committed
1422 1423
  end
end