File: packer_spec.rb

package info (click to toggle)
ruby-msgpack 1.8.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 972 kB
  • sloc: ruby: 4,789; ansic: 4,309; java: 1,809; makefile: 4
file content (619 lines) | stat: -rw-r--r-- 18,102 bytes parent folder | download | duplicates (2)
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
# encoding: ascii-8bit
require 'spec/spec_helper'

require 'stringio'
require 'tempfile'
require 'zlib'

if defined?(Encoding)
  Encoding.default_external = 'ASCII-8BIT'
end

describe MessagePack::Packer do
  let :packer do
    MessagePack::Packer.new
  end

  it 'initialize' do
    MessagePack::Packer.new
    MessagePack::Packer.new(nil)
    MessagePack::Packer.new(StringIO.new)
    MessagePack::Packer.new({})
    MessagePack::Packer.new(StringIO.new, {})
  end

  it 'gets IO or object which has #write to write/append data to it' do
    sample_data = {"message" => "morning!", "num" => 1}
    sample_packed = MessagePack.pack(sample_data)

    Tempfile.open("for_io") do |file|
      file.sync = true
      p1 = MessagePack::Packer.new(file)
      p1.write sample_data
      p1.flush

      file.rewind
      expect(file.read).to eql(sample_packed)
      file.unlink
    end

    dio = StringIO.new
    p2 = MessagePack::Packer.new(dio)
    p2.write sample_data
    p2.flush
    dio.rewind
    expect(dio.string).to eql(sample_packed)

    dio = StringIO.new
    writer = Zlib::GzipWriter.new(dio)
    writer.sync = true
    p3 = MessagePack::Packer.new(writer)
    p3.write sample_data
    p3.flush
    writer.flush(Zlib::FINISH)
    writer.close
    dio.rewind
    compressed = dio.string
    str = Zlib::GzipReader.wrap(StringIO.new(compressed)){|gz| gz.read }
    expect(str).to eql(sample_packed)

    class DummyIO
      def initialize
        @buf = "".force_encoding('ASCII-8BIT')
        @pos = 0
      end
      def write(val)
        @buf << val.to_s
      end
      def read(length=nil,outbuf="")
        if @pos == @buf.size
          nil
        elsif length.nil?
          val = @buf[@pos..(@buf.size)]
          @pos = @buf.size
          outbuf << val
          outbuf
        else
          val = @buf[@pos..(@pos + length)]
          @pos += val.size
          @pos = @buf.size if @pos > @buf.size
          outbuf << val
          outbuf
        end
      end
      def flush
        # nop
      end
      def close
        # nop
      end
    end

    dio = DummyIO.new
    p4 = MessagePack::Packer.new(dio)
    p4.write sample_data
    p4.flush
    expect(dio.read).to eql(sample_packed)
  end

  it 'gets options to specify how to pack values' do
    u1 = MessagePack::Packer.new
    u1.compatibility_mode?.should == false

    u2 = MessagePack::Packer.new(compatibility_mode: true)
    u2.compatibility_mode?.should == true
  end

  it 'write' do
    packer.write([])
    packer.to_s.should == "\x90"
  end

  it 'write_nil' do
    packer.write_nil
    packer.to_s.should == "\xc0"
  end

  it 'write_array_header 0' do
    packer.write_array_header(0)
    packer.to_s.should == "\x90"
  end

  it 'write_array_header 1' do
    packer.write_array_header(1)
    packer.to_s.should == "\x91"
  end

  it 'write_map_header 0' do
    packer.write_map_header(0)
    packer.to_s.should == "\x80"
  end

  it 'write_map_header 1' do
    packer.write_map_header(1)
    packer.to_s.should == "\x81"
  end

  it 'write_bin_header 0' do
    packer.write_bin_header(0)
    packer.to_s.should == "\xC4\x00"
  end

  it 'write_bin_header 255' do
    packer.write_bin_header(255)
    packer.to_s.should == "\xC4\xFF"
  end

  it 'write_bin_header 256' do
    packer.write_bin_header(256)
    packer.to_s.should == "\xC5\x01\x00"
  end

  it 'write_bin_header 65535' do
    packer.write_bin_header(65535)
    packer.to_s.should == "\xC5\xFF\xFF"
  end

  it 'write_bin_header 65536' do
    packer.write_bin_header(65536)
    packer.to_s.should == "\xC6\x00\x01\x00\x00"
  end

  it 'write_bin_header 999999' do
    packer.write_bin_header(999999)
    packer.to_s.should == "\xC6\x00\x0F\x42\x3F"
  end

  it 'write_bin' do
    packer.write_bin("hello")
    packer.to_s.should == "\xC4\x05hello"
  end

  describe '#write_float32' do
    tests = [
      ['small floats', 3.14, "\xCA\x40\x48\xF5\xC3"],
      ['big floats', Math::PI * 1_000_000_000_000_000_000, "\xCA\x5E\x2E\x64\xB7"],
      ['negative floats', -2.1, "\xCA\xC0\x06\x66\x66"],
      ['integer', 123, "\xCA\x42\xF6\x00\x00"],
    ]

    tests.each do |ctx, numeric, packed|
      context("with #{ctx}") do
        it("encodes #{numeric} as float32") do
          packer.write_float32(numeric)
          packer.to_s.should == packed
        end
      end
    end

    context 'with non numeric' do
      it 'raises argument error' do
        expect { packer.write_float32('abc') }.to raise_error(ArgumentError)
      end
    end
  end

  it 'flush' do
    io = StringIO.new
    pk = MessagePack::Packer.new(io)
    pk.write_nil
    pk.flush
    pk.to_s.should == ''
    io.string.should == "\xc0"
  end

  it 'to_msgpack returns String' do
    nil.to_msgpack.class.should == String
    true.to_msgpack.class.should == String
    false.to_msgpack.class.should == String
    1.to_msgpack.class.should == String
    1.0.to_msgpack.class.should == String
    "".to_msgpack.class.should == String
    Hash.new.to_msgpack.class.should == String
    Array.new.to_msgpack.class.should == String
  end

  it 'to_msgpack with packer equals to_msgpack' do
    nil.to_msgpack(MessagePack::Packer.new).to_str.should == nil.to_msgpack
    true.to_msgpack(MessagePack::Packer.new).to_str.should == true.to_msgpack
    false.to_msgpack(MessagePack::Packer.new).to_str.should == false.to_msgpack
    1.to_msgpack(MessagePack::Packer.new).to_str.should == 1.to_msgpack
    1.0.to_msgpack(MessagePack::Packer.new).to_str.should == 1.0.to_msgpack
    "".to_msgpack(MessagePack::Packer.new).to_str.should == "".to_msgpack
    Hash.new.to_msgpack(MessagePack::Packer.new).to_str.should == Hash.new.to_msgpack
    Array.new.to_msgpack(MessagePack::Packer.new).to_str.should == Array.new.to_msgpack
  end

  it 'raises type error on wrong type' do
    packer = MessagePack::Packer.new
    expect { packer.write_float "hello" }.to raise_error(TypeError)
    expect { packer.write_string 1 }.to raise_error(TypeError)
    expect { packer.write_bin 1 }.to raise_error(TypeError)
    expect { packer.write_array "hello" }.to raise_error(TypeError)
    expect { packer.write_hash "hello" }.to raise_error(TypeError)
    expect { packer.write_symbol "hello" }.to raise_error(TypeError)
    expect { packer.write_int "hello" }.to raise_error(TypeError)
    expect { packer.write_extension "hello" }.to raise_error(TypeError)
  end

  class CustomPack01
    def to_msgpack(pk=nil)
      return MessagePack.pack(self, pk) unless pk.class == MessagePack::Packer
      pk.write_array_header(2)
      pk.write(1)
      pk.write(2)
      return pk
    end
  end

  class CustomPack02
    def to_msgpack(pk=nil)
      [1,2].to_msgpack(pk)
    end
  end

  it 'calls custom to_msgpack method' do
    MessagePack.pack(CustomPack01.new).should == [1,2].to_msgpack
    MessagePack.pack(CustomPack02.new).should == [1,2].to_msgpack
    CustomPack01.new.to_msgpack.should == [1,2].to_msgpack
    CustomPack02.new.to_msgpack.should == [1,2].to_msgpack
  end

  it 'calls custom to_msgpack method with io' do
    s01 = StringIO.new
    MessagePack.pack(CustomPack01.new, s01)
    s01.string.should == [1,2].to_msgpack

    s02 = StringIO.new
    MessagePack.pack(CustomPack02.new, s02)
    s02.string.should == [1,2].to_msgpack

    s03 = StringIO.new
    CustomPack01.new.to_msgpack(s03)
    s03.string.should == [1,2].to_msgpack

    s04 = StringIO.new
    CustomPack02.new.to_msgpack(s04)
    s04.string.should == [1,2].to_msgpack
  end

  context 'in compatibility mode' do
    it 'does not use the bin types' do
      packed = MessagePack.pack('hello'.force_encoding(Encoding::BINARY), compatibility_mode: true)
      packed.should eq("\xA5hello")
      packed = MessagePack.pack(('hello' * 100).force_encoding(Encoding::BINARY), compatibility_mode: true)
      packed.should start_with("\xDA\x01\xF4")

      packer = MessagePack::Packer.new(compatibility_mode: 1)
      packed = packer.pack(('hello' * 100).force_encoding(Encoding::BINARY))
      packed.to_str.should start_with("\xDA\x01\xF4")
    end

    it 'does not use the str8 type' do
      packed = MessagePack.pack('x' * 32, compatibility_mode: true)
      packed.should start_with("\xDA\x00\x20")
    end
  end

  class ValueOne
    def initialize(num)
      @num = num
    end
    def num
      @num
    end
    def to_msgpack_ext
      @num.to_msgpack
    end
    def self.from_msgpack_ext(data)
      self.new(MessagePack.unpack(data))
    end
  end

  class ValueTwo
    def initialize(num)
      @num_s = num.to_s
    end
    def num
      @num_s.to_i
    end
    def to_msgpack_ext
      @num_s.to_msgpack
    end
    def self.from_msgpack_ext(data)
      self.new(MessagePack.unpack(data))
    end
  end

  describe '#type_registered?' do
    it 'receive Class or Integer, and return bool' do
      expect(subject.type_registered?(0x00)).to be_falsy
      expect(subject.type_registered?(0x01)).to be_falsy
      expect(subject.type_registered?(::ValueOne)).to be_falsy
    end

    it 'returns true if specified type or class is already registered' do
      subject.register_type(0x30, ::ValueOne, :to_msgpack_ext)
      subject.register_type(0x31, ::ValueTwo, :to_msgpack_ext)

      expect(subject.type_registered?(0x00)).to be_falsy
      expect(subject.type_registered?(0x01)).to be_falsy

      expect(subject.type_registered?(0x30)).to be_truthy
      expect(subject.type_registered?(0x31)).to be_truthy
      expect(subject.type_registered?(::ValueOne)).to be_truthy
      expect(subject.type_registered?(::ValueTwo)).to be_truthy
    end
  end

  describe '#register_type' do
    it 'get type and class mapping for packing' do
      packer = MessagePack::Packer.new
      packer.register_type(0x01, ValueOne){|obj| obj.to_msgpack_ext }
      packer.register_type(0x02, ValueTwo){|obj| obj.to_msgpack_ext }

      packer = MessagePack::Packer.new
      packer.register_type(0x01, ValueOne, :to_msgpack_ext)
      packer.register_type(0x02, ValueTwo, :to_msgpack_ext)

      packer = MessagePack::Packer.new
      packer.register_type(0x01, ValueOne, &:to_msgpack_ext)
      packer.register_type(0x02, ValueTwo, &:to_msgpack_ext)
    end

    it 'returns a Hash which contains map of Class and type' do
      packer = MessagePack::Packer.new
      packer.register_type(0x01, ValueOne, :to_msgpack_ext)
      packer.register_type(0x02, ValueTwo, :to_msgpack_ext)

      expect(packer.registered_types).to be_a(Array)
      expect(packer.registered_types.size).to eq(2)

      one = packer.registered_types[0]
      expect(one.keys.sort).to eq([:type, :class, :packer].sort)
      expect(one[:type]).to eq(0x01)
      expect(one[:class]).to eq(ValueOne)
      expect(one[:packer]).to be_a(Proc)

      two = packer.registered_types[1]
      expect(two.keys.sort).to eq([:type, :class, :packer].sort)
      expect(two[:type]).to eq(0x02)
      expect(two[:class]).to eq(ValueTwo)
      expect(two[:packer]).to be_a(Proc)
    end

    context 'when it has no ext type but a super class has' do
      before { stub_const('Value', Class.new) }
      before do
        Value.class_eval do
          def to_msgpack_ext
            'value_msgpacked'
          end
        end
      end
      before { packer.register_type(0x01, Value, :to_msgpack_ext) }

      context "when it is a child class" do
        before { stub_const('InheritedValue', Class.new(Value)) }
        subject { packer.pack(InheritedValue.new).to_s }

        it { is_expected.to eq "\xC7\x0F\x01value_msgpacked" }

        context "when it is a grandchild class" do
          before { stub_const('InheritedTwiceValue', Class.new(InheritedValue)) }
          subject { packer.pack(InheritedTwiceValue.new).to_s }

          it { is_expected.to eq "\xC7\x0F\x01value_msgpacked" }
        end
      end
    end

    context 'when it and its super class has an ext type' do
      before { stub_const('Value', Class.new) }
      before do
        Value.class_eval do
          def to_msgpack_ext
            'value_msgpacked'
          end
        end
      end
      before { packer.register_type(0x01, Value, :to_msgpack_ext) }

      context "when it is a child class" do
        before { stub_const('InheritedValue', Class.new(Value)) }
        before do
          InheritedValue.class_eval do
            def to_msgpack_ext
              'inherited_value_msgpacked'
            end
          end
        end

        before { packer.register_type(0x02, InheritedValue, :to_msgpack_ext) }
        subject { packer.pack(InheritedValue.new).to_s }

        it { is_expected.to eq "\xC7\x19\x02inherited_value_msgpacked" }
      end

      context "even when it is a child class" do
        before { stub_const('InheritedValue', Class.new(Value)) }
        before do
          InheritedValue.class_eval do
            def to_msgpack_ext
              'inherited_value_msgpacked'
            end
          end
        end

        before { packer.register_type(0x02, InheritedValue, :to_msgpack_ext) }
        subject { packer.pack(Value.new).to_s }

        it { is_expected.to eq "\xC7\x0F\x01value_msgpacked" }
      end
    end

    context 'when it has no ext type but an included module has' do
      subject { packer.pack(Value.new).to_s }

      before do
        mod = Module.new do
          def to_msgpack_ext
            'value_msgpacked'
          end
        end
        stub_const('Mod', mod)
      end
      before { packer.register_type(0x01, Mod, :to_msgpack_ext) }

      before { stub_const('Value', Class.new{ include Mod }) }

      it { is_expected.to eq "\xC7\x0F\x01value_msgpacked" }
    end

    context 'when it has no ext type but it was extended by a module which has one' do
      subject { packer.pack(object).to_s }
      let(:object) { Object.new.extend Mod }

      before do
        mod = Module.new do
          def to_msgpack_ext
            'value_msgpacked'
          end
        end
        stub_const('Mod', mod)
      end
      before { packer.register_type(0x01, Mod, :to_msgpack_ext) }


      it { is_expected.to eq "\xC7\x0F\x01value_msgpacked" }
    end

    shared_examples_for 'extension subclasses core type' do |klass|
      before { stub_const('Value', Class.new(klass)) }
      let(:object) { Value.new }
      subject { packer.pack(object).to_s }

      it "defaults to #{klass.name} packer if no extension is present" do
        expect(subject).to eq(MessagePack.dump(klass.new))
      end

      it "uses core type extension for #{klass.name}" do
        packer.register_type(0x01, Value, ->(_) { 'value_msgpacked' })
        expect(subject).to eq("\xC7\x0F\x01value_msgpacked")
      end
    end
    it_behaves_like 'extension subclasses core type', Hash
    it_behaves_like 'extension subclasses core type', Array
    it_behaves_like 'extension subclasses core type', String

    context 'when registering a type for symbols' do
      before { packer.register_type(0x00, ::Symbol, :to_msgpack_ext) }

      it 'packs symbols in an ext type' do
        expect(packer.pack(:symbol).to_s).to eq "\xc7\x06\x00symbol"
      end
    end
  end

  describe "fixnum and bignum" do
    it "fixnum.to_msgpack" do
      23.to_msgpack.should == "\x17"
    end

    it "fixnum.to_msgpack(packer)" do
      23.to_msgpack(packer)
      packer.to_s.should == "\x17"
    end

    it "bignum.to_msgpack" do
      -4294967296.to_msgpack.should == "\xD3\xFF\xFF\xFF\xFF\x00\x00\x00\x00"
    end

    it "bignum.to_msgpack(packer)" do
      -4294967296.to_msgpack(packer)
      packer.to_s.should == "\xD3\xFF\xFF\xFF\xFF\x00\x00\x00\x00"
    end

    it "unpack(fixnum)" do
      MessagePack.unpack("\x17").should == 23
    end

    it "unpack(bignum)" do
      MessagePack.unpack("\xD3\xFF\xFF\xFF\xFF\x00\x00\x00\x00").should == -4294967296
    end
  end

  describe "ext formats" do
    [1, 2, 4, 8, 16].zip([0xd4, 0xd5, 0xd6, 0xd7, 0xd8]).each do |n,b|
      it "msgpack fixext #{n} format" do
        MessagePack::ExtensionValue.new(1, "a"*n).to_msgpack.should ==
          [b, 1].pack('CC') + "a"*n
      end
    end

    it "msgpack ext 8 format" do
      MessagePack::ExtensionValue.new(1, "").to_msgpack.should ==
        [0xc7, 0, 1].pack('CCC') + ""
      MessagePack::ExtensionValue.new(-1, "a"*255).to_msgpack.should ==
        [0xc7, 255, -1].pack('CCC') + "a"*255
    end

    it "msgpack ext 16 format" do
      MessagePack::ExtensionValue.new(1, "a"*256).to_msgpack.should ==
        [0xc8, 256, 1].pack('CnC') + "a"*256
      MessagePack::ExtensionValue.new(-1, "a"*65535).to_msgpack.should ==
        [0xc8, 65535, -1].pack('CnC') + "a"*65535
    end

    it "msgpack ext 32 format" do
      MessagePack::ExtensionValue.new(1, "a"*65536).to_msgpack.should ==
        [0xc9, 65536, 1].pack('CNC') + "a"*65536
      MessagePack::ExtensionValue.new(-1, "a"*65538).to_msgpack.should ==
        [0xc9, 65538, -1].pack('CNC') + "a"*65538
    end
  end

  it "doesn't allow #dup or #clone" do
    expect(subject).to_not respond_to :dup
    expect(subject).to_not respond_to :clone
  end

  it "doesn't crash when marking an uninitialized buffer" do
    stress = GC.stress
    begin
      GC.stress = true

      MessagePack::Packer.new.buffer
      Object.new
    ensure
      GC.stress = stress
    end
  end

  it "doesn't crash when using recursive packers concurrently" do
    hash_with_indifferent_access = Class.new(Hash)
    msgpack = MessagePack::Factory.new
    msgpack.register_type(
      0x02,
      hash_with_indifferent_access,
      packer: ->(value, packer) do
        packer.write("a".b * 600_0000) # Over MSGPACK_BUFFER_STRING_WRITE_REFERENCE_DEFAULT
        packer.write(value.to_h)
        GC.start(full_mark: true, immediate_mark: true, immediate_sweep: true)
      end,
      unpacker: ->(unpacker) { hash_with_indifferent_access.new(unpacker.read) },
      recursive: true
    )

    packer = msgpack.packer

    top_hash = hash = hash_with_indifferent_access.new
    10.times do
      hash["a"] = new_hash = hash_with_indifferent_access.new
      hash = new_hash
    end
    packer.write(top_hash)
    packer.write(top_hash)
    packer.full_pack
  end
end