-
Notifications
You must be signed in to change notification settings - Fork 6k
/
DataSourceContractTest.java
636 lines (555 loc) · 23.5 KB
/
DataSourceContractTest.java
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
/*
* Copyright (C) 2020 The Android Open Source Project
*
* 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 com.google.android.exoplayer2.testutil;
import static com.google.android.exoplayer2.util.Assertions.checkArgument;
import static com.google.android.exoplayer2.util.Assertions.checkNotNull;
import static com.google.android.exoplayer2.util.Util.castNonNull;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import android.net.Uri;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DataSourceException;
import com.google.android.exoplayer2.upstream.DataSpec;
import com.google.android.exoplayer2.upstream.TransferListener;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.Util;
import com.google.common.collect.ImmutableList;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.Mockito;
/**
* A collection of contract tests for {@link DataSource} implementations.
*
* <p>Subclasses should only include the logic necessary to construct the DataSource and allow it to
* successfully read data. They shouldn't include any new {@link Test @Test} methods -
* implementation-specific tests should be in a separate class.
*
* <p>Most implementations should pass all these tests. If necessary, subclasses can disable tests
* by overriding the {@link Test @Test} method with a no-op implementation. It's recommended (but
* not required) to also annotate this {@link Ignore @Ignore} so that JUnit correclty reports the
* test as skipped/ignored instead of passing.
*/
@RequiresApi(19)
public abstract class DataSourceContractTest {
@Rule public final AdditionalFailureInfo additionalFailureInfo = new AdditionalFailureInfo();
/** Creates and returns an instance of the {@link DataSource}. */
protected abstract DataSource createDataSource() throws Exception;
/**
* Returns the {@link DataSource} that will be included in the {@link TransferListener} callbacks
* for the {@link DataSource} most recently created by {@link #createDataSource()}. If it's the
* same {@link DataSource} then {@code null} can be returned.
*/
@Nullable
protected DataSource getTransferListenerDataSource() {
return null;
}
/**
* Returns whether the {@link DataSource} will continue reading indefinitely for unbounded {@link
* DataSpec DataSpecs}.
*/
protected boolean unboundedReadsAreIndefinite() {
return false;
}
/**
* Returns {@link TestResource} instances.
*
* <p>Each resource will be used to exercise the {@link DataSource} instance, allowing different
* behaviours to be tested.
*
* <p>If multiple resources are returned, it's recommended to disambiguate them using {@link
* TestResource.Builder#setName(String)}.
*/
protected abstract ImmutableList<TestResource> getTestResources() throws Exception;
/**
* Returns a {@link Uri} that doesn't resolve.
*
* <p>This is used to test how a {@link DataSource} handles nonexistent data.
*/
protected abstract Uri getNotFoundUri();
@Test
public void unboundedDataSpec_readUntilEnd() throws Exception {
ImmutableList<TestResource> resources = getTestResources();
Assertions.checkArgument(!resources.isEmpty(), "Must provide at least one test resource.");
for (int i = 0; i < resources.size(); i++) {
additionalFailureInfo.setInfo(getFailureLabel(resources, i));
TestResource resource = resources.get(i);
DataSource dataSource = createDataSource();
try {
long length = dataSource.open(new DataSpec(resource.getUri()));
byte[] data =
unboundedReadsAreIndefinite()
? Util.readExactly(dataSource, resource.getExpectedBytes().length)
: Util.readToEnd(dataSource);
if (length != C.LENGTH_UNSET) {
assertThat(length).isEqualTo(resource.getExpectedBytes().length);
}
assertThat(data).isEqualTo(resource.getExpectedBytes());
} finally {
dataSource.close();
}
additionalFailureInfo.setInfo(null);
}
}
@Test
public void dataSpecWithPosition_readUntilEnd() throws Exception {
ImmutableList<TestResource> resources = getTestResources();
Assertions.checkArgument(!resources.isEmpty(), "Must provide at least one test resource.");
for (int i = 0; i < resources.size(); i++) {
additionalFailureInfo.setInfo(getFailureLabel(resources, i));
TestResource resource = resources.get(i);
DataSource dataSource = createDataSource();
try {
long length =
dataSource.open(
new DataSpec.Builder().setUri(resource.getUri()).setPosition(3).build());
byte[] data =
unboundedReadsAreIndefinite()
? Util.readExactly(dataSource, resource.getExpectedBytes().length - 3)
: Util.readToEnd(dataSource);
if (length != C.LENGTH_UNSET) {
assertThat(length).isEqualTo(resource.getExpectedBytes().length - 3);
}
byte[] expectedData =
Arrays.copyOfRange(resource.getExpectedBytes(), 3, resource.getExpectedBytes().length);
assertThat(data).isEqualTo(expectedData);
} finally {
dataSource.close();
}
additionalFailureInfo.setInfo(null);
}
}
@Test
public void dataSpecWithLength_readExpectedRange() throws Exception {
ImmutableList<TestResource> resources = getTestResources();
Assertions.checkArgument(!resources.isEmpty(), "Must provide at least one test resource.");
for (int i = 0; i < resources.size(); i++) {
additionalFailureInfo.setInfo(getFailureLabel(resources, i));
TestResource resource = resources.get(i);
DataSource dataSource = createDataSource();
try {
long length =
dataSource.open(new DataSpec.Builder().setUri(resource.getUri()).setLength(4).build());
byte[] data = Util.readToEnd(dataSource);
assertThat(length).isEqualTo(4);
byte[] expectedData = Arrays.copyOf(resource.getExpectedBytes(), 4);
assertThat(data).isEqualTo(expectedData);
} finally {
dataSource.close();
}
additionalFailureInfo.setInfo(null);
}
}
@Test
public void dataSpecWithPositionAndLength_readExpectedRange() throws Exception {
ImmutableList<TestResource> resources = getTestResources();
Assertions.checkArgument(!resources.isEmpty(), "Must provide at least one test resource.");
for (int i = 0; i < resources.size(); i++) {
additionalFailureInfo.setInfo(getFailureLabel(resources, i));
TestResource resource = resources.get(i);
DataSource dataSource = createDataSource();
try {
long length =
dataSource.open(
new DataSpec.Builder()
.setUri(resource.getUri())
.setPosition(2)
.setLength(2)
.build());
byte[] data = Util.readToEnd(dataSource);
assertThat(length).isEqualTo(2);
byte[] expectedData = Arrays.copyOfRange(resource.getExpectedBytes(), 2, 4);
assertThat(data).isEqualTo(expectedData);
} finally {
dataSource.close();
}
additionalFailureInfo.setInfo(null);
}
}
@Test
public void dataSpecWithPositionAtEnd_readsZeroBytes() throws Exception {
ImmutableList<TestResource> resources = getTestResources();
Assertions.checkArgument(!resources.isEmpty(), "Must provide at least one test resource.");
for (int i = 0; i < resources.size(); i++) {
additionalFailureInfo.setInfo(getFailureLabel(resources, i));
TestResource resource = resources.get(i);
int resourceLength = resource.getExpectedBytes().length;
DataSource dataSource = createDataSource();
DataSpec dataSpec =
new DataSpec.Builder().setUri(resource.getUri()).setPosition(resourceLength).build();
try {
long length = dataSource.open(dataSpec);
byte[] data =
unboundedReadsAreIndefinite() ? Util.EMPTY_BYTE_ARRAY : Util.readToEnd(dataSource);
// The DataSource.open() contract requires the returned length to equal the length in the
// DataSpec if set. This is true even though the DataSource implementation may know that
// fewer bytes will be read in this case.
if (length != C.LENGTH_UNSET) {
assertThat(length).isEqualTo(0);
}
assertThat(data).isEmpty();
} finally {
dataSource.close();
}
additionalFailureInfo.setInfo(null);
}
}
@Test
public void dataSpecWithPositionAtEndAndLength_readsZeroBytes() throws Exception {
ImmutableList<TestResource> resources = getTestResources();
Assertions.checkArgument(!resources.isEmpty(), "Must provide at least one test resource.");
for (int i = 0; i < resources.size(); i++) {
additionalFailureInfo.setInfo(getFailureLabel(resources, i));
TestResource resource = resources.get(i);
int resourceLength = resource.getExpectedBytes().length;
DataSource dataSource = createDataSource();
DataSpec dataSpec =
new DataSpec.Builder()
.setUri(resource.getUri())
.setPosition(resourceLength)
.setLength(1)
.build();
try {
long length = dataSource.open(dataSpec);
byte[] data =
unboundedReadsAreIndefinite() ? Util.EMPTY_BYTE_ARRAY : Util.readToEnd(dataSource);
// The DataSource.open() contract requires the returned length to equal the length in the
// DataSpec if set. This is true even though the DataSource implementation may know that
// fewer bytes will be read in this case.
assertThat(length).isEqualTo(1);
assertThat(data).isEmpty();
} finally {
dataSource.close();
}
additionalFailureInfo.setInfo(null);
}
}
@Test
public void dataSpecWithPositionOutOfRange_throwsPositionOutOfRangeException() throws Exception {
ImmutableList<TestResource> resources = getTestResources();
Assertions.checkArgument(!resources.isEmpty(), "Must provide at least one test resource.");
for (int i = 0; i < resources.size(); i++) {
additionalFailureInfo.setInfo(getFailureLabel(resources, i));
TestResource resource = resources.get(i);
int resourceLength = resource.getExpectedBytes().length;
DataSource dataSource = createDataSource();
DataSpec dataSpec =
new DataSpec.Builder().setUri(resource.getUri()).setPosition(resourceLength + 1).build();
try {
IOException exception = assertThrows(IOException.class, () -> dataSource.open(dataSpec));
assertThat(DataSourceException.isCausedByPositionOutOfRange(exception)).isTrue();
} finally {
dataSource.close();
}
additionalFailureInfo.setInfo(null);
}
}
@Test
public void dataSpecWithEndPositionOutOfRange_readsToEnd() throws Exception {
ImmutableList<TestResource> resources = getTestResources();
Assertions.checkArgument(!resources.isEmpty(), "Must provide at least one test resource.");
for (int i = 0; i < resources.size(); i++) {
additionalFailureInfo.setInfo(getFailureLabel(resources, i));
TestResource resource = resources.get(i);
int resourceLength = resource.getExpectedBytes().length;
DataSource dataSource = createDataSource();
DataSpec dataSpec =
new DataSpec.Builder()
.setUri(resource.getUri())
.setPosition(resourceLength - 1)
.setLength(2)
.build();
try {
long length = dataSource.open(dataSpec);
byte[] data = Util.readExactly(dataSource, /* length= */ 1);
// TODO: Decide what the allowed behavior should be for the next read, and assert it.
// The DataSource.open() contract requires the returned length to equal the length in the
// DataSpec if set. This is true even though the DataSource implementation may know that
// fewer bytes will be read in this case.
assertThat(length).isEqualTo(2);
byte[] expectedData =
Arrays.copyOfRange(resource.getExpectedBytes(), resourceLength - 1, resourceLength);
assertThat(data).isEqualTo(expectedData);
} finally {
dataSource.close();
}
additionalFailureInfo.setInfo(null);
}
}
/**
* {@link DataSpec#FLAG_ALLOW_GZIP} should either be ignored by {@link DataSource}
* implementations, or correctly handled (i.e. the data is decompressed before being returned from
* {@link DataSource#read(byte[], int, int)}).
*/
@Test
public void unboundedDataSpecWithGzipFlag_readUntilEnd() throws Exception {
ImmutableList<TestResource> resources = getTestResources();
Assertions.checkArgument(!resources.isEmpty(), "Must provide at least one test resource.");
for (int i = 0; i < resources.size(); i++) {
additionalFailureInfo.setInfo(getFailureLabel(resources, i));
TestResource resource = resources.get(i);
DataSource dataSource = createDataSource();
try {
long length =
dataSource.open(
new DataSpec.Builder()
.setUri(resource.getUri())
.setFlags(DataSpec.FLAG_ALLOW_GZIP)
.build());
byte[] data =
unboundedReadsAreIndefinite()
? Util.readExactly(dataSource, resource.getExpectedBytes().length)
: Util.readToEnd(dataSource);
if (length != C.LENGTH_UNSET) {
assertThat(length).isEqualTo(resource.getExpectedBytes().length);
}
assertThat(data).isEqualTo(resource.getExpectedBytes());
} finally {
dataSource.close();
}
additionalFailureInfo.setInfo(null);
}
}
@Test
public void resourceNotFound() throws Exception {
DataSource dataSource = createDataSource();
assertThrows(IOException.class, () -> dataSource.open(new DataSpec(getNotFoundUri())));
dataSource.close();
}
@Test
public void transferListenerCallbacks() throws Exception {
ImmutableList<TestResource> resources = getTestResources();
Assertions.checkArgument(!resources.isEmpty(), "Must provide at least one test resource.");
for (int i = 0; i < resources.size(); i++) {
additionalFailureInfo.setInfo(getFailureLabel(resources, i));
DataSource dataSource = createDataSource();
FakeTransferListener listener = spy(new FakeTransferListener());
dataSource.addTransferListener(listener);
InOrder inOrder = Mockito.inOrder(listener);
@Nullable DataSource callbackSource = getTransferListenerDataSource();
if (callbackSource == null) {
callbackSource = dataSource;
}
DataSpec reportedDataSpec = null;
boolean reportedNetwork = false;
TestResource resource = resources.get(i);
DataSpec dataSpec = new DataSpec.Builder().setUri(resource.getUri()).build();
try {
dataSource.open(dataSpec);
// Verify onTransferInitializing() and onTransferStart() have been called exactly from
// DataSource.open().
ArgumentCaptor<DataSpec> dataSpecArgumentCaptor = ArgumentCaptor.forClass(DataSpec.class);
ArgumentCaptor<Boolean> isNetworkArgumentCaptor = ArgumentCaptor.forClass(Boolean.class);
inOrder
.verify(listener)
.onTransferInitializing(
eq(callbackSource),
dataSpecArgumentCaptor.capture(),
isNetworkArgumentCaptor.capture());
reportedDataSpec = dataSpecArgumentCaptor.getValue();
reportedNetwork = isNetworkArgumentCaptor.getValue();
inOrder
.verify(listener)
.onTransferStart(callbackSource, castNonNull(reportedDataSpec), reportedNetwork);
inOrder.verifyNoMoreInteractions();
if (unboundedReadsAreIndefinite()) {
Util.readExactly(dataSource, resource.getExpectedBytes().length);
} else {
Util.readToEnd(dataSource);
}
// Verify sufficient onBytesTransferred() callbacks have been triggered before closing the
// DataSource.
assertThat(listener.bytesTransferred).isAtLeast(resource.getExpectedBytes().length);
} finally {
dataSource.close();
inOrder
.verify(listener)
.onTransferEnd(callbackSource, castNonNull(reportedDataSpec), reportedNetwork);
inOrder.verifyNoMoreInteractions();
}
additionalFailureInfo.setInfo(null);
}
}
@Test
public void resourceNotFound_transferListenerCallbacks() throws Exception {
DataSource dataSource = createDataSource();
TransferListener listener = mock(TransferListener.class);
dataSource.addTransferListener(listener);
@Nullable DataSource callbackSource = getTransferListenerDataSource();
if (callbackSource == null) {
callbackSource = dataSource;
}
assertThrows(IOException.class, () -> dataSource.open(new DataSpec(getNotFoundUri())));
// Verify onTransferInitializing() has been called exactly from DataSource.open().
verify(listener).onTransferInitializing(eq(callbackSource), any(), anyBoolean());
verifyNoMoreInteractions(listener);
dataSource.close();
verifyNoMoreInteractions(listener);
}
@Test
public void getUri_returnsNonNullValueOnlyWhileOpen() throws Exception {
ImmutableList<TestResource> resources = getTestResources();
Assertions.checkArgument(!resources.isEmpty(), "Must provide at least one test resource.");
for (int i = 0; i < resources.size(); i++) {
additionalFailureInfo.setInfo(getFailureLabel(resources, i));
TestResource resource = resources.get(i);
DataSource dataSource = createDataSource();
try {
assertThat(dataSource.getUri()).isNull();
dataSource.open(new DataSpec(resource.getUri()));
assertThat(dataSource.getUri()).isNotNull();
} finally {
dataSource.close();
}
assertThat(dataSource.getUri()).isNull();
additionalFailureInfo.setInfo(null);
}
}
@Test
public void getUri_resourceNotFound_returnsNullIfNotOpened() throws Exception {
DataSource dataSource = createDataSource();
assertThat(dataSource.getUri()).isNull();
assertThrows(IOException.class, () -> dataSource.open(new DataSpec(getNotFoundUri())));
dataSource.close();
assertThat(dataSource.getUri()).isNull();
}
@Test
public void getResponseHeaders_isEmptyWhileNotOpen() throws Exception {
ImmutableList<TestResource> resources = getTestResources();
Assertions.checkArgument(!resources.isEmpty(), "Must provide at least one test resource.");
for (int i = 0; i < resources.size(); i++) {
additionalFailureInfo.setInfo(getFailureLabel(resources, i));
TestResource resource = resources.get(i);
DataSource dataSource = createDataSource();
try {
assertThat(dataSource.getResponseHeaders()).isEmpty();
dataSource.open(new DataSpec(resource.getUri()));
} finally {
dataSource.close();
}
assertThat(dataSource.getResponseHeaders()).isEmpty();
additionalFailureInfo.setInfo(null);
}
}
@Test
public void getResponseHeaders_resourceNotFound_isEmptyWhileNotOpen() throws Exception {
DataSource dataSource = createDataSource();
assertThat(dataSource.getResponseHeaders()).isEmpty();
assertThrows(IOException.class, () -> dataSource.open(new DataSpec(getNotFoundUri())));
dataSource.close();
assertThat(dataSource.getResponseHeaders()).isEmpty();
}
/** Build a label to make it clear which resource caused a given test failure. */
private static String getFailureLabel(List<TestResource> resources, int i) {
if (resources.size() == 1) {
return "";
} else if (resources.get(i).getName() != null) {
return "resource name: " + resources.get(i).getName();
} else {
return String.format("resource[%s]", i);
}
}
/** Information about a resource that can be used to test the {@link DataSource} instance. */
public static final class TestResource {
@Nullable private final String name;
private final Uri uri;
private final byte[] expectedBytes;
private TestResource(@Nullable String name, Uri uri, byte[] expectedBytes) {
this.name = name;
this.uri = uri;
this.expectedBytes = expectedBytes;
}
/** Returns a human-readable name for the resource, for use in test failure messages. */
@Nullable
public String getName() {
return name;
}
/** Returns the URI where the resource is available. */
public Uri getUri() {
return uri;
}
/** Returns the expected contents of this resource. */
public byte[] getExpectedBytes() {
return expectedBytes;
}
/** Builder for {@link TestResource} instances. */
public static final class Builder {
private @MonotonicNonNull String name;
private @MonotonicNonNull Uri uri;
private byte @MonotonicNonNull [] expectedBytes;
/**
* Sets a human-readable name for this resource which will be shown in test failure messages.
*/
public Builder setName(String name) {
this.name = name;
return this;
}
/** Sets the URI where this resource is located. */
public Builder setUri(String uri) {
return setUri(Uri.parse(uri));
}
/** Sets the URI where this resource is located. */
public Builder setUri(Uri uri) {
this.uri = uri;
return this;
}
/**
* Sets the expected contents of this resource.
*
* <p>Must be at least 5 bytes.
*/
public Builder setExpectedBytes(byte[] expectedBytes) {
checkArgument(expectedBytes.length >= 5);
this.expectedBytes = expectedBytes;
return this;
}
public TestResource build() {
return new TestResource(name, checkNotNull(uri), checkNotNull(expectedBytes));
}
}
}
/** A {@link TransferListener} that only keeps track of the transferred bytes. */
public static class FakeTransferListener implements TransferListener {
private int bytesTransferred;
@Override
public void onTransferInitializing(DataSource source, DataSpec dataSpec, boolean isNetwork) {}
@Override
public void onTransferStart(DataSource source, DataSpec dataSpec, boolean isNetwork) {}
@Override
public void onBytesTransferred(
DataSource source, DataSpec dataSpec, boolean isNetwork, int bytesTransferred) {
this.bytesTransferred += bytesTransferred;
}
@Override
public void onTransferEnd(DataSource source, DataSpec dataSpec, boolean isNetwork) {}
}
}