summaryrefslogtreecommitdiff
path: root/spec/ruby/core/string/shared/encode.rb
blob: 9466308886ee9d11691c857dc40a8daecb1adf41 (plain)
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
# -*- encoding: utf-8 -*-
# frozen_string_literal: false
describe :string_encode, shared: true do
  describe "when passed no options" do
    it "transcodes to Encoding.default_internal when set" do
      Encoding.default_internal = Encoding::UTF_8
      str = [0xA4, 0xA2].pack('CC').force_encoding Encoding::EUC_JP
      str.send(@method).should == "あ"
    end

    it "transcodes a 7-bit String despite no generic converting being available" do
      -> do
        Encoding::Converter.new Encoding::Emacs_Mule, Encoding::BINARY
      end.should raise_error(Encoding::ConverterNotFoundError)

      Encoding.default_internal = Encoding::Emacs_Mule
      str = "\x79".force_encoding Encoding::BINARY

      str.send(@method).should == "y".force_encoding(Encoding::BINARY)
    end

    it "raises an Encoding::ConverterNotFoundError when no conversion is possible" do
      Encoding.default_internal = Encoding::Emacs_Mule
      str = [0x80].pack('C').force_encoding Encoding::BINARY
      -> { str.send(@method) }.should raise_error(Encoding::ConverterNotFoundError)
    end
  end

  describe "when passed to encoding" do
    it "accepts a String argument" do
      str = [0xA4, 0xA2].pack('CC').force_encoding Encoding::EUC_JP
      str.send(@method, "utf-8").should == "あ"
    end

    it "calls #to_str to convert the object to an Encoding" do
      enc = mock("string encode encoding")
      enc.should_receive(:to_str).and_return("utf-8")

      str = [0xA4, 0xA2].pack('CC').force_encoding Encoding::EUC_JP
      str.send(@method, enc).should == "あ"
    end

    it "transcodes to the passed encoding" do
      str = [0xA4, 0xA2].pack('CC').force_encoding Encoding::EUC_JP
      str.send(@method, Encoding::UTF_8).should == "あ"
    end

    it "transcodes Japanese multibyte characters" do
      str = "あいうえお"
      str.send(@method, Encoding::ISO_2022_JP).should ==
        "\e\x24\x42\x24\x22\x24\x24\x24\x26\x24\x28\x24\x2A\e\x28\x42".force_encoding(Encoding::ISO_2022_JP)
    end

    it "transcodes a 7-bit String despite no generic converting being available" do
      -> do
        Encoding::Converter.new Encoding::Emacs_Mule, Encoding::BINARY
      end.should raise_error(Encoding::ConverterNotFoundError)

      str = "\x79".force_encoding Encoding::BINARY
      str.send(@method, Encoding::Emacs_Mule).should == "y".force_encoding(Encoding::BINARY)
    end

    it "raises an Encoding::ConverterNotFoundError when no conversion is possible" do
      str = [0x80].pack('C').force_encoding Encoding::BINARY
      -> do
        str.send(@method, Encoding::Emacs_Mule)
      end.should raise_error(Encoding::ConverterNotFoundError)
    end

    it "raises an Encoding::ConverterNotFoundError for an invalid encoding" do
      -> do
        "abc".send(@method, "xyz")
      end.should raise_error(Encoding::ConverterNotFoundError)
    end
  end

  describe "when passed options" do
    it "does not process transcoding options if not transcoding" do
      result = "あ\ufffdあ".send(@method, undef: :replace)
      result.should == "あ\ufffdあ"
    end

    it "calls #to_hash to convert the object" do
      options = mock("string encode options")
      options.should_receive(:to_hash).and_return({ undef: :replace })

      result = "あ\ufffdあ".send(@method, **options)
      result.should == "あ\ufffdあ"
    end

    it "transcodes to Encoding.default_internal when set" do
      Encoding.default_internal = Encoding::UTF_8
      str = [0xA4, 0xA2].pack('CC').force_encoding Encoding::EUC_JP
      str.send(@method, invalid: :replace).should == "あ"
    end

    it "raises an Encoding::ConverterNotFoundError when no conversion is possible despite 'invalid: :replace, undef: :replace'" do
      Encoding.default_internal = Encoding::Emacs_Mule
      str = [0x80].pack('C').force_encoding Encoding::BINARY
      -> do
        str.send(@method, invalid: :replace, undef: :replace)
      end.should raise_error(Encoding::ConverterNotFoundError)
    end

    it "replaces invalid characters when replacing Emacs-Mule encoded strings" do
      got = [0x80].pack('C').force_encoding('Emacs-Mule').send(@method, invalid: :replace)

      got.should == "?".encode('Emacs-Mule')
    end
  end

  describe "when passed to, from" do
    it "transcodes between the encodings ignoring the String encoding" do
      str = "あ"
      result = [0xA6, 0xD0, 0x8F, 0xAB, 0xE4, 0x8F, 0xAB, 0xB1].pack('C8')
      result.force_encoding Encoding::EUC_JP
      str.send(@method, "euc-jp", "ibm437").should == result
    end

    it "calls #to_str to convert the from object to an Encoding" do
      enc = mock("string encode encoding")
      enc.should_receive(:to_str).and_return("ibm437")

      str = "あ"
      result = [0xA6, 0xD0, 0x8F, 0xAB, 0xE4, 0x8F, 0xAB, 0xB1].pack('C8')
      result.force_encoding Encoding::EUC_JP

      str.send(@method, "euc-jp", enc).should == result
    end
  end

  describe "when passed to, options" do
    it "replaces undefined characters in the destination encoding" do
      result = "あ?あ".send(@method, Encoding::EUC_JP, undef: :replace)
      # testing for: "\xA4\xA2?\xA4\xA2"
      xA4xA2 = [0xA4, 0xA2].pack('CC')
      result.should == "#{xA4xA2}?#{xA4xA2}".force_encoding("euc-jp")
    end

    it "replaces invalid characters in the destination encoding" do
      xFF = [0xFF].pack('C').force_encoding('utf-8')
      "ab#{xFF}c".send(@method, Encoding::ISO_8859_1, invalid: :replace).should == "ab?c"
    end

    it "calls #to_hash to convert the options object" do
      options = mock("string encode options")
      options.should_receive(:to_hash).and_return({ undef: :replace })

      result = "あ?あ".send(@method, Encoding::EUC_JP, **options)
      xA4xA2 = [0xA4, 0xA2].pack('CC').force_encoding('utf-8')
      result.should == "#{xA4xA2}?#{xA4xA2}".force_encoding("euc-jp")
    end
  end

  describe "when passed to, from, options" do
    it "replaces undefined characters in the destination encoding" do
      str = "あ?あ".force_encoding Encoding::BINARY
      result = str.send(@method, "euc-jp", "utf-8", undef: :replace)
      xA4xA2 = [0xA4, 0xA2].pack('CC').force_encoding('utf-8')
      result.should == "#{xA4xA2}?#{xA4xA2}".force_encoding("euc-jp")
    end

    it "replaces invalid characters in the destination encoding" do
      xFF = [0xFF].pack('C').force_encoding('utf-8')
      str = "ab#{xFF}c".force_encoding Encoding::BINARY
      str.send(@method, "iso-8859-1", "utf-8", invalid: :replace).should == "ab?c"
    end

    it "calls #to_str to convert the to object to an encoding" do
      to = mock("string encode to encoding")
      to.should_receive(:to_str).and_return("iso-8859-1")

      xFF = [0xFF].pack('C').force_encoding('utf-8')
      str = "ab#{xFF}c".force_encoding Encoding::BINARY
      str.send(@method, to, "utf-8", invalid: :replace).should == "ab?c"
    end

    it "calls #to_str to convert the from object to an encoding" do
      from = mock("string encode to encoding")
      from.should_receive(:to_str).and_return("utf-8")

      xFF = [0xFF].pack('C').force_encoding('utf-8')
      str = "ab#{xFF}c".force_encoding Encoding::BINARY
      str.send(@method, "iso-8859-1", from, invalid: :replace).should == "ab?c"
    end

    it "calls #to_hash to convert the options object" do
      options = mock("string encode options")
      options.should_receive(:to_hash).and_return({ invalid: :replace })

      xFF = [0xFF].pack('C').force_encoding('utf-8')
      str = "ab#{xFF}c".force_encoding Encoding::BINARY
      str.send(@method, "iso-8859-1", "utf-8", **options).should == "ab?c"
    end
  end

  describe "given the fallback option" do
    context "given a hash" do
      it "looks up the replacement value from the hash" do
        encoded = "B\ufffd".encode(Encoding::US_ASCII, fallback: { "\ufffd" => "bar" })
        encoded.should == "Bbar"
      end

      it "calls to_str on the returned value" do
        obj = Object.new
        obj.should_receive(:to_str).and_return("bar")
        encoded = "B\ufffd".encode(Encoding::US_ASCII, fallback: { "\ufffd" => obj })
        encoded.should == "Bbar"
      end

      it "does not call to_s on the returned value" do
        obj = Object.new
        obj.should_not_receive(:to_s)
        -> {
          "B\ufffd".encode(Encoding::US_ASCII, fallback: { "\ufffd" => obj })
        }.should raise_error(TypeError, "no implicit conversion of Object into String")
      end

      it "raises an error if the key is not present in the hash" do
        -> {
          "B\ufffd".encode(Encoding::US_ASCII, fallback: { "foo" => "bar" })
        }.should raise_error(Encoding::UndefinedConversionError, "U+FFFD from UTF-8 to US-ASCII")
      end

      it "raises an error if the value is itself invalid" do
        -> {
          "B\ufffd".encode(Encoding::US_ASCII, fallback: { "\ufffd" => "\uffee" })
        }.should raise_error(ArgumentError, "too big fallback string")
      end

      it "uses the hash's default value if set" do
        hash = {}
        hash.default = "bar"
        encoded = "B\ufffd".encode(Encoding::US_ASCII, fallback: hash)
        encoded.should == "Bbar"
      end

      it "uses the result of calling default_proc if set" do
        hash = {}
        hash.default_proc = -> _, _ { "bar" }
        encoded = "B\ufffd".encode(Encoding::US_ASCII, fallback: hash)
        encoded.should == "Bbar"
      end
    end

    context "given an object inheriting from Hash" do
      before do
        klass = Class.new(Hash)
        @hash_like = klass.new
        @hash_like["\ufffd"] = "bar"
      end

      it "looks up the replacement value from the object" do
        encoded = "B\ufffd".encode(Encoding::US_ASCII, fallback: @hash_like)
        encoded.should == "Bbar"
      end
    end

    context "given an object responding to []" do
      before do
        klass = Class.new do
          def [](c) = c.bytes.inspect
        end
        @hash_like = klass.new
      end

      it "calls [] on the object, passing the invalid character" do
        encoded = "B\ufffd".encode(Encoding::US_ASCII, fallback: @hash_like)
        encoded.should == "B[239, 191, 189]"
      end
    end

    context "given an object not responding to []" do
      before do
        @non_hash_like = Object.new
      end

      it "raises an error" do
        -> {
          "B\ufffd".encode(Encoding::US_ASCII, fallback: @non_hash_like)
        }.should raise_error(Encoding::UndefinedConversionError, "U+FFFD from UTF-8 to US-ASCII")
      end
    end

    context "given a proc" do
      it "calls the proc to get the replacement value, passing in the invalid character" do
        encoded = "B\ufffd".encode(Encoding::US_ASCII, fallback: proc { |c| c.bytes.inspect })
        encoded.should == "B[239, 191, 189]"
      end

      it "calls to_str on the returned value" do
        obj = Object.new
        obj.should_receive(:to_str).and_return("bar")
        encoded = "B\ufffd".encode(Encoding::US_ASCII, fallback: proc { |c| obj })
        encoded.should == "Bbar"
      end

      it "does not call to_s on the returned value" do
        obj = Object.new
        obj.should_not_receive(:to_s)
        -> {
          "B\ufffd".encode(Encoding::US_ASCII, fallback: proc { |c| obj })
        }.should raise_error(TypeError, "no implicit conversion of Object into String")
      end

      it "raises an error if the returned value is itself invalid" do
        -> {
          "B\ufffd".encode(Encoding::US_ASCII, fallback: -> c { "\uffee" })
        }.should raise_error(ArgumentError, "too big fallback string")
      end
    end

    context "given a lambda" do
      it "calls the lambda to get the replacement value, passing in the invalid character" do
        encoded = "B\ufffd".encode(Encoding::US_ASCII, fallback: -> c { c.bytes.inspect })
        encoded.should == "B[239, 191, 189]"
      end

      it "calls to_str on the returned value" do
        obj = Object.new
        obj.should_receive(:to_str).and_return("bar")
        encoded = "B\ufffd".encode(Encoding::US_ASCII, fallback: -> c { obj })
        encoded.should == "Bbar"
      end

      it "does not call to_s on the returned value" do
        obj = Object.new
        obj.should_not_receive(:to_s)
        -> {
          "B\ufffd".encode(Encoding::US_ASCII, fallback: -> c { obj })
        }.should raise_error(TypeError, "no implicit conversion of Object into String")
      end

      it "raises an error if the returned value is itself invalid" do
        -> {
          "B\ufffd".encode(Encoding::US_ASCII, fallback: -> c { "\uffee" })
        }.should raise_error(ArgumentError, "too big fallback string")
      end
    end

    context "given a method" do
      def replace(c) = c.bytes.inspect
      def replace_bad(c) = "\uffee"

      def replace_to_str(c)
        obj = Object.new
        obj.should_receive(:to_str).and_return("bar")
        obj
      end

      def replace_to_s(c)
        obj = Object.new
        obj.should_not_receive(:to_s)
        obj
      end

      it "calls the method to get the replacement value, passing in the invalid character" do
        encoded = "B\ufffd".encode(Encoding::US_ASCII, fallback: method(:replace))
        encoded.should == "B[239, 191, 189]"
      end

      it "calls to_str on the returned value" do
        encoded = "B\ufffd".encode(Encoding::US_ASCII, fallback: method(:replace_to_str))
        encoded.should == "Bbar"
      end

      it "does not call to_s on the returned value" do
        -> {
          "B\ufffd".encode(Encoding::US_ASCII, fallback: method(:replace_to_s))
        }.should raise_error(TypeError, "no implicit conversion of Object into String")
      end

      it "raises an error if the returned value is itself invalid" do
        -> {
          "B\ufffd".encode(Encoding::US_ASCII, fallback: method(:replace_bad))
        }.should raise_error(ArgumentError, "too big fallback string")
      end
    end
  end

  describe "given the xml: :text option" do
    it "replaces all instances of '&' with '&'" do
      '& and &'.send(@method, "UTF-8", xml: :text).should == '& and &'
    end

    it "replaces all instances of '<' with '&lt;'" do
      '< and <'.send(@method, "UTF-8", xml: :text).should == '&lt; and &lt;'
    end

    it "replaces all instances of '>' with '&gt;'" do
      '> and >'.send(@method, "UTF-8", xml: :text).should == '&gt; and &gt;'
    end

    it "does not replace '\"'" do
      '" and "'.send(@method, "UTF-8", xml: :text).should == '" and "'
    end

    it "replaces undefined characters with their upper-case hexadecimal numeric character references" do
      'ürst'.send(@method, Encoding::US_ASCII, xml: :text).should == '&#xFC;rst'
    end
  end

  describe "given the xml: :attr option" do
    it "surrounds the encoded text with double-quotes" do
      'abc'.send(@method, "UTF-8", xml: :attr).should == '"abc"'
    end

    it "replaces all instances of '&' with '&amp;'" do
      '& and &'.send(@method, "UTF-8", xml: :attr).should == '"&amp; and &amp;"'
    end

    it "replaces all instances of '<' with '&lt;'" do
      '< and <'.send(@method, "UTF-8", xml: :attr).should == '"&lt; and &lt;"'
    end

    it "replaces all instances of '>' with '&gt;'" do
      '> and >'.send(@method, "UTF-8", xml: :attr).should == '"&gt; and &gt;"'
    end

    it "replaces all instances of '\"' with '&quot;'" do
      '" and "'.send(@method, "UTF-8", xml: :attr).should == '"&quot; and &quot;"'
    end

    it "replaces undefined characters with their upper-case hexadecimal numeric character references" do
      'ürst'.send(@method, Encoding::US_ASCII, xml: :attr).should == '"&#xFC;rst"'
    end
  end

  it "raises ArgumentError if the value of the :xml option is not :text or :attr" do
    -> { ''.send(@method, "UTF-8", xml: :other) }.should raise_error(ArgumentError)
  end
end