summaryrefslogtreecommitdiff
path: root/okhttp/src/test/java/okhttp3/ResponseBodyJvmTest.kt
blob: 730a77bed562eb41eeab2e50a5ddf4b4b519e19a (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
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
/*
 * Copyright (C) 2016 Square, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package okhttp3

import assertk.assertThat
import assertk.assertions.isEqualTo
import assertk.assertions.isTrue
import java.io.IOException
import java.io.InputStreamReader
import java.io.Reader
import java.nio.charset.StandardCharsets
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.test.assertFailsWith
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.ResponseBody.Companion.toResponseBody
import okhttp3.internal.and
import okio.Buffer
import okio.BufferedSource
import okio.ByteString
import okio.ByteString.Companion.decodeHex
import okio.ForwardingSource
import okio.buffer
import org.junit.jupiter.api.Test

class ResponseBodyJvmTest {
  @Test
  fun stringEmpty() {
    val body = body("")
    assertThat(body.string()).isEqualTo("")
  }

  @Test
  fun stringLooksLikeBomButTooShort() {
    val body = body("000048")
    assertThat(body.string()).isEqualTo("\u0000\u0000H")
  }

  @Test
  fun stringDefaultsToUtf8() {
    val body = body("68656c6c6f")
    assertThat(body.string()).isEqualTo("hello")
  }

  @Test
  fun stringExplicitCharset() {
    val body = body("00000068000000650000006c0000006c0000006f", "utf-32be")
    assertThat(body.string()).isEqualTo("hello")
  }

  @Test
  fun stringBomOverridesExplicitCharset() {
    val body = body("0000feff00000068000000650000006c0000006c0000006f", "utf-8")
    assertThat(body.string()).isEqualTo("hello")
  }

  @Test
  fun stringBomUtf8() {
    val body = body("efbbbf68656c6c6f")
    assertThat(body.string()).isEqualTo("hello")
  }

  @Test
  fun stringBomUtf16Be() {
    val body = body("feff00680065006c006c006f")
    assertThat(body.string()).isEqualTo("hello")
  }

  @Test
  fun stringBomUtf16Le() {
    val body = body("fffe680065006c006c006f00")
    assertThat(body.string()).isEqualTo("hello")
  }

  @Test
  fun stringBomUtf32Be() {
    val body = body("0000feff00000068000000650000006c0000006c0000006f")
    assertThat(body.string()).isEqualTo("hello")
  }

  @Test
  fun stringBomUtf32Le() {
    val body = body("fffe000068000000650000006c0000006c0000006f000000")
    assertThat(body.string()).isEqualTo("hello")
  }

  @Test
  fun stringClosesUnderlyingSource() {
    val closed = AtomicBoolean()
    val body: ResponseBody =
      object : ResponseBody() {
        override fun contentType(): MediaType? {
          return null
        }

        override fun contentLength(): Long {
          return 5
        }

        override fun source(): BufferedSource {
          val source = Buffer().writeUtf8("hello")
          return object : ForwardingSource(source) {
            @Throws(IOException::class)
            override fun close() {
              closed.set(true)
              super.close()
            }
          }.buffer()
        }
      }
    assertThat(body.string()).isEqualTo("hello")
    assertThat(closed.get()).isTrue()
  }

  @Test
  fun readerEmpty() {
    val body = body("")
    assertThat(exhaust(body.charStream())).isEqualTo("")
  }

  @Test
  fun readerLooksLikeBomButTooShort() {
    val body = body("000048")
    assertThat(exhaust(body.charStream())).isEqualTo("\u0000\u0000H")
  }

  @Test
  fun readerDefaultsToUtf8() {
    val body = body("68656c6c6f")
    assertThat(exhaust(body.charStream())).isEqualTo("hello")
  }

  @Test
  fun readerExplicitCharset() {
    val body = body("00000068000000650000006c0000006c0000006f", "utf-32be")
    assertThat(exhaust(body.charStream())).isEqualTo("hello")
  }

  @Test
  fun readerBomUtf8() {
    val body = body("efbbbf68656c6c6f")
    assertThat(exhaust(body.charStream())).isEqualTo("hello")
  }

  @Test
  fun readerBomUtf16Be() {
    val body = body("feff00680065006c006c006f")
    assertThat(exhaust(body.charStream())).isEqualTo("hello")
  }

  @Test
  fun readerBomUtf16Le() {
    val body = body("fffe680065006c006c006f00")
    assertThat(exhaust(body.charStream())).isEqualTo("hello")
  }

  @Test
  fun readerBomUtf32Be() {
    val body = body("0000feff00000068000000650000006c0000006c0000006f")
    assertThat(exhaust(body.charStream())).isEqualTo("hello")
  }

  @Test
  fun readerBomUtf32Le() {
    val body = body("fffe000068000000650000006c0000006c0000006f000000")
    assertThat(exhaust(body.charStream())).isEqualTo("hello")
  }

  @Test
  fun readerClosedBeforeBomClosesUnderlyingSource() {
    val closed = AtomicBoolean()
    val body: ResponseBody =
      object : ResponseBody() {
        override fun contentType(): MediaType? {
          return null
        }

        override fun contentLength(): Long {
          return 5
        }

        override fun source(): BufferedSource {
          val body = body("fffe680065006c006c006f00")
          return object : ForwardingSource(body.source()) {
            @Throws(IOException::class)
            override fun close() {
              closed.set(true)
              super.close()
            }
          }.buffer()
        }
      }
    body.charStream().close()
    assertThat(closed.get()).isTrue()
  }

  @Test
  fun readerClosedAfterBomClosesUnderlyingSource() {
    val closed = AtomicBoolean()
    val body: ResponseBody =
      object : ResponseBody() {
        override fun contentType(): MediaType? {
          return null
        }

        override fun contentLength(): Long {
          return 5
        }

        override fun source(): BufferedSource {
          val body = body("fffe680065006c006c006f00")
          return object : ForwardingSource(body.source()) {
            @Throws(IOException::class)
            override fun close() {
              closed.set(true)
              super.close()
            }
          }.buffer()
        }
      }
    val reader = body.charStream()
    assertThat(reader.read()).isEqualTo('h'.code)
    reader.close()
    assertThat(closed.get()).isTrue()
  }

  @Test
  fun sourceSeesBom() {
    val body = "efbbbf68656c6c6f".decodeHex().toResponseBody()
    val source = body.source()
    assertThat(source.readByte() and 0xff).isEqualTo(0xef)
    assertThat(source.readByte() and 0xff).isEqualTo(0xbb)
    assertThat(source.readByte() and 0xff).isEqualTo(0xbf)
    assertThat(source.readUtf8()).isEqualTo("hello")
  }

  @Test
  fun bytesEmpty() {
    val body = body("")
    assertThat(body.bytes().size).isEqualTo(0)
  }

  @Test
  fun bytesSeesBom() {
    val body = body("efbbbf68656c6c6f")
    val bytes = body.bytes()
    assertThat(bytes[0] and 0xff).isEqualTo(0xef)
    assertThat(bytes[1] and 0xff).isEqualTo(0xbb)
    assertThat(bytes[2] and 0xff).isEqualTo(0xbf)
    assertThat(String(bytes, 3, 5, StandardCharsets.UTF_8)).isEqualTo("hello")
  }

  @Test
  fun bytesClosesUnderlyingSource() {
    val closed = AtomicBoolean()
    val body: ResponseBody =
      object : ResponseBody() {
        override fun contentType(): MediaType? {
          return null
        }

        override fun contentLength(): Long {
          return 5
        }

        override fun source(): BufferedSource {
          val source = Buffer().writeUtf8("hello")
          return object : ForwardingSource(source) {
            @Throws(IOException::class)
            override fun close() {
              closed.set(true)
              super.close()
            }
          }.buffer()
        }
      }
    assertThat(body.bytes().size).isEqualTo(5)
    assertThat(closed.get()).isTrue()
  }

  @Test
  fun bytesThrowsWhenLengthsDisagree() {
    val body: ResponseBody =
      object : ResponseBody() {
        override fun contentType(): MediaType? {
          return null
        }

        override fun contentLength(): Long {
          return 10
        }

        override fun source(): BufferedSource {
          return Buffer().writeUtf8("hello")
        }
      }
    assertFailsWith<IOException> {
      body.bytes()
    }.also { expected ->
      assertThat(expected.message).isEqualTo(
        "Content-Length (10) and stream length (5) disagree",
      )
    }
  }

  @Test
  fun bytesThrowsMoreThanIntMaxValue() {
    val body: ResponseBody =
      object : ResponseBody() {
        override fun contentType(): MediaType? {
          return null
        }

        override fun contentLength(): Long {
          return Int.MAX_VALUE + 1L
        }

        override fun source(): BufferedSource {
          throw AssertionError()
        }
      }
    assertFailsWith<IOException> {
      body.bytes()
    }.also { expected ->
      assertThat(expected.message).isEqualTo(
        "Cannot buffer entire body for content length: 2147483648",
      )
    }
  }

  @Test
  fun byteStringEmpty() {
    val body = body("")
    assertThat(body.byteString()).isEqualTo(ByteString.EMPTY)
  }

  @Test
  fun byteStringSeesBom() {
    val body = body("efbbbf68656c6c6f")
    val actual = body.byteString()
    val expected: ByteString = "efbbbf68656c6c6f".decodeHex()
    assertThat(actual).isEqualTo(expected)
  }

  @Test
  fun byteStringClosesUnderlyingSource() {
    val closed = AtomicBoolean()
    val body: ResponseBody =
      object : ResponseBody() {
        override fun contentType(): MediaType? {
          return null
        }

        override fun contentLength(): Long {
          return 5
        }

        override fun source(): BufferedSource {
          val source = Buffer().writeUtf8("hello")
          return object : ForwardingSource(source) {
            @Throws(IOException::class)
            override fun close() {
              closed.set(true)
              super.close()
            }
          }.buffer()
        }
      }
    assertThat(body.byteString().size).isEqualTo(5)
    assertThat(closed.get()).isTrue()
  }

  @Test
  fun byteStringThrowsWhenLengthsDisagree() {
    val body: ResponseBody =
      object : ResponseBody() {
        override fun contentType(): MediaType? {
          return null
        }

        override fun contentLength(): Long {
          return 10
        }

        override fun source(): BufferedSource {
          return Buffer().writeUtf8("hello")
        }
      }
    assertFailsWith<IOException> {
      body.byteString()
    }.also { expected ->
      assertThat(expected.message).isEqualTo(
        "Content-Length (10) and stream length (5) disagree",
      )
    }
  }

  @Test
  fun byteStringThrowsMoreThanIntMaxValue() {
    val body: ResponseBody =
      object : ResponseBody() {
        override fun contentType(): MediaType? {
          return null
        }

        override fun contentLength(): Long {
          return Int.MAX_VALUE + 1L
        }

        override fun source(): BufferedSource {
          throw AssertionError()
        }
      }
    assertFailsWith<IOException> {
      body.byteString()
    }.also { expected ->
      assertThat(expected.message).isEqualTo(
        "Cannot buffer entire body for content length: 2147483648",
      )
    }
  }

  @Test
  fun byteStreamEmpty() {
    val body = body("")
    val bytes = body.byteStream()
    assertThat(bytes.read()).isEqualTo(-1)
  }

  @Test
  fun byteStreamSeesBom() {
    val body = body("efbbbf68656c6c6f")
    val bytes = body.byteStream()
    assertThat(bytes.read()).isEqualTo(0xef)
    assertThat(bytes.read()).isEqualTo(0xbb)
    assertThat(bytes.read()).isEqualTo(0xbf)
    assertThat(exhaust(InputStreamReader(bytes, StandardCharsets.UTF_8))).isEqualTo("hello")
  }

  @Test
  fun byteStreamClosesUnderlyingSource() {
    val closed = AtomicBoolean()
    val body: ResponseBody =
      object : ResponseBody() {
        override fun contentType(): MediaType? {
          return null
        }

        override fun contentLength(): Long {
          return 5
        }

        override fun source(): BufferedSource {
          val source = Buffer().writeUtf8("hello")
          return object : ForwardingSource(source) {
            @Throws(IOException::class)
            override fun close() {
              closed.set(true)
              super.close()
            }
          }.buffer()
        }
      }
    body.byteStream().close()
    assertThat(closed.get()).isTrue()
  }

  @Test
  fun unicodeTextWithUnsupportedEncoding() {
    val text = "eile oli oliiviõli"
    val body = text.toResponseBody("text/plain; charset=unknown".toMediaType())
    assertThat(body.string()).isEqualTo(text)
  }

  companion object {
    @JvmOverloads
    fun body(
      hex: String,
      charset: String? = null,
    ): ResponseBody {
      val mediaType = if (charset == null) null else "any/thing; charset=$charset".toMediaType()
      return hex.decodeHex().toResponseBody(mediaType)
    }

    fun exhaust(reader: Reader): String {
      val builder = StringBuilder()
      val buf = CharArray(10)
      var read: Int
      while (reader.read(buf).also { read = it } != -1) {
        builder.appendRange(buf, 0, read)
      }
      return builder.toString()
    }
  }
}