Commit e991a801 by tonihei Committed by Oliver Woodman

Use Truth instead of framework asserts in all tests.

This achieves two things:
1. All our tests use the same type of assertions.
2. The tests currently run as instrumentation test can be moved to
   Robolectric without changing the assertions.

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=182910542
parent aa1b41bf
Showing with 872 additions and 730 deletions
...@@ -15,8 +15,7 @@ ...@@ -15,8 +15,7 @@
*/ */
package com.google.android.exoplayer2.ext.cronet; package com.google.android.exoplayer2.ext.cronet;
import static org.junit.Assert.assertArrayEquals; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
...@@ -53,13 +52,13 @@ public final class ByteArrayUploadDataProviderTest { ...@@ -53,13 +52,13 @@ public final class ByteArrayUploadDataProviderTest {
@Test @Test
public void testGetLength() { public void testGetLength() {
assertEquals(TEST_DATA.length, byteArrayUploadDataProvider.getLength()); assertThat(byteArrayUploadDataProvider.getLength()).isEqualTo(TEST_DATA.length);
} }
@Test @Test
public void testReadFullBuffer() throws IOException { public void testReadFullBuffer() throws IOException {
byteArrayUploadDataProvider.read(mockUploadDataSink, byteBuffer); byteArrayUploadDataProvider.read(mockUploadDataSink, byteBuffer);
assertArrayEquals(TEST_DATA, byteBuffer.array()); assertThat(byteBuffer.array()).isEqualTo(TEST_DATA);
} }
@Test @Test
...@@ -69,12 +68,12 @@ public final class ByteArrayUploadDataProviderTest { ...@@ -69,12 +68,12 @@ public final class ByteArrayUploadDataProviderTest {
byteBuffer = ByteBuffer.allocate(TEST_DATA.length / 2); byteBuffer = ByteBuffer.allocate(TEST_DATA.length / 2);
// Read half of the data. // Read half of the data.
byteArrayUploadDataProvider.read(mockUploadDataSink, byteBuffer); byteArrayUploadDataProvider.read(mockUploadDataSink, byteBuffer);
assertArrayEquals(firstHalf, byteBuffer.array()); assertThat(byteBuffer.array()).isEqualTo(firstHalf);
// Read the second half of the data. // Read the second half of the data.
byteBuffer.rewind(); byteBuffer.rewind();
byteArrayUploadDataProvider.read(mockUploadDataSink, byteBuffer); byteArrayUploadDataProvider.read(mockUploadDataSink, byteBuffer);
assertArrayEquals(secondHalf, byteBuffer.array()); assertThat(byteBuffer.array()).isEqualTo(secondHalf);
verify(mockUploadDataSink, times(2)).onReadSucceeded(false); verify(mockUploadDataSink, times(2)).onReadSucceeded(false);
} }
...@@ -82,13 +81,13 @@ public final class ByteArrayUploadDataProviderTest { ...@@ -82,13 +81,13 @@ public final class ByteArrayUploadDataProviderTest {
public void testRewind() throws IOException { public void testRewind() throws IOException {
// Read all the data. // Read all the data.
byteArrayUploadDataProvider.read(mockUploadDataSink, byteBuffer); byteArrayUploadDataProvider.read(mockUploadDataSink, byteBuffer);
assertArrayEquals(TEST_DATA, byteBuffer.array()); assertThat(byteBuffer.array()).isEqualTo(TEST_DATA);
// Rewind and make sure it can be read again. // Rewind and make sure it can be read again.
byteBuffer.clear(); byteBuffer.clear();
byteArrayUploadDataProvider.rewind(mockUploadDataSink); byteArrayUploadDataProvider.rewind(mockUploadDataSink);
byteArrayUploadDataProvider.read(mockUploadDataSink, byteBuffer); byteArrayUploadDataProvider.read(mockUploadDataSink, byteBuffer);
assertArrayEquals(TEST_DATA, byteBuffer.array()); assertThat(byteBuffer.array()).isEqualTo(TEST_DATA);
verify(mockUploadDataSink).onRewindSucceeded(); verify(mockUploadDataSink).onRewindSucceeded();
} }
......
...@@ -32,6 +32,7 @@ android { ...@@ -32,6 +32,7 @@ android {
dependencies { dependencies {
compile project(modulePrefix + 'library-core') compile project(modulePrefix + 'library-core')
androidTestCompile 'com.google.truth:truth:' + truthVersion
} }
ext { ext {
......
...@@ -15,6 +15,8 @@ ...@@ -15,6 +15,8 @@
*/ */
package com.google.android.exoplayer2.ext.vp9; package com.google.android.exoplayer2.ext.vp9;
import static com.google.common.truth.Truth.assertThat;
import android.content.Context; import android.content.Context;
import android.net.Uri; import android.net.Uri;
import android.os.Looper; import android.os.Looper;
...@@ -73,8 +75,8 @@ public class VpxPlaybackTest extends InstrumentationTestCase { ...@@ -73,8 +75,8 @@ public class VpxPlaybackTest extends InstrumentationTestCase {
playUri(INVALID_BITSTREAM_URI); playUri(INVALID_BITSTREAM_URI);
fail(); fail();
} catch (Exception e) { } catch (Exception e) {
assertNotNull(e.getCause()); assertThat(e.getCause()).isNotNull();
assertTrue(e.getCause() instanceof VpxDecoderException); assertThat(e.getCause()).isInstanceOf(VpxDecoderException.class);
} }
} }
......
...@@ -46,6 +46,7 @@ dependencies { ...@@ -46,6 +46,7 @@ dependencies {
compile 'com.android.support:support-annotations:' + supportLibraryVersion compile 'com.android.support:support-annotations:' + supportLibraryVersion
androidTestCompile 'com.google.dexmaker:dexmaker:' + dexmakerVersion androidTestCompile 'com.google.dexmaker:dexmaker:' + dexmakerVersion
androidTestCompile 'com.google.dexmaker:dexmaker-mockito:' + dexmakerVersion androidTestCompile 'com.google.dexmaker:dexmaker-mockito:' + dexmakerVersion
androidTestCompile 'com.google.truth:truth:' + truthVersion
androidTestCompile 'org.mockito:mockito-core:' + mockitoVersion androidTestCompile 'org.mockito:mockito-core:' + mockitoVersion
testCompile 'com.google.truth:truth:' + truthVersion testCompile 'com.google.truth:truth:' + truthVersion
testCompile 'junit:junit:' + junitVersion testCompile 'junit:junit:' + junitVersion
......
...@@ -15,11 +15,11 @@ ...@@ -15,11 +15,11 @@
*/ */
package com.google.android.exoplayer2.drm; package com.google.android.exoplayer2.drm;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Matchers.any; import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import android.test.InstrumentationTestCase; import android.test.InstrumentationTestCase;
import android.test.MoreAsserts;
import android.util.Pair; import android.util.Pair;
import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.drm.DrmInitData.SchemeData; import com.google.android.exoplayer2.drm.DrmInitData.SchemeData;
...@@ -86,7 +86,7 @@ public class OfflineLicenseHelperTest extends InstrumentationTestCase { ...@@ -86,7 +86,7 @@ public class OfflineLicenseHelperTest extends InstrumentationTestCase {
byte[] offlineLicenseKeySetId = offlineLicenseHelper.downloadLicense(newDrmInitData()); byte[] offlineLicenseKeySetId = offlineLicenseHelper.downloadLicense(newDrmInitData());
assertNull(offlineLicenseKeySetId); assertThat(offlineLicenseKeySetId).isNull();
} }
public void testDownloadLicenseDoesNotFailIfDurationNotAvailable() throws Exception { public void testDownloadLicenseDoesNotFailIfDurationNotAvailable() throws Exception {
...@@ -94,7 +94,7 @@ public class OfflineLicenseHelperTest extends InstrumentationTestCase { ...@@ -94,7 +94,7 @@ public class OfflineLicenseHelperTest extends InstrumentationTestCase {
byte[] offlineLicenseKeySetId = offlineLicenseHelper.downloadLicense(newDrmInitData()); byte[] offlineLicenseKeySetId = offlineLicenseHelper.downloadLicense(newDrmInitData());
assertNotNull(offlineLicenseKeySetId); assertThat(offlineLicenseKeySetId).isNotNull();
} }
public void testGetLicenseDurationRemainingSec() throws Exception { public void testGetLicenseDurationRemainingSec() throws Exception {
...@@ -108,8 +108,8 @@ public class OfflineLicenseHelperTest extends InstrumentationTestCase { ...@@ -108,8 +108,8 @@ public class OfflineLicenseHelperTest extends InstrumentationTestCase {
Pair<Long, Long> licenseDurationRemainingSec = offlineLicenseHelper Pair<Long, Long> licenseDurationRemainingSec = offlineLicenseHelper
.getLicenseDurationRemainingSec(offlineLicenseKeySetId); .getLicenseDurationRemainingSec(offlineLicenseKeySetId);
assertEquals(licenseDuration, (long) licenseDurationRemainingSec.first); assertThat(licenseDurationRemainingSec.first).isEqualTo(licenseDuration);
assertEquals(playbackDuration, (long) licenseDurationRemainingSec.second); assertThat(licenseDurationRemainingSec.second).isEqualTo(playbackDuration);
} }
public void testGetLicenseDurationRemainingSecExpiredLicense() throws Exception { public void testGetLicenseDurationRemainingSecExpiredLicense() throws Exception {
...@@ -123,8 +123,8 @@ public class OfflineLicenseHelperTest extends InstrumentationTestCase { ...@@ -123,8 +123,8 @@ public class OfflineLicenseHelperTest extends InstrumentationTestCase {
Pair<Long, Long> licenseDurationRemainingSec = offlineLicenseHelper Pair<Long, Long> licenseDurationRemainingSec = offlineLicenseHelper
.getLicenseDurationRemainingSec(offlineLicenseKeySetId); .getLicenseDurationRemainingSec(offlineLicenseKeySetId);
assertEquals(licenseDuration, (long) licenseDurationRemainingSec.first); assertThat(licenseDurationRemainingSec.first).isEqualTo(licenseDuration);
assertEquals(playbackDuration, (long) licenseDurationRemainingSec.second); assertThat(licenseDurationRemainingSec.second).isEqualTo(playbackDuration);
} }
private void setDefaultStubKeySetId() private void setDefaultStubKeySetId()
...@@ -139,8 +139,8 @@ public class OfflineLicenseHelperTest extends InstrumentationTestCase { ...@@ -139,8 +139,8 @@ public class OfflineLicenseHelperTest extends InstrumentationTestCase {
private static void assertOfflineLicenseKeySetIdEqual( private static void assertOfflineLicenseKeySetIdEqual(
byte[] expectedKeySetId, byte[] actualKeySetId) throws Exception { byte[] expectedKeySetId, byte[] actualKeySetId) throws Exception {
assertNotNull(actualKeySetId); assertThat(actualKeySetId).isNotNull();
MoreAsserts.assertEquals(expectedKeySetId, actualKeySetId); assertThat(actualKeySetId).isEqualTo(expectedKeySetId);
} }
private void setStubLicenseAndPlaybackDurationValues(long licenseDuration, private void setStubLicenseAndPlaybackDurationValues(long licenseDuration,
......
...@@ -15,6 +15,9 @@ ...@@ -15,6 +15,9 @@
*/ */
package com.google.android.exoplayer2.extractor.ogg; package com.google.android.exoplayer2.extractor.ogg;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.testutil.FakeExtractorInput; import com.google.android.exoplayer2.testutil.FakeExtractorInput;
import com.google.android.exoplayer2.util.ParsableByteArray; import com.google.android.exoplayer2.util.ParsableByteArray;
...@@ -60,28 +63,33 @@ public final class DefaultOggSeekerTest extends TestCase { ...@@ -60,28 +63,33 @@ public final class DefaultOggSeekerTest extends TestCase {
} }
// Test granule 0 from file start // Test granule 0 from file start
assertEquals(0, seekTo(input, oggSeeker, 0, 0)); assertThat(seekTo(input, oggSeeker, 0, 0)).isEqualTo(0);
assertEquals(0, input.getPosition()); assertThat(input.getPosition()).isEqualTo(0);
// Test granule 0 from file end // Test granule 0 from file end
assertEquals(0, seekTo(input, oggSeeker, 0, testFile.data.length - 1)); assertThat(seekTo(input, oggSeeker, 0, testFile.data.length - 1)).isEqualTo(0);
assertEquals(0, input.getPosition()); assertThat(input.getPosition()).isEqualTo(0);
{ // Test last granule { // Test last granule
long currentGranule = seekTo(input, oggSeeker, testFile.lastGranule, 0); long currentGranule = seekTo(input, oggSeeker, testFile.lastGranule, 0);
long position = testFile.data.length; long position = testFile.data.length;
assertTrue((testFile.lastGranule > currentGranule && position > input.getPosition()) assertThat(
|| (testFile.lastGranule == currentGranule && position == input.getPosition())); (testFile.lastGranule > currentGranule && position > input.getPosition())
|| (testFile.lastGranule == currentGranule && position == input.getPosition()))
.isTrue();
} }
{ // Test exact granule { // Test exact granule
input.setPosition(testFile.data.length / 2); input.setPosition(testFile.data.length / 2);
oggSeeker.skipToNextPage(input); oggSeeker.skipToNextPage(input);
assertTrue(pageHeader.populate(input, true)); assertThat(pageHeader.populate(input, true)).isTrue();
long position = input.getPosition() + pageHeader.headerSize + pageHeader.bodySize; long position = input.getPosition() + pageHeader.headerSize + pageHeader.bodySize;
long currentGranule = seekTo(input, oggSeeker, pageHeader.granulePosition, 0); long currentGranule = seekTo(input, oggSeeker, pageHeader.granulePosition, 0);
assertTrue((pageHeader.granulePosition > currentGranule && position > input.getPosition()) assertThat(
|| (pageHeader.granulePosition == currentGranule && position == input.getPosition())); (pageHeader.granulePosition > currentGranule && position > input.getPosition())
|| (pageHeader.granulePosition == currentGranule
&& position == input.getPosition()))
.isTrue();
} }
for (int i = 0; i < 100; i += 1) { for (int i = 0; i < 100; i += 1) {
...@@ -91,16 +99,17 @@ public final class DefaultOggSeekerTest extends TestCase { ...@@ -91,16 +99,17 @@ public final class DefaultOggSeekerTest extends TestCase {
long currentGranule = seekTo(input, oggSeeker, targetGranule, initialPosition); long currentGranule = seekTo(input, oggSeeker, targetGranule, initialPosition);
long currentPosition = input.getPosition(); long currentPosition = input.getPosition();
assertTrue("getNextSeekPosition() didn't leave input on a page start.", assertWithMessage("getNextSeekPosition() didn't leave input on a page start.")
pageHeader.populate(input, true)); .that(pageHeader.populate(input, true))
.isTrue();
if (currentGranule == 0) { if (currentGranule == 0) {
assertEquals(0, currentPosition); assertThat(currentPosition).isEqualTo(0);
} else { } else {
int previousPageStart = testFile.findPreviousPageStart(currentPosition); int previousPageStart = testFile.findPreviousPageStart(currentPosition);
input.setPosition(previousPageStart); input.setPosition(previousPageStart);
assertTrue(pageHeader.populate(input, true)); assertThat(pageHeader.populate(input, true)).isTrue();
assertEquals(pageHeader.granulePosition, currentGranule); assertThat(currentGranule).isEqualTo(pageHeader.granulePosition);
} }
input.setPosition((int) currentPosition); input.setPosition((int) currentPosition);
......
...@@ -15,6 +15,8 @@ ...@@ -15,6 +15,8 @@
*/ */
package com.google.android.exoplayer2.extractor.ogg; package com.google.android.exoplayer2.extractor.ogg;
import static com.google.common.truth.Truth.assertThat;
import android.test.InstrumentationTestCase; import android.test.InstrumentationTestCase;
import com.google.android.exoplayer2.extractor.Extractor; import com.google.android.exoplayer2.extractor.Extractor;
import com.google.android.exoplayer2.testutil.ExtractorAsserts; import com.google.android.exoplayer2.testutil.ExtractorAsserts;
...@@ -56,44 +58,47 @@ public final class OggExtractorTest extends InstrumentationTestCase { ...@@ -56,44 +58,47 @@ public final class OggExtractorTest extends InstrumentationTestCase {
} }
public void testSniffVorbis() throws Exception { public void testSniffVorbis() throws Exception {
byte[] data = TestUtil.joinByteArrays( byte[] data =
TestUtil.joinByteArrays(
OggTestData.buildOggHeader(0x02, 0, 1000, 1), OggTestData.buildOggHeader(0x02, 0, 1000, 1),
TestUtil.createByteArray(7), // Laces TestUtil.createByteArray(7), // Laces
new byte[] {0x01, 'v', 'o', 'r', 'b', 'i', 's'}); new byte[] {0x01, 'v', 'o', 'r', 'b', 'i', 's'});
assertTrue(sniff(data)); assertThat(sniff(data)).isTrue();
} }
public void testSniffFlac() throws Exception { public void testSniffFlac() throws Exception {
byte[] data = TestUtil.joinByteArrays( byte[] data =
TestUtil.joinByteArrays(
OggTestData.buildOggHeader(0x02, 0, 1000, 1), OggTestData.buildOggHeader(0x02, 0, 1000, 1),
TestUtil.createByteArray(5), // Laces TestUtil.createByteArray(5), // Laces
new byte[] {0x7F, 'F', 'L', 'A', 'C'}); new byte[] {0x7F, 'F', 'L', 'A', 'C'});
assertTrue(sniff(data)); assertThat(sniff(data)).isTrue();
} }
public void testSniffFailsOpusFile() throws Exception { public void testSniffFailsOpusFile() throws Exception {
byte[] data = TestUtil.joinByteArrays( byte[] data =
OggTestData.buildOggHeader(0x02, 0, 1000, 0x00), TestUtil.joinByteArrays(
new byte[] {'O', 'p', 'u', 's'}); OggTestData.buildOggHeader(0x02, 0, 1000, 0x00), new byte[] {'O', 'p', 'u', 's'});
assertFalse(sniff(data)); assertThat(sniff(data)).isFalse();
} }
public void testSniffFailsInvalidOggHeader() throws Exception { public void testSniffFailsInvalidOggHeader() throws Exception {
byte[] data = OggTestData.buildOggHeader(0x00, 0, 1000, 0x00); byte[] data = OggTestData.buildOggHeader(0x00, 0, 1000, 0x00);
assertFalse(sniff(data)); assertThat(sniff(data)).isFalse();
} }
public void testSniffInvalidHeader() throws Exception { public void testSniffInvalidHeader() throws Exception {
byte[] data = TestUtil.joinByteArrays( byte[] data =
TestUtil.joinByteArrays(
OggTestData.buildOggHeader(0x02, 0, 1000, 1), OggTestData.buildOggHeader(0x02, 0, 1000, 1),
TestUtil.createByteArray(7), // Laces TestUtil.createByteArray(7), // Laces
new byte[] {0x7F, 'X', 'o', 'r', 'b', 'i', 's'}); new byte[] {0x7F, 'X', 'o', 'r', 'b', 'i', 's'});
assertFalse(sniff(data)); assertThat(sniff(data)).isFalse();
} }
public void testSniffFailsEOF() throws Exception { public void testSniffFailsEOF() throws Exception {
byte[] data = OggTestData.buildOggHeader(0x02, 0, 1000, 0x00); byte[] data = OggTestData.buildOggHeader(0x02, 0, 1000, 0x00);
assertFalse(sniff(data)); assertThat(sniff(data)).isFalse();
} }
private boolean sniff(byte[] data) throws InterruptedException, IOException { private boolean sniff(byte[] data) throws InterruptedException, IOException {
......
...@@ -15,8 +15,9 @@ ...@@ -15,8 +15,9 @@
*/ */
package com.google.android.exoplayer2.extractor.ogg; package com.google.android.exoplayer2.extractor.ogg;
import static com.google.common.truth.Truth.assertThat;
import android.test.InstrumentationTestCase; import android.test.InstrumentationTestCase;
import android.test.MoreAsserts;
import com.google.android.exoplayer2.testutil.FakeExtractorInput; import com.google.android.exoplayer2.testutil.FakeExtractorInput;
import com.google.android.exoplayer2.testutil.OggTestData; import com.google.android.exoplayer2.testutil.OggTestData;
import com.google.android.exoplayer2.testutil.TestUtil; import com.google.android.exoplayer2.testutil.TestUtil;
...@@ -48,7 +49,8 @@ public final class OggPacketTest extends InstrumentationTestCase { ...@@ -48,7 +49,8 @@ public final class OggPacketTest extends InstrumentationTestCase {
byte[] thirdPacket = TestUtil.buildTestData(256, random); byte[] thirdPacket = TestUtil.buildTestData(256, random);
byte[] fourthPacket = TestUtil.buildTestData(271, random); byte[] fourthPacket = TestUtil.buildTestData(271, random);
FakeExtractorInput input = OggTestData.createInput( FakeExtractorInput input =
OggTestData.createInput(
TestUtil.joinByteArrays( TestUtil.joinByteArrays(
// First page with a single packet. // First page with a single packet.
OggTestData.buildOggHeader(0x02, 0, 1000, 0x01), OggTestData.buildOggHeader(0x02, 0, 1000, 0x01),
...@@ -64,40 +66,41 @@ public final class OggPacketTest extends InstrumentationTestCase { ...@@ -64,40 +66,41 @@ public final class OggPacketTest extends InstrumentationTestCase {
OggTestData.buildOggHeader(0x04, 128, 1003, 0x04), OggTestData.buildOggHeader(0x04, 128, 1003, 0x04),
TestUtil.createByteArray(0xFF, 0x01, 0xFF, 0x10), // Laces TestUtil.createByteArray(0xFF, 0x01, 0xFF, 0x10), // Laces
thirdPacket, thirdPacket,
fourthPacket), true); fourthPacket),
true);
assertReadPacket(input, firstPacket); assertReadPacket(input, firstPacket);
assertTrue((oggPacket.getPageHeader().type & 0x02) == 0x02); assertThat((oggPacket.getPageHeader().type & 0x02) == 0x02).isTrue();
assertFalse((oggPacket.getPageHeader().type & 0x04) == 0x04); assertThat((oggPacket.getPageHeader().type & 0x04) == 0x04).isFalse();
assertEquals(0x02, oggPacket.getPageHeader().type); assertThat(oggPacket.getPageHeader().type).isEqualTo(0x02);
assertEquals(27 + 1, oggPacket.getPageHeader().headerSize); assertThat(oggPacket.getPageHeader().headerSize).isEqualTo(27 + 1);
assertEquals(8, oggPacket.getPageHeader().bodySize); assertThat(oggPacket.getPageHeader().bodySize).isEqualTo(8);
assertEquals(0x00, oggPacket.getPageHeader().revision); assertThat(oggPacket.getPageHeader().revision).isEqualTo(0x00);
assertEquals(1, oggPacket.getPageHeader().pageSegmentCount); assertThat(oggPacket.getPageHeader().pageSegmentCount).isEqualTo(1);
assertEquals(1000, oggPacket.getPageHeader().pageSequenceNumber); assertThat(oggPacket.getPageHeader().pageSequenceNumber).isEqualTo(1000);
assertEquals(4096, oggPacket.getPageHeader().streamSerialNumber); assertThat(oggPacket.getPageHeader().streamSerialNumber).isEqualTo(4096);
assertEquals(0, oggPacket.getPageHeader().granulePosition); assertThat(oggPacket.getPageHeader().granulePosition).isEqualTo(0);
assertReadPacket(input, secondPacket); assertReadPacket(input, secondPacket);
assertFalse((oggPacket.getPageHeader().type & 0x02) == 0x02); assertThat((oggPacket.getPageHeader().type & 0x02) == 0x02).isFalse();
assertFalse((oggPacket.getPageHeader().type & 0x04) == 0x04); assertThat((oggPacket.getPageHeader().type & 0x04) == 0x04).isFalse();
assertEquals(0, oggPacket.getPageHeader().type); assertThat(oggPacket.getPageHeader().type).isEqualTo(0);
assertEquals(27 + 2, oggPacket.getPageHeader().headerSize); assertThat(oggPacket.getPageHeader().headerSize).isEqualTo(27 + 2);
assertEquals(255 + 17, oggPacket.getPageHeader().bodySize); assertThat(oggPacket.getPageHeader().bodySize).isEqualTo(255 + 17);
assertEquals(2, oggPacket.getPageHeader().pageSegmentCount); assertThat(oggPacket.getPageHeader().pageSegmentCount).isEqualTo(2);
assertEquals(1001, oggPacket.getPageHeader().pageSequenceNumber); assertThat(oggPacket.getPageHeader().pageSequenceNumber).isEqualTo(1001);
assertEquals(16, oggPacket.getPageHeader().granulePosition); assertThat(oggPacket.getPageHeader().granulePosition).isEqualTo(16);
assertReadPacket(input, thirdPacket); assertReadPacket(input, thirdPacket);
assertFalse((oggPacket.getPageHeader().type & 0x02) == 0x02); assertThat((oggPacket.getPageHeader().type & 0x02) == 0x02).isFalse();
assertTrue((oggPacket.getPageHeader().type & 0x04) == 0x04); assertThat((oggPacket.getPageHeader().type & 0x04) == 0x04).isTrue();
assertEquals(4, oggPacket.getPageHeader().type); assertThat(oggPacket.getPageHeader().type).isEqualTo(4);
assertEquals(27 + 4, oggPacket.getPageHeader().headerSize); assertThat(oggPacket.getPageHeader().headerSize).isEqualTo(27 + 4);
assertEquals(255 + 1 + 255 + 16, oggPacket.getPageHeader().bodySize); assertThat(oggPacket.getPageHeader().bodySize).isEqualTo(255 + 1 + 255 + 16);
assertEquals(4, oggPacket.getPageHeader().pageSegmentCount); assertThat(oggPacket.getPageHeader().pageSegmentCount).isEqualTo(4);
// Page 1002 is empty, so current page is 1003. // Page 1002 is empty, so current page is 1003.
assertEquals(1003, oggPacket.getPageHeader().pageSequenceNumber); assertThat(oggPacket.getPageHeader().pageSequenceNumber).isEqualTo(1003);
assertEquals(128, oggPacket.getPageHeader().granulePosition); assertThat(oggPacket.getPageHeader().granulePosition).isEqualTo(128);
assertReadPacket(input, fourthPacket); assertReadPacket(input, fourthPacket);
...@@ -135,9 +138,9 @@ public final class OggPacketTest extends InstrumentationTestCase { ...@@ -135,9 +138,9 @@ public final class OggPacketTest extends InstrumentationTestCase {
Arrays.copyOfRange(firstPacket, 510, 510 + 8)), true); Arrays.copyOfRange(firstPacket, 510, 510 + 8)), true);
assertReadPacket(input, firstPacket); assertReadPacket(input, firstPacket);
assertTrue((oggPacket.getPageHeader().type & 0x04) == 0x04); assertThat((oggPacket.getPageHeader().type & 0x04) == 0x04).isTrue();
assertFalse((oggPacket.getPageHeader().type & 0x02) == 0x02); assertThat((oggPacket.getPageHeader().type & 0x02) == 0x02).isFalse();
assertEquals(1001, oggPacket.getPageHeader().pageSequenceNumber); assertThat(oggPacket.getPageHeader().pageSequenceNumber).isEqualTo(1001);
assertReadEof(input); assertReadEof(input);
} }
...@@ -165,9 +168,9 @@ public final class OggPacketTest extends InstrumentationTestCase { ...@@ -165,9 +168,9 @@ public final class OggPacketTest extends InstrumentationTestCase {
Arrays.copyOfRange(firstPacket, 510 + 255 + 255, 510 + 255 + 255 + 8)), true); Arrays.copyOfRange(firstPacket, 510 + 255 + 255, 510 + 255 + 255 + 8)), true);
assertReadPacket(input, firstPacket); assertReadPacket(input, firstPacket);
assertTrue((oggPacket.getPageHeader().type & 0x04) == 0x04); assertThat((oggPacket.getPageHeader().type & 0x04) == 0x04).isTrue();
assertFalse((oggPacket.getPageHeader().type & 0x02) == 0x02); assertThat((oggPacket.getPageHeader().type & 0x02) == 0x02).isFalse();
assertEquals(1003, oggPacket.getPageHeader().pageSequenceNumber); assertThat(oggPacket.getPageHeader().pageSequenceNumber).isEqualTo(1003);
assertReadEof(input); assertReadEof(input);
} }
...@@ -218,19 +221,19 @@ public final class OggPacketTest extends InstrumentationTestCase { ...@@ -218,19 +221,19 @@ public final class OggPacketTest extends InstrumentationTestCase {
while (readPacket(input)) { while (readPacket(input)) {
packetCounter++; packetCounter++;
} }
assertEquals(277, packetCounter); assertThat(packetCounter).isEqualTo(277);
} }
private void assertReadPacket(FakeExtractorInput extractorInput, byte[] expected) private void assertReadPacket(FakeExtractorInput extractorInput, byte[] expected)
throws IOException, InterruptedException { throws IOException, InterruptedException {
assertTrue(readPacket(extractorInput)); assertThat(readPacket(extractorInput)).isTrue();
ParsableByteArray payload = oggPacket.getPayload(); ParsableByteArray payload = oggPacket.getPayload();
MoreAsserts.assertEquals(expected, Arrays.copyOf(payload.data, payload.limit())); assertThat(Arrays.copyOf(payload.data, payload.limit())).isEqualTo(expected);
} }
private void assertReadEof(FakeExtractorInput extractorInput) private void assertReadEof(FakeExtractorInput extractorInput)
throws IOException, InterruptedException { throws IOException, InterruptedException {
assertFalse(readPacket(extractorInput)); assertThat(readPacket(extractorInput)).isFalse();
} }
private boolean readPacket(FakeExtractorInput input) private boolean readPacket(FakeExtractorInput input)
......
...@@ -15,11 +15,12 @@ ...@@ -15,11 +15,12 @@
*/ */
package com.google.android.exoplayer2.extractor.ogg; package com.google.android.exoplayer2.extractor.ogg;
import static org.junit.Assert.fail;
import com.google.android.exoplayer2.testutil.OggTestData; import com.google.android.exoplayer2.testutil.OggTestData;
import com.google.android.exoplayer2.testutil.TestUtil; import com.google.android.exoplayer2.testutil.TestUtil;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Random; import java.util.Random;
import junit.framework.Assert;
/** /**
* Generates test data. * Generates test data.
...@@ -119,7 +120,7 @@ import junit.framework.Assert; ...@@ -119,7 +120,7 @@ import junit.framework.Assert;
return i; return i;
} }
} }
Assert.fail(); fail();
return -1; return -1;
} }
......
...@@ -15,6 +15,8 @@ ...@@ -15,6 +15,8 @@
*/ */
package com.google.android.exoplayer2.extractor.ts; package com.google.android.exoplayer2.extractor.ts;
import static com.google.common.truth.Truth.assertThat;
import android.test.InstrumentationTestCase; import android.test.InstrumentationTestCase;
import android.util.SparseArray; import android.util.SparseArray;
import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.C;
...@@ -92,12 +94,11 @@ public final class TsExtractorTest extends InstrumentationTestCase { ...@@ -92,12 +94,11 @@ public final class TsExtractorTest extends InstrumentationTestCase {
readResult = tsExtractor.read(input, seekPositionHolder); readResult = tsExtractor.read(input, seekPositionHolder);
} }
CustomEsReader reader = factory.esReader; CustomEsReader reader = factory.esReader;
assertEquals(2, reader.packetsRead); assertThat(reader.packetsRead).isEqualTo(2);
TrackOutput trackOutput = reader.getTrackOutput(); TrackOutput trackOutput = reader.getTrackOutput();
assertTrue(trackOutput == output.trackOutputs.get(257 /* PID of audio track. */)); assertThat(trackOutput == output.trackOutputs.get(257 /* PID of audio track. */)).isTrue();
assertEquals( assertThat(((FakeTrackOutput) trackOutput).format)
Format.createTextSampleFormat("1/257", "mime", null, 0, 0, "und", null, 0), .isEqualTo(Format.createTextSampleFormat("1/257", "mime", null, 0, 0, "und", null, 0));
((FakeTrackOutput) trackOutput).format);
} }
public void testCustomInitialSectionReader() throws Exception { public void testCustomInitialSectionReader() throws Exception {
...@@ -115,7 +116,7 @@ public final class TsExtractorTest extends InstrumentationTestCase { ...@@ -115,7 +116,7 @@ public final class TsExtractorTest extends InstrumentationTestCase {
while (readResult != Extractor.RESULT_END_OF_INPUT) { while (readResult != Extractor.RESULT_END_OF_INPUT) {
readResult = tsExtractor.read(input, seekPositionHolder); readResult = tsExtractor.read(input, seekPositionHolder);
} }
assertEquals(1, factory.sdtReader.consumedSdts); assertThat(factory.sdtReader.consumedSdts).isEqualTo(1);
} }
private static void writeJunkData(ByteArrayOutputStream out, int length) { private static void writeJunkData(ByteArrayOutputStream out, int length) {
...@@ -145,7 +146,7 @@ public final class TsExtractorTest extends InstrumentationTestCase { ...@@ -145,7 +146,7 @@ public final class TsExtractorTest extends InstrumentationTestCase {
@Override @Override
public SparseArray<TsPayloadReader> createInitialPayloadReaders() { public SparseArray<TsPayloadReader> createInitialPayloadReaders() {
if (provideSdtReader) { if (provideSdtReader) {
assertNull(sdtReader); assertThat(sdtReader).isNull();
SparseArray<TsPayloadReader> mapping = new SparseArray<>(); SparseArray<TsPayloadReader> mapping = new SparseArray<>();
sdtReader = new SdtSectionReader(); sdtReader = new SdtSectionReader();
mapping.put(17, new SectionReader(sdtReader)); mapping.put(17, new SectionReader(sdtReader));
...@@ -226,21 +227,21 @@ public final class TsExtractorTest extends InstrumentationTestCase { ...@@ -226,21 +227,21 @@ public final class TsExtractorTest extends InstrumentationTestCase {
// original_network_id(16), reserved_future_use(8) // original_network_id(16), reserved_future_use(8)
sectionData.skipBytes(11); sectionData.skipBytes(11);
// Start of the service loop. // Start of the service loop.
assertEquals(0x5566 /* arbitrary service id */, sectionData.readUnsignedShort()); assertThat(sectionData.readUnsignedShort()).isEqualTo(0x5566 /* arbitrary service id */);
// reserved_future_use(6), EIT_schedule_flag(1), EIT_present_following_flag(1) // reserved_future_use(6), EIT_schedule_flag(1), EIT_present_following_flag(1)
sectionData.skipBytes(1); sectionData.skipBytes(1);
// Assert there is only one service. // Assert there is only one service.
// Remove running_status(3), free_CA_mode(1) from the descriptors_loop_length with the mask. // Remove running_status(3), free_CA_mode(1) from the descriptors_loop_length with the mask.
assertEquals(sectionData.readUnsignedShort() & 0xFFF, sectionData.bytesLeft()); assertThat(sectionData.readUnsignedShort() & 0xFFF).isEqualTo(sectionData.bytesLeft());
while (sectionData.bytesLeft() > 0) { while (sectionData.bytesLeft() > 0) {
int descriptorTag = sectionData.readUnsignedByte(); int descriptorTag = sectionData.readUnsignedByte();
int descriptorLength = sectionData.readUnsignedByte(); int descriptorLength = sectionData.readUnsignedByte();
if (descriptorTag == 72 /* service descriptor */) { if (descriptorTag == 72 /* service descriptor */) {
assertEquals(1, sectionData.readUnsignedByte()); // Service type: Digital TV. assertThat(sectionData.readUnsignedByte()).isEqualTo(1); // Service type: Digital TV.
int serviceProviderNameLength = sectionData.readUnsignedByte(); int serviceProviderNameLength = sectionData.readUnsignedByte();
assertEquals("Some provider", sectionData.readString(serviceProviderNameLength)); assertThat(sectionData.readString(serviceProviderNameLength)).isEqualTo("Some provider");
int serviceNameLength = sectionData.readUnsignedByte(); int serviceNameLength = sectionData.readUnsignedByte();
assertEquals("Some Channel", sectionData.readString(serviceNameLength)); assertThat(sectionData.readString(serviceNameLength)).isEqualTo("Some Channel");
} else { } else {
sectionData.skipBytes(descriptorLength); sectionData.skipBytes(descriptorLength);
} }
......
...@@ -15,6 +15,8 @@ ...@@ -15,6 +15,8 @@
*/ */
package com.google.android.exoplayer2.source; package com.google.android.exoplayer2.source;
import static com.google.common.truth.Truth.assertThat;
import android.test.InstrumentationTestCase; import android.test.InstrumentationTestCase;
import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Player; import com.google.android.exoplayer2.Player;
...@@ -52,10 +54,12 @@ public final class ClippingMediaSourceTest extends InstrumentationTestCase { ...@@ -52,10 +54,12 @@ public final class ClippingMediaSourceTest extends InstrumentationTestCase {
Timeline clippedTimeline = getClippedTimeline(timeline, 0, TEST_PERIOD_DURATION_US); Timeline clippedTimeline = getClippedTimeline(timeline, 0, TEST_PERIOD_DURATION_US);
assertEquals(1, clippedTimeline.getWindowCount()); assertThat(clippedTimeline.getWindowCount()).isEqualTo(1);
assertEquals(1, clippedTimeline.getPeriodCount()); assertThat(clippedTimeline.getPeriodCount()).isEqualTo(1);
assertEquals(TEST_PERIOD_DURATION_US, clippedTimeline.getWindow(0, window).getDurationUs()); assertThat(clippedTimeline.getWindow(0, window).getDurationUs())
assertEquals(TEST_PERIOD_DURATION_US, clippedTimeline.getPeriod(0, period).getDurationUs()); .isEqualTo(TEST_PERIOD_DURATION_US);
assertThat(clippedTimeline.getPeriod(0, period).getDurationUs())
.isEqualTo(TEST_PERIOD_DURATION_US);
} }
public void testClippingUnseekableWindowThrows() throws IOException { public void testClippingUnseekableWindowThrows() throws IOException {
...@@ -68,7 +72,7 @@ public final class ClippingMediaSourceTest extends InstrumentationTestCase { ...@@ -68,7 +72,7 @@ public final class ClippingMediaSourceTest extends InstrumentationTestCase {
getClippedTimeline(timeline, 1, TEST_PERIOD_DURATION_US); getClippedTimeline(timeline, 1, TEST_PERIOD_DURATION_US);
fail("Expected clipping to fail."); fail("Expected clipping to fail.");
} catch (IllegalClippingException e) { } catch (IllegalClippingException e) {
assertEquals(IllegalClippingException.REASON_NOT_SEEKABLE_TO_START, e.reason); assertThat(e.reason).isEqualTo(IllegalClippingException.REASON_NOT_SEEKABLE_TO_START);
} }
} }
...@@ -77,10 +81,10 @@ public final class ClippingMediaSourceTest extends InstrumentationTestCase { ...@@ -77,10 +81,10 @@ public final class ClippingMediaSourceTest extends InstrumentationTestCase {
Timeline clippedTimeline = getClippedTimeline(timeline, TEST_CLIP_AMOUNT_US, Timeline clippedTimeline = getClippedTimeline(timeline, TEST_CLIP_AMOUNT_US,
TEST_PERIOD_DURATION_US); TEST_PERIOD_DURATION_US);
assertEquals(TEST_PERIOD_DURATION_US - TEST_CLIP_AMOUNT_US, assertThat(clippedTimeline.getWindow(0, window).getDurationUs())
clippedTimeline.getWindow(0, window).getDurationUs()); .isEqualTo(TEST_PERIOD_DURATION_US - TEST_CLIP_AMOUNT_US);
assertEquals(TEST_PERIOD_DURATION_US - TEST_CLIP_AMOUNT_US, assertThat(clippedTimeline.getPeriod(0, period).getDurationUs())
clippedTimeline.getPeriod(0, period).getDurationUs()); .isEqualTo(TEST_PERIOD_DURATION_US - TEST_CLIP_AMOUNT_US);
} }
public void testClippingEnd() throws IOException { public void testClippingEnd() throws IOException {
...@@ -88,10 +92,10 @@ public final class ClippingMediaSourceTest extends InstrumentationTestCase { ...@@ -88,10 +92,10 @@ public final class ClippingMediaSourceTest extends InstrumentationTestCase {
Timeline clippedTimeline = getClippedTimeline(timeline, 0, Timeline clippedTimeline = getClippedTimeline(timeline, 0,
TEST_PERIOD_DURATION_US - TEST_CLIP_AMOUNT_US); TEST_PERIOD_DURATION_US - TEST_CLIP_AMOUNT_US);
assertEquals(TEST_PERIOD_DURATION_US - TEST_CLIP_AMOUNT_US, assertThat(clippedTimeline.getWindow(0, window).getDurationUs())
clippedTimeline.getWindow(0, window).getDurationUs()); .isEqualTo(TEST_PERIOD_DURATION_US - TEST_CLIP_AMOUNT_US);
assertEquals(TEST_PERIOD_DURATION_US - TEST_CLIP_AMOUNT_US, assertThat(clippedTimeline.getPeriod(0, period).getDurationUs())
clippedTimeline.getPeriod(0, period).getDurationUs()); .isEqualTo(TEST_PERIOD_DURATION_US - TEST_CLIP_AMOUNT_US);
} }
public void testClippingStartAndEndInitial() throws IOException { public void testClippingStartAndEndInitial() throws IOException {
...@@ -103,10 +107,10 @@ public final class ClippingMediaSourceTest extends InstrumentationTestCase { ...@@ -103,10 +107,10 @@ public final class ClippingMediaSourceTest extends InstrumentationTestCase {
Timeline clippedTimeline = getClippedTimeline(timeline, TEST_CLIP_AMOUNT_US, Timeline clippedTimeline = getClippedTimeline(timeline, TEST_CLIP_AMOUNT_US,
TEST_PERIOD_DURATION_US - TEST_CLIP_AMOUNT_US * 2); TEST_PERIOD_DURATION_US - TEST_CLIP_AMOUNT_US * 2);
assertEquals(TEST_PERIOD_DURATION_US - TEST_CLIP_AMOUNT_US * 3, assertThat(clippedTimeline.getWindow(0, window).getDurationUs())
clippedTimeline.getWindow(0, window).getDurationUs()); .isEqualTo(TEST_PERIOD_DURATION_US - TEST_CLIP_AMOUNT_US * 3);
assertEquals(TEST_PERIOD_DURATION_US - TEST_CLIP_AMOUNT_US * 3, assertThat(clippedTimeline.getPeriod(0, period).getDurationUs())
clippedTimeline.getPeriod(0, period).getDurationUs()); .isEqualTo(TEST_PERIOD_DURATION_US - TEST_CLIP_AMOUNT_US * 3);
} }
public void testClippingStartAndEnd() throws IOException { public void testClippingStartAndEnd() throws IOException {
...@@ -114,10 +118,10 @@ public final class ClippingMediaSourceTest extends InstrumentationTestCase { ...@@ -114,10 +118,10 @@ public final class ClippingMediaSourceTest extends InstrumentationTestCase {
Timeline clippedTimeline = getClippedTimeline(timeline, TEST_CLIP_AMOUNT_US, Timeline clippedTimeline = getClippedTimeline(timeline, TEST_CLIP_AMOUNT_US,
TEST_PERIOD_DURATION_US - TEST_CLIP_AMOUNT_US * 2); TEST_PERIOD_DURATION_US - TEST_CLIP_AMOUNT_US * 2);
assertEquals(TEST_PERIOD_DURATION_US - TEST_CLIP_AMOUNT_US * 3, assertThat(clippedTimeline.getWindow(0, window).getDurationUs())
clippedTimeline.getWindow(0, window).getDurationUs()); .isEqualTo(TEST_PERIOD_DURATION_US - TEST_CLIP_AMOUNT_US * 3);
assertEquals(TEST_PERIOD_DURATION_US - TEST_CLIP_AMOUNT_US * 3, assertThat(clippedTimeline.getPeriod(0, period).getDurationUs())
clippedTimeline.getPeriod(0, period).getDurationUs()); .isEqualTo(TEST_PERIOD_DURATION_US - TEST_CLIP_AMOUNT_US * 3);
} }
public void testWindowAndPeriodIndices() throws IOException { public void testWindowAndPeriodIndices() throws IOException {
......
...@@ -15,6 +15,8 @@ ...@@ -15,6 +15,8 @@
*/ */
package com.google.android.exoplayer2.source; package com.google.android.exoplayer2.source;
import static com.google.common.truth.Truth.assertThat;
import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Player; import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.Timeline; import com.google.android.exoplayer2.Timeline;
...@@ -77,8 +79,9 @@ public final class ConcatenatingMediaSourceTest extends TestCase { ...@@ -77,8 +79,9 @@ public final class ConcatenatingMediaSourceTest extends TestCase {
} }
public void testMultipleMediaSources() throws IOException { public void testMultipleMediaSources() throws IOException {
Timeline[] timelines = { createFakeTimeline(3, 111), createFakeTimeline(1, 222), Timeline[] timelines = {
createFakeTimeline(3, 333) }; createFakeTimeline(3, 111), createFakeTimeline(1, 222), createFakeTimeline(3, 333)
};
Timeline timeline = getConcatenatedTimeline(false, timelines); Timeline timeline = getConcatenatedTimeline(false, timelines);
TimelineAsserts.assertWindowIds(timeline, 111, 222, 333); TimelineAsserts.assertWindowIds(timeline, 111, 222, 333);
TimelineAsserts.assertPeriodCounts(timeline, 3, 1, 3); TimelineAsserts.assertPeriodCounts(timeline, 3, 1, 3);
...@@ -98,10 +101,10 @@ public final class ConcatenatingMediaSourceTest extends TestCase { ...@@ -98,10 +101,10 @@ public final class ConcatenatingMediaSourceTest extends TestCase {
C.INDEX_UNSET, 0, 1); C.INDEX_UNSET, 0, 1);
TimelineAsserts.assertNextWindowIndices(timeline, Player.REPEAT_MODE_ONE, true, 0, 1, 2); TimelineAsserts.assertNextWindowIndices(timeline, Player.REPEAT_MODE_ONE, true, 0, 1, 2);
TimelineAsserts.assertNextWindowIndices(timeline, Player.REPEAT_MODE_ALL, true, 2, 0, 1); TimelineAsserts.assertNextWindowIndices(timeline, Player.REPEAT_MODE_ALL, true, 2, 0, 1);
assertEquals(0, timeline.getFirstWindowIndex(false)); assertThat(timeline.getFirstWindowIndex(false)).isEqualTo(0);
assertEquals(2, timeline.getLastWindowIndex(false)); assertThat(timeline.getLastWindowIndex(false)).isEqualTo(2);
assertEquals(2, timeline.getFirstWindowIndex(true)); assertThat(timeline.getFirstWindowIndex(true)).isEqualTo(2);
assertEquals(0, timeline.getLastWindowIndex(true)); assertThat(timeline.getLastWindowIndex(true)).isEqualTo(0);
timeline = getConcatenatedTimeline(true, timelines); timeline = getConcatenatedTimeline(true, timelines);
TimelineAsserts.assertWindowIds(timeline, 111, 222, 333); TimelineAsserts.assertWindowIds(timeline, 111, 222, 333);
...@@ -117,8 +120,8 @@ public final class ConcatenatingMediaSourceTest extends TestCase { ...@@ -117,8 +120,8 @@ public final class ConcatenatingMediaSourceTest extends TestCase {
1, 2, C.INDEX_UNSET); 1, 2, C.INDEX_UNSET);
TimelineAsserts.assertNextWindowIndices(timeline, Player.REPEAT_MODE_ONE, shuffled, 1, 2, 0); TimelineAsserts.assertNextWindowIndices(timeline, Player.REPEAT_MODE_ONE, shuffled, 1, 2, 0);
TimelineAsserts.assertNextWindowIndices(timeline, Player.REPEAT_MODE_ALL, shuffled, 1, 2, 0); TimelineAsserts.assertNextWindowIndices(timeline, Player.REPEAT_MODE_ALL, shuffled, 1, 2, 0);
assertEquals(0, timeline.getFirstWindowIndex(shuffled)); assertThat(timeline.getFirstWindowIndex(shuffled)).isEqualTo(0);
assertEquals(2, timeline.getLastWindowIndex(shuffled)); assertThat(timeline.getLastWindowIndex(shuffled)).isEqualTo(2);
} }
} }
...@@ -152,9 +155,16 @@ public final class ConcatenatingMediaSourceTest extends TestCase { ...@@ -152,9 +155,16 @@ public final class ConcatenatingMediaSourceTest extends TestCase {
public void testEmptyTimelineMediaSources() throws IOException { public void testEmptyTimelineMediaSources() throws IOException {
// Empty timelines in the front, back, and the middle (single and multiple in a row). // Empty timelines in the front, back, and the middle (single and multiple in a row).
Timeline[] timelines = { Timeline.EMPTY, createFakeTimeline(1, 111), Timeline.EMPTY, Timeline[] timelines = {
Timeline.EMPTY, createFakeTimeline(2, 222), Timeline.EMPTY, createFakeTimeline(3, 333), Timeline.EMPTY,
Timeline.EMPTY }; createFakeTimeline(1, 111),
Timeline.EMPTY,
Timeline.EMPTY,
createFakeTimeline(2, 222),
Timeline.EMPTY,
createFakeTimeline(3, 333),
Timeline.EMPTY
};
Timeline timeline = getConcatenatedTimeline(false, timelines); Timeline timeline = getConcatenatedTimeline(false, timelines);
TimelineAsserts.assertWindowIds(timeline, 111, 222, 333); TimelineAsserts.assertWindowIds(timeline, 111, 222, 333);
TimelineAsserts.assertPeriodCounts(timeline, 1, 2, 3); TimelineAsserts.assertPeriodCounts(timeline, 1, 2, 3);
...@@ -174,10 +184,10 @@ public final class ConcatenatingMediaSourceTest extends TestCase { ...@@ -174,10 +184,10 @@ public final class ConcatenatingMediaSourceTest extends TestCase {
C.INDEX_UNSET, 0, 1); C.INDEX_UNSET, 0, 1);
TimelineAsserts.assertNextWindowIndices(timeline, Player.REPEAT_MODE_ONE, true, 0, 1, 2); TimelineAsserts.assertNextWindowIndices(timeline, Player.REPEAT_MODE_ONE, true, 0, 1, 2);
TimelineAsserts.assertNextWindowIndices(timeline, Player.REPEAT_MODE_ALL, true, 2, 0, 1); TimelineAsserts.assertNextWindowIndices(timeline, Player.REPEAT_MODE_ALL, true, 2, 0, 1);
assertEquals(0, timeline.getFirstWindowIndex(false)); assertThat(timeline.getFirstWindowIndex(false)).isEqualTo(0);
assertEquals(2, timeline.getLastWindowIndex(false)); assertThat(timeline.getLastWindowIndex(false)).isEqualTo(2);
assertEquals(2, timeline.getFirstWindowIndex(true)); assertThat(timeline.getFirstWindowIndex(true)).isEqualTo(2);
assertEquals(0, timeline.getLastWindowIndex(true)); assertThat(timeline.getLastWindowIndex(true)).isEqualTo(0);
timeline = getConcatenatedTimeline(true, timelines); timeline = getConcatenatedTimeline(true, timelines);
TimelineAsserts.assertWindowIds(timeline, 111, 222, 333); TimelineAsserts.assertWindowIds(timeline, 111, 222, 333);
...@@ -193,8 +203,8 @@ public final class ConcatenatingMediaSourceTest extends TestCase { ...@@ -193,8 +203,8 @@ public final class ConcatenatingMediaSourceTest extends TestCase {
1, 2, C.INDEX_UNSET); 1, 2, C.INDEX_UNSET);
TimelineAsserts.assertNextWindowIndices(timeline, Player.REPEAT_MODE_ONE, shuffled, 1, 2, 0); TimelineAsserts.assertNextWindowIndices(timeline, Player.REPEAT_MODE_ONE, shuffled, 1, 2, 0);
TimelineAsserts.assertNextWindowIndices(timeline, Player.REPEAT_MODE_ALL, shuffled, 1, 2, 0); TimelineAsserts.assertNextWindowIndices(timeline, Player.REPEAT_MODE_ALL, shuffled, 1, 2, 0);
assertEquals(0, timeline.getFirstWindowIndex(shuffled)); assertThat(timeline.getFirstWindowIndex(shuffled)).isEqualTo(0);
assertEquals(2, timeline.getLastWindowIndex(shuffled)); assertThat(timeline.getLastWindowIndex(shuffled)).isEqualTo(2);
} }
} }
......
...@@ -15,6 +15,7 @@ ...@@ -15,6 +15,7 @@
*/ */
package com.google.android.exoplayer2.source; package com.google.android.exoplayer2.source;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import android.os.ConditionVariable; import android.os.ConditionVariable;
...@@ -135,8 +136,8 @@ public final class DynamicConcatenatingMediaSourceTest extends TestCase { ...@@ -135,8 +136,8 @@ public final class DynamicConcatenatingMediaSourceTest extends TestCase {
C.INDEX_UNSET, 0, 1); C.INDEX_UNSET, 0, 1);
TimelineAsserts.assertPreviousWindowIndices(timeline, Player.REPEAT_MODE_ONE, false, 0, 1, 2); TimelineAsserts.assertPreviousWindowIndices(timeline, Player.REPEAT_MODE_ONE, false, 0, 1, 2);
TimelineAsserts.assertPreviousWindowIndices(timeline, Player.REPEAT_MODE_ALL, false, 2, 0, 1); TimelineAsserts.assertPreviousWindowIndices(timeline, Player.REPEAT_MODE_ALL, false, 2, 0, 1);
assertEquals(0, timeline.getFirstWindowIndex(false)); assertThat(timeline.getFirstWindowIndex(false)).isEqualTo(0);
assertEquals(timeline.getWindowCount() - 1, timeline.getLastWindowIndex(false)); assertThat(timeline.getLastWindowIndex(false)).isEqualTo(timeline.getWindowCount() - 1);
TimelineAsserts.assertNextWindowIndices(timeline, Player.REPEAT_MODE_OFF, true, TimelineAsserts.assertNextWindowIndices(timeline, Player.REPEAT_MODE_OFF, true,
C.INDEX_UNSET, 0, 1); C.INDEX_UNSET, 0, 1);
TimelineAsserts.assertNextWindowIndices(timeline, Player.REPEAT_MODE_ONE, true, 0, 1, 2); TimelineAsserts.assertNextWindowIndices(timeline, Player.REPEAT_MODE_ONE, true, 0, 1, 2);
...@@ -145,8 +146,8 @@ public final class DynamicConcatenatingMediaSourceTest extends TestCase { ...@@ -145,8 +146,8 @@ public final class DynamicConcatenatingMediaSourceTest extends TestCase {
1, 2, C.INDEX_UNSET); 1, 2, C.INDEX_UNSET);
TimelineAsserts.assertPreviousWindowIndices(timeline, Player.REPEAT_MODE_ONE, true, 0, 1, 2); TimelineAsserts.assertPreviousWindowIndices(timeline, Player.REPEAT_MODE_ONE, true, 0, 1, 2);
TimelineAsserts.assertPreviousWindowIndices(timeline, Player.REPEAT_MODE_ALL, true, 1, 2, 0); TimelineAsserts.assertPreviousWindowIndices(timeline, Player.REPEAT_MODE_ALL, true, 1, 2, 0);
assertEquals(timeline.getWindowCount() - 1, timeline.getFirstWindowIndex(true)); assertThat(timeline.getFirstWindowIndex(true)).isEqualTo(timeline.getWindowCount() - 1);
assertEquals(0, timeline.getLastWindowIndex(true)); assertThat(timeline.getLastWindowIndex(true)).isEqualTo(0);
// Assert all periods can be prepared. // Assert all periods can be prepared.
testRunner.assertPrepareAndReleaseAllPeriods(); testRunner.assertPrepareAndReleaseAllPeriods();
...@@ -258,7 +259,7 @@ public final class DynamicConcatenatingMediaSourceTest extends TestCase { ...@@ -258,7 +259,7 @@ public final class DynamicConcatenatingMediaSourceTest extends TestCase {
// called yet. // called yet.
MediaPeriod lazyPeriod = testRunner.createPeriod(new MediaPeriodId(0)); MediaPeriod lazyPeriod = testRunner.createPeriod(new MediaPeriodId(0));
ConditionVariable preparedCondition = testRunner.preparePeriod(lazyPeriod, 0); ConditionVariable preparedCondition = testRunner.preparePeriod(lazyPeriod, 0);
assertFalse(preparedCondition.block(1)); assertThat(preparedCondition.block(1)).isFalse();
// Assert that a second period can also be created and released without problems. // Assert that a second period can also be created and released without problems.
MediaPeriod secondLazyPeriod = testRunner.createPeriod(new MediaPeriodId(0)); MediaPeriod secondLazyPeriod = testRunner.createPeriod(new MediaPeriodId(0));
...@@ -276,7 +277,7 @@ public final class DynamicConcatenatingMediaSourceTest extends TestCase { ...@@ -276,7 +277,7 @@ public final class DynamicConcatenatingMediaSourceTest extends TestCase {
TimelineAsserts.assertPeriodCounts(timeline, 8, 1, 2, 9); TimelineAsserts.assertPeriodCounts(timeline, 8, 1, 2, 9);
TimelineAsserts.assertWindowIds(timeline, 888, 111, 222, 999); TimelineAsserts.assertWindowIds(timeline, 888, 111, 222, 999);
TimelineAsserts.assertWindowIsDynamic(timeline, false, false, false, false); TimelineAsserts.assertWindowIsDynamic(timeline, false, false, false, false);
assertTrue(preparedCondition.block(1)); assertThat(preparedCondition.block(1)).isTrue();
// Release the period and source. // Release the period and source.
testRunner.releasePeriod(lazyPeriod); testRunner.releasePeriod(lazyPeriod);
...@@ -299,7 +300,9 @@ public final class DynamicConcatenatingMediaSourceTest extends TestCase { ...@@ -299,7 +300,9 @@ public final class DynamicConcatenatingMediaSourceTest extends TestCase {
timeline = testRunner.assertTimelineChangeBlocking(); timeline = testRunner.assertTimelineChangeBlocking();
TimelineAsserts.assertEmpty(timeline); TimelineAsserts.assertEmpty(timeline);
mediaSource.addMediaSources(Arrays.asList(new MediaSource[] { mediaSource.addMediaSources(
Arrays.asList(
new MediaSource[] {
new FakeMediaSource(Timeline.EMPTY, null), new FakeMediaSource(Timeline.EMPTY, null), new FakeMediaSource(Timeline.EMPTY, null), new FakeMediaSource(Timeline.EMPTY, null),
new FakeMediaSource(Timeline.EMPTY, null), new FakeMediaSource(Timeline.EMPTY, null), new FakeMediaSource(Timeline.EMPTY, null), new FakeMediaSource(Timeline.EMPTY, null),
new FakeMediaSource(Timeline.EMPTY, null), new FakeMediaSource(Timeline.EMPTY, null) new FakeMediaSource(Timeline.EMPTY, null), new FakeMediaSource(Timeline.EMPTY, null)
...@@ -334,10 +337,10 @@ public final class DynamicConcatenatingMediaSourceTest extends TestCase { ...@@ -334,10 +337,10 @@ public final class DynamicConcatenatingMediaSourceTest extends TestCase {
C.INDEX_UNSET, 0, 1); C.INDEX_UNSET, 0, 1);
TimelineAsserts.assertNextWindowIndices(timeline, Player.REPEAT_MODE_ONE, true, 0, 1, 2); TimelineAsserts.assertNextWindowIndices(timeline, Player.REPEAT_MODE_ONE, true, 0, 1, 2);
TimelineAsserts.assertNextWindowIndices(timeline, Player.REPEAT_MODE_ALL, true, 2, 0, 1); TimelineAsserts.assertNextWindowIndices(timeline, Player.REPEAT_MODE_ALL, true, 2, 0, 1);
assertEquals(0, timeline.getFirstWindowIndex(false)); assertThat(timeline.getFirstWindowIndex(false)).isEqualTo(0);
assertEquals(2, timeline.getLastWindowIndex(false)); assertThat(timeline.getLastWindowIndex(false)).isEqualTo(2);
assertEquals(2, timeline.getFirstWindowIndex(true)); assertThat(timeline.getFirstWindowIndex(true)).isEqualTo(2);
assertEquals(0, timeline.getLastWindowIndex(true)); assertThat(timeline.getLastWindowIndex(true)).isEqualTo(0);
testRunner.assertPrepareAndReleaseAllPeriods(); testRunner.assertPrepareAndReleaseAllPeriods();
} }
...@@ -439,7 +442,7 @@ public final class DynamicConcatenatingMediaSourceTest extends TestCase { ...@@ -439,7 +442,7 @@ public final class DynamicConcatenatingMediaSourceTest extends TestCase {
} }
}); });
Timeline timeline = timelineGrabber.assertTimelineChangeBlocking(); Timeline timeline = timelineGrabber.assertTimelineChangeBlocking();
assertEquals(1, timeline.getWindowCount()); assertThat(timeline.getWindowCount()).isEqualTo(1);
} finally { } finally {
dummyMainThread.release(); dummyMainThread.release();
} }
...@@ -450,16 +453,18 @@ public final class DynamicConcatenatingMediaSourceTest extends TestCase { ...@@ -450,16 +453,18 @@ public final class DynamicConcatenatingMediaSourceTest extends TestCase {
try { try {
testRunner.prepareSource(); testRunner.prepareSource();
final TimelineGrabber timelineGrabber = new TimelineGrabber(testRunner); final TimelineGrabber timelineGrabber = new TimelineGrabber(testRunner);
dummyMainThread.runOnMainThread(new Runnable() { dummyMainThread.runOnMainThread(
new Runnable() {
@Override @Override
public void run() { public void run() {
mediaSource.addMediaSources( mediaSource.addMediaSources(
Arrays.asList(new MediaSource[] {createFakeMediaSource(), createFakeMediaSource()}), Arrays.asList(
new MediaSource[] {createFakeMediaSource(), createFakeMediaSource()}),
timelineGrabber); timelineGrabber);
} }
}); });
Timeline timeline = timelineGrabber.assertTimelineChangeBlocking(); Timeline timeline = timelineGrabber.assertTimelineChangeBlocking();
assertEquals(2, timeline.getWindowCount()); assertThat(timeline.getWindowCount()).isEqualTo(2);
} finally { } finally {
dummyMainThread.release(); dummyMainThread.release();
} }
...@@ -477,7 +482,7 @@ public final class DynamicConcatenatingMediaSourceTest extends TestCase { ...@@ -477,7 +482,7 @@ public final class DynamicConcatenatingMediaSourceTest extends TestCase {
} }
}); });
Timeline timeline = timelineGrabber.assertTimelineChangeBlocking(); Timeline timeline = timelineGrabber.assertTimelineChangeBlocking();
assertEquals(1, timeline.getWindowCount()); assertThat(timeline.getWindowCount()).isEqualTo(1);
} finally { } finally {
dummyMainThread.release(); dummyMainThread.release();
} }
...@@ -488,16 +493,19 @@ public final class DynamicConcatenatingMediaSourceTest extends TestCase { ...@@ -488,16 +493,19 @@ public final class DynamicConcatenatingMediaSourceTest extends TestCase {
try { try {
testRunner.prepareSource(); testRunner.prepareSource();
final TimelineGrabber timelineGrabber = new TimelineGrabber(testRunner); final TimelineGrabber timelineGrabber = new TimelineGrabber(testRunner);
dummyMainThread.runOnMainThread(new Runnable() { dummyMainThread.runOnMainThread(
new Runnable() {
@Override @Override
public void run() { public void run() {
mediaSource.addMediaSources(/* index */ 0, mediaSource.addMediaSources(
Arrays.asList(new MediaSource[] {createFakeMediaSource(), createFakeMediaSource()}), /* index */ 0,
Arrays.asList(
new MediaSource[] {createFakeMediaSource(), createFakeMediaSource()}),
timelineGrabber); timelineGrabber);
} }
}); });
Timeline timeline = timelineGrabber.assertTimelineChangeBlocking(); Timeline timeline = timelineGrabber.assertTimelineChangeBlocking();
assertEquals(2, timeline.getWindowCount()); assertThat(timeline.getWindowCount()).isEqualTo(2);
} finally { } finally {
dummyMainThread.release(); dummyMainThread.release();
} }
...@@ -523,7 +531,7 @@ public final class DynamicConcatenatingMediaSourceTest extends TestCase { ...@@ -523,7 +531,7 @@ public final class DynamicConcatenatingMediaSourceTest extends TestCase {
} }
}); });
Timeline timeline = timelineGrabber.assertTimelineChangeBlocking(); Timeline timeline = timelineGrabber.assertTimelineChangeBlocking();
assertEquals(0, timeline.getWindowCount()); assertThat(timeline.getWindowCount()).isEqualTo(0);
} finally { } finally {
dummyMainThread.release(); dummyMainThread.release();
} }
...@@ -533,10 +541,12 @@ public final class DynamicConcatenatingMediaSourceTest extends TestCase { ...@@ -533,10 +541,12 @@ public final class DynamicConcatenatingMediaSourceTest extends TestCase {
DummyMainThread dummyMainThread = new DummyMainThread(); DummyMainThread dummyMainThread = new DummyMainThread();
try { try {
testRunner.prepareSource(); testRunner.prepareSource();
dummyMainThread.runOnMainThread(new Runnable() { dummyMainThread.runOnMainThread(
new Runnable() {
@Override @Override
public void run() { public void run() {
mediaSource.addMediaSources(Arrays.asList( mediaSource.addMediaSources(
Arrays.asList(
new MediaSource[] {createFakeMediaSource(), createFakeMediaSource()})); new MediaSource[] {createFakeMediaSource(), createFakeMediaSource()}));
} }
}); });
...@@ -551,7 +561,7 @@ public final class DynamicConcatenatingMediaSourceTest extends TestCase { ...@@ -551,7 +561,7 @@ public final class DynamicConcatenatingMediaSourceTest extends TestCase {
} }
}); });
Timeline timeline = timelineGrabber.assertTimelineChangeBlocking(); Timeline timeline = timelineGrabber.assertTimelineChangeBlocking();
assertEquals(2, timeline.getWindowCount()); assertThat(timeline.getWindowCount()).isEqualTo(2);
} finally { } finally {
dummyMainThread.release(); dummyMainThread.release();
} }
...@@ -624,7 +634,7 @@ public final class DynamicConcatenatingMediaSourceTest extends TestCase { ...@@ -624,7 +634,7 @@ public final class DynamicConcatenatingMediaSourceTest extends TestCase {
finishedCondition.open(); finishedCondition.open();
} }
}); });
assertTrue(finishedCondition.block(MediaSourceTestRunner.TIMEOUT_MS)); assertThat(finishedCondition.block(MediaSourceTestRunner.TIMEOUT_MS)).isTrue();
} }
public void release() { public void release() {
...@@ -657,7 +667,7 @@ public final class DynamicConcatenatingMediaSourceTest extends TestCase { ...@@ -657,7 +667,7 @@ public final class DynamicConcatenatingMediaSourceTest extends TestCase {
} }
public Timeline assertTimelineChangeBlocking() { public Timeline assertTimelineChangeBlocking() {
assertTrue(finishedCondition.block(MediaSourceTestRunner.TIMEOUT_MS)); assertThat(finishedCondition.block(MediaSourceTestRunner.TIMEOUT_MS)).isTrue();
if (error != null) { if (error != null) {
throw error; throw error;
} }
......
...@@ -15,6 +15,8 @@ ...@@ -15,6 +15,8 @@
*/ */
package com.google.android.exoplayer2.source; package com.google.android.exoplayer2.source;
import static com.google.common.truth.Truth.assertThat;
import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Timeline; import com.google.android.exoplayer2.Timeline;
import com.google.android.exoplayer2.source.MergingMediaSource.IllegalMergeException; import com.google.android.exoplayer2.source.MergingMediaSource.IllegalMergeException;
...@@ -53,7 +55,7 @@ public class MergingMediaSourceTest extends TestCase { ...@@ -53,7 +55,7 @@ public class MergingMediaSourceTest extends TestCase {
testMergingMediaSourcePrepare(firstTimeline, secondTimeline); testMergingMediaSourcePrepare(firstTimeline, secondTimeline);
fail("Expected merging to fail."); fail("Expected merging to fail.");
} catch (IllegalMergeException e) { } catch (IllegalMergeException e) {
assertEquals(IllegalMergeException.REASON_PERIOD_COUNT_MISMATCH, e.reason); assertThat(e.reason).isEqualTo(IllegalMergeException.REASON_PERIOD_COUNT_MISMATCH);
} }
} }
...@@ -71,7 +73,7 @@ public class MergingMediaSourceTest extends TestCase { ...@@ -71,7 +73,7 @@ public class MergingMediaSourceTest extends TestCase {
try { try {
Timeline timeline = testRunner.prepareSource(); Timeline timeline = testRunner.prepareSource();
// The merged timeline should always be the one from the first child. // The merged timeline should always be the one from the first child.
assertEquals(timelines[0], timeline); assertThat(timeline).isEqualTo(timelines[0]);
} finally { } finally {
testRunner.release(); testRunner.release();
} }
......
...@@ -15,6 +15,8 @@ ...@@ -15,6 +15,8 @@
*/ */
package com.google.android.exoplayer2.text.ssa; package com.google.android.exoplayer2.text.ssa;
import static com.google.common.truth.Truth.assertThat;
import android.test.InstrumentationTestCase; import android.test.InstrumentationTestCase;
import com.google.android.exoplayer2.testutil.TestUtil; import com.google.android.exoplayer2.testutil.TestUtil;
import java.io.IOException; import java.io.IOException;
...@@ -38,8 +40,8 @@ public final class SsaDecoderTest extends InstrumentationTestCase { ...@@ -38,8 +40,8 @@ public final class SsaDecoderTest extends InstrumentationTestCase {
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), EMPTY); byte[] bytes = TestUtil.getByteArray(getInstrumentation(), EMPTY);
SsaSubtitle subtitle = decoder.decode(bytes, bytes.length, false); SsaSubtitle subtitle = decoder.decode(bytes, bytes.length, false);
assertEquals(0, subtitle.getEventTimeCount()); assertThat(subtitle.getEventTimeCount()).isEqualTo(0);
assertTrue(subtitle.getCues(0).isEmpty()); assertThat(subtitle.getCues(0).isEmpty()).isTrue();
} }
public void testDecodeTypical() throws IOException { public void testDecodeTypical() throws IOException {
...@@ -47,7 +49,7 @@ public final class SsaDecoderTest extends InstrumentationTestCase { ...@@ -47,7 +49,7 @@ public final class SsaDecoderTest extends InstrumentationTestCase {
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), TYPICAL); byte[] bytes = TestUtil.getByteArray(getInstrumentation(), TYPICAL);
SsaSubtitle subtitle = decoder.decode(bytes, bytes.length, false); SsaSubtitle subtitle = decoder.decode(bytes, bytes.length, false);
assertEquals(6, subtitle.getEventTimeCount()); assertThat(subtitle.getEventTimeCount()).isEqualTo(6);
assertTypicalCue1(subtitle, 0); assertTypicalCue1(subtitle, 0);
assertTypicalCue2(subtitle, 2); assertTypicalCue2(subtitle, 2);
assertTypicalCue3(subtitle, 4); assertTypicalCue3(subtitle, 4);
...@@ -63,7 +65,7 @@ public final class SsaDecoderTest extends InstrumentationTestCase { ...@@ -63,7 +65,7 @@ public final class SsaDecoderTest extends InstrumentationTestCase {
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), TYPICAL_DIALOGUE_ONLY); byte[] bytes = TestUtil.getByteArray(getInstrumentation(), TYPICAL_DIALOGUE_ONLY);
SsaSubtitle subtitle = decoder.decode(bytes, bytes.length, false); SsaSubtitle subtitle = decoder.decode(bytes, bytes.length, false);
assertEquals(6, subtitle.getEventTimeCount()); assertThat(subtitle.getEventTimeCount()).isEqualTo(6);
assertTypicalCue1(subtitle, 0); assertTypicalCue1(subtitle, 0);
assertTypicalCue2(subtitle, 2); assertTypicalCue2(subtitle, 2);
assertTypicalCue3(subtitle, 4); assertTypicalCue3(subtitle, 4);
...@@ -75,7 +77,7 @@ public final class SsaDecoderTest extends InstrumentationTestCase { ...@@ -75,7 +77,7 @@ public final class SsaDecoderTest extends InstrumentationTestCase {
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), INVALID_TIMECODES); byte[] bytes = TestUtil.getByteArray(getInstrumentation(), INVALID_TIMECODES);
SsaSubtitle subtitle = decoder.decode(bytes, bytes.length, false); SsaSubtitle subtitle = decoder.decode(bytes, bytes.length, false);
assertEquals(2, subtitle.getEventTimeCount()); assertThat(subtitle.getEventTimeCount()).isEqualTo(2);
assertTypicalCue3(subtitle, 0); assertTypicalCue3(subtitle, 0);
} }
...@@ -84,40 +86,40 @@ public final class SsaDecoderTest extends InstrumentationTestCase { ...@@ -84,40 +86,40 @@ public final class SsaDecoderTest extends InstrumentationTestCase {
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), NO_END_TIMECODES); byte[] bytes = TestUtil.getByteArray(getInstrumentation(), NO_END_TIMECODES);
SsaSubtitle subtitle = decoder.decode(bytes, bytes.length, false); SsaSubtitle subtitle = decoder.decode(bytes, bytes.length, false);
assertEquals(3, subtitle.getEventTimeCount()); assertThat(subtitle.getEventTimeCount()).isEqualTo(3);
assertEquals(0, subtitle.getEventTime(0)); assertThat(subtitle.getEventTime(0)).isEqualTo(0);
assertEquals("This is the first subtitle.", assertThat(subtitle.getCues(subtitle.getEventTime(0)).get(0).text.toString())
subtitle.getCues(subtitle.getEventTime(0)).get(0).text.toString()); .isEqualTo("This is the first subtitle.");
assertEquals(2340000, subtitle.getEventTime(1)); assertThat(subtitle.getEventTime(1)).isEqualTo(2340000);
assertEquals("This is the second subtitle \nwith a newline \nand another.", assertThat(subtitle.getCues(subtitle.getEventTime(1)).get(0).text.toString())
subtitle.getCues(subtitle.getEventTime(1)).get(0).text.toString()); .isEqualTo("This is the second subtitle \nwith a newline \nand another.");
assertEquals(4560000, subtitle.getEventTime(2)); assertThat(subtitle.getEventTime(2)).isEqualTo(4560000);
assertEquals("This is the third subtitle, with a comma.", assertThat(subtitle.getCues(subtitle.getEventTime(2)).get(0).text.toString())
subtitle.getCues(subtitle.getEventTime(2)).get(0).text.toString()); .isEqualTo("This is the third subtitle, with a comma.");
} }
private static void assertTypicalCue1(SsaSubtitle subtitle, int eventIndex) { private static void assertTypicalCue1(SsaSubtitle subtitle, int eventIndex) {
assertEquals(0, subtitle.getEventTime(eventIndex)); assertThat(subtitle.getEventTime(eventIndex)).isEqualTo(0);
assertEquals("This is the first subtitle.", assertThat(subtitle.getCues(subtitle.getEventTime(eventIndex)).get(0).text.toString())
subtitle.getCues(subtitle.getEventTime(eventIndex)).get(0).text.toString()); .isEqualTo("This is the first subtitle.");
assertEquals(1230000, subtitle.getEventTime(eventIndex + 1)); assertThat(subtitle.getEventTime(eventIndex + 1)).isEqualTo(1230000);
} }
private static void assertTypicalCue2(SsaSubtitle subtitle, int eventIndex) { private static void assertTypicalCue2(SsaSubtitle subtitle, int eventIndex) {
assertEquals(2340000, subtitle.getEventTime(eventIndex)); assertThat(subtitle.getEventTime(eventIndex)).isEqualTo(2340000);
assertEquals("This is the second subtitle \nwith a newline \nand another.", assertThat(subtitle.getCues(subtitle.getEventTime(eventIndex)).get(0).text.toString())
subtitle.getCues(subtitle.getEventTime(eventIndex)).get(0).text.toString()); .isEqualTo("This is the second subtitle \nwith a newline \nand another.");
assertEquals(3450000, subtitle.getEventTime(eventIndex + 1)); assertThat(subtitle.getEventTime(eventIndex + 1)).isEqualTo(3450000);
} }
private static void assertTypicalCue3(SsaSubtitle subtitle, int eventIndex) { private static void assertTypicalCue3(SsaSubtitle subtitle, int eventIndex) {
assertEquals(4560000, subtitle.getEventTime(eventIndex)); assertThat(subtitle.getEventTime(eventIndex)).isEqualTo(4560000);
assertEquals("This is the third subtitle, with a comma.", assertThat(subtitle.getCues(subtitle.getEventTime(eventIndex)).get(0).text.toString())
subtitle.getCues(subtitle.getEventTime(eventIndex)).get(0).text.toString()); .isEqualTo("This is the third subtitle, with a comma.");
assertEquals(8900000, subtitle.getEventTime(eventIndex + 1)); assertThat(subtitle.getEventTime(eventIndex + 1)).isEqualTo(8900000);
} }
} }
...@@ -15,6 +15,8 @@ ...@@ -15,6 +15,8 @@
*/ */
package com.google.android.exoplayer2.text.subrip; package com.google.android.exoplayer2.text.subrip;
import static com.google.common.truth.Truth.assertThat;
import android.test.InstrumentationTestCase; import android.test.InstrumentationTestCase;
import com.google.android.exoplayer2.testutil.TestUtil; import com.google.android.exoplayer2.testutil.TestUtil;
import java.io.IOException; import java.io.IOException;
...@@ -39,8 +41,8 @@ public final class SubripDecoderTest extends InstrumentationTestCase { ...@@ -39,8 +41,8 @@ public final class SubripDecoderTest extends InstrumentationTestCase {
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), EMPTY_FILE); byte[] bytes = TestUtil.getByteArray(getInstrumentation(), EMPTY_FILE);
SubripSubtitle subtitle = decoder.decode(bytes, bytes.length, false); SubripSubtitle subtitle = decoder.decode(bytes, bytes.length, false);
assertEquals(0, subtitle.getEventTimeCount()); assertThat(subtitle.getEventTimeCount()).isEqualTo(0);
assertTrue(subtitle.getCues(0).isEmpty()); assertThat(subtitle.getCues(0).isEmpty()).isTrue();
} }
public void testDecodeTypical() throws IOException { public void testDecodeTypical() throws IOException {
...@@ -48,7 +50,7 @@ public final class SubripDecoderTest extends InstrumentationTestCase { ...@@ -48,7 +50,7 @@ public final class SubripDecoderTest extends InstrumentationTestCase {
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), TYPICAL_FILE); byte[] bytes = TestUtil.getByteArray(getInstrumentation(), TYPICAL_FILE);
SubripSubtitle subtitle = decoder.decode(bytes, bytes.length, false); SubripSubtitle subtitle = decoder.decode(bytes, bytes.length, false);
assertEquals(6, subtitle.getEventTimeCount()); assertThat(subtitle.getEventTimeCount()).isEqualTo(6);
assertTypicalCue1(subtitle, 0); assertTypicalCue1(subtitle, 0);
assertTypicalCue2(subtitle, 2); assertTypicalCue2(subtitle, 2);
assertTypicalCue3(subtitle, 4); assertTypicalCue3(subtitle, 4);
...@@ -59,7 +61,7 @@ public final class SubripDecoderTest extends InstrumentationTestCase { ...@@ -59,7 +61,7 @@ public final class SubripDecoderTest extends InstrumentationTestCase {
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), TYPICAL_WITH_BYTE_ORDER_MARK); byte[] bytes = TestUtil.getByteArray(getInstrumentation(), TYPICAL_WITH_BYTE_ORDER_MARK);
SubripSubtitle subtitle = decoder.decode(bytes, bytes.length, false); SubripSubtitle subtitle = decoder.decode(bytes, bytes.length, false);
assertEquals(6, subtitle.getEventTimeCount()); assertThat(subtitle.getEventTimeCount()).isEqualTo(6);
assertTypicalCue1(subtitle, 0); assertTypicalCue1(subtitle, 0);
assertTypicalCue2(subtitle, 2); assertTypicalCue2(subtitle, 2);
assertTypicalCue3(subtitle, 4); assertTypicalCue3(subtitle, 4);
...@@ -70,7 +72,7 @@ public final class SubripDecoderTest extends InstrumentationTestCase { ...@@ -70,7 +72,7 @@ public final class SubripDecoderTest extends InstrumentationTestCase {
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), TYPICAL_EXTRA_BLANK_LINE); byte[] bytes = TestUtil.getByteArray(getInstrumentation(), TYPICAL_EXTRA_BLANK_LINE);
SubripSubtitle subtitle = decoder.decode(bytes, bytes.length, false); SubripSubtitle subtitle = decoder.decode(bytes, bytes.length, false);
assertEquals(6, subtitle.getEventTimeCount()); assertThat(subtitle.getEventTimeCount()).isEqualTo(6);
assertTypicalCue1(subtitle, 0); assertTypicalCue1(subtitle, 0);
assertTypicalCue2(subtitle, 2); assertTypicalCue2(subtitle, 2);
assertTypicalCue3(subtitle, 4); assertTypicalCue3(subtitle, 4);
...@@ -82,7 +84,7 @@ public final class SubripDecoderTest extends InstrumentationTestCase { ...@@ -82,7 +84,7 @@ public final class SubripDecoderTest extends InstrumentationTestCase {
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), TYPICAL_MISSING_TIMECODE); byte[] bytes = TestUtil.getByteArray(getInstrumentation(), TYPICAL_MISSING_TIMECODE);
SubripSubtitle subtitle = decoder.decode(bytes, bytes.length, false); SubripSubtitle subtitle = decoder.decode(bytes, bytes.length, false);
assertEquals(4, subtitle.getEventTimeCount()); assertThat(subtitle.getEventTimeCount()).isEqualTo(4);
assertTypicalCue1(subtitle, 0); assertTypicalCue1(subtitle, 0);
assertTypicalCue3(subtitle, 2); assertTypicalCue3(subtitle, 2);
} }
...@@ -93,7 +95,7 @@ public final class SubripDecoderTest extends InstrumentationTestCase { ...@@ -93,7 +95,7 @@ public final class SubripDecoderTest extends InstrumentationTestCase {
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), TYPICAL_MISSING_SEQUENCE); byte[] bytes = TestUtil.getByteArray(getInstrumentation(), TYPICAL_MISSING_SEQUENCE);
SubripSubtitle subtitle = decoder.decode(bytes, bytes.length, false); SubripSubtitle subtitle = decoder.decode(bytes, bytes.length, false);
assertEquals(4, subtitle.getEventTimeCount()); assertThat(subtitle.getEventTimeCount()).isEqualTo(4);
assertTypicalCue1(subtitle, 0); assertTypicalCue1(subtitle, 0);
assertTypicalCue3(subtitle, 2); assertTypicalCue3(subtitle, 2);
} }
...@@ -104,7 +106,7 @@ public final class SubripDecoderTest extends InstrumentationTestCase { ...@@ -104,7 +106,7 @@ public final class SubripDecoderTest extends InstrumentationTestCase {
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), TYPICAL_NEGATIVE_TIMESTAMPS); byte[] bytes = TestUtil.getByteArray(getInstrumentation(), TYPICAL_NEGATIVE_TIMESTAMPS);
SubripSubtitle subtitle = decoder.decode(bytes, bytes.length, false); SubripSubtitle subtitle = decoder.decode(bytes, bytes.length, false);
assertEquals(2, subtitle.getEventTimeCount()); assertThat(subtitle.getEventTimeCount()).isEqualTo(2);
assertTypicalCue3(subtitle, 0); assertTypicalCue3(subtitle, 0);
} }
...@@ -114,7 +116,7 @@ public final class SubripDecoderTest extends InstrumentationTestCase { ...@@ -114,7 +116,7 @@ public final class SubripDecoderTest extends InstrumentationTestCase {
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), TYPICAL_UNEXPECTED_END); byte[] bytes = TestUtil.getByteArray(getInstrumentation(), TYPICAL_UNEXPECTED_END);
SubripSubtitle subtitle = decoder.decode(bytes, bytes.length, false); SubripSubtitle subtitle = decoder.decode(bytes, bytes.length, false);
assertEquals(4, subtitle.getEventTimeCount()); assertThat(subtitle.getEventTimeCount()).isEqualTo(4);
assertTypicalCue1(subtitle, 0); assertTypicalCue1(subtitle, 0);
assertTypicalCue2(subtitle, 2); assertTypicalCue2(subtitle, 2);
} }
...@@ -124,40 +126,40 @@ public final class SubripDecoderTest extends InstrumentationTestCase { ...@@ -124,40 +126,40 @@ public final class SubripDecoderTest extends InstrumentationTestCase {
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), NO_END_TIMECODES_FILE); byte[] bytes = TestUtil.getByteArray(getInstrumentation(), NO_END_TIMECODES_FILE);
SubripSubtitle subtitle = decoder.decode(bytes, bytes.length, false); SubripSubtitle subtitle = decoder.decode(bytes, bytes.length, false);
assertEquals(3, subtitle.getEventTimeCount()); assertThat(subtitle.getEventTimeCount()).isEqualTo(3);
assertEquals(0, subtitle.getEventTime(0)); assertThat(subtitle.getEventTime(0)).isEqualTo(0);
assertEquals("SubRip doesn't technically allow missing end timecodes.", assertThat(subtitle.getCues(subtitle.getEventTime(0)).get(0).text.toString())
subtitle.getCues(subtitle.getEventTime(0)).get(0).text.toString()); .isEqualTo("SubRip doesn't technically allow missing end timecodes.");
assertEquals(2345000, subtitle.getEventTime(1)); assertThat(subtitle.getEventTime(1)).isEqualTo(2345000);
assertEquals("We interpret it to mean that a subtitle extends to the start of the next one.", assertThat(subtitle.getCues(subtitle.getEventTime(1)).get(0).text.toString())
subtitle.getCues(subtitle.getEventTime(1)).get(0).text.toString()); .isEqualTo("We interpret it to mean that a subtitle extends to the start of the next one.");
assertEquals(3456000, subtitle.getEventTime(2)); assertThat(subtitle.getEventTime(2)).isEqualTo(3456000);
assertEquals("Or to the end of the media.", assertThat(subtitle.getCues(subtitle.getEventTime(2)).get(0).text.toString())
subtitle.getCues(subtitle.getEventTime(2)).get(0).text.toString()); .isEqualTo("Or to the end of the media.");
} }
private static void assertTypicalCue1(SubripSubtitle subtitle, int eventIndex) { private static void assertTypicalCue1(SubripSubtitle subtitle, int eventIndex) {
assertEquals(0, subtitle.getEventTime(eventIndex)); assertThat(subtitle.getEventTime(eventIndex)).isEqualTo(0);
assertEquals("This is the first subtitle.", assertThat(subtitle.getCues(subtitle.getEventTime(eventIndex)).get(0).text.toString())
subtitle.getCues(subtitle.getEventTime(eventIndex)).get(0).text.toString()); .isEqualTo("This is the first subtitle.");
assertEquals(1234000, subtitle.getEventTime(eventIndex + 1)); assertThat(subtitle.getEventTime(eventIndex + 1)).isEqualTo(1234000);
} }
private static void assertTypicalCue2(SubripSubtitle subtitle, int eventIndex) { private static void assertTypicalCue2(SubripSubtitle subtitle, int eventIndex) {
assertEquals(2345000, subtitle.getEventTime(eventIndex)); assertThat(subtitle.getEventTime(eventIndex)).isEqualTo(2345000);
assertEquals("This is the second subtitle.\nSecond subtitle with second line.", assertThat(subtitle.getCues(subtitle.getEventTime(eventIndex)).get(0).text.toString())
subtitle.getCues(subtitle.getEventTime(eventIndex)).get(0).text.toString()); .isEqualTo("This is the second subtitle.\nSecond subtitle with second line.");
assertEquals(3456000, subtitle.getEventTime(eventIndex + 1)); assertThat(subtitle.getEventTime(eventIndex + 1)).isEqualTo(3456000);
} }
private static void assertTypicalCue3(SubripSubtitle subtitle, int eventIndex) { private static void assertTypicalCue3(SubripSubtitle subtitle, int eventIndex) {
assertEquals(4567000, subtitle.getEventTime(eventIndex)); assertThat(subtitle.getEventTime(eventIndex)).isEqualTo(4567000);
assertEquals("This is the third subtitle.", assertThat(subtitle.getCues(subtitle.getEventTime(eventIndex)).get(0).text.toString())
subtitle.getCues(subtitle.getEventTime(eventIndex)).get(0).text.toString()); .isEqualTo("This is the third subtitle.");
assertEquals(8901000, subtitle.getEventTime(eventIndex + 1)); assertThat(subtitle.getEventTime(eventIndex + 1)).isEqualTo(8901000);
} }
} }
...@@ -15,6 +15,8 @@ ...@@ -15,6 +15,8 @@
*/ */
package com.google.android.exoplayer2.upstream; package com.google.android.exoplayer2.upstream;
import static com.google.common.truth.Truth.assertThat;
import android.app.Instrumentation; import android.app.Instrumentation;
import android.content.ContentProvider; import android.content.ContentProvider;
import android.content.ContentResolver; import android.content.ContentResolver;
...@@ -75,7 +77,7 @@ public final class ContentDataSourceTest extends InstrumentationTestCase { ...@@ -75,7 +77,7 @@ public final class ContentDataSourceTest extends InstrumentationTestCase {
fail(); fail();
} catch (ContentDataSource.ContentDataSourceException e) { } catch (ContentDataSource.ContentDataSourceException e) {
// Expected. // Expected.
assertTrue(e.getCause() instanceof FileNotFoundException); assertThat(e.getCause()).isInstanceOf(FileNotFoundException.class);
} finally { } finally {
dataSource.close(); dataSource.close();
} }
......
...@@ -15,6 +15,7 @@ ...@@ -15,6 +15,7 @@
*/ */
package com.google.android.exoplayer2.upstream.cache; package com.google.android.exoplayer2.upstream.cache;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.any; import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
...@@ -67,8 +68,8 @@ public final class CachedRegionTrackerTest extends InstrumentationTestCase { ...@@ -67,8 +68,8 @@ public final class CachedRegionTrackerTest extends InstrumentationTestCase {
} }
public void testGetRegion_noSpansInCache() { public void testGetRegion_noSpansInCache() {
assertEquals(CachedRegionTracker.NOT_CACHED, tracker.getRegionEndTimeMs(100)); assertThat(tracker.getRegionEndTimeMs(100)).isEqualTo(CachedRegionTracker.NOT_CACHED);
assertEquals(CachedRegionTracker.NOT_CACHED, tracker.getRegionEndTimeMs(150)); assertThat(tracker.getRegionEndTimeMs(150)).isEqualTo(CachedRegionTracker.NOT_CACHED);
} }
public void testGetRegion_fullyCached() throws Exception { public void testGetRegion_fullyCached() throws Exception {
...@@ -76,8 +77,8 @@ public final class CachedRegionTrackerTest extends InstrumentationTestCase { ...@@ -76,8 +77,8 @@ public final class CachedRegionTrackerTest extends InstrumentationTestCase {
cache, cache,
newCacheSpan(100, 100)); newCacheSpan(100, 100));
assertEquals(CachedRegionTracker.CACHED_TO_END, tracker.getRegionEndTimeMs(101)); assertThat(tracker.getRegionEndTimeMs(101)).isEqualTo(CachedRegionTracker.CACHED_TO_END);
assertEquals(CachedRegionTracker.CACHED_TO_END, tracker.getRegionEndTimeMs(121)); assertThat(tracker.getRegionEndTimeMs(121)).isEqualTo(CachedRegionTracker.CACHED_TO_END);
} }
public void testGetRegion_partiallyCached() throws Exception { public void testGetRegion_partiallyCached() throws Exception {
...@@ -85,8 +86,8 @@ public final class CachedRegionTrackerTest extends InstrumentationTestCase { ...@@ -85,8 +86,8 @@ public final class CachedRegionTrackerTest extends InstrumentationTestCase {
cache, cache,
newCacheSpan(100, 40)); newCacheSpan(100, 40));
assertEquals(200, tracker.getRegionEndTimeMs(101)); assertThat(tracker.getRegionEndTimeMs(101)).isEqualTo(200);
assertEquals(200, tracker.getRegionEndTimeMs(121)); assertThat(tracker.getRegionEndTimeMs(121)).isEqualTo(200);
} }
public void testGetRegion_multipleSpanAddsJoinedCorrectly() throws Exception { public void testGetRegion_multipleSpanAddsJoinedCorrectly() throws Exception {
...@@ -97,8 +98,8 @@ public final class CachedRegionTrackerTest extends InstrumentationTestCase { ...@@ -97,8 +98,8 @@ public final class CachedRegionTrackerTest extends InstrumentationTestCase {
cache, cache,
newCacheSpan(120, 20)); newCacheSpan(120, 20));
assertEquals(200, tracker.getRegionEndTimeMs(101)); assertThat(tracker.getRegionEndTimeMs(101)).isEqualTo(200);
assertEquals(200, tracker.getRegionEndTimeMs(121)); assertThat(tracker.getRegionEndTimeMs(121)).isEqualTo(200);
} }
public void testGetRegion_fullyCachedThenPartiallyRemoved() throws Exception { public void testGetRegion_fullyCachedThenPartiallyRemoved() throws Exception {
...@@ -112,10 +113,10 @@ public final class CachedRegionTrackerTest extends InstrumentationTestCase { ...@@ -112,10 +113,10 @@ public final class CachedRegionTrackerTest extends InstrumentationTestCase {
cache, cache,
newCacheSpan(140, 40)); newCacheSpan(140, 40));
assertEquals(200, tracker.getRegionEndTimeMs(101)); assertThat(tracker.getRegionEndTimeMs(101)).isEqualTo(200);
assertEquals(200, tracker.getRegionEndTimeMs(121)); assertThat(tracker.getRegionEndTimeMs(121)).isEqualTo(200);
assertEquals(CachedRegionTracker.CACHED_TO_END, tracker.getRegionEndTimeMs(181)); assertThat(tracker.getRegionEndTimeMs(181)).isEqualTo(CachedRegionTracker.CACHED_TO_END);
} }
public void testGetRegion_subchunkEstimation() throws Exception { public void testGetRegion_subchunkEstimation() throws Exception {
...@@ -123,8 +124,8 @@ public final class CachedRegionTrackerTest extends InstrumentationTestCase { ...@@ -123,8 +124,8 @@ public final class CachedRegionTrackerTest extends InstrumentationTestCase {
cache, cache,
newCacheSpan(100, 10)); newCacheSpan(100, 10));
assertEquals(50, tracker.getRegionEndTimeMs(101)); assertThat(tracker.getRegionEndTimeMs(101)).isEqualTo(50);
assertEquals(CachedRegionTracker.NOT_CACHED, tracker.getRegionEndTimeMs(111)); assertThat(tracker.getRegionEndTimeMs(111)).isEqualTo(CachedRegionTracker.NOT_CACHED);
} }
private CacheSpan newCacheSpan(int position, int length) throws IOException { private CacheSpan newCacheSpan(int position, int length) throws IOException {
......
...@@ -15,6 +15,9 @@ ...@@ -15,6 +15,9 @@
*/ */
package com.google.android.exoplayer2.upstream.cache; package com.google.android.exoplayer2.upstream.cache;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import android.test.InstrumentationTestCase; import android.test.InstrumentationTestCase;
import com.google.android.exoplayer2.util.Util; import com.google.android.exoplayer2.util.Util;
import java.io.File; import java.io.File;
...@@ -88,39 +91,39 @@ public class SimpleCacheSpanTest extends InstrumentationTestCase { ...@@ -88,39 +91,39 @@ public class SimpleCacheSpanTest extends InstrumentationTestCase {
for (File file : cacheDir.listFiles()) { for (File file : cacheDir.listFiles()) {
SimpleCacheSpan cacheEntry = SimpleCacheSpan.createCacheEntry(file, index); SimpleCacheSpan cacheEntry = SimpleCacheSpan.createCacheEntry(file, index);
if (file.equals(wrongEscapedV2file)) { if (file.equals(wrongEscapedV2file)) {
assertNull(cacheEntry); assertThat(cacheEntry).isNull();
} else { } else {
assertNotNull(cacheEntry); assertThat(cacheEntry).isNotNull();
} }
} }
assertTrue(v3file.exists()); assertThat(v3file.exists()).isTrue();
assertFalse(v2file.exists()); assertThat(v2file.exists()).isFalse();
assertTrue(wrongEscapedV2file.exists()); assertThat(wrongEscapedV2file.exists()).isTrue();
assertFalse(v1File.exists()); assertThat(v1File.exists()).isFalse();
File[] files = cacheDir.listFiles(); File[] files = cacheDir.listFiles();
assertEquals(4, files.length); assertThat(files).hasLength(4);
Set<String> keys = index.getKeys(); Set<String> keys = index.getKeys();
assertEquals("There should be only one key for all files.", 1, keys.size()); assertWithMessage("There should be only one key for all files.").that(keys).hasSize(1);
assertTrue(keys.contains(key)); assertThat(keys).contains(key);
TreeSet<SimpleCacheSpan> spans = index.get(key).getSpans(); TreeSet<SimpleCacheSpan> spans = index.get(key).getSpans();
assertTrue("upgradeOldFiles() shouldn't add any spans.", spans.isEmpty()); assertWithMessage("upgradeOldFiles() shouldn't add any spans.").that(spans.isEmpty()).isTrue();
HashMap<Long, Long> cachedPositions = new HashMap<>(); HashMap<Long, Long> cachedPositions = new HashMap<>();
for (File file : files) { for (File file : files) {
SimpleCacheSpan cacheSpan = SimpleCacheSpan.createCacheEntry(file, index); SimpleCacheSpan cacheSpan = SimpleCacheSpan.createCacheEntry(file, index);
if (cacheSpan != null) { if (cacheSpan != null) {
assertEquals(key, cacheSpan.key); assertThat(cacheSpan.key).isEqualTo(key);
cachedPositions.put(cacheSpan.position, cacheSpan.lastAccessTimestamp); cachedPositions.put(cacheSpan.position, cacheSpan.lastAccessTimestamp);
} }
} }
assertEquals(1, (long) cachedPositions.get((long) 0)); assertThat(cachedPositions.get((long) 0)).isEqualTo(1);
assertEquals(2, (long) cachedPositions.get((long) 1)); assertThat(cachedPositions.get((long) 1)).isEqualTo(2);
assertEquals(6, (long) cachedPositions.get((long) 5)); assertThat(cachedPositions.get((long) 5)).isEqualTo(6);
} }
private static void createTestFile(File file, int length) throws IOException { private static void createTestFile(File file, int length) throws IOException {
...@@ -143,14 +146,14 @@ public class SimpleCacheSpanTest extends InstrumentationTestCase { ...@@ -143,14 +146,14 @@ public class SimpleCacheSpanTest extends InstrumentationTestCase {
File cacheFile = createCacheSpanFile(cacheDir, id, offset, 1, lastAccessTimestamp); File cacheFile = createCacheSpanFile(cacheDir, id, offset, 1, lastAccessTimestamp);
SimpleCacheSpan cacheSpan = SimpleCacheSpan.createCacheEntry(cacheFile, index); SimpleCacheSpan cacheSpan = SimpleCacheSpan.createCacheEntry(cacheFile, index);
String message = cacheFile.toString(); String message = cacheFile.toString();
assertNotNull(message, cacheSpan); assertWithMessage(message).that(cacheSpan).isNotNull();
assertEquals(message, cacheDir, cacheFile.getParentFile()); assertWithMessage(message).that(cacheFile.getParentFile()).isEqualTo(cacheDir);
assertEquals(message, key, cacheSpan.key); assertWithMessage(message).that(cacheSpan.key).isEqualTo(key);
assertEquals(message, offset, cacheSpan.position); assertWithMessage(message).that(cacheSpan.position).isEqualTo(offset);
assertEquals(message, 1, cacheSpan.length); assertWithMessage(message).that(cacheSpan.length).isEqualTo(1);
assertTrue(message, cacheSpan.isCached); assertWithMessage(message).that(cacheSpan.isCached).isTrue();
assertEquals(message, cacheFile, cacheSpan.file); assertWithMessage(message).that(cacheSpan.file).isEqualTo(cacheFile);
assertEquals(message, lastAccessTimestamp, cacheSpan.lastAccessTimestamp); assertWithMessage(message).that(cacheSpan.lastAccessTimestamp).isEqualTo(lastAccessTimestamp);
} }
private void assertNullCacheSpan(File parent, String key, long offset, private void assertNullCacheSpan(File parent, String key, long offset,
...@@ -158,7 +161,7 @@ public class SimpleCacheSpanTest extends InstrumentationTestCase { ...@@ -158,7 +161,7 @@ public class SimpleCacheSpanTest extends InstrumentationTestCase {
File cacheFile = SimpleCacheSpan.getCacheFile(parent, index.assignIdForKey(key), offset, File cacheFile = SimpleCacheSpan.getCacheFile(parent, index.assignIdForKey(key), offset,
lastAccessTimestamp); lastAccessTimestamp);
CacheSpan cacheSpan = SimpleCacheSpan.createCacheEntry(cacheFile, index); CacheSpan cacheSpan = SimpleCacheSpan.createCacheEntry(cacheFile, index);
assertNull(cacheFile.toString(), cacheSpan); assertWithMessage(cacheFile.toString()).that(cacheSpan).isNull();
} }
} }
...@@ -142,10 +142,7 @@ public class DefaultEbmlReaderTest { ...@@ -142,10 +142,7 @@ public class DefaultEbmlReaderTest {
// Check that we really did get to the end of input. // Check that we really did get to the end of input.
assertThat(input.readFully(new byte[1], 0, 1, true)).isFalse(); assertThat(input.readFully(new byte[1], 0, 1, true)).isFalse();
assertThat(output.events).hasSize(expectedEvents.size()); assertThat(output.events).containsExactlyElementsIn(expectedEvents).inOrder();
for (int i = 0; i < expectedEvents.size(); i++) {
assertThat(output.events.get(i)).isEqualTo(expectedEvents.get(i));
}
} }
/** /**
......
...@@ -83,11 +83,9 @@ public class SimpleCacheTest { ...@@ -83,11 +83,9 @@ public class SimpleCacheTest {
addCache(simpleCache, KEY_1, 0, 15); addCache(simpleCache, KEY_1, 0, 15);
Set<String> cachedKeys = simpleCache.getKeys(); Set<String> cachedKeys = simpleCache.getKeys();
assertThat(cachedKeys).hasSize(1); assertThat(cachedKeys).containsExactly(KEY_1);
assertThat(cachedKeys.contains(KEY_1)).isTrue();
cachedSpans = simpleCache.getCachedSpans(KEY_1); cachedSpans = simpleCache.getCachedSpans(KEY_1);
assertThat(cachedSpans).hasSize(1); assertThat(cachedSpans).contains(cacheSpan1);
assertThat(cachedSpans.contains(cacheSpan1)).isTrue();
assertThat(simpleCache.getCacheSpace()).isEqualTo(15); assertThat(simpleCache.getCacheSpace()).isEqualTo(15);
simpleCache.releaseHoleSpan(cacheSpan1); simpleCache.releaseHoleSpan(cacheSpan1);
......
...@@ -17,7 +17,7 @@ package com.google.android.exoplayer2.util; ...@@ -17,7 +17,7 @@ package com.google.android.exoplayer2.util;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static java.nio.charset.Charset.forName; import static java.nio.charset.Charset.forName;
import static junit.framework.TestCase.fail; import static org.junit.Assert.fail;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.util.Arrays; import java.util.Arrays;
......
...@@ -15,6 +15,8 @@ ...@@ -15,6 +15,8 @@
*/ */
package com.google.android.exoplayer2.source.dash; package com.google.android.exoplayer2.source.dash;
import static com.google.common.truth.Truth.assertThat;
import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.drm.DrmInitData; import com.google.android.exoplayer2.drm.DrmInitData;
...@@ -36,25 +38,25 @@ public final class DashUtilTest extends TestCase { ...@@ -36,25 +38,25 @@ public final class DashUtilTest extends TestCase {
public void testLoadDrmInitDataFromManifest() throws Exception { public void testLoadDrmInitDataFromManifest() throws Exception {
Period period = newPeriod(newAdaptationSets(newRepresentations(newDrmInitData()))); Period period = newPeriod(newAdaptationSets(newRepresentations(newDrmInitData())));
DrmInitData drmInitData = DashUtil.loadDrmInitData(DummyDataSource.INSTANCE, period); DrmInitData drmInitData = DashUtil.loadDrmInitData(DummyDataSource.INSTANCE, period);
assertEquals(newDrmInitData(), drmInitData); assertThat(drmInitData).isEqualTo(newDrmInitData());
} }
public void testLoadDrmInitDataMissing() throws Exception { public void testLoadDrmInitDataMissing() throws Exception {
Period period = newPeriod(newAdaptationSets(newRepresentations(null /* no init data */))); Period period = newPeriod(newAdaptationSets(newRepresentations(null /* no init data */)));
DrmInitData drmInitData = DashUtil.loadDrmInitData(DummyDataSource.INSTANCE, period); DrmInitData drmInitData = DashUtil.loadDrmInitData(DummyDataSource.INSTANCE, period);
assertNull(drmInitData); assertThat(drmInitData).isNull();
} }
public void testLoadDrmInitDataNoRepresentations() throws Exception { public void testLoadDrmInitDataNoRepresentations() throws Exception {
Period period = newPeriod(newAdaptationSets(/* no representation */)); Period period = newPeriod(newAdaptationSets(/* no representation */));
DrmInitData drmInitData = DashUtil.loadDrmInitData(DummyDataSource.INSTANCE, period); DrmInitData drmInitData = DashUtil.loadDrmInitData(DummyDataSource.INSTANCE, period);
assertNull(drmInitData); assertThat(drmInitData).isNull();
} }
public void testLoadDrmInitDataNoAdaptationSets() throws Exception { public void testLoadDrmInitDataNoAdaptationSets() throws Exception {
Period period = newPeriod(/* no adaptation set */); Period period = newPeriod(/* no adaptation set */);
DrmInitData drmInitData = DashUtil.loadDrmInitData(DummyDataSource.INSTANCE, period); DrmInitData drmInitData = DashUtil.loadDrmInitData(DummyDataSource.INSTANCE, period);
assertNull(drmInitData); assertThat(drmInitData).isNull();
} }
private static Period newPeriod(AdaptationSet... adaptationSets) { private static Period newPeriod(AdaptationSet... adaptationSets) {
......
...@@ -15,6 +15,8 @@ ...@@ -15,6 +15,8 @@
*/ */
package com.google.android.exoplayer2.source.dash.manifest; package com.google.android.exoplayer2.source.dash.manifest;
import static com.google.common.truth.Truth.assertThat;
import android.net.Uri; import android.net.Uri;
import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.source.dash.manifest.SegmentBase.SingleSegmentBase; import com.google.android.exoplayer2.source.dash.manifest.SegmentBase.SingleSegmentBase;
...@@ -129,33 +131,35 @@ public class DashManifestTest extends TestCase { ...@@ -129,33 +131,35 @@ public class DashManifestTest extends TestCase {
} }
private static void assertManifestEquals(DashManifest expected, DashManifest actual) { private static void assertManifestEquals(DashManifest expected, DashManifest actual) {
assertEquals(expected.availabilityStartTimeMs, actual.availabilityStartTimeMs); assertThat(actual.availabilityStartTimeMs).isEqualTo(expected.availabilityStartTimeMs);
assertEquals(expected.durationMs, actual.durationMs); assertThat(actual.durationMs).isEqualTo(expected.durationMs);
assertEquals(expected.minBufferTimeMs, actual.minBufferTimeMs); assertThat(actual.minBufferTimeMs).isEqualTo(expected.minBufferTimeMs);
assertEquals(expected.dynamic, actual.dynamic); assertThat(actual.dynamic).isEqualTo(expected.dynamic);
assertEquals(expected.minUpdatePeriodMs, actual.minUpdatePeriodMs); assertThat(actual.minUpdatePeriodMs).isEqualTo(expected.minUpdatePeriodMs);
assertEquals(expected.timeShiftBufferDepthMs, actual.timeShiftBufferDepthMs); assertThat(actual.timeShiftBufferDepthMs).isEqualTo(expected.timeShiftBufferDepthMs);
assertEquals(expected.suggestedPresentationDelayMs, actual.suggestedPresentationDelayMs); assertThat(actual.suggestedPresentationDelayMs)
assertEquals(expected.publishTimeMs, actual.publishTimeMs); .isEqualTo(expected.suggestedPresentationDelayMs);
assertEquals(expected.utcTiming, actual.utcTiming); assertThat(actual.publishTimeMs).isEqualTo(expected.publishTimeMs);
assertEquals(expected.location, actual.location); assertThat(actual.utcTiming).isEqualTo(expected.utcTiming);
assertEquals(expected.getPeriodCount(), actual.getPeriodCount()); assertThat(actual.location).isEqualTo(expected.location);
assertThat(actual.getPeriodCount()).isEqualTo(expected.getPeriodCount());
for (int i = 0; i < expected.getPeriodCount(); i++) { for (int i = 0; i < expected.getPeriodCount(); i++) {
Period expectedPeriod = expected.getPeriod(i); Period expectedPeriod = expected.getPeriod(i);
Period actualPeriod = actual.getPeriod(i); Period actualPeriod = actual.getPeriod(i);
assertEquals(expectedPeriod.id, actualPeriod.id); assertThat(actualPeriod.id).isEqualTo(expectedPeriod.id);
assertEquals(expectedPeriod.startMs, actualPeriod.startMs); assertThat(actualPeriod.startMs).isEqualTo(expectedPeriod.startMs);
List<AdaptationSet> expectedAdaptationSets = expectedPeriod.adaptationSets; List<AdaptationSet> expectedAdaptationSets = expectedPeriod.adaptationSets;
List<AdaptationSet> actualAdaptationSets = actualPeriod.adaptationSets; List<AdaptationSet> actualAdaptationSets = actualPeriod.adaptationSets;
assertEquals(expectedAdaptationSets.size(), actualAdaptationSets.size()); assertThat(actualAdaptationSets).hasSize(expectedAdaptationSets.size());
for (int j = 0; j < expectedAdaptationSets.size(); j++) { for (int j = 0; j < expectedAdaptationSets.size(); j++) {
AdaptationSet expectedAdaptationSet = expectedAdaptationSets.get(j); AdaptationSet expectedAdaptationSet = expectedAdaptationSets.get(j);
AdaptationSet actualAdaptationSet = actualAdaptationSets.get(j); AdaptationSet actualAdaptationSet = actualAdaptationSets.get(j);
assertEquals(expectedAdaptationSet.id, actualAdaptationSet.id); assertThat(actualAdaptationSet.id).isEqualTo(expectedAdaptationSet.id);
assertEquals(expectedAdaptationSet.type, actualAdaptationSet.type); assertThat(actualAdaptationSet.type).isEqualTo(expectedAdaptationSet.type);
assertEquals(expectedAdaptationSet.accessibilityDescriptors, assertThat(actualAdaptationSet.accessibilityDescriptors)
actualAdaptationSet.accessibilityDescriptors); .isEqualTo(expectedAdaptationSet.accessibilityDescriptors);
assertEquals(expectedAdaptationSet.representations, actualAdaptationSet.representations); assertThat(actualAdaptationSet.representations)
.isEqualTo(expectedAdaptationSet.representations);
} }
} }
} }
......
...@@ -15,6 +15,8 @@ ...@@ -15,6 +15,8 @@
*/ */
package com.google.android.exoplayer2.source.dash.manifest; package com.google.android.exoplayer2.source.dash.manifest;
import static com.google.common.truth.Truth.assertThat;
import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.C;
import junit.framework.TestCase; import junit.framework.TestCase;
...@@ -72,16 +74,16 @@ public class RangedUriTest extends TestCase { ...@@ -72,16 +74,16 @@ public class RangedUriTest extends TestCase {
private void assertMerge(RangedUri rangeA, RangedUri rangeB, RangedUri expected, String baseUrl) { private void assertMerge(RangedUri rangeA, RangedUri rangeB, RangedUri expected, String baseUrl) {
RangedUri merged = rangeA.attemptMerge(rangeB, baseUrl); RangedUri merged = rangeA.attemptMerge(rangeB, baseUrl);
assertEquals(expected, merged); assertThat(merged).isEqualTo(expected);
merged = rangeB.attemptMerge(rangeA, baseUrl); merged = rangeB.attemptMerge(rangeA, baseUrl);
assertEquals(expected, merged); assertThat(merged).isEqualTo(expected);
} }
private void assertNonMerge(RangedUri rangeA, RangedUri rangeB, String baseUrl) { private void assertNonMerge(RangedUri rangeA, RangedUri rangeB, String baseUrl) {
RangedUri merged = rangeA.attemptMerge(rangeB, baseUrl); RangedUri merged = rangeA.attemptMerge(rangeB, baseUrl);
assertNull(merged); assertThat(merged).isNull();
merged = rangeB.attemptMerge(rangeA, baseUrl); merged = rangeB.attemptMerge(rangeA, baseUrl);
assertNull(merged); assertThat(merged).isNull();
} }
} }
...@@ -15,6 +15,8 @@ ...@@ -15,6 +15,8 @@
*/ */
package com.google.android.exoplayer2.source.dash.manifest; package com.google.android.exoplayer2.source.dash.manifest;
import static com.google.common.truth.Truth.assertThat;
import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.source.dash.manifest.SegmentBase.SingleSegmentBase; import com.google.android.exoplayer2.source.dash.manifest.SegmentBase.SingleSegmentBase;
import com.google.android.exoplayer2.util.MimeTypes; import com.google.android.exoplayer2.util.MimeTypes;
...@@ -32,13 +34,13 @@ public class RepresentationTest extends TestCase { ...@@ -32,13 +34,13 @@ public class RepresentationTest extends TestCase {
MimeTypes.VIDEO_H264, 2500000, 1920, 1080, Format.NO_VALUE, null, 0); MimeTypes.VIDEO_H264, 2500000, 1920, 1080, Format.NO_VALUE, null, 0);
Representation representation = Representation.newInstance("test_stream_1", 3, format, uri, Representation representation = Representation.newInstance("test_stream_1", 3, format, uri,
base); base);
assertEquals("test_stream_1.0.3", representation.getCacheKey()); assertThat(representation.getCacheKey()).isEqualTo("test_stream_1.0.3");
format = Format.createVideoContainerFormat("150", MimeTypes.APPLICATION_MP4, null, format = Format.createVideoContainerFormat("150", MimeTypes.APPLICATION_MP4, null,
MimeTypes.VIDEO_H264, 2500000, 1920, 1080, Format.NO_VALUE, null, 0); MimeTypes.VIDEO_H264, 2500000, 1920, 1080, Format.NO_VALUE, null, 0);
representation = Representation.newInstance("test_stream_1", Representation.REVISION_ID_DEFAULT, representation = Representation.newInstance("test_stream_1", Representation.REVISION_ID_DEFAULT,
format, uri, base); format, uri, base);
assertEquals("test_stream_1.150.-1", representation.getCacheKey()); assertThat(representation.getCacheKey()).isEqualTo("test_stream_1.150.-1");
} }
} }
...@@ -15,6 +15,8 @@ ...@@ -15,6 +15,8 @@
*/ */
package com.google.android.exoplayer2.source.dash.manifest; package com.google.android.exoplayer2.source.dash.manifest;
import static com.google.common.truth.Truth.assertThat;
import junit.framework.TestCase; import junit.framework.TestCase;
/** /**
...@@ -26,31 +28,31 @@ public class UrlTemplateTest extends TestCase { ...@@ -26,31 +28,31 @@ public class UrlTemplateTest extends TestCase {
String template = "QualityLevels($Bandwidth$)/Fragments(video=$Time$,format=mpd-time-csf)"; String template = "QualityLevels($Bandwidth$)/Fragments(video=$Time$,format=mpd-time-csf)";
UrlTemplate urlTemplate = UrlTemplate.compile(template); UrlTemplate urlTemplate = UrlTemplate.compile(template);
String url = urlTemplate.buildUri("abc1", 10, 650000, 5000); String url = urlTemplate.buildUri("abc1", 10, 650000, 5000);
assertEquals("QualityLevels(650000)/Fragments(video=5000,format=mpd-time-csf)", url); assertThat(url).isEqualTo("QualityLevels(650000)/Fragments(video=5000,format=mpd-time-csf)");
template = "$RepresentationID$/$Number$"; template = "$RepresentationID$/$Number$";
urlTemplate = UrlTemplate.compile(template); urlTemplate = UrlTemplate.compile(template);
url = urlTemplate.buildUri("abc1", 10, 650000, 5000); url = urlTemplate.buildUri("abc1", 10, 650000, 5000);
assertEquals("abc1/10", url); assertThat(url).isEqualTo("abc1/10");
template = "chunk_ctvideo_cfm4s_rid$RepresentationID$_cn$Number$_w2073857842_mpd.m4s"; template = "chunk_ctvideo_cfm4s_rid$RepresentationID$_cn$Number$_w2073857842_mpd.m4s";
urlTemplate = UrlTemplate.compile(template); urlTemplate = UrlTemplate.compile(template);
url = urlTemplate.buildUri("abc1", 10, 650000, 5000); url = urlTemplate.buildUri("abc1", 10, 650000, 5000);
assertEquals("chunk_ctvideo_cfm4s_ridabc1_cn10_w2073857842_mpd.m4s", url); assertThat(url).isEqualTo("chunk_ctvideo_cfm4s_ridabc1_cn10_w2073857842_mpd.m4s");
} }
public void testFull() { public void testFull() {
String template = "$Bandwidth$_a_$RepresentationID$_b_$Time$_c_$Number$"; String template = "$Bandwidth$_a_$RepresentationID$_b_$Time$_c_$Number$";
UrlTemplate urlTemplate = UrlTemplate.compile(template); UrlTemplate urlTemplate = UrlTemplate.compile(template);
String url = urlTemplate.buildUri("abc1", 10, 650000, 5000); String url = urlTemplate.buildUri("abc1", 10, 650000, 5000);
assertEquals("650000_a_abc1_b_5000_c_10", url); assertThat(url).isEqualTo("650000_a_abc1_b_5000_c_10");
} }
public void testFullWithDollarEscaping() { public void testFullWithDollarEscaping() {
String template = "$$$Bandwidth$$$_a$$_$RepresentationID$_b_$Time$_c_$Number$$$"; String template = "$$$Bandwidth$$$_a$$_$RepresentationID$_b_$Time$_c_$Number$$$";
UrlTemplate urlTemplate = UrlTemplate.compile(template); UrlTemplate urlTemplate = UrlTemplate.compile(template);
String url = urlTemplate.buildUri("abc1", 10, 650000, 5000); String url = urlTemplate.buildUri("abc1", 10, 650000, 5000);
assertEquals("$650000$_a$_abc1_b_5000_c_10$", url); assertThat(url).isEqualTo("$650000$_a$_abc1_b_5000_c_10$");
} }
public void testInvalidSubstitution() { public void testInvalidSubstitution() {
......
...@@ -21,6 +21,9 @@ import static com.google.android.exoplayer2.source.dash.offline.DashDownloadTest ...@@ -21,6 +21,9 @@ import static com.google.android.exoplayer2.source.dash.offline.DashDownloadTest
import static com.google.android.exoplayer2.testutil.CacheAsserts.assertCacheEmpty; import static com.google.android.exoplayer2.testutil.CacheAsserts.assertCacheEmpty;
import static com.google.android.exoplayer2.testutil.CacheAsserts.assertCachedData; import static com.google.android.exoplayer2.testutil.CacheAsserts.assertCachedData;
import static com.google.android.exoplayer2.testutil.CacheAsserts.assertDataCached; import static com.google.android.exoplayer2.testutil.CacheAsserts.assertDataCached;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import android.test.InstrumentationTestCase; import android.test.InstrumentationTestCase;
import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.C;
...@@ -73,7 +76,7 @@ public class DashDownloaderTest extends InstrumentationTestCase { ...@@ -73,7 +76,7 @@ public class DashDownloaderTest extends InstrumentationTestCase {
DashManifest manifest = dashDownloader.getManifest(); DashManifest manifest = dashDownloader.getManifest();
assertNotNull(manifest); assertThat(manifest).isNotNull();
assertCachedData(cache, fakeDataSet); assertCachedData(cache, fakeDataSet);
} }
...@@ -101,7 +104,7 @@ public class DashDownloaderTest extends InstrumentationTestCase { ...@@ -101,7 +104,7 @@ public class DashDownloaderTest extends InstrumentationTestCase {
// on the second try it downloads the rest of the data // on the second try it downloads the rest of the data
DashManifest manifest = dashDownloader.getManifest(); DashManifest manifest = dashDownloader.getManifest();
assertNotNull(manifest); assertThat(manifest).isNotNull();
assertCachedData(cache, fakeDataSet); assertCachedData(cache, fakeDataSet);
} }
...@@ -203,8 +206,8 @@ public class DashDownloaderTest extends InstrumentationTestCase { ...@@ -203,8 +206,8 @@ public class DashDownloaderTest extends InstrumentationTestCase {
.setRandomData("text_segment_2", 2) .setRandomData("text_segment_2", 2)
.setRandomData("text_segment_3", 3); .setRandomData("text_segment_3", 3);
FakeDataSource fakeDataSource = new FakeDataSource(fakeDataSet); FakeDataSource fakeDataSource = new FakeDataSource(fakeDataSet);
Factory factory = Mockito.mock(Factory.class); Factory factory = mock(Factory.class);
Mockito.when(factory.createDataSource()).thenReturn(fakeDataSource); when(factory.createDataSource()).thenReturn(fakeDataSource);
DashDownloader dashDownloader = new DashDownloader(TEST_MPD_URI, DashDownloader dashDownloader = new DashDownloader(TEST_MPD_URI,
new DownloaderConstructorHelper(cache, factory)); new DownloaderConstructorHelper(cache, factory));
...@@ -213,15 +216,15 @@ public class DashDownloaderTest extends InstrumentationTestCase { ...@@ -213,15 +216,15 @@ public class DashDownloaderTest extends InstrumentationTestCase {
dashDownloader.download(null); dashDownloader.download(null);
DataSpec[] openedDataSpecs = fakeDataSource.getAndClearOpenedDataSpecs(); DataSpec[] openedDataSpecs = fakeDataSource.getAndClearOpenedDataSpecs();
assertEquals(8, openedDataSpecs.length); assertThat(openedDataSpecs.length).isEqualTo(8);
assertEquals(TEST_MPD_URI, openedDataSpecs[0].uri); assertThat(openedDataSpecs[0].uri).isEqualTo(TEST_MPD_URI);
assertEquals("audio_init_data", openedDataSpecs[1].uri.getPath()); assertThat(openedDataSpecs[1].uri.getPath()).isEqualTo("audio_init_data");
assertEquals("audio_segment_1", openedDataSpecs[2].uri.getPath()); assertThat(openedDataSpecs[2].uri.getPath()).isEqualTo("audio_segment_1");
assertEquals("text_segment_1", openedDataSpecs[3].uri.getPath()); assertThat(openedDataSpecs[3].uri.getPath()).isEqualTo("text_segment_1");
assertEquals("audio_segment_2", openedDataSpecs[4].uri.getPath()); assertThat(openedDataSpecs[4].uri.getPath()).isEqualTo("audio_segment_2");
assertEquals("text_segment_2", openedDataSpecs[5].uri.getPath()); assertThat(openedDataSpecs[5].uri.getPath()).isEqualTo("text_segment_2");
assertEquals("audio_segment_3", openedDataSpecs[6].uri.getPath()); assertThat(openedDataSpecs[6].uri.getPath()).isEqualTo("audio_segment_3");
assertEquals("text_segment_3", openedDataSpecs[7].uri.getPath()); assertThat(openedDataSpecs[7].uri.getPath()).isEqualTo("text_segment_3");
} }
public void testProgressiveDownloadSeparatePeriods() throws Exception { public void testProgressiveDownloadSeparatePeriods() throws Exception {
...@@ -235,8 +238,8 @@ public class DashDownloaderTest extends InstrumentationTestCase { ...@@ -235,8 +238,8 @@ public class DashDownloaderTest extends InstrumentationTestCase {
.setRandomData("period_2_segment_2", 2) .setRandomData("period_2_segment_2", 2)
.setRandomData("period_2_segment_3", 3); .setRandomData("period_2_segment_3", 3);
FakeDataSource fakeDataSource = new FakeDataSource(fakeDataSet); FakeDataSource fakeDataSource = new FakeDataSource(fakeDataSet);
Factory factory = Mockito.mock(Factory.class); Factory factory = mock(Factory.class);
Mockito.when(factory.createDataSource()).thenReturn(fakeDataSource); when(factory.createDataSource()).thenReturn(fakeDataSource);
DashDownloader dashDownloader = new DashDownloader(TEST_MPD_URI, DashDownloader dashDownloader = new DashDownloader(TEST_MPD_URI,
new DownloaderConstructorHelper(cache, factory)); new DownloaderConstructorHelper(cache, factory));
...@@ -245,15 +248,15 @@ public class DashDownloaderTest extends InstrumentationTestCase { ...@@ -245,15 +248,15 @@ public class DashDownloaderTest extends InstrumentationTestCase {
dashDownloader.download(null); dashDownloader.download(null);
DataSpec[] openedDataSpecs = fakeDataSource.getAndClearOpenedDataSpecs(); DataSpec[] openedDataSpecs = fakeDataSource.getAndClearOpenedDataSpecs();
assertEquals(8, openedDataSpecs.length); assertThat(openedDataSpecs.length).isEqualTo(8);
assertEquals(TEST_MPD_URI, openedDataSpecs[0].uri); assertThat(openedDataSpecs[0].uri).isEqualTo(TEST_MPD_URI);
assertEquals("audio_init_data", openedDataSpecs[1].uri.getPath()); assertThat(openedDataSpecs[1].uri.getPath()).isEqualTo("audio_init_data");
assertEquals("audio_segment_1", openedDataSpecs[2].uri.getPath()); assertThat(openedDataSpecs[2].uri.getPath()).isEqualTo("audio_segment_1");
assertEquals("audio_segment_2", openedDataSpecs[3].uri.getPath()); assertThat(openedDataSpecs[3].uri.getPath()).isEqualTo("audio_segment_2");
assertEquals("audio_segment_3", openedDataSpecs[4].uri.getPath()); assertThat(openedDataSpecs[4].uri.getPath()).isEqualTo("audio_segment_3");
assertEquals("period_2_segment_1", openedDataSpecs[5].uri.getPath()); assertThat(openedDataSpecs[5].uri.getPath()).isEqualTo("period_2_segment_1");
assertEquals("period_2_segment_2", openedDataSpecs[6].uri.getPath()); assertThat(openedDataSpecs[6].uri.getPath()).isEqualTo("period_2_segment_2");
assertEquals("period_2_segment_3", openedDataSpecs[7].uri.getPath()); assertThat(openedDataSpecs[7].uri.getPath()).isEqualTo("period_2_segment_3");
} }
public void testDownloadRepresentationFailure() throws Exception { public void testDownloadRepresentationFailure() throws Exception {
...@@ -400,9 +403,9 @@ public class DashDownloaderTest extends InstrumentationTestCase { ...@@ -400,9 +403,9 @@ public class DashDownloaderTest extends InstrumentationTestCase {
private static void assertCounters(DashDownloader dashDownloader, int totalSegments, private static void assertCounters(DashDownloader dashDownloader, int totalSegments,
int downloadedSegments, int downloadedBytes) { int downloadedSegments, int downloadedBytes) {
assertEquals(totalSegments, dashDownloader.getTotalSegments()); assertThat(dashDownloader.getTotalSegments()).isEqualTo(totalSegments);
assertEquals(downloadedSegments, dashDownloader.getDownloadedSegments()); assertThat(dashDownloader.getDownloadedSegments()).isEqualTo(downloadedSegments);
assertEquals(downloadedBytes, dashDownloader.getDownloadedBytes()); assertThat(dashDownloader.getDownloadedBytes()).isEqualTo(downloadedBytes);
} }
} }
...@@ -30,6 +30,7 @@ import static com.google.android.exoplayer2.source.hls.offline.HlsDownloadTestDa ...@@ -30,6 +30,7 @@ import static com.google.android.exoplayer2.source.hls.offline.HlsDownloadTestDa
import static com.google.android.exoplayer2.source.hls.offline.HlsDownloadTestData.MEDIA_PLAYLIST_DATA; import static com.google.android.exoplayer2.source.hls.offline.HlsDownloadTestData.MEDIA_PLAYLIST_DATA;
import static com.google.android.exoplayer2.testutil.CacheAsserts.assertCacheEmpty; import static com.google.android.exoplayer2.testutil.CacheAsserts.assertCacheEmpty;
import static com.google.android.exoplayer2.testutil.CacheAsserts.assertCachedData; import static com.google.android.exoplayer2.testutil.CacheAsserts.assertCachedData;
import static com.google.common.truth.Truth.assertThat;
import android.net.Uri; import android.net.Uri;
import android.test.InstrumentationTestCase; import android.test.InstrumentationTestCase;
...@@ -78,7 +79,7 @@ public class HlsDownloaderTest extends InstrumentationTestCase { ...@@ -78,7 +79,7 @@ public class HlsDownloaderTest extends InstrumentationTestCase {
public void testDownloadManifest() throws Exception { public void testDownloadManifest() throws Exception {
HlsMasterPlaylist manifest = hlsDownloader.getManifest(); HlsMasterPlaylist manifest = hlsDownloader.getManifest();
assertNotNull(manifest); assertThat(manifest).isNotNull();
assertCachedData(cache, fakeDataSet, MASTER_PLAYLIST_URI); assertCachedData(cache, fakeDataSet, MASTER_PLAYLIST_URI);
} }
...@@ -97,9 +98,10 @@ public class HlsDownloaderTest extends InstrumentationTestCase { ...@@ -97,9 +98,10 @@ public class HlsDownloaderTest extends InstrumentationTestCase {
hlsDownloader.selectRepresentations(new String[] {MEDIA_PLAYLIST_1_URI}); hlsDownloader.selectRepresentations(new String[] {MEDIA_PLAYLIST_1_URI});
hlsDownloader.download(null); hlsDownloader.download(null);
assertEquals(4, hlsDownloader.getTotalSegments()); assertThat(hlsDownloader.getTotalSegments()).isEqualTo(4);
assertEquals(4, hlsDownloader.getDownloadedSegments()); assertThat(hlsDownloader.getDownloadedSegments()).isEqualTo(4);
assertEquals(MEDIA_PLAYLIST_DATA.length + 10 + 11 + 12, hlsDownloader.getDownloadedBytes()); assertThat(hlsDownloader.getDownloadedBytes())
.isEqualTo(MEDIA_PLAYLIST_DATA.length + 10 + 11 + 12);
} }
public void testInitStatus() throws Exception { public void testInitStatus() throws Exception {
...@@ -111,9 +113,10 @@ public class HlsDownloaderTest extends InstrumentationTestCase { ...@@ -111,9 +113,10 @@ public class HlsDownloaderTest extends InstrumentationTestCase {
newHlsDownloader.selectRepresentations(new String[] {MEDIA_PLAYLIST_1_URI}); newHlsDownloader.selectRepresentations(new String[] {MEDIA_PLAYLIST_1_URI});
newHlsDownloader.init(); newHlsDownloader.init();
assertEquals(4, newHlsDownloader.getTotalSegments()); assertThat(newHlsDownloader.getTotalSegments()).isEqualTo(4);
assertEquals(4, newHlsDownloader.getDownloadedSegments()); assertThat(newHlsDownloader.getDownloadedSegments()).isEqualTo(4);
assertEquals(MEDIA_PLAYLIST_DATA.length + 10 + 11 + 12, newHlsDownloader.getDownloadedBytes()); assertThat(newHlsDownloader.getDownloadedBytes())
.isEqualTo(MEDIA_PLAYLIST_DATA.length + 10 + 11 + 12);
} }
public void testDownloadRepresentation() throws Exception { public void testDownloadRepresentation() throws Exception {
......
...@@ -15,6 +15,8 @@ ...@@ -15,6 +15,8 @@
*/ */
package com.google.android.exoplayer2.source.hls.playlist; package com.google.android.exoplayer2.source.hls.playlist;
import static com.google.common.truth.Truth.assertThat;
import android.net.Uri; import android.net.Uri;
import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.Format;
...@@ -23,7 +25,6 @@ import com.google.android.exoplayer2.util.MimeTypes; ...@@ -23,7 +25,6 @@ import com.google.android.exoplayer2.util.MimeTypes;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.util.Collections;
import java.util.List; import java.util.List;
import junit.framework.TestCase; import junit.framework.TestCase;
...@@ -89,43 +90,43 @@ public class HlsMasterPlaylistParserTest extends TestCase { ...@@ -89,43 +90,43 @@ public class HlsMasterPlaylistParserTest extends TestCase {
+ "#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=\"aud2\",LANGUAGE=\"en\",NAME=\"English\"," + "#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=\"aud2\",LANGUAGE=\"en\",NAME=\"English\","
+ "AUTOSELECT=YES,DEFAULT=YES,CHANNELS=\"6\",URI=\"a2/prog_index.m3u8\"\n"; + "AUTOSELECT=YES,DEFAULT=YES,CHANNELS=\"6\",URI=\"a2/prog_index.m3u8\"\n";
public void testParseMasterPlaylist() throws IOException{ public void testParseMasterPlaylist() throws IOException {
HlsMasterPlaylist masterPlaylist = parseMasterPlaylist(PLAYLIST_URI, PLAYLIST_SIMPLE); HlsMasterPlaylist masterPlaylist = parseMasterPlaylist(PLAYLIST_URI, PLAYLIST_SIMPLE);
List<HlsMasterPlaylist.HlsUrl> variants = masterPlaylist.variants; List<HlsMasterPlaylist.HlsUrl> variants = masterPlaylist.variants;
assertEquals(5, variants.size()); assertThat(variants).hasSize(5);
assertNull(masterPlaylist.muxedCaptionFormats); assertThat(masterPlaylist.muxedCaptionFormats).isNull();
assertEquals(1280000, variants.get(0).format.bitrate); assertThat(variants.get(0).format.bitrate).isEqualTo(1280000);
assertEquals("mp4a.40.2,avc1.66.30", variants.get(0).format.codecs); assertThat(variants.get(0).format.codecs).isEqualTo("mp4a.40.2,avc1.66.30");
assertEquals(304, variants.get(0).format.width); assertThat(variants.get(0).format.width).isEqualTo(304);
assertEquals(128, variants.get(0).format.height); assertThat(variants.get(0).format.height).isEqualTo(128);
assertEquals("http://example.com/low.m3u8", variants.get(0).url); assertThat(variants.get(0).url).isEqualTo("http://example.com/low.m3u8");
assertEquals(1280000, variants.get(1).format.bitrate); assertThat(variants.get(1).format.bitrate).isEqualTo(1280000);
assertEquals("mp4a.40.2 , avc1.66.30 ", variants.get(1).format.codecs); assertThat(variants.get(1).format.codecs).isEqualTo("mp4a.40.2 , avc1.66.30 ");
assertEquals("http://example.com/spaces_in_codecs.m3u8", variants.get(1).url); assertThat(variants.get(1).url).isEqualTo("http://example.com/spaces_in_codecs.m3u8");
assertEquals(2560000, variants.get(2).format.bitrate); assertThat(variants.get(2).format.bitrate).isEqualTo(2560000);
assertNull(variants.get(2).format.codecs); assertThat(variants.get(2).format.codecs).isNull();
assertEquals(384, variants.get(2).format.width); assertThat(variants.get(2).format.width).isEqualTo(384);
assertEquals(160, variants.get(2).format.height); assertThat(variants.get(2).format.height).isEqualTo(160);
assertEquals(25.0f, variants.get(2).format.frameRate); assertThat(variants.get(2).format.frameRate).isEqualTo(25.0f);
assertEquals("http://example.com/mid.m3u8", variants.get(2).url); assertThat(variants.get(2).url).isEqualTo("http://example.com/mid.m3u8");
assertEquals(7680000, variants.get(3).format.bitrate); assertThat(variants.get(3).format.bitrate).isEqualTo(7680000);
assertNull(variants.get(3).format.codecs); assertThat(variants.get(3).format.codecs).isNull();
assertEquals(Format.NO_VALUE, variants.get(3).format.width); assertThat(variants.get(3).format.width).isEqualTo(Format.NO_VALUE);
assertEquals(Format.NO_VALUE, variants.get(3).format.height); assertThat(variants.get(3).format.height).isEqualTo(Format.NO_VALUE);
assertEquals(29.997f, variants.get(3).format.frameRate); assertThat(variants.get(3).format.frameRate).isEqualTo(29.997f);
assertEquals("http://example.com/hi.m3u8", variants.get(3).url); assertThat(variants.get(3).url).isEqualTo("http://example.com/hi.m3u8");
assertEquals(65000, variants.get(4).format.bitrate); assertThat(variants.get(4).format.bitrate).isEqualTo(65000);
assertEquals("mp4a.40.5", variants.get(4).format.codecs); assertThat(variants.get(4).format.codecs).isEqualTo("mp4a.40.5");
assertEquals(Format.NO_VALUE, variants.get(4).format.width); assertThat(variants.get(4).format.width).isEqualTo(Format.NO_VALUE);
assertEquals(Format.NO_VALUE, variants.get(4).format.height); assertThat(variants.get(4).format.height).isEqualTo(Format.NO_VALUE);
assertEquals((float) Format.NO_VALUE, variants.get(4).format.frameRate); assertThat(variants.get(4).format.frameRate).isEqualTo((float) Format.NO_VALUE);
assertEquals("http://example.com/audio-only.m3u8", variants.get(4).url); assertThat(variants.get(4).url).isEqualTo("http://example.com/audio-only.m3u8");
} }
public void testMasterPlaylistWithBandwdithAverage() throws IOException { public void testMasterPlaylistWithBandwdithAverage() throws IOException {
...@@ -134,8 +135,8 @@ public class HlsMasterPlaylistParserTest extends TestCase { ...@@ -134,8 +135,8 @@ public class HlsMasterPlaylistParserTest extends TestCase {
List<HlsMasterPlaylist.HlsUrl> variants = masterPlaylist.variants; List<HlsMasterPlaylist.HlsUrl> variants = masterPlaylist.variants;
assertEquals(1280000, variants.get(0).format.bitrate); assertThat(variants.get(0).format.bitrate).isEqualTo(1280000);
assertEquals(1270000, variants.get(1).format.bitrate); assertThat(variants.get(1).format.bitrate).isEqualTo(1270000);
} }
public void testPlaylistWithInvalidHeader() throws IOException { public void testPlaylistWithInvalidHeader() throws IOException {
...@@ -149,28 +150,28 @@ public class HlsMasterPlaylistParserTest extends TestCase { ...@@ -149,28 +150,28 @@ public class HlsMasterPlaylistParserTest extends TestCase {
public void testPlaylistWithClosedCaption() throws IOException { public void testPlaylistWithClosedCaption() throws IOException {
HlsMasterPlaylist playlist = parseMasterPlaylist(PLAYLIST_URI, PLAYLIST_WITH_CC); HlsMasterPlaylist playlist = parseMasterPlaylist(PLAYLIST_URI, PLAYLIST_WITH_CC);
assertEquals(1, playlist.muxedCaptionFormats.size()); assertThat(playlist.muxedCaptionFormats).hasSize(1);
Format closedCaptionFormat = playlist.muxedCaptionFormats.get(0); Format closedCaptionFormat = playlist.muxedCaptionFormats.get(0);
assertEquals(MimeTypes.APPLICATION_CEA708, closedCaptionFormat.sampleMimeType); assertThat(closedCaptionFormat.sampleMimeType).isEqualTo(MimeTypes.APPLICATION_CEA708);
assertEquals(4, closedCaptionFormat.accessibilityChannel); assertThat(closedCaptionFormat.accessibilityChannel).isEqualTo(4);
assertEquals("es", closedCaptionFormat.language); assertThat(closedCaptionFormat.language).isEqualTo("es");
} }
public void testPlaylistWithoutClosedCaptions() throws IOException { public void testPlaylistWithoutClosedCaptions() throws IOException {
HlsMasterPlaylist playlist = parseMasterPlaylist(PLAYLIST_URI, PLAYLIST_WITHOUT_CC); HlsMasterPlaylist playlist = parseMasterPlaylist(PLAYLIST_URI, PLAYLIST_WITHOUT_CC);
assertEquals(Collections.emptyList(), playlist.muxedCaptionFormats); assertThat(playlist.muxedCaptionFormats).isEmpty();
} }
public void testCodecPropagation() throws IOException { public void testCodecPropagation() throws IOException {
HlsMasterPlaylist playlist = parseMasterPlaylist(PLAYLIST_URI, PLAYLIST_WITH_AUDIO_MEDIA_TAG); HlsMasterPlaylist playlist = parseMasterPlaylist(PLAYLIST_URI, PLAYLIST_WITH_AUDIO_MEDIA_TAG);
Format firstAudioFormat = playlist.audios.get(0).format; Format firstAudioFormat = playlist.audios.get(0).format;
assertEquals("mp4a.40.2", firstAudioFormat.codecs); assertThat(firstAudioFormat.codecs).isEqualTo("mp4a.40.2");
assertEquals(MimeTypes.AUDIO_AAC, firstAudioFormat.sampleMimeType); assertThat(firstAudioFormat.sampleMimeType).isEqualTo(MimeTypes.AUDIO_AAC);
Format secondAudioFormat = playlist.audios.get(1).format; Format secondAudioFormat = playlist.audios.get(1).format;
assertEquals("ac-3", secondAudioFormat.codecs); assertThat(secondAudioFormat.codecs).isEqualTo("ac-3");
assertEquals(MimeTypes.AUDIO_AC3, secondAudioFormat.sampleMimeType); assertThat(secondAudioFormat.sampleMimeType).isEqualTo(MimeTypes.AUDIO_AC3);
} }
private static HlsMasterPlaylist parseMasterPlaylist(String uri, String playlistString) private static HlsMasterPlaylist parseMasterPlaylist(String uri, String playlistString)
......
...@@ -15,6 +15,8 @@ ...@@ -15,6 +15,8 @@
*/ */
package com.google.android.exoplayer2.source.hls.playlist; package com.google.android.exoplayer2.source.hls.playlist;
import static com.google.common.truth.Truth.assertThat;
import android.net.Uri; import android.net.Uri;
import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.source.hls.playlist.HlsMediaPlaylist.Segment; import com.google.android.exoplayer2.source.hls.playlist.HlsMediaPlaylist.Segment;
...@@ -69,67 +71,71 @@ public class HlsMediaPlaylistParserTest extends TestCase { ...@@ -69,67 +71,71 @@ public class HlsMediaPlaylistParserTest extends TestCase {
playlistString.getBytes(Charset.forName(C.UTF8_NAME))); playlistString.getBytes(Charset.forName(C.UTF8_NAME)));
try { try {
HlsPlaylist playlist = new HlsPlaylistParser().parse(playlistUri, inputStream); HlsPlaylist playlist = new HlsPlaylistParser().parse(playlistUri, inputStream);
assertNotNull(playlist); assertThat(playlist).isNotNull();
HlsMediaPlaylist mediaPlaylist = (HlsMediaPlaylist) playlist; HlsMediaPlaylist mediaPlaylist = (HlsMediaPlaylist) playlist;
assertEquals(HlsMediaPlaylist.PLAYLIST_TYPE_VOD, mediaPlaylist.playlistType); assertThat(mediaPlaylist.playlistType).isEqualTo(HlsMediaPlaylist.PLAYLIST_TYPE_VOD);
assertEquals(mediaPlaylist.durationUs - 25000000, mediaPlaylist.startOffsetUs); assertThat(mediaPlaylist.startOffsetUs).isEqualTo(mediaPlaylist.durationUs - 25000000);
assertEquals(2679, mediaPlaylist.mediaSequence); assertThat(mediaPlaylist.mediaSequence).isEqualTo(2679);
assertEquals(3, mediaPlaylist.version); assertThat(mediaPlaylist.version).isEqualTo(3);
assertTrue(mediaPlaylist.hasEndTag); assertThat(mediaPlaylist.hasEndTag).isTrue();
List<Segment> segments = mediaPlaylist.segments; List<Segment> segments = mediaPlaylist.segments;
assertNotNull(segments); assertThat(segments).isNotNull();
assertEquals(5, segments.size()); assertThat(segments).hasSize(5);
Segment segment = segments.get(0); Segment segment = segments.get(0);
assertEquals(4, mediaPlaylist.discontinuitySequence + segment.relativeDiscontinuitySequence); assertThat(mediaPlaylist.discontinuitySequence + segment.relativeDiscontinuitySequence)
assertEquals(7975000, segment.durationUs); .isEqualTo(4);
assertNull(segment.fullSegmentEncryptionKeyUri); assertThat(segment.durationUs).isEqualTo(7975000);
assertNull(segment.encryptionIV); assertThat(segment.fullSegmentEncryptionKeyUri).isNull();
assertEquals(51370, segment.byterangeLength); assertThat(segment.encryptionIV).isNull();
assertEquals(0, segment.byterangeOffset); assertThat(segment.byterangeLength).isEqualTo(51370);
assertEquals("https://priv.example.com/fileSequence2679.ts", segment.url); assertThat(segment.byterangeOffset).isEqualTo(0);
assertThat(segment.url).isEqualTo("https://priv.example.com/fileSequence2679.ts");
segment = segments.get(1); segment = segments.get(1);
assertEquals(0, segment.relativeDiscontinuitySequence); assertThat(segment.relativeDiscontinuitySequence).isEqualTo(0);
assertEquals(7975000, segment.durationUs); assertThat(segment.durationUs).isEqualTo(7975000);
assertEquals("https://priv.example.com/key.php?r=2680", segment.fullSegmentEncryptionKeyUri); assertThat(segment.fullSegmentEncryptionKeyUri)
assertEquals("0x1566B", segment.encryptionIV); .isEqualTo("https://priv.example.com/key.php?r=2680");
assertEquals(51501, segment.byterangeLength); assertThat(segment.encryptionIV).isEqualTo("0x1566B");
assertEquals(2147483648L, segment.byterangeOffset); assertThat(segment.byterangeLength).isEqualTo(51501);
assertEquals("https://priv.example.com/fileSequence2680.ts", segment.url); assertThat(segment.byterangeOffset).isEqualTo(2147483648L);
assertThat(segment.url).isEqualTo("https://priv.example.com/fileSequence2680.ts");
segment = segments.get(2); segment = segments.get(2);
assertEquals(0, segment.relativeDiscontinuitySequence); assertThat(segment.relativeDiscontinuitySequence).isEqualTo(0);
assertEquals(7941000, segment.durationUs); assertThat(segment.durationUs).isEqualTo(7941000);
assertNull(segment.fullSegmentEncryptionKeyUri); assertThat(segment.fullSegmentEncryptionKeyUri).isNull();
assertEquals(null, segment.encryptionIV); assertThat(segment.encryptionIV).isEqualTo(null);
assertEquals(51501, segment.byterangeLength); assertThat(segment.byterangeLength).isEqualTo(51501);
assertEquals(2147535149L, segment.byterangeOffset); assertThat(segment.byterangeOffset).isEqualTo(2147535149L);
assertEquals("https://priv.example.com/fileSequence2681.ts", segment.url); assertThat(segment.url).isEqualTo("https://priv.example.com/fileSequence2681.ts");
segment = segments.get(3); segment = segments.get(3);
assertEquals(1, segment.relativeDiscontinuitySequence); assertThat(segment.relativeDiscontinuitySequence).isEqualTo(1);
assertEquals(7975000, segment.durationUs); assertThat(segment.durationUs).isEqualTo(7975000);
assertEquals("https://priv.example.com/key.php?r=2682", segment.fullSegmentEncryptionKeyUri); assertThat(segment.fullSegmentEncryptionKeyUri)
.isEqualTo("https://priv.example.com/key.php?r=2682");
// 0xA7A == 2682. // 0xA7A == 2682.
assertNotNull(segment.encryptionIV); assertThat(segment.encryptionIV).isNotNull();
assertEquals("A7A", segment.encryptionIV.toUpperCase(Locale.getDefault())); assertThat(segment.encryptionIV.toUpperCase(Locale.getDefault())).isEqualTo("A7A");
assertEquals(51740, segment.byterangeLength); assertThat(segment.byterangeLength).isEqualTo(51740);
assertEquals(2147586650L, segment.byterangeOffset); assertThat(segment.byterangeOffset).isEqualTo(2147586650L);
assertEquals("https://priv.example.com/fileSequence2682.ts", segment.url); assertThat(segment.url).isEqualTo("https://priv.example.com/fileSequence2682.ts");
segment = segments.get(4); segment = segments.get(4);
assertEquals(1, segment.relativeDiscontinuitySequence); assertThat(segment.relativeDiscontinuitySequence).isEqualTo(1);
assertEquals(7975000, segment.durationUs); assertThat(segment.durationUs).isEqualTo(7975000);
assertEquals("https://priv.example.com/key.php?r=2682", segment.fullSegmentEncryptionKeyUri); assertThat(segment.fullSegmentEncryptionKeyUri)
.isEqualTo("https://priv.example.com/key.php?r=2682");
// 0xA7B == 2683. // 0xA7B == 2683.
assertNotNull(segment.encryptionIV); assertThat(segment.encryptionIV).isNotNull();
assertEquals("A7B", segment.encryptionIV.toUpperCase(Locale.getDefault())); assertThat(segment.encryptionIV.toUpperCase(Locale.getDefault())).isEqualTo("A7B");
assertEquals(C.LENGTH_UNSET, segment.byterangeLength); assertThat(segment.byterangeLength).isEqualTo(C.LENGTH_UNSET);
assertEquals(0, segment.byterangeOffset); assertThat(segment.byterangeOffset).isEqualTo(0);
assertEquals("https://priv.example.com/fileSequence2683.ts", segment.url); assertThat(segment.url).isEqualTo("https://priv.example.com/fileSequence2683.ts");
} catch (IOException exception) { } catch (IOException exception) {
fail(exception.getMessage()); fail(exception.getMessage());
} }
......
...@@ -15,7 +15,8 @@ ...@@ -15,7 +15,8 @@
*/ */
package com.google.android.exoplayer2.source.smoothstreaming.manifest; package com.google.android.exoplayer2.source.smoothstreaming.manifest;
import android.test.MoreAsserts; import static com.google.common.truth.Truth.assertThat;
import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.source.smoothstreaming.manifest.SsManifest.ProtectionElement; import com.google.android.exoplayer2.source.smoothstreaming.manifest.SsManifest.ProtectionElement;
...@@ -75,28 +76,28 @@ public class SsManifestTest extends TestCase { ...@@ -75,28 +76,28 @@ public class SsManifestTest extends TestCase {
} }
private static void assertManifestEquals(SsManifest expected, SsManifest actual) { private static void assertManifestEquals(SsManifest expected, SsManifest actual) {
assertEquals(expected.durationUs, actual.durationUs); assertThat(actual.durationUs).isEqualTo(expected.durationUs);
assertEquals(expected.dvrWindowLengthUs, actual.dvrWindowLengthUs); assertThat(actual.dvrWindowLengthUs).isEqualTo(expected.dvrWindowLengthUs);
assertEquals(expected.isLive, actual.isLive); assertThat(actual.isLive).isEqualTo(expected.isLive);
assertEquals(expected.lookAheadCount, actual.lookAheadCount); assertThat(actual.lookAheadCount).isEqualTo(expected.lookAheadCount);
assertEquals(expected.majorVersion, actual.majorVersion); assertThat(actual.majorVersion).isEqualTo(expected.majorVersion);
assertEquals(expected.minorVersion, actual.minorVersion); assertThat(actual.minorVersion).isEqualTo(expected.minorVersion);
assertEquals(expected.protectionElement.uuid, actual.protectionElement.uuid); assertThat(actual.protectionElement.uuid).isEqualTo(expected.protectionElement.uuid);
assertEquals(expected.protectionElement, actual.protectionElement); assertThat(actual.protectionElement).isEqualTo(expected.protectionElement);
for (int i = 0; i < expected.streamElements.length; i++) { for (int i = 0; i < expected.streamElements.length; i++) {
StreamElement expectedStreamElement = expected.streamElements[i]; StreamElement expectedStreamElement = expected.streamElements[i];
StreamElement actualStreamElement = actual.streamElements[i]; StreamElement actualStreamElement = actual.streamElements[i];
assertEquals(expectedStreamElement.chunkCount, actualStreamElement.chunkCount); assertThat(actualStreamElement.chunkCount).isEqualTo(expectedStreamElement.chunkCount);
assertEquals(expectedStreamElement.displayHeight, actualStreamElement.displayHeight); assertThat(actualStreamElement.displayHeight).isEqualTo(expectedStreamElement.displayHeight);
assertEquals(expectedStreamElement.displayWidth, actualStreamElement.displayWidth); assertThat(actualStreamElement.displayWidth).isEqualTo(expectedStreamElement.displayWidth);
assertEquals(expectedStreamElement.language, actualStreamElement.language); assertThat(actualStreamElement.language).isEqualTo(expectedStreamElement.language);
assertEquals(expectedStreamElement.maxHeight, actualStreamElement.maxHeight); assertThat(actualStreamElement.maxHeight).isEqualTo(expectedStreamElement.maxHeight);
assertEquals(expectedStreamElement.maxWidth, actualStreamElement.maxWidth); assertThat(actualStreamElement.maxWidth).isEqualTo(expectedStreamElement.maxWidth);
assertEquals(expectedStreamElement.name, actualStreamElement.name); assertThat(actualStreamElement.name).isEqualTo(expectedStreamElement.name);
assertEquals(expectedStreamElement.subType, actualStreamElement.subType); assertThat(actualStreamElement.subType).isEqualTo(expectedStreamElement.subType);
assertEquals(expectedStreamElement.timescale, actualStreamElement.timescale); assertThat(actualStreamElement.timescale).isEqualTo(expectedStreamElement.timescale);
assertEquals(expectedStreamElement.type, actualStreamElement.type); assertThat(actualStreamElement.type).isEqualTo(expectedStreamElement.type);
MoreAsserts.assertEquals(expectedStreamElement.formats, actualStreamElement.formats); assertThat(actualStreamElement.formats).isEqualTo(expectedStreamElement.formats);
} }
} }
......
...@@ -15,6 +15,9 @@ ...@@ -15,6 +15,9 @@
*/ */
package com.google.android.exoplayer2.playbacktests.gts; package com.google.android.exoplayer2.playbacktests.gts;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import android.net.Uri; import android.net.Uri;
import android.test.ActivityInstrumentationTestCase2; import android.test.ActivityInstrumentationTestCase2;
import android.util.Log; import android.util.Log;
...@@ -89,15 +92,16 @@ public final class DashDownloadTest extends ActivityInstrumentationTestCase2<Hos ...@@ -89,15 +92,16 @@ public final class DashDownloadTest extends ActivityInstrumentationTestCase2<Hos
// Download representations // Download representations
DashDownloader dashDownloader = downloadContent(false, Float.NaN); DashDownloader dashDownloader = downloadContent(false, Float.NaN);
assertEquals(cache.getCacheSpace() - manifestLength, dashDownloader.getDownloadedBytes()); assertThat(dashDownloader.getDownloadedBytes())
.isEqualTo(cache.getCacheSpace() - manifestLength);
testRunner.setStreamName("test_h264_fixed_download"). testRunner.setStreamName("test_h264_fixed_download").
setDataSourceFactory(newOfflineCacheDataSourceFactory()).run(); setDataSourceFactory(newOfflineCacheDataSourceFactory()).run();
dashDownloader.remove(); dashDownloader.remove();
assertEquals("There should be no content left.", 0, cache.getKeys().size()); assertWithMessage("There should be no content left.").that(cache.getKeys().size()).isEqualTo(0);
assertEquals("There should be no content left.", 0, cache.getCacheSpace()); assertWithMessage("There should be no content left.").that(cache.getCacheSpace()).isEqualTo(0);
} }
public void testPartialDownload() throws Exception { public void testPartialDownload() throws Exception {
...@@ -114,7 +118,7 @@ public final class DashDownloadTest extends ActivityInstrumentationTestCase2<Hos ...@@ -114,7 +118,7 @@ public final class DashDownloadTest extends ActivityInstrumentationTestCase2<Hos
// Make sure it doesn't download any data // Make sure it doesn't download any data
dashDownloader = downloadContent(true, Float.NaN); dashDownloader = downloadContent(true, Float.NaN);
assertEquals(downloadedBytes, dashDownloader.getDownloadedBytes()); assertThat(dashDownloader.getDownloadedBytes()).isEqualTo(downloadedBytes);
testRunner.setStreamName("test_h264_fixed_partial_download") testRunner.setStreamName("test_h264_fixed_partial_download")
.setDataSourceFactory(newOfflineCacheDataSourceFactory()).run(); .setDataSourceFactory(newOfflineCacheDataSourceFactory()).run();
......
...@@ -15,6 +15,8 @@ ...@@ -15,6 +15,8 @@
*/ */
package com.google.android.exoplayer2.playbacktests.gts; package com.google.android.exoplayer2.playbacktests.gts;
import static com.google.common.truth.Truth.assertThat;
import android.test.ActivityInstrumentationTestCase2; import android.test.ActivityInstrumentationTestCase2;
import com.google.android.exoplayer2.ExoPlayer; import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.Player; import com.google.android.exoplayer2.Player;
...@@ -603,8 +605,8 @@ public final class DashStreamingTest extends ActivityInstrumentationTestCase2<Ho ...@@ -603,8 +605,8 @@ public final class DashStreamingTest extends ActivityInstrumentationTestCase2<Ho
return; return;
} }
MediaCodecInfo decoderInfo = MediaCodecUtil.getDecoderInfo(MimeTypes.VIDEO_H264, false); MediaCodecInfo decoderInfo = MediaCodecUtil.getDecoderInfo(MimeTypes.VIDEO_H264, false);
assertNotNull(decoderInfo); assertThat(decoderInfo).isNotNull();
assertTrue(Util.SDK_INT < 21 || decoderInfo.adaptive); assertThat(Util.SDK_INT < 21 || decoderInfo.adaptive).isTrue();
} }
public void testDecoderInfoH265V24() throws DecoderQueryException { public void testDecoderInfoH265V24() throws DecoderQueryException {
...@@ -612,7 +614,7 @@ public final class DashStreamingTest extends ActivityInstrumentationTestCase2<Ho ...@@ -612,7 +614,7 @@ public final class DashStreamingTest extends ActivityInstrumentationTestCase2<Ho
// Pass. // Pass.
return; return;
} }
assertTrue(MediaCodecUtil.getDecoderInfo(MimeTypes.VIDEO_H265, false).adaptive); assertThat(MediaCodecUtil.getDecoderInfo(MimeTypes.VIDEO_H265, false).adaptive).isTrue();
} }
public void testDecoderInfoVP9V24() throws DecoderQueryException { public void testDecoderInfoVP9V24() throws DecoderQueryException {
...@@ -620,7 +622,7 @@ public final class DashStreamingTest extends ActivityInstrumentationTestCase2<Ho ...@@ -620,7 +622,7 @@ public final class DashStreamingTest extends ActivityInstrumentationTestCase2<Ho
// Pass. // Pass.
return; return;
} }
assertTrue(MediaCodecUtil.getDecoderInfo(MimeTypes.VIDEO_VP9, false).adaptive); assertThat(MediaCodecUtil.getDecoderInfo(MimeTypes.VIDEO_VP9, false).adaptive).isTrue();
} }
// Internal. // Internal.
......
...@@ -64,7 +64,6 @@ import com.google.android.exoplayer2.util.Util; ...@@ -64,7 +64,6 @@ import com.google.android.exoplayer2.util.Util;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import junit.framework.AssertionFailedError;
/** {@link DashHostedTest} builder. */ /** {@link DashHostedTest} builder. */
public final class DashTestRunner { public final class DashTestRunner {
...@@ -362,7 +361,7 @@ public final class DashTestRunner { ...@@ -362,7 +361,7 @@ public final class DashTestRunner {
// Assert that consecutive dropped frames were within limit. // Assert that consecutive dropped frames were within limit.
DecoderCountersUtil.assertConsecutiveDroppedBufferLimit(tag + VIDEO_TAG_SUFFIX, DecoderCountersUtil.assertConsecutiveDroppedBufferLimit(tag + VIDEO_TAG_SUFFIX,
videoCounters, MAX_CONSECUTIVE_DROPPED_VIDEO_FRAMES); videoCounters, MAX_CONSECUTIVE_DROPPED_VIDEO_FRAMES);
} catch (AssertionFailedError e) { } catch (AssertionError e) {
if (trackSelector.includedAdditionalVideoFormats) { if (trackSelector.includedAdditionalVideoFormats) {
// Retry limiting to CDD mandated formats (b/28220076). // Retry limiting to CDD mandated formats (b/28220076).
Log.e(tag, "Too many dropped or consecutive dropped frames.", e); Log.e(tag, "Too many dropped or consecutive dropped frames.", e);
......
...@@ -15,6 +15,9 @@ ...@@ -15,6 +15,9 @@
*/ */
package com.google.android.exoplayer2.playbacktests.gts; package com.google.android.exoplayer2.playbacktests.gts;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import android.media.MediaDrm.MediaDrmStateException; import android.media.MediaDrm.MediaDrmStateException;
import android.net.Uri; import android.net.Uri;
import android.test.ActivityInstrumentationTestCase2; import android.test.ActivityInstrumentationTestCase2;
...@@ -33,7 +36,6 @@ import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory; ...@@ -33,7 +36,6 @@ import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory;
import com.google.android.exoplayer2.util.MimeTypes; import com.google.android.exoplayer2.util.MimeTypes;
import com.google.android.exoplayer2.util.Util; import com.google.android.exoplayer2.util.Util;
import java.io.IOException; import java.io.IOException;
import junit.framework.Assert;
/** /**
* Tests Widevine encrypted DASH playbacks using offline keys. * Tests Widevine encrypted DASH playbacks using offline keys.
...@@ -98,7 +100,7 @@ public final class DashWidevineOfflineTest extends ActivityInstrumentationTestCa ...@@ -98,7 +100,7 @@ public final class DashWidevineOfflineTest extends ActivityInstrumentationTestCa
// Renew license after playback should still work // Renew license after playback should still work
offlineLicenseKeySetId = offlineLicenseHelper.renewLicense(offlineLicenseKeySetId); offlineLicenseKeySetId = offlineLicenseHelper.renewLicense(offlineLicenseKeySetId);
Assert.assertNotNull(offlineLicenseKeySetId); assertThat(offlineLicenseKeySetId).isNotNull();
} }
public void testWidevineOfflineReleasedLicenseV22() throws Throwable { public void testWidevineOfflineReleasedLicenseV22() throws Throwable {
...@@ -136,8 +138,10 @@ public final class DashWidevineOfflineTest extends ActivityInstrumentationTestCa ...@@ -136,8 +138,10 @@ public final class DashWidevineOfflineTest extends ActivityInstrumentationTestCa
// Wait until the license expires // Wait until the license expires
long licenseDuration = long licenseDuration =
offlineLicenseHelper.getLicenseDurationRemainingSec(offlineLicenseKeySetId).first; offlineLicenseHelper.getLicenseDurationRemainingSec(offlineLicenseKeySetId).first;
assertTrue("License duration should be less than 30 sec. " assertWithMessage(
+ "Server settings might have changed.", licenseDuration < 30); "License duration should be less than 30 sec. " + "Server settings might have changed.")
.that(licenseDuration < 30)
.isTrue();
while (licenseDuration > 0) { while (licenseDuration > 0) {
synchronized (this) { synchronized (this) {
wait(licenseDuration * 1000 + 2000); wait(licenseDuration * 1000 + 2000);
...@@ -145,7 +149,9 @@ public final class DashWidevineOfflineTest extends ActivityInstrumentationTestCa ...@@ -145,7 +149,9 @@ public final class DashWidevineOfflineTest extends ActivityInstrumentationTestCa
long previousDuration = licenseDuration; long previousDuration = licenseDuration;
licenseDuration = licenseDuration =
offlineLicenseHelper.getLicenseDurationRemainingSec(offlineLicenseKeySetId).first; offlineLicenseHelper.getLicenseDurationRemainingSec(offlineLicenseKeySetId).first;
assertTrue("License duration should be decreasing.", previousDuration > licenseDuration); assertWithMessage("License duration should be decreasing.")
.that(previousDuration > licenseDuration)
.isTrue();
} }
// DefaultDrmSessionManager should renew the license and stream play fine // DefaultDrmSessionManager should renew the license and stream play fine
...@@ -162,8 +168,10 @@ public final class DashWidevineOfflineTest extends ActivityInstrumentationTestCa ...@@ -162,8 +168,10 @@ public final class DashWidevineOfflineTest extends ActivityInstrumentationTestCa
Pair<Long, Long> licenseDurationRemainingSec = Pair<Long, Long> licenseDurationRemainingSec =
offlineLicenseHelper.getLicenseDurationRemainingSec(offlineLicenseKeySetId); offlineLicenseHelper.getLicenseDurationRemainingSec(offlineLicenseKeySetId);
long licenseDuration = licenseDurationRemainingSec.first; long licenseDuration = licenseDurationRemainingSec.first;
assertTrue("License duration should be less than 30 sec. " assertWithMessage(
+ "Server settings might have changed.", licenseDuration < 30); "License duration should be less than 30 sec. " + "Server settings might have changed.")
.that(licenseDuration < 30)
.isTrue();
ActionSchedule schedule = new ActionSchedule.Builder(TAG) ActionSchedule schedule = new ActionSchedule.Builder(TAG)
.waitForPlaybackState(Player.STATE_READY) .waitForPlaybackState(Player.STATE_READY)
.delay(3000).pause().delay(licenseDuration * 1000 + 2000).play().build(); .delay(3000).pause().delay(licenseDuration * 1000 + 2000).play().build();
...@@ -178,8 +186,8 @@ public final class DashWidevineOfflineTest extends ActivityInstrumentationTestCa ...@@ -178,8 +186,8 @@ public final class DashWidevineOfflineTest extends ActivityInstrumentationTestCa
Uri.parse(DashTestData.WIDEVINE_H264_MANIFEST)); Uri.parse(DashTestData.WIDEVINE_H264_MANIFEST));
DrmInitData drmInitData = DashUtil.loadDrmInitData(dataSource, dashManifest.getPeriod(0)); DrmInitData drmInitData = DashUtil.loadDrmInitData(dataSource, dashManifest.getPeriod(0));
offlineLicenseKeySetId = offlineLicenseHelper.downloadLicense(drmInitData); offlineLicenseKeySetId = offlineLicenseHelper.downloadLicense(drmInitData);
Assert.assertNotNull(offlineLicenseKeySetId); assertThat(offlineLicenseKeySetId).isNotNull();
Assert.assertTrue(offlineLicenseKeySetId.length > 0); assertThat(offlineLicenseKeySetId.length).isGreaterThan(0);
testRunner.setOfflineLicenseKeySetId(offlineLicenseKeySetId); testRunner.setOfflineLicenseKeySetId(offlineLicenseKeySetId);
} }
......
...@@ -27,4 +27,5 @@ android { ...@@ -27,4 +27,5 @@ android {
dependencies { dependencies {
compile project(modulePrefix + 'library-core') compile project(modulePrefix + 'library-core')
compile 'org.mockito:mockito-core:' + mockitoVersion compile 'org.mockito:mockito-core:' + mockitoVersion
compile 'com.google.truth:truth:' + truthVersion
} }
...@@ -15,11 +15,10 @@ ...@@ -15,11 +15,10 @@
*/ */
package com.google.android.exoplayer2.testutil; package com.google.android.exoplayer2.testutil;
import static junit.framework.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import static junit.framework.Assert.assertTrue; import static com.google.common.truth.Truth.assertWithMessage;
import android.net.Uri; import android.net.Uri;
import android.test.MoreAsserts;
import com.google.android.exoplayer2.testutil.FakeDataSet.FakeData; import com.google.android.exoplayer2.testutil.FakeDataSet.FakeData;
import com.google.android.exoplayer2.upstream.DataSource; import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DataSpec; import com.google.android.exoplayer2.upstream.DataSpec;
...@@ -76,7 +75,7 @@ public final class CacheAsserts { ...@@ -76,7 +75,7 @@ public final class CacheAsserts {
assertDataCached(cache, uri, data); assertDataCached(cache, uri, data);
totalLength += data.length; totalLength += data.length;
} }
assertEquals(totalLength, cache.getCacheSpace()); assertThat(cache.getCacheSpace()).isEqualTo(totalLength);
} }
/** /**
...@@ -112,8 +111,9 @@ public final class CacheAsserts { ...@@ -112,8 +111,9 @@ public final class CacheAsserts {
dataSource.open(dataSpec); dataSource.open(dataSpec);
try { try {
byte[] bytes = TestUtil.readToEnd(dataSource); byte[] bytes = TestUtil.readToEnd(dataSource);
MoreAsserts.assertEquals( assertWithMessage("Cached data doesn't match expected for '" + dataSpec.uri + "',")
"Cached data doesn't match expected for '" + dataSpec.uri + "',", expected, bytes); .that(bytes)
.isEqualTo(expected);
} finally { } finally {
dataSource.close(); dataSource.close();
} }
...@@ -122,15 +122,15 @@ public final class CacheAsserts { ...@@ -122,15 +122,15 @@ public final class CacheAsserts {
/** Asserts that there is no cache content for the given {@code uriStrings}. */ /** Asserts that there is no cache content for the given {@code uriStrings}. */
public static void assertDataNotCached(Cache cache, String... uriStrings) { public static void assertDataNotCached(Cache cache, String... uriStrings) {
for (String uriString : uriStrings) { for (String uriString : uriStrings) {
assertTrue( assertWithMessage("There is cached data for '" + uriString + "',")
"There is cached data for '" + uriString + "',", .that(cache.getCachedSpans(CacheUtil.generateKey(Uri.parse(uriString))).isEmpty())
cache.getCachedSpans(CacheUtil.generateKey(Uri.parse(uriString))).isEmpty()); .isTrue();
} }
} }
/** Asserts that the cache is empty. */ /** Asserts that the cache is empty. */
public static void assertCacheEmpty(Cache cache) { public static void assertCacheEmpty(Cache cache) {
assertEquals(0, cache.getCacheSpace()); assertThat(cache.getCacheSpace()).isEqualTo(0);
} }
private CacheAsserts() {} private CacheAsserts() {}
......
...@@ -15,8 +15,9 @@ ...@@ -15,8 +15,9 @@
*/ */
package com.google.android.exoplayer2.testutil; package com.google.android.exoplayer2.testutil;
import static com.google.common.truth.Truth.assertWithMessage;
import com.google.android.exoplayer2.decoder.DecoderCounters; import com.google.android.exoplayer2.decoder.DecoderCounters;
import junit.framework.TestCase;
/** /**
* Assertions for {@link DecoderCounters}. * Assertions for {@link DecoderCounters}.
...@@ -41,30 +42,60 @@ public final class DecoderCountersUtil { ...@@ -41,30 +42,60 @@ public final class DecoderCountersUtil {
int expected) { int expected) {
counters.ensureUpdated(); counters.ensureUpdated();
int actual = counters.skippedOutputBufferCount; int actual = counters.skippedOutputBufferCount;
TestCase.assertEquals("Codec(" + name + ") skipped " + actual + " buffers. Expected " assertWithMessage(
+ expected + ".", expected, actual); "Codec(" + name + ") skipped " + actual + " buffers. Expected " + expected + ".")
.that(actual)
.isEqualTo(expected);
} }
public static void assertTotalBufferCount(String name, DecoderCounters counters, int minCount, public static void assertTotalBufferCount(String name, DecoderCounters counters, int minCount,
int maxCount) { int maxCount) {
int actual = getTotalBufferCount(counters); int actual = getTotalBufferCount(counters);
TestCase.assertTrue("Codec(" + name + ") output " + actual + " buffers. Expected in range [" assertWithMessage(
+ minCount + ", " + maxCount + "].", minCount <= actual && actual <= maxCount); "Codec("
+ name
+ ") output "
+ actual
+ " buffers. Expected in range ["
+ minCount
+ ", "
+ maxCount
+ "].")
.that(minCount <= actual && actual <= maxCount)
.isTrue();
} }
public static void assertDroppedBufferLimit(String name, DecoderCounters counters, int limit) { public static void assertDroppedBufferLimit(String name, DecoderCounters counters, int limit) {
counters.ensureUpdated(); counters.ensureUpdated();
int actual = counters.droppedBufferCount; int actual = counters.droppedBufferCount;
TestCase.assertTrue("Codec(" + name + ") was late decoding: " + actual + " buffers. " assertWithMessage(
+ "Limit: " + limit + ".", actual <= limit); "Codec("
+ name
+ ") was late decoding: "
+ actual
+ " buffers. "
+ "Limit: "
+ limit
+ ".")
.that(actual)
.isAtMost(limit);
} }
public static void assertConsecutiveDroppedBufferLimit(String name, DecoderCounters counters, public static void assertConsecutiveDroppedBufferLimit(String name, DecoderCounters counters,
int limit) { int limit) {
counters.ensureUpdated(); counters.ensureUpdated();
int actual = counters.maxConsecutiveDroppedBufferCount; int actual = counters.maxConsecutiveDroppedBufferCount;
TestCase.assertTrue("Codec(" + name + ") was late decoding: " + actual assertWithMessage(
+ " buffers consecutively. " + "Limit: " + limit + ".", actual <= limit); "Codec("
+ name
+ ") was late decoding: "
+ actual
+ " buffers consecutively. "
+ "Limit: "
+ limit
+ ".")
.that(actual)
.isAtMost(limit);
} }
} }
...@@ -15,6 +15,8 @@ ...@@ -15,6 +15,8 @@
*/ */
package com.google.android.exoplayer2.testutil; package com.google.android.exoplayer2.testutil;
import static com.google.common.truth.Truth.assertWithMessage;
import android.os.ConditionVariable; import android.os.ConditionVariable;
import android.os.Looper; import android.os.Looper;
import android.os.SystemClock; import android.os.SystemClock;
...@@ -46,7 +48,6 @@ import com.google.android.exoplayer2.util.Clock; ...@@ -46,7 +48,6 @@ import com.google.android.exoplayer2.util.Clock;
import com.google.android.exoplayer2.util.HandlerWrapper; import com.google.android.exoplayer2.util.HandlerWrapper;
import com.google.android.exoplayer2.util.Util; import com.google.android.exoplayer2.util.Util;
import com.google.android.exoplayer2.video.VideoRendererEventListener; import com.google.android.exoplayer2.video.VideoRendererEventListener;
import junit.framework.Assert;
/** /**
* A {@link HostedTest} for {@link ExoPlayer} playback tests. * A {@link HostedTest} for {@link ExoPlayer} playback tests.
...@@ -219,9 +220,12 @@ public abstract class ExoHostedTest extends Player.DefaultEventListener implemen ...@@ -219,9 +220,12 @@ public abstract class ExoHostedTest extends Player.DefaultEventListener implemen
// Assert that the playback spanned the correct duration of time. // Assert that the playback spanned the correct duration of time.
long minAllowedActualPlayingTimeMs = playingTimeToAssertMs - MAX_PLAYING_TIME_DISCREPANCY_MS; long minAllowedActualPlayingTimeMs = playingTimeToAssertMs - MAX_PLAYING_TIME_DISCREPANCY_MS;
long maxAllowedActualPlayingTimeMs = playingTimeToAssertMs + MAX_PLAYING_TIME_DISCREPANCY_MS; long maxAllowedActualPlayingTimeMs = playingTimeToAssertMs + MAX_PLAYING_TIME_DISCREPANCY_MS;
Assert.assertTrue("Total playing time: " + totalPlayingTimeMs + ". Expected: " assertWithMessage(
+ playingTimeToAssertMs, minAllowedActualPlayingTimeMs <= totalPlayingTimeMs "Total playing time: " + totalPlayingTimeMs + ". Expected: " + playingTimeToAssertMs)
&& totalPlayingTimeMs <= maxAllowedActualPlayingTimeMs); .that(
minAllowedActualPlayingTimeMs <= totalPlayingTimeMs
&& totalPlayingTimeMs <= maxAllowedActualPlayingTimeMs)
.isTrue();
} }
// Make any additional assertions. // Make any additional assertions.
assertPassed(audioDecoderCounters, videoDecoderCounters); assertPassed(audioDecoderCounters, videoDecoderCounters);
......
...@@ -15,6 +15,8 @@ ...@@ -15,6 +15,8 @@
*/ */
package com.google.android.exoplayer2.testutil; package com.google.android.exoplayer2.testutil;
import static com.google.common.truth.Truth.assertThat;
import android.os.HandlerThread; import android.os.HandlerThread;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import com.google.android.exoplayer2.DefaultLoadControl; import com.google.android.exoplayer2.DefaultLoadControl;
...@@ -22,7 +24,6 @@ import com.google.android.exoplayer2.ExoPlaybackException; ...@@ -22,7 +24,6 @@ import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.LoadControl; import com.google.android.exoplayer2.LoadControl;
import com.google.android.exoplayer2.Player; import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.Player.DiscontinuityReason;
import com.google.android.exoplayer2.Renderer; import com.google.android.exoplayer2.Renderer;
import com.google.android.exoplayer2.RenderersFactory; import com.google.android.exoplayer2.RenderersFactory;
import com.google.android.exoplayer2.SimpleExoPlayer; import com.google.android.exoplayer2.SimpleExoPlayer;
...@@ -41,10 +42,10 @@ import com.google.android.exoplayer2.util.HandlerWrapper; ...@@ -41,10 +42,10 @@ import com.google.android.exoplayer2.util.HandlerWrapper;
import com.google.android.exoplayer2.util.MimeTypes; import com.google.android.exoplayer2.util.MimeTypes;
import com.google.android.exoplayer2.video.VideoRendererEventListener; import com.google.android.exoplayer2.video.VideoRendererEventListener;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import junit.framework.Assert;
/** /**
* Helper class to run an ExoPlayer test. * Helper class to run an ExoPlayer test.
...@@ -97,7 +98,7 @@ public final class ExoPlayerTestRunner extends Player.DefaultEventListener ...@@ -97,7 +98,7 @@ public final class ExoPlayerTestRunner extends Player.DefaultEventListener
* @return This builder. * @return This builder.
*/ */
public Builder setTimeline(Timeline timeline) { public Builder setTimeline(Timeline timeline) {
Assert.assertNull(mediaSource); assertThat(mediaSource).isNull();
this.timeline = timeline; this.timeline = timeline;
return this; return this;
} }
...@@ -111,7 +112,7 @@ public final class ExoPlayerTestRunner extends Player.DefaultEventListener ...@@ -111,7 +112,7 @@ public final class ExoPlayerTestRunner extends Player.DefaultEventListener
* @return This builder. * @return This builder.
*/ */
public Builder setManifest(Object manifest) { public Builder setManifest(Object manifest) {
Assert.assertNull(mediaSource); assertThat(mediaSource).isNull();
this.manifest = manifest; this.manifest = manifest;
return this; return this;
} }
...@@ -127,8 +128,8 @@ public final class ExoPlayerTestRunner extends Player.DefaultEventListener ...@@ -127,8 +128,8 @@ public final class ExoPlayerTestRunner extends Player.DefaultEventListener
* @return This builder. * @return This builder.
*/ */
public Builder setMediaSource(MediaSource mediaSource) { public Builder setMediaSource(MediaSource mediaSource) {
Assert.assertNull(timeline); assertThat(timeline).isNull();
Assert.assertNull(manifest); assertThat(manifest).isNull();
this.mediaSource = mediaSource; this.mediaSource = mediaSource;
return this; return this;
} }
...@@ -182,7 +183,7 @@ public final class ExoPlayerTestRunner extends Player.DefaultEventListener ...@@ -182,7 +183,7 @@ public final class ExoPlayerTestRunner extends Player.DefaultEventListener
* @return This builder. * @return This builder.
*/ */
public Builder setRenderers(Renderer... renderers) { public Builder setRenderers(Renderer... renderers) {
Assert.assertNull(renderersFactory); assertThat(renderersFactory).isNull();
this.renderers = renderers; this.renderers = renderers;
return this; return this;
} }
...@@ -196,7 +197,7 @@ public final class ExoPlayerTestRunner extends Player.DefaultEventListener ...@@ -196,7 +197,7 @@ public final class ExoPlayerTestRunner extends Player.DefaultEventListener
* @return This builder. * @return This builder.
*/ */
public Builder setRenderersFactory(RenderersFactory renderersFactory) { public Builder setRenderersFactory(RenderersFactory renderersFactory) {
Assert.assertNull(renderers); assertThat(renderers).isNull();
this.renderersFactory = renderersFactory; this.renderersFactory = renderersFactory;
return this; return this;
} }
...@@ -478,10 +479,7 @@ public final class ExoPlayerTestRunner extends Player.DefaultEventListener ...@@ -478,10 +479,7 @@ public final class ExoPlayerTestRunner extends Player.DefaultEventListener
* @param timelines A list of expected {@link Timeline}s. * @param timelines A list of expected {@link Timeline}s.
*/ */
public void assertTimelinesEqual(Timeline... timelines) { public void assertTimelinesEqual(Timeline... timelines) {
Assert.assertEquals(timelines.length, this.timelines.size()); assertThat(this.timelines).containsExactlyElementsIn(Arrays.asList(timelines)).inOrder();
for (int i = 0; i < timelines.length; i++) {
Assert.assertEquals(timelines[i], this.timelines.get(i));
}
} }
/** /**
...@@ -492,22 +490,16 @@ public final class ExoPlayerTestRunner extends Player.DefaultEventListener ...@@ -492,22 +490,16 @@ public final class ExoPlayerTestRunner extends Player.DefaultEventListener
* @param manifests A list of expected manifests. * @param manifests A list of expected manifests.
*/ */
public void assertManifestsEqual(Object... manifests) { public void assertManifestsEqual(Object... manifests) {
Assert.assertEquals(manifests.length, this.manifests.size()); assertThat(this.manifests).containsExactlyElementsIn(Arrays.asList(manifests)).inOrder();
for (int i = 0; i < manifests.length; i++) {
Assert.assertEquals(manifests[i], this.manifests.get(i));
}
} }
/** /**
* Asserts that the timeline change reasons reported by * Asserts that the timeline change reasons reported by {@link
* {@link Player.EventListener#onTimelineChanged(Timeline, Object, int)} are equal to the provided * Player.EventListener#onTimelineChanged(Timeline, Object, int)} are equal to the provided
* timeline change reasons. * timeline change reasons.
*/ */
public void assertTimelineChangeReasonsEqual(@Player.TimelineChangeReason int... reasons) { public void assertTimelineChangeReasonsEqual(Integer... reasons) {
Assert.assertEquals(reasons.length, timelineChangeReasons.size()); assertThat(timelineChangeReasons).containsExactlyElementsIn(Arrays.asList(reasons)).inOrder();
for (int i = 0; i < reasons.length; i++) {
Assert.assertEquals(reasons[i], (int) timelineChangeReasons.get(i));
}
} }
/** /**
...@@ -518,28 +510,26 @@ public final class ExoPlayerTestRunner extends Player.DefaultEventListener ...@@ -518,28 +510,26 @@ public final class ExoPlayerTestRunner extends Player.DefaultEventListener
* @param trackGroupArray The expected {@link TrackGroupArray}. * @param trackGroupArray The expected {@link TrackGroupArray}.
*/ */
public void assertTrackGroupsEqual(TrackGroupArray trackGroupArray) { public void assertTrackGroupsEqual(TrackGroupArray trackGroupArray) {
Assert.assertEquals(trackGroupArray, this.trackGroups); assertThat(this.trackGroups).isEqualTo(trackGroupArray);
} }
/** /**
* Asserts that {@link Player.EventListener#onPositionDiscontinuity(int)} was not called. * Asserts that {@link Player.EventListener#onPositionDiscontinuity(int)} was not called.
*/ */
public void assertNoPositionDiscontinuities() { public void assertNoPositionDiscontinuities() {
Assert.assertTrue(discontinuityReasons.isEmpty()); assertThat(discontinuityReasons).isEmpty();
} }
/** /**
* Asserts that the discontinuity reasons reported by * Asserts that the discontinuity reasons reported by {@link
* {@link Player.EventListener#onPositionDiscontinuity(int)} are equal to the provided values. * Player.EventListener#onPositionDiscontinuity(int)} are equal to the provided values.
* *
* @param discontinuityReasons The expected discontinuity reasons. * @param discontinuityReasons The expected discontinuity reasons.
*/ */
public void assertPositionDiscontinuityReasonsEqual( public void assertPositionDiscontinuityReasonsEqual(Integer... discontinuityReasons) {
@DiscontinuityReason int... discontinuityReasons) { assertThat(this.discontinuityReasons)
Assert.assertEquals(discontinuityReasons.length, this.discontinuityReasons.size()); .containsExactlyElementsIn(Arrays.asList(discontinuityReasons))
for (int i = 0; i < discontinuityReasons.length; i++) { .inOrder();
Assert.assertEquals(discontinuityReasons[i], (int) this.discontinuityReasons.get(i));
}
} }
/** /**
...@@ -550,11 +540,10 @@ public final class ExoPlayerTestRunner extends Player.DefaultEventListener ...@@ -550,11 +540,10 @@ public final class ExoPlayerTestRunner extends Player.DefaultEventListener
* *
* @param periodIndices A list of expected period indices. * @param periodIndices A list of expected period indices.
*/ */
public void assertPlayedPeriodIndices(int... periodIndices) { public void assertPlayedPeriodIndices(Integer... periodIndices) {
Assert.assertEquals(periodIndices.length, this.periodIndices.size()); assertThat(this.periodIndices)
for (int i = 0; i < periodIndices.length; i++) { .containsExactlyElementsIn(Arrays.asList(periodIndices))
Assert.assertEquals(periodIndices[i], (int) this.periodIndices.get(i)); .inOrder();
}
} }
// Private implementation details. // Private implementation details.
......
...@@ -15,6 +15,8 @@ ...@@ -15,6 +15,8 @@
*/ */
package com.google.android.exoplayer2.testutil; package com.google.android.exoplayer2.testutil;
import static com.google.common.truth.Truth.assertThat;
import android.app.Instrumentation; import android.app.Instrumentation;
import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.extractor.Extractor; import com.google.android.exoplayer2.extractor.Extractor;
...@@ -26,7 +28,6 @@ import com.google.android.exoplayer2.testutil.FakeExtractorInput.SimulatedIOExce ...@@ -26,7 +28,6 @@ import com.google.android.exoplayer2.testutil.FakeExtractorInput.SimulatedIOExce
import com.google.android.exoplayer2.util.Assertions; import com.google.android.exoplayer2.util.Assertions;
import java.io.IOException; import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
import junit.framework.Assert;
/** /**
* Assertion methods for {@link Extractor}. * Assertion methods for {@link Extractor}.
...@@ -126,7 +127,7 @@ public final class ExtractorAsserts { ...@@ -126,7 +127,7 @@ public final class ExtractorAsserts {
.setSimulatePartialReads(simulatePartialReads).build(); .setSimulatePartialReads(simulatePartialReads).build();
if (sniffFirst) { if (sniffFirst) {
Assert.assertTrue(TestUtil.sniffTestData(extractor, input)); assertThat(TestUtil.sniffTestData(extractor, input)).isTrue();
input.resetPeekPosition(); input.resetPeekPosition();
} }
......
...@@ -15,12 +15,13 @@ ...@@ -15,12 +15,13 @@
*/ */
package com.google.android.exoplayer2.testutil; package com.google.android.exoplayer2.testutil;
import static com.google.common.truth.Truth.assertThat;
import android.util.SparseBooleanArray; import android.util.SparseBooleanArray;
import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.extractor.ExtractorInput; import com.google.android.exoplayer2.extractor.ExtractorInput;
import java.io.EOFException; import java.io.EOFException;
import java.io.IOException; import java.io.IOException;
import junit.framework.Assert;
/** /**
* A fake {@link ExtractorInput} capable of simulating various scenarios. * A fake {@link ExtractorInput} capable of simulating various scenarios.
...@@ -84,7 +85,7 @@ public final class FakeExtractorInput implements ExtractorInput { ...@@ -84,7 +85,7 @@ public final class FakeExtractorInput implements ExtractorInput {
* @param position The position to set. * @param position The position to set.
*/ */
public void setPosition(int position) { public void setPosition(int position) {
Assert.assertTrue(0 <= position && position <= data.length); assertThat(0 <= position && position <= data.length).isTrue();
readPosition = position; readPosition = position;
peekPosition = position; peekPosition = position;
} }
...@@ -180,7 +181,7 @@ public final class FakeExtractorInput implements ExtractorInput { ...@@ -180,7 +181,7 @@ public final class FakeExtractorInput implements ExtractorInput {
@Override @Override
public <E extends Throwable> void setRetryPosition(long position, E e) throws E { public <E extends Throwable> void setRetryPosition(long position, E e) throws E {
Assert.assertTrue(position >= 0); assertThat(position >= 0).isTrue();
readPosition = (int) position; readPosition = (int) position;
throw e; throw e;
} }
......
...@@ -15,6 +15,9 @@ ...@@ -15,6 +15,9 @@
*/ */
package com.google.android.exoplayer2.testutil; package com.google.android.exoplayer2.testutil;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import android.app.Instrumentation; import android.app.Instrumentation;
import android.util.SparseArray; import android.util.SparseArray;
import com.google.android.exoplayer2.extractor.ExtractorOutput; import com.google.android.exoplayer2.extractor.ExtractorOutput;
...@@ -22,7 +25,6 @@ import com.google.android.exoplayer2.extractor.SeekMap; ...@@ -22,7 +25,6 @@ import com.google.android.exoplayer2.extractor.SeekMap;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import junit.framework.Assert;
/** /**
* A fake {@link ExtractorOutput}. * A fake {@link ExtractorOutput}.
...@@ -50,7 +52,7 @@ public final class FakeExtractorOutput implements ExtractorOutput, Dumper.Dumpab ...@@ -50,7 +52,7 @@ public final class FakeExtractorOutput implements ExtractorOutput, Dumper.Dumpab
public FakeTrackOutput track(int id, int type) { public FakeTrackOutput track(int id, int type) {
FakeTrackOutput output = trackOutputs.get(id); FakeTrackOutput output = trackOutputs.get(id);
if (output == null) { if (output == null) {
Assert.assertFalse(tracksEnded); assertThat(tracksEnded).isFalse();
numberOfTracks++; numberOfTracks++;
output = new FakeTrackOutput(); output = new FakeTrackOutput();
trackOutputs.put(id, output); trackOutputs.put(id, output);
...@@ -69,19 +71,19 @@ public final class FakeExtractorOutput implements ExtractorOutput, Dumper.Dumpab ...@@ -69,19 +71,19 @@ public final class FakeExtractorOutput implements ExtractorOutput, Dumper.Dumpab
} }
public void assertEquals(FakeExtractorOutput expected) { public void assertEquals(FakeExtractorOutput expected) {
Assert.assertEquals(expected.numberOfTracks, numberOfTracks); assertThat(numberOfTracks).isEqualTo(expected.numberOfTracks);
Assert.assertEquals(expected.tracksEnded, tracksEnded); assertThat(tracksEnded).isEqualTo(expected.tracksEnded);
if (expected.seekMap == null) { if (expected.seekMap == null) {
Assert.assertNull(seekMap); assertThat(seekMap).isNull();
} else { } else {
// TODO: Bulk up this check if possible. // TODO: Bulk up this check if possible.
Assert.assertNotNull(seekMap); assertThat(seekMap).isNotNull();
Assert.assertEquals(expected.seekMap.getClass(), seekMap.getClass()); assertThat(seekMap.getClass()).isEqualTo(expected.seekMap.getClass());
Assert.assertEquals(expected.seekMap.isSeekable(), seekMap.isSeekable()); assertThat(seekMap.isSeekable()).isEqualTo(expected.seekMap.isSeekable());
Assert.assertEquals(expected.seekMap.getSeekPoints(0), seekMap.getSeekPoints(0)); assertThat(seekMap.getSeekPoints(0)).isEqualTo(expected.seekMap.getSeekPoints(0));
} }
for (int i = 0; i < numberOfTracks; i++) { for (int i = 0; i < numberOfTracks; i++) {
Assert.assertEquals(expected.trackOutputs.keyAt(i), trackOutputs.keyAt(i)); assertThat(trackOutputs.keyAt(i)).isEqualTo(expected.trackOutputs.keyAt(i));
trackOutputs.valueAt(i).assertEquals(expected.trackOutputs.valueAt(i)); trackOutputs.valueAt(i).assertEquals(expected.trackOutputs.valueAt(i));
} }
} }
...@@ -107,7 +109,7 @@ public final class FakeExtractorOutput implements ExtractorOutput, Dumper.Dumpab ...@@ -107,7 +109,7 @@ public final class FakeExtractorOutput implements ExtractorOutput, Dumper.Dumpab
out.close(); out.close();
} else { } else {
String expected = TestUtil.getString(instrumentation, dumpFile); String expected = TestUtil.getString(instrumentation, dumpFile);
Assert.assertEquals(dumpFile, expected, actual); assertWithMessage(dumpFile).that(actual).isEqualTo(expected);
} }
} }
......
...@@ -15,6 +15,8 @@ ...@@ -15,6 +15,8 @@
*/ */
package com.google.android.exoplayer2.testutil; package com.google.android.exoplayer2.testutil;
import static com.google.common.truth.Truth.assertThat;
import android.os.Handler; import android.os.Handler;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.C;
...@@ -25,7 +27,6 @@ import com.google.android.exoplayer2.source.TrackGroup; ...@@ -25,7 +27,6 @@ import com.google.android.exoplayer2.source.TrackGroup;
import com.google.android.exoplayer2.source.TrackGroupArray; import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.trackselection.TrackSelection; import com.google.android.exoplayer2.trackselection.TrackSelection;
import java.io.IOException; import java.io.IOException;
import junit.framework.Assert;
/** /**
* Fake {@link MediaPeriod} that provides tracks from the given {@link TrackGroupArray}. Selecting * Fake {@link MediaPeriod} that provides tracks from the given {@link TrackGroupArray}. Selecting
...@@ -119,14 +120,14 @@ public class FakeMediaPeriod implements MediaPeriod { ...@@ -119,14 +120,14 @@ public class FakeMediaPeriod implements MediaPeriod {
@Override @Override
public TrackGroupArray getTrackGroups() { public TrackGroupArray getTrackGroups() {
Assert.assertTrue(prepared); assertThat(prepared).isTrue();
return trackGroupArray; return trackGroupArray;
} }
@Override @Override
public long selectTracks(TrackSelection[] selections, boolean[] mayRetainStreamFlags, public long selectTracks(TrackSelection[] selections, boolean[] mayRetainStreamFlags,
SampleStream[] streams, boolean[] streamResetFlags, long positionUs) { SampleStream[] streams, boolean[] streamResetFlags, long positionUs) {
Assert.assertTrue(prepared); assertThat(prepared).isTrue();
int rendererCount = selections.length; int rendererCount = selections.length;
for (int i = 0; i < rendererCount; i++) { for (int i = 0; i < rendererCount; i++) {
if (streams[i] != null && (selections[i] == null || !mayRetainStreamFlags[i])) { if (streams[i] != null && (selections[i] == null || !mayRetainStreamFlags[i])) {
...@@ -134,12 +135,12 @@ public class FakeMediaPeriod implements MediaPeriod { ...@@ -134,12 +135,12 @@ public class FakeMediaPeriod implements MediaPeriod {
} }
if (streams[i] == null && selections[i] != null) { if (streams[i] == null && selections[i] != null) {
TrackSelection selection = selections[i]; TrackSelection selection = selections[i];
Assert.assertTrue(1 <= selection.length()); assertThat(selection.length()).isAtLeast(1);
TrackGroup trackGroup = selection.getTrackGroup(); TrackGroup trackGroup = selection.getTrackGroup();
Assert.assertTrue(trackGroupArray.indexOf(trackGroup) != C.INDEX_UNSET); assertThat(trackGroupArray.indexOf(trackGroup) != C.INDEX_UNSET).isTrue();
int indexInTrackGroup = selection.getIndexInTrackGroup(selection.getSelectedIndex()); int indexInTrackGroup = selection.getIndexInTrackGroup(selection.getSelectedIndex());
Assert.assertTrue(0 <= indexInTrackGroup); assertThat(indexInTrackGroup).isAtLeast(0);
Assert.assertTrue(indexInTrackGroup < trackGroup.length); assertThat(indexInTrackGroup).isLessThan(trackGroup.length);
streams[i] = createSampleStream(selection); streams[i] = createSampleStream(selection);
streamResetFlags[i] = true; streamResetFlags[i] = true;
} }
...@@ -159,7 +160,7 @@ public class FakeMediaPeriod implements MediaPeriod { ...@@ -159,7 +160,7 @@ public class FakeMediaPeriod implements MediaPeriod {
@Override @Override
public long readDiscontinuity() { public long readDiscontinuity() {
Assert.assertTrue(prepared); assertThat(prepared).isTrue();
long positionDiscontinuityUs = this.discontinuityPositionUs; long positionDiscontinuityUs = this.discontinuityPositionUs;
this.discontinuityPositionUs = C.TIME_UNSET; this.discontinuityPositionUs = C.TIME_UNSET;
return positionDiscontinuityUs; return positionDiscontinuityUs;
...@@ -167,13 +168,13 @@ public class FakeMediaPeriod implements MediaPeriod { ...@@ -167,13 +168,13 @@ public class FakeMediaPeriod implements MediaPeriod {
@Override @Override
public long getBufferedPositionUs() { public long getBufferedPositionUs() {
Assert.assertTrue(prepared); assertThat(prepared).isTrue();
return C.TIME_END_OF_SOURCE; return C.TIME_END_OF_SOURCE;
} }
@Override @Override
public long seekToUs(long positionUs) { public long seekToUs(long positionUs) {
Assert.assertTrue(prepared); assertThat(prepared).isTrue();
return positionUs + seekOffsetUs; return positionUs + seekOffsetUs;
} }
...@@ -184,13 +185,13 @@ public class FakeMediaPeriod implements MediaPeriod { ...@@ -184,13 +185,13 @@ public class FakeMediaPeriod implements MediaPeriod {
@Override @Override
public long getNextLoadPositionUs() { public long getNextLoadPositionUs() {
Assert.assertTrue(prepared); assertThat(prepared).isTrue();
return C.TIME_END_OF_SOURCE; return C.TIME_END_OF_SOURCE;
} }
@Override @Override
public boolean continueLoading(long positionUs) { public boolean continueLoading(long positionUs) {
Assert.assertTrue(prepared); assertThat(prepared).isTrue();
return false; return false;
} }
......
...@@ -15,6 +15,8 @@ ...@@ -15,6 +15,8 @@
*/ */
package com.google.android.exoplayer2.testutil; package com.google.android.exoplayer2.testutil;
import static com.google.common.truth.Truth.assertThat;
import android.os.Handler; import android.os.Handler;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import com.google.android.exoplayer2.ExoPlayer; import com.google.android.exoplayer2.ExoPlayer;
...@@ -28,7 +30,6 @@ import com.google.android.exoplayer2.upstream.Allocator; ...@@ -28,7 +30,6 @@ import com.google.android.exoplayer2.upstream.Allocator;
import com.google.android.exoplayer2.util.Assertions; import com.google.android.exoplayer2.util.Assertions;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import junit.framework.Assert;
/** /**
* Fake {@link MediaSource} that provides a given timeline. Creating the period will return a * Fake {@link MediaSource} that provides a given timeline. Creating the period will return a
...@@ -75,7 +76,7 @@ public class FakeMediaSource implements MediaSource { ...@@ -75,7 +76,7 @@ public class FakeMediaSource implements MediaSource {
@Override @Override
public synchronized void prepareSource( public synchronized void prepareSource(
ExoPlayer player, boolean isTopLevelSource, Listener listener) { ExoPlayer player, boolean isTopLevelSource, Listener listener) {
Assert.assertFalse(preparedSource); assertThat(preparedSource).isFalse();
preparedSource = true; preparedSource = true;
this.listener = listener; this.listener = listener;
sourceInfoRefreshHandler = new Handler(); sourceInfoRefreshHandler = new Handler();
...@@ -86,13 +87,13 @@ public class FakeMediaSource implements MediaSource { ...@@ -86,13 +87,13 @@ public class FakeMediaSource implements MediaSource {
@Override @Override
public void maybeThrowSourceInfoRefreshError() throws IOException { public void maybeThrowSourceInfoRefreshError() throws IOException {
Assert.assertTrue(preparedSource); assertThat(preparedSource).isTrue();
} }
@Override @Override
public MediaPeriod createPeriod(MediaPeriodId id, Allocator allocator) { public MediaPeriod createPeriod(MediaPeriodId id, Allocator allocator) {
Assert.assertTrue(preparedSource); assertThat(preparedSource).isTrue();
Assert.assertFalse(releasedSource); assertThat(releasedSource).isFalse();
Assertions.checkIndex(id.periodIndex, 0, timeline.getPeriodCount()); Assertions.checkIndex(id.periodIndex, 0, timeline.getPeriodCount());
FakeMediaPeriod mediaPeriod = createFakeMediaPeriod(id, trackGroupArray, allocator); FakeMediaPeriod mediaPeriod = createFakeMediaPeriod(id, trackGroupArray, allocator);
activeMediaPeriods.add(mediaPeriod); activeMediaPeriods.add(mediaPeriod);
...@@ -102,18 +103,18 @@ public class FakeMediaSource implements MediaSource { ...@@ -102,18 +103,18 @@ public class FakeMediaSource implements MediaSource {
@Override @Override
public void releasePeriod(MediaPeriod mediaPeriod) { public void releasePeriod(MediaPeriod mediaPeriod) {
Assert.assertTrue(preparedSource); assertThat(preparedSource).isTrue();
Assert.assertFalse(releasedSource); assertThat(releasedSource).isFalse();
FakeMediaPeriod fakeMediaPeriod = (FakeMediaPeriod) mediaPeriod; FakeMediaPeriod fakeMediaPeriod = (FakeMediaPeriod) mediaPeriod;
Assert.assertTrue(activeMediaPeriods.remove(fakeMediaPeriod)); assertThat(activeMediaPeriods.remove(fakeMediaPeriod)).isTrue();
fakeMediaPeriod.release(); fakeMediaPeriod.release();
} }
@Override @Override
public void releaseSource() { public void releaseSource() {
Assert.assertTrue(preparedSource); assertThat(preparedSource).isTrue();
Assert.assertFalse(releasedSource); assertThat(releasedSource).isFalse();
Assert.assertTrue(activeMediaPeriods.isEmpty()); assertThat(activeMediaPeriods.isEmpty()).isTrue();
releasedSource = true; releasedSource = true;
} }
...@@ -127,8 +128,8 @@ public class FakeMediaSource implements MediaSource { ...@@ -127,8 +128,8 @@ public class FakeMediaSource implements MediaSource {
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
Assert.assertFalse(releasedSource); assertThat(releasedSource).isFalse();
Assert.assertTrue(preparedSource); assertThat(preparedSource).isTrue();
timeline = newTimeline; timeline = newTimeline;
manifest = newManifest; manifest = newManifest;
listener.onSourceInfoRefreshed(FakeMediaSource.this, timeline, manifest); listener.onSourceInfoRefreshed(FakeMediaSource.this, timeline, manifest);
...@@ -144,14 +145,14 @@ public class FakeMediaSource implements MediaSource { ...@@ -144,14 +145,14 @@ public class FakeMediaSource implements MediaSource {
* Assert that the source and all periods have been released. * Assert that the source and all periods have been released.
*/ */
public void assertReleased() { public void assertReleased() {
Assert.assertTrue(releasedSource || !preparedSource); assertThat(releasedSource || !preparedSource).isTrue();
} }
/** /**
* Assert that a media period for the given id has been created. * Assert that a media period for the given id has been created.
*/ */
public void assertMediaPeriodCreated(MediaPeriodId mediaPeriodId) { public void assertMediaPeriodCreated(MediaPeriodId mediaPeriodId) {
Assert.assertTrue(createdMediaPeriods.contains(mediaPeriodId)); assertThat(createdMediaPeriods).contains(mediaPeriodId);
} }
protected FakeMediaPeriod createFakeMediaPeriod(MediaPeriodId id, TrackGroupArray trackGroupArray, protected FakeMediaPeriod createFakeMediaPeriod(MediaPeriodId id, TrackGroupArray trackGroupArray,
......
...@@ -15,6 +15,8 @@ ...@@ -15,6 +15,8 @@
*/ */
package com.google.android.exoplayer2.testutil; package com.google.android.exoplayer2.testutil;
import static com.google.common.truth.Truth.assertThat;
import com.google.android.exoplayer2.BaseRenderer; import com.google.android.exoplayer2.BaseRenderer;
import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.ExoPlaybackException; import com.google.android.exoplayer2.ExoPlaybackException;
...@@ -26,7 +28,6 @@ import com.google.android.exoplayer2.util.MimeTypes; ...@@ -26,7 +28,6 @@ import com.google.android.exoplayer2.util.MimeTypes;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import junit.framework.Assert;
/** /**
* Fake {@link Renderer} that supports any format with the matching MIME type. The renderer * Fake {@link Renderer} that supports any format with the matching MIME type. The renderer
...@@ -65,7 +66,7 @@ public class FakeRenderer extends BaseRenderer { ...@@ -65,7 +66,7 @@ public class FakeRenderer extends BaseRenderer {
buffer.data = null; buffer.data = null;
if (result == C.RESULT_FORMAT_READ) { if (result == C.RESULT_FORMAT_READ) {
formatReadCount++; formatReadCount++;
Assert.assertTrue(expectedFormats.contains(formatHolder.format)); assertThat(expectedFormats).contains(formatHolder.format);
} else if (result == C.RESULT_BUFFER_READ) { } else if (result == C.RESULT_BUFFER_READ) {
bufferReadCount++; bufferReadCount++;
if (buffer.isEndOfStream()) { if (buffer.isEndOfStream()) {
......
...@@ -15,7 +15,8 @@ ...@@ -15,7 +15,8 @@
*/ */
package com.google.android.exoplayer2.testutil; package com.google.android.exoplayer2.testutil;
import android.test.MoreAsserts; import static com.google.common.truth.Truth.assertThat;
import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.extractor.ExtractorInput; import com.google.android.exoplayer2.extractor.ExtractorInput;
...@@ -25,7 +26,6 @@ import java.io.EOFException; ...@@ -25,7 +26,6 @@ import java.io.EOFException;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import junit.framework.Assert;
/** /**
* A fake {@link TrackOutput}. * A fake {@link TrackOutput}.
...@@ -98,15 +98,15 @@ public final class FakeTrackOutput implements TrackOutput, Dumper.Dumpable { ...@@ -98,15 +98,15 @@ public final class FakeTrackOutput implements TrackOutput, Dumper.Dumpable {
} }
public void assertSampleCount(int count) { public void assertSampleCount(int count) {
Assert.assertEquals(count, sampleTimesUs.size()); assertThat(sampleTimesUs).hasSize(count);
} }
public void assertSample(int index, byte[] data, long timeUs, int flags, CryptoData cryptoData) { public void assertSample(int index, byte[] data, long timeUs, int flags, CryptoData cryptoData) {
byte[] actualData = getSampleData(index); byte[] actualData = getSampleData(index);
MoreAsserts.assertEquals(data, actualData); assertThat(actualData).isEqualTo(data);
Assert.assertEquals(timeUs, (long) sampleTimesUs.get(index)); assertThat(sampleTimesUs.get(index)).isEqualTo(timeUs);
Assert.assertEquals(flags, (int) sampleFlags.get(index)); assertThat(sampleFlags.get(index)).isEqualTo(flags);
Assert.assertEquals(cryptoData, cryptoDatas.get(index)); assertThat(cryptoDatas.get(index)).isEqualTo(cryptoData);
} }
public byte[] getSampleData(int index) { public byte[] getSampleData(int index) {
...@@ -115,18 +115,18 @@ public final class FakeTrackOutput implements TrackOutput, Dumper.Dumpable { ...@@ -115,18 +115,18 @@ public final class FakeTrackOutput implements TrackOutput, Dumper.Dumpable {
} }
public void assertEquals(FakeTrackOutput expected) { public void assertEquals(FakeTrackOutput expected) {
Assert.assertEquals(expected.format, format); assertThat(format).isEqualTo(expected.format);
Assert.assertEquals(expected.sampleTimesUs.size(), sampleTimesUs.size()); assertThat(sampleTimesUs).hasSize(expected.sampleTimesUs.size());
MoreAsserts.assertEquals(expected.sampleData, sampleData); assertThat(sampleData).isEqualTo(expected.sampleData);
for (int i = 0; i < sampleTimesUs.size(); i++) { for (int i = 0; i < sampleTimesUs.size(); i++) {
Assert.assertEquals(expected.sampleTimesUs.get(i), sampleTimesUs.get(i)); assertThat(sampleTimesUs.get(i)).isEqualTo(expected.sampleTimesUs.get(i));
Assert.assertEquals(expected.sampleFlags.get(i), sampleFlags.get(i)); assertThat(sampleFlags.get(i)).isEqualTo(expected.sampleFlags.get(i));
Assert.assertEquals(expected.sampleStartOffsets.get(i), sampleStartOffsets.get(i)); assertThat(sampleStartOffsets.get(i)).isEqualTo(expected.sampleStartOffsets.get(i));
Assert.assertEquals(expected.sampleEndOffsets.get(i), sampleEndOffsets.get(i)); assertThat(sampleEndOffsets.get(i)).isEqualTo(expected.sampleEndOffsets.get(i));
if (expected.cryptoDatas.get(i) == null) { if (expected.cryptoDatas.get(i) == null) {
Assert.assertNull(cryptoDatas.get(i)); assertThat(cryptoDatas.get(i)).isNull();
} else { } else {
Assert.assertEquals(expected.cryptoDatas.get(i), cryptoDatas.get(i)); assertThat(cryptoDatas.get(i)).isEqualTo(expected.cryptoDatas.get(i));
} }
} }
} }
......
...@@ -15,13 +15,14 @@ ...@@ -15,13 +15,14 @@
*/ */
package com.google.android.exoplayer2.testutil; package com.google.android.exoplayer2.testutil;
import static com.google.common.truth.Truth.assertThat;
import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.source.TrackGroup; import com.google.android.exoplayer2.source.TrackGroup;
import com.google.android.exoplayer2.source.chunk.MediaChunk; import com.google.android.exoplayer2.source.chunk.MediaChunk;
import com.google.android.exoplayer2.trackselection.TrackSelection; import com.google.android.exoplayer2.trackselection.TrackSelection;
import java.util.List; import java.util.List;
import junit.framework.Assert;
/** /**
* A fake {@link TrackSelection} that only returns 1 fixed track, and allows querying the number * A fake {@link TrackSelection} that only returns 1 fixed track, and allows querying the number
...@@ -42,7 +43,7 @@ public final class FakeTrackSelection implements TrackSelection { ...@@ -42,7 +43,7 @@ public final class FakeTrackSelection implements TrackSelection {
@Override @Override
public void enable() { public void enable() {
// assert that track selection is in disabled state before this call. // assert that track selection is in disabled state before this call.
Assert.assertFalse(isEnabled); assertThat(isEnabled).isFalse();
enableCount++; enableCount++;
isEnabled = true; isEnabled = true;
} }
...@@ -50,7 +51,7 @@ public final class FakeTrackSelection implements TrackSelection { ...@@ -50,7 +51,7 @@ public final class FakeTrackSelection implements TrackSelection {
@Override @Override
public void disable() { public void disable() {
// assert that track selection is in enabled state before this call. // assert that track selection is in enabled state before this call.
Assert.assertTrue(isEnabled); assertThat(isEnabled).isTrue();
releaseCount++; releaseCount++;
isEnabled = false; isEnabled = false;
} }
...@@ -77,7 +78,7 @@ public final class FakeTrackSelection implements TrackSelection { ...@@ -77,7 +78,7 @@ public final class FakeTrackSelection implements TrackSelection {
@Override @Override
public int indexOf(Format format) { public int indexOf(Format format) {
Assert.assertTrue(isEnabled); assertThat(isEnabled).isTrue();
return 0; return 0;
} }
...@@ -119,18 +120,18 @@ public final class FakeTrackSelection implements TrackSelection { ...@@ -119,18 +120,18 @@ public final class FakeTrackSelection implements TrackSelection {
@Override @Override
public void updateSelectedTrack(long playbackPositionUs, long bufferedDurationUs, public void updateSelectedTrack(long playbackPositionUs, long bufferedDurationUs,
long availableDurationUs) { long availableDurationUs) {
Assert.assertTrue(isEnabled); assertThat(isEnabled).isTrue();
} }
@Override @Override
public int evaluateQueueSize(long playbackPositionUs, List<? extends MediaChunk> queue) { public int evaluateQueueSize(long playbackPositionUs, List<? extends MediaChunk> queue) {
Assert.assertTrue(isEnabled); assertThat(isEnabled).isTrue();
return 0; return 0;
} }
@Override @Override
public boolean blacklist(int index, long blacklistDurationMs) { public boolean blacklist(int index, long blacklistDurationMs) {
Assert.assertTrue(isEnabled); assertThat(isEnabled).isTrue();
return false; return false;
} }
......
...@@ -15,7 +15,7 @@ ...@@ -15,7 +15,7 @@
*/ */
package com.google.android.exoplayer2.testutil; package com.google.android.exoplayer2.testutil;
import static junit.framework.Assert.fail; import static org.junit.Assert.fail;
import android.app.Activity; import android.app.Activity;
import android.content.Context; import android.content.Context;
......
...@@ -15,9 +15,8 @@ ...@@ -15,9 +15,8 @@
*/ */
package com.google.android.exoplayer2.testutil; package com.google.android.exoplayer2.testutil;
import static junit.framework.Assert.assertNotNull; import static com.google.common.truth.Truth.assertThat;
import static junit.framework.Assert.assertTrue; import static org.junit.Assert.fail;
import static junit.framework.Assert.fail;
import android.os.ConditionVariable; import android.os.ConditionVariable;
import android.os.Handler; import android.os.Handler;
...@@ -90,7 +89,7 @@ public class MediaSourceTestRunner { ...@@ -90,7 +89,7 @@ public class MediaSourceTestRunner {
} }
} }
}); });
assertTrue(finishedCondition.block(TIMEOUT_MS)); assertThat(finishedCondition.block(TIMEOUT_MS)).isTrue();
if (throwable[0] != null) { if (throwable[0] != null) {
Util.sneakyThrow(throwable[0]); Util.sneakyThrow(throwable[0]);
} }
...@@ -138,7 +137,7 @@ public class MediaSourceTestRunner { ...@@ -138,7 +137,7 @@ public class MediaSourceTestRunner {
holder[0] = mediaSource.createPeriod(periodId, allocator); holder[0] = mediaSource.createPeriod(periodId, allocator);
} }
}); });
assertNotNull(holder[0]); assertThat(holder[0]).isNotNull();
return holder[0]; return holder[0];
} }
...@@ -201,7 +200,7 @@ public class MediaSourceTestRunner { ...@@ -201,7 +200,7 @@ public class MediaSourceTestRunner {
* runner was created if neither method has been called). * runner was created if neither method has been called).
*/ */
public void assertNoTimelineChange() { public void assertNoTimelineChange() {
assertTrue(timelines.isEmpty()); assertThat(timelines.isEmpty()).isTrue();
} }
/** /**
...@@ -224,7 +223,7 @@ public class MediaSourceTestRunner { ...@@ -224,7 +223,7 @@ public class MediaSourceTestRunner {
public Timeline assertTimelineChangeBlocking() { public Timeline assertTimelineChangeBlocking() {
try { try {
timeline = timelines.poll(TIMEOUT_MS, TimeUnit.MILLISECONDS); timeline = timelines.poll(TIMEOUT_MS, TimeUnit.MILLISECONDS);
assertNotNull(timeline); // Null indicates the poll timed out. assertThat(timeline).isNotNull(); // Null indicates the poll timed out.
assertNoTimelineChange(); assertNoTimelineChange();
return timeline; return timeline;
} catch (InterruptedException e) { } catch (InterruptedException e) {
...@@ -254,12 +253,12 @@ public class MediaSourceTestRunner { ...@@ -254,12 +253,12 @@ public class MediaSourceTestRunner {
private void assertPrepareAndReleasePeriod(MediaPeriodId mediaPeriodId) { private void assertPrepareAndReleasePeriod(MediaPeriodId mediaPeriodId) {
MediaPeriod mediaPeriod = createPeriod(mediaPeriodId); MediaPeriod mediaPeriod = createPeriod(mediaPeriodId);
ConditionVariable preparedCondition = preparePeriod(mediaPeriod, 0); ConditionVariable preparedCondition = preparePeriod(mediaPeriod, 0);
assertTrue(preparedCondition.block(TIMEOUT_MS)); assertThat(preparedCondition.block(TIMEOUT_MS)).isTrue();
// MediaSource is supposed to support multiple calls to createPeriod with the same id without an // MediaSource is supposed to support multiple calls to createPeriod with the same id without an
// intervening call to releasePeriod. // intervening call to releasePeriod.
MediaPeriod secondMediaPeriod = createPeriod(mediaPeriodId); MediaPeriod secondMediaPeriod = createPeriod(mediaPeriodId);
ConditionVariable secondPreparedCondition = preparePeriod(secondMediaPeriod, 0); ConditionVariable secondPreparedCondition = preparePeriod(secondMediaPeriod, 0);
assertTrue(secondPreparedCondition.block(TIMEOUT_MS)); assertThat(secondPreparedCondition.block(TIMEOUT_MS)).isTrue();
// Release the periods. // Release the periods.
releasePeriod(mediaPeriod); releasePeriod(mediaPeriod);
releasePeriod(secondMediaPeriod); releasePeriod(secondMediaPeriod);
......
...@@ -15,9 +15,11 @@ ...@@ -15,9 +15,11 @@
*/ */
package com.google.android.exoplayer2.testutil; package com.google.android.exoplayer2.testutil;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import android.app.Instrumentation; import android.app.Instrumentation;
import android.content.Context; import android.content.Context;
import android.test.MoreAsserts;
import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.extractor.Extractor; import com.google.android.exoplayer2.extractor.Extractor;
import com.google.android.exoplayer2.testutil.FakeExtractorInput.SimulatedIOException; import com.google.android.exoplayer2.testutil.FakeExtractorInput.SimulatedIOException;
...@@ -29,7 +31,6 @@ import java.io.IOException; ...@@ -29,7 +31,6 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.Arrays; import java.util.Arrays;
import java.util.Random; import java.util.Random;
import junit.framework.Assert;
/** /**
* Utility methods for tests. * Utility methods for tests.
...@@ -71,7 +72,7 @@ public class TestUtil { ...@@ -71,7 +72,7 @@ public class TestUtil {
while (position < length) { while (position < length) {
int bytesRead = dataSource.read(data, position, data.length - position); int bytesRead = dataSource.read(data, position, data.length - position);
if (bytesRead == C.RESULT_END_OF_INPUT) { if (bytesRead == C.RESULT_END_OF_INPUT) {
Assert.fail("Not enough data could be read: " + position + " < " + length); fail("Not enough data could be read: " + position + " < " + length);
} else { } else {
position += bytesRead; position += bytesRead;
} }
...@@ -164,13 +165,14 @@ public class TestUtil { ...@@ -164,13 +165,14 @@ public class TestUtil {
* data length. If false then it's asserted that {@link C#LENGTH_UNSET} is returned. * data length. If false then it's asserted that {@link C#LENGTH_UNSET} is returned.
* @throws IOException If an error occurs reading fom the {@link DataSource}. * @throws IOException If an error occurs reading fom the {@link DataSource}.
*/ */
public static void assertDataSourceContent(DataSource dataSource, DataSpec dataSpec, public static void assertDataSourceContent(
byte[] expectedData, boolean expectKnownLength) throws IOException { DataSource dataSource, DataSpec dataSpec, byte[] expectedData, boolean expectKnownLength)
throws IOException {
try { try {
long length = dataSource.open(dataSpec); long length = dataSource.open(dataSpec);
Assert.assertEquals(expectKnownLength ? expectedData.length : C.LENGTH_UNSET, length); assertThat(length).isEqualTo(expectKnownLength ? expectedData.length : C.LENGTH_UNSET);
byte[] readData = TestUtil.readToEnd(dataSource); byte[] readData = readToEnd(dataSource);
MoreAsserts.assertEquals(expectedData, readData); assertThat(readData).isEqualTo(expectedData);
} finally { } finally {
dataSource.close(); dataSource.close();
} }
......
...@@ -15,7 +15,8 @@ ...@@ -15,7 +15,8 @@
*/ */
package com.google.android.exoplayer2.testutil; package com.google.android.exoplayer2.testutil;
import static junit.framework.Assert.assertEquals; import static com.google.common.truth.Truth.assertThat;
import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Player; import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.Timeline; import com.google.android.exoplayer2.Timeline;
...@@ -27,6 +28,10 @@ import com.google.android.exoplayer2.Timeline.Window; ...@@ -27,6 +28,10 @@ import com.google.android.exoplayer2.Timeline.Window;
*/ */
public final class TimelineAsserts { public final class TimelineAsserts {
private static final int[] REPEAT_MODES = {
Player.REPEAT_MODE_OFF, Player.REPEAT_MODE_ONE, Player.REPEAT_MODE_ALL
};
private TimelineAsserts() {} private TimelineAsserts() {}
/** /**
...@@ -36,8 +41,8 @@ public final class TimelineAsserts { ...@@ -36,8 +41,8 @@ public final class TimelineAsserts {
assertWindowIds(timeline); assertWindowIds(timeline);
assertPeriodCounts(timeline); assertPeriodCounts(timeline);
for (boolean shuffled : new boolean[] {false, true}) { for (boolean shuffled : new boolean[] {false, true}) {
assertEquals(C.INDEX_UNSET, timeline.getFirstWindowIndex(shuffled)); assertThat(timeline.getFirstWindowIndex(shuffled)).isEqualTo(C.INDEX_UNSET);
assertEquals(C.INDEX_UNSET, timeline.getLastWindowIndex(shuffled)); assertThat(timeline.getLastWindowIndex(shuffled)).isEqualTo(C.INDEX_UNSET);
} }
} }
...@@ -49,11 +54,11 @@ public final class TimelineAsserts { ...@@ -49,11 +54,11 @@ public final class TimelineAsserts {
*/ */
public static void assertWindowIds(Timeline timeline, Object... expectedWindowIds) { public static void assertWindowIds(Timeline timeline, Object... expectedWindowIds) {
Window window = new Window(); Window window = new Window();
assertEquals(expectedWindowIds.length, timeline.getWindowCount()); assertThat(timeline.getWindowCount()).isEqualTo(expectedWindowIds.length);
for (int i = 0; i < timeline.getWindowCount(); i++) { for (int i = 0; i < timeline.getWindowCount(); i++) {
timeline.getWindow(i, window, true); timeline.getWindow(i, window, true);
if (expectedWindowIds[i] != null) { if (expectedWindowIds[i] != null) {
assertEquals(expectedWindowIds[i], window.id); assertThat(window.id).isEqualTo(expectedWindowIds[i]);
} }
} }
} }
...@@ -65,7 +70,7 @@ public final class TimelineAsserts { ...@@ -65,7 +70,7 @@ public final class TimelineAsserts {
Window window = new Window(); Window window = new Window();
for (int i = 0; i < timeline.getWindowCount(); i++) { for (int i = 0; i < timeline.getWindowCount(); i++) {
timeline.getWindow(i, window, true); timeline.getWindow(i, window, true);
assertEquals(windowIsDynamic[i], window.isDynamic); assertThat(window.isDynamic).isEqualTo(windowIsDynamic[i]);
} }
} }
...@@ -77,8 +82,8 @@ public final class TimelineAsserts { ...@@ -77,8 +82,8 @@ public final class TimelineAsserts {
@Player.RepeatMode int repeatMode, boolean shuffleModeEnabled, @Player.RepeatMode int repeatMode, boolean shuffleModeEnabled,
int... expectedPreviousWindowIndices) { int... expectedPreviousWindowIndices) {
for (int i = 0; i < timeline.getWindowCount(); i++) { for (int i = 0; i < timeline.getWindowCount(); i++) {
assertEquals(expectedPreviousWindowIndices[i], assertThat(timeline.getPreviousWindowIndex(i, repeatMode, shuffleModeEnabled))
timeline.getPreviousWindowIndex(i, repeatMode, shuffleModeEnabled)); .isEqualTo(expectedPreviousWindowIndices[i]);
} }
} }
...@@ -89,8 +94,8 @@ public final class TimelineAsserts { ...@@ -89,8 +94,8 @@ public final class TimelineAsserts {
public static void assertNextWindowIndices(Timeline timeline, @Player.RepeatMode int repeatMode, public static void assertNextWindowIndices(Timeline timeline, @Player.RepeatMode int repeatMode,
boolean shuffleModeEnabled, int... expectedNextWindowIndices) { boolean shuffleModeEnabled, int... expectedNextWindowIndices) {
for (int i = 0; i < timeline.getWindowCount(); i++) { for (int i = 0; i < timeline.getWindowCount(); i++) {
assertEquals(expectedNextWindowIndices[i], assertThat(timeline.getNextWindowIndex(i, repeatMode, shuffleModeEnabled))
timeline.getNextWindowIndex(i, repeatMode, shuffleModeEnabled)); .isEqualTo(expectedNextWindowIndices[i]);
} }
} }
...@@ -106,14 +111,14 @@ public final class TimelineAsserts { ...@@ -106,14 +111,14 @@ public final class TimelineAsserts {
for (int i = 0; i < windowCount; i++) { for (int i = 0; i < windowCount; i++) {
accumulatedPeriodCounts[i + 1] = accumulatedPeriodCounts[i] + expectedPeriodCounts[i]; accumulatedPeriodCounts[i + 1] = accumulatedPeriodCounts[i] + expectedPeriodCounts[i];
} }
assertEquals(accumulatedPeriodCounts[accumulatedPeriodCounts.length - 1], assertThat(timeline.getPeriodCount())
timeline.getPeriodCount()); .isEqualTo(accumulatedPeriodCounts[accumulatedPeriodCounts.length - 1]);
Window window = new Window(); Window window = new Window();
Period period = new Period(); Period period = new Period();
for (int i = 0; i < windowCount; i++) { for (int i = 0; i < windowCount; i++) {
timeline.getWindow(i, window, true); timeline.getWindow(i, window, true);
assertEquals(accumulatedPeriodCounts[i], window.firstPeriodIndex); assertThat(window.firstPeriodIndex).isEqualTo(accumulatedPeriodCounts[i]);
assertEquals(accumulatedPeriodCounts[i + 1] - 1, window.lastPeriodIndex); assertThat(window.lastPeriodIndex).isEqualTo(accumulatedPeriodCounts[i + 1] - 1);
} }
int expectedWindowIndex = 0; int expectedWindowIndex = 0;
for (int i = 0; i < timeline.getPeriodCount(); i++) { for (int i = 0; i < timeline.getPeriodCount(); i++) {
...@@ -121,18 +126,18 @@ public final class TimelineAsserts { ...@@ -121,18 +126,18 @@ public final class TimelineAsserts {
while (i >= accumulatedPeriodCounts[expectedWindowIndex + 1]) { while (i >= accumulatedPeriodCounts[expectedWindowIndex + 1]) {
expectedWindowIndex++; expectedWindowIndex++;
} }
assertEquals(expectedWindowIndex, period.windowIndex); assertThat(period.windowIndex).isEqualTo(expectedWindowIndex);
assertEquals(i, timeline.getIndexOfPeriod(period.uid)); assertThat(timeline.getIndexOfPeriod(period.uid)).isEqualTo(i);
for (@Player.RepeatMode int repeatMode for (int repeatMode : REPEAT_MODES) {
: new int[] {Player.REPEAT_MODE_OFF, Player.REPEAT_MODE_ONE, Player.REPEAT_MODE_ALL}) {
if (i < accumulatedPeriodCounts[expectedWindowIndex + 1] - 1) { if (i < accumulatedPeriodCounts[expectedWindowIndex + 1] - 1) {
assertEquals(i + 1, timeline.getNextPeriodIndex(i, period, window, repeatMode, false)); assertThat(timeline.getNextPeriodIndex(i, period, window, repeatMode, false))
.isEqualTo(i + 1);
} else { } else {
int nextWindow = timeline.getNextWindowIndex(expectedWindowIndex, repeatMode, false); int nextWindow = timeline.getNextWindowIndex(expectedWindowIndex, repeatMode, false);
int nextPeriod = nextWindow == C.INDEX_UNSET ? C.INDEX_UNSET int nextPeriod = nextWindow == C.INDEX_UNSET ? C.INDEX_UNSET
: accumulatedPeriodCounts[nextWindow]; : accumulatedPeriodCounts[nextWindow];
assertEquals(nextPeriod, timeline.getNextPeriodIndex(i, period, window, repeatMode, assertThat(timeline.getNextPeriodIndex(i, period, window, repeatMode, false))
false)); .isEqualTo(nextPeriod);
} }
} }
} }
...@@ -145,7 +150,7 @@ public final class TimelineAsserts { ...@@ -145,7 +150,7 @@ public final class TimelineAsserts {
Period period = new Period(); Period period = new Period();
for (int i = 0; i < timeline.getPeriodCount(); i++) { for (int i = 0; i < timeline.getPeriodCount(); i++) {
timeline.getPeriod(i, period); timeline.getPeriod(i, period);
assertEquals(expectedAdGroupCounts[i], period.getAdGroupCount()); assertThat(period.getAdGroupCount()).isEqualTo(expectedAdGroupCounts[i]);
} }
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment