From 04b662e79166a78b94149b8174594497da34f6c0 Mon Sep 17 00:00:00 2001 From: Dominik Stadler Date: Sun, 15 Dec 2024 15:48:04 +0100 Subject: [PATCH] Migrate to JUnit 5 --- build.gradle | 5 +- .../CountingSeekableRingBufferImpl.java | 28 +-- .../audio/buffer/RangeDownloadingBuffer.java | 20 +- .../audio/download/RangeDownloadHTTP.java | 4 +- .../dstadler/audio/example/SimplePlayer.java | 4 +- ...tractBlockingSeekableRingBufferTester.java | 55 ++--- .../BlockingSeekableRingBufferTest.java | 25 +- .../buffer/BufferPersistenceDTOTest.java | 8 +- .../audio/buffer/BufferPersistenceTest.java | 10 +- .../org/dstadler/audio/buffer/ChunkTest.java | 6 +- .../CountingSeekableRingBufferImplTest.java | 17 +- ...skBasedBlockingSeekableRingBufferTest.java | 100 ++++---- .../dstadler/audio/buffer/MockHTTPTest.java | 35 ++- .../buffer/RangeDownloadingBufferTest.java | 218 ++++++++++-------- .../audio/buffer/SynchronizingTest.java | 8 +- .../audio/download/RangeDownloadFileTest.java | 33 ++- .../audio/download/RangeDownloadHTTPTest.java | 51 ++-- .../org/dstadler/audio/fm4/FM4CacheTest.java | 65 +++--- .../org/dstadler/audio/fm4/FM4StreamTest.java | 35 ++- .../java/org/dstadler/audio/fm4/FM4Test.java | 31 ++- .../audio/player/AudioSPIPlayerTest.java | 20 +- .../player/BufferBasedTempoStrategyTest.java | 10 +- .../player/ConstantTempoStrategyTest.java | 4 +- .../audio/player/JLayerPlayerTest.java | 12 +- .../audio/player/TarsosDSPPlayerTest.java | 22 +- .../audio/player/TempoStrategyTest.java | 82 ++++--- .../org/dstadler/audio/stream/StreamTest.java | 29 +-- .../util/ClearablePipedInputStreamTest.java | 15 +- .../org/dstadler/audio/util/DataPipeTest.java | 11 +- .../util/RuntimeInterruptedExceptionTest.java | 4 +- 30 files changed, 461 insertions(+), 506 deletions(-) diff --git a/build.gradle b/build.gradle index cfe07dc..97309a5 100644 --- a/build.gradle +++ b/build.gradle @@ -72,7 +72,9 @@ dependencies { // don't include it in the jar-file runtimeOnly files('src/runtime/resources') - testImplementation 'org.junit.vintage:junit-vintage-engine:5.11.3' + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.11.3' + testImplementation 'org.junit.jupiter:junit-jupiter-params:5.11.3' + testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.11.3' testImplementation 'org.dstadler:commons-test:1.0.0.21' testImplementation 'org.apache.commons:commons-rng-simple:1.6' } @@ -93,6 +95,7 @@ test { // avoid failures because Gradle provides it's own version of JNA in the system properties systemProperties['jna.boot.library.path'] = null + useJUnitPlatform() } jacoco { diff --git a/src/main/java/org/dstadler/audio/buffer/CountingSeekableRingBufferImpl.java b/src/main/java/org/dstadler/audio/buffer/CountingSeekableRingBufferImpl.java index c677b1d..bb18002 100644 --- a/src/main/java/org/dstadler/audio/buffer/CountingSeekableRingBufferImpl.java +++ b/src/main/java/org/dstadler/audio/buffer/CountingSeekableRingBufferImpl.java @@ -249,19 +249,19 @@ private double getPerSecond(AtomicLong bytesWrittenOverall) { public String toString() { //long time = System.currentTimeMillis() - start; /*", time: " + time + "/" + (double)time / 1000 +*/ - return String.format("Start: %d, " + - "CPS: %.2f, " + - "CPSRead: %.2f, " + - "CPSWritten: %.2f, " + - "Written: %d bytes/%d chunks, %.2f bytes/s, %.2f chunks/s, " + - "Read: %d bytes/%d chunks, %.2f bytes/s, %.2f chunks/s, " + - "%s", - start, - getChunksPerSecond(), - getChunksReadPerSecond(), - getChunksWrittenPerSecond(), - bytesWrittenOverall.get(), chunksWrittenOverall.get(), getPerSecond(bytesWrittenOverall), getPerSecond(chunksWrittenOverall), - bytesReadOverall.get(), chunksReadOverall.get(), getPerSecond(bytesReadOverall), getPerSecond(chunksReadOverall), - delegate.toString()); + return ("Start: %d, " + + "CPS: %.2f, " + + "CPSRead: %.2f, " + + "CPSWritten: %.2f, " + + "Written: %d bytes/%d chunks, %.2f bytes/s, %.2f chunks/s, " + + "Read: %d bytes/%d chunks, %.2f bytes/s, %.2f chunks/s, " + + "%s").formatted( + start, + getChunksPerSecond(), + getChunksReadPerSecond(), + getChunksWrittenPerSecond(), + bytesWrittenOverall.get(), chunksWrittenOverall.get(), getPerSecond(bytesWrittenOverall), getPerSecond(chunksWrittenOverall), + bytesReadOverall.get(), chunksReadOverall.get(), getPerSecond(bytesReadOverall), getPerSecond(chunksReadOverall), + delegate.toString()); } } diff --git a/src/main/java/org/dstadler/audio/buffer/RangeDownloadingBuffer.java b/src/main/java/org/dstadler/audio/buffer/RangeDownloadingBuffer.java index 954a476..2a96ece 100644 --- a/src/main/java/org/dstadler/audio/buffer/RangeDownloadingBuffer.java +++ b/src/main/java/org/dstadler/audio/buffer/RangeDownloadingBuffer.java @@ -115,8 +115,8 @@ public int fillupBuffer(int min, int max) throws IOException { throw e; } - log.warning(String.format("Retry %,d: Failed to download, buffer: %,d bytes, chunkSize: %,d, bufferedChunks: %,d, " + - "min: %,d, max: %,d from position %,d: length: %,d: %s", + log.warning(("Retry %,d: Failed to download, buffer: %,d bytes, chunkSize: %,d, bufferedChunks: %,d, " + + "min: %,d, max: %,d from position %,d: length: %,d: %s").formatted( retries, buffer.size(), chunkSize, bufferedChunks, min, max, nextDownloadPos, download.getLength(), e)); @@ -173,7 +173,7 @@ private int downloadChunksSync(int min, int max) throws IOException { toDownload, bufferedChunks, buffer.size()); if (log.isLoggable(Level.FINE)) { - log.fine(String.format("Downloading %,d chunks at download-position %,d from %s", + log.fine("Downloading %,d chunks at download-position %,d from %s".formatted( toDownload, nextDownloadPos, download)); } @@ -232,10 +232,10 @@ public Chunk next() { // empty() indicates that we cannot fetch more data any more if(buffer.empty() && !empty()) { try { - log.info(String.format("Filling buffer for next() with download-position at %,d, length %,d, buffer: %s", + log.info("Filling buffer for next() with download-position at %,d, length %,d, buffer: %s".formatted( nextDownloadPos, download.getLength(), buffer)); int chunks = fillupBuffer(-1, 10); - log.info(String.format("Downloaded %,d chunks, now at download-position %,d, length %,d, buffer: %s", + log.info("Downloaded %,d chunks, now at download-position %,d, length %,d, buffer: %s".formatted( chunks, nextDownloadPos, download.getLength(), buffer)); } catch (IOException e) { throw new IllegalStateException("Failed to fill-up buffer", e); @@ -256,15 +256,15 @@ public Chunk peek() { // empty() indicates that we cannot fetch more data any more if(buffer.empty() && !empty()) { try { - log.info(String.format("Filling buffer for peek() with download-position at %,d, length %,d, buffer: %s", + log.info("Filling buffer for peek() with download-position at %,d, length %,d, buffer: %s".formatted( nextDownloadPos, download.getLength(), buffer)); int chunks = fillupBuffer(-1, 10); - log.info(String.format("Downloaded %,d chunks, now at download-position %,d, length %,d, buffer: %s", + log.info("Downloaded %,d chunks, now at download-position %,d, length %,d, buffer: %s".formatted( chunks, nextDownloadPos, download.getLength(), buffer)); } catch (IOException e) { log.log(Level.WARNING, - String.format("Failed to fill-up buffer for peek, now at download-position %,d, length %,d, buffer: %s", - nextDownloadPos, download.getLength(), buffer), e); + "Failed to fill-up buffer for peek, now at download-position %,d, length %,d, buffer: %s".formatted( + nextDownloadPos, download.getLength(), buffer), e); return null; } } @@ -408,7 +408,7 @@ public synchronized BufferPersistenceDTO toPersistence(Stream stream, boolean pl long startPosition = nextDownloadPos - (long) buffer.size() * chunkSize; if(startPosition < 0) { - log.warning(String.format("Found invalid startPosition: %,d with next download-position at %,d and buffer-size of %,d, resetting to 0", + log.warning("Found invalid startPosition: %,d with next download-position at %,d and buffer-size of %,d, resetting to 0".formatted( startPosition, nextDownloadPos, buffer.size() * chunkSize)); startPosition = 0; } diff --git a/src/main/java/org/dstadler/audio/download/RangeDownloadHTTP.java b/src/main/java/org/dstadler/audio/download/RangeDownloadHTTP.java index c889baa..aa8a02d 100644 --- a/src/main/java/org/dstadler/audio/download/RangeDownloadHTTP.java +++ b/src/main/java/org/dstadler/audio/download/RangeDownloadHTTP.java @@ -89,7 +89,7 @@ public RangeDownloadHTTP(String url, String user, String pwd) throws IOException httpClient.getHttpClient().getConnectionManager().closeIdleConnections(0, TimeUnit.SECONDS); } - log.info(String.format("Prepared download of %s, length: %,d", url, length)); + log.info("Prepared download of %s, length: %,d".formatted(url, length)); } @Override @@ -105,7 +105,7 @@ public byte[] readRange(long start, int size) throws IOException { length, start, size); if(start + size > length) { - log.info(String.format("Reducing number of bytes to read for %s at position %,d from %,d bytes to %,d bytes because of length of stream %,d", + log.info("Reducing number of bytes to read for %s at position %,d from %,d bytes to %,d bytes because of length of stream %,d".formatted( url, start, size, length - start, length)); size = (int)(length - start); } diff --git a/src/main/java/org/dstadler/audio/example/SimplePlayer.java b/src/main/java/org/dstadler/audio/example/SimplePlayer.java index 22ea134..285ce6b 100644 --- a/src/main/java/org/dstadler/audio/example/SimplePlayer.java +++ b/src/main/java/org/dstadler/audio/example/SimplePlayer.java @@ -9,7 +9,7 @@ import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; -import java.nio.file.Paths; +import java.nio.file.Path; import java.util.logging.Level; import java.util.logging.Logger; @@ -40,7 +40,7 @@ public static void main(String[] args) throws Exception { private static void run(String file) { log.info("Playing file " + file); - try (final InputStream input = new BufferedInputStream(Files.newInputStream(Paths.get(file)), CHUNK_SIZE)) { + try (final InputStream input = new BufferedInputStream(Files.newInputStream(Path.of(file)), CHUNK_SIZE)) { AudioPlayer player = createPlayer(input); //player.setOptions(""); diff --git a/src/test/java/org/dstadler/audio/buffer/AbstractBlockingSeekableRingBufferTester.java b/src/test/java/org/dstadler/audio/buffer/AbstractBlockingSeekableRingBufferTester.java index 1685fb5..fba3a01 100644 --- a/src/test/java/org/dstadler/audio/buffer/AbstractBlockingSeekableRingBufferTester.java +++ b/src/test/java/org/dstadler/audio/buffer/AbstractBlockingSeekableRingBufferTester.java @@ -4,15 +4,10 @@ import org.dstadler.commons.testing.MemoryLeakVerifier; import org.dstadler.commons.testing.TestHelpers; import org.dstadler.commons.testing.ThreadTestHelper; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public abstract class AbstractBlockingSeekableRingBufferTester { private static final Chunk CHUNK_1 = new Chunk(new byte[] { 1, 2, 3 }, "", 0); @@ -26,7 +21,7 @@ public abstract class AbstractBlockingSeekableRingBufferTester { abstract SeekableRingBuffer getBlockingSeekableRingBuffer(); - @After + @AfterEach public void tearDown() { verifier.assertGarbageCollected(); } @@ -212,20 +207,16 @@ public void testSizes() { public void addAndGetMany() { for(byte i = 0;i < 20;i++) { buffer.add(new Chunk(new byte[] { i }, "", 0)); - assertEquals("Failed for i: " + i, - Math.min(i+1, 9), buffer.size()); - assertEquals("Failed for i: " + i, - Math.min(i+1, 9), buffer.fill()); + assertEquals(Math.min(i+1, 9), buffer.size(), "Failed for i: " + i); + assertEquals(Math.min(i+1, 9), buffer.fill(), "Failed for i: " + i); } assertEquals(9, buffer.size()); assertEquals(9, buffer.fill()); for(byte i = 11;i < 20;i++) { - assertEquals("Failed for i: " + i, - new Chunk(new byte[] { i }, "", 0), buffer.next()); - assertEquals("Failed for i: " + i, - 9, buffer.fill()); + assertEquals(new Chunk(new byte[] { i }, "", 0), buffer.next(), "Failed for i: " + i); + assertEquals(9, buffer.fill(), "Failed for i: " + i); } assertEquals(0, buffer.size()); @@ -279,13 +270,13 @@ protected ThreadTestHelper createThreadTestHelper() { @Test public void testSeekInEmptyBuffer() { - assertEquals("Cannot seek 0 buffer", 0, buffer.seek(0)); - assertEquals("Cannot seek forward in empty buffer", 0, buffer.seek(1)); + assertEquals(0, buffer.seek(0), "Cannot seek 0 buffer"); + assertEquals(0, buffer.seek(1), "Cannot seek forward in empty buffer"); assertEquals(0, buffer.size()); - assertEquals("Can seek backwards", -1, buffer.seek(-1)); + assertEquals(-1, buffer.seek(-1), "Can seek backwards"); assertEquals(1, buffer.size()); - assertEquals("Can seek forward now", 1, buffer.seek(1)); + assertEquals(1, buffer.seek(1), "Can seek forward now"); assertEquals(0, buffer.size()); } @@ -294,19 +285,19 @@ public void testSeekInFilledBuffer() { buffer.add(CHUNK_1); buffer.add(CHUNK_2); - assertEquals("Cannot seek 0 buffer even when not empty", 0, buffer.seek(0)); + assertEquals(0, buffer.seek(0), "Cannot seek 0 buffer even when not empty"); assertEquals(CHUNK_1, buffer.peek()); assertEquals(2, buffer.size()); - assertEquals("Can seek forward in filled buffer", 1, buffer.seek(1)); + assertEquals(1, buffer.seek(1), "Can seek forward in filled buffer"); assertEquals(CHUNK_2, buffer.peek()); assertEquals(1, buffer.size()); - assertEquals("Can seek backwards in filled buffer", -1, buffer.seek(-1)); + assertEquals(-1, buffer.seek(-1), "Can seek backwards in filled buffer"); assertEquals(CHUNK_1, buffer.peek()); assertEquals(2, buffer.size()); - assertEquals("Can seek forward again", 1, buffer.seek(1)); + assertEquals(1, buffer.seek(1), "Can seek forward again"); assertEquals(CHUNK_2, buffer.peek()); assertEquals(1, buffer.size()); assertEquals(2, buffer.fill()); @@ -317,20 +308,20 @@ public void testSeekInFullBuffer() { for(byte i = 0;i < 15;i++) { buffer.add(new Chunk(new byte[] { i }, "", 0)); } - assertTrue("buffer should be full now", buffer.full()); + assertTrue(buffer.full(), "buffer should be full now"); assertFalse(buffer.empty()); assertArrayEquals(new byte[] { 6 }, buffer.peek().getData()); assertEquals(new Chunk(new byte[] { 6 }, "", 0), buffer.peek()); assertEquals(9, buffer.size()); assertEquals(9, buffer.fill()); - assertEquals("Cannot seek backwards in full buffer", 0, buffer.seek(-1)); + assertEquals(0, buffer.seek(-1), "Cannot seek backwards in full buffer"); assertArrayEquals(new byte[] { 6 }, buffer.peek().getData()); assertEquals(new Chunk(new byte[] { 6 }, "", 0), buffer.peek()); assertEquals(9, buffer.size()); assertEquals(9, buffer.fill()); - assertEquals("Can seek forward in full buffer, making it non-full", 1, buffer.seek(1)); + assertEquals(1, buffer.seek(1), "Can seek forward in full buffer, making it non-full"); assertArrayEquals(new byte[] { 7 }, buffer.peek().getData()); assertEquals(new Chunk(new byte[] { 7 }, "", 0), buffer.peek()); assertFalse(buffer.full()); @@ -338,7 +329,7 @@ public void testSeekInFullBuffer() { assertEquals(8, buffer.size()); assertEquals(9, buffer.fill()); - assertEquals("Can seek backwards now, making the buffer full again", -1, buffer.seek(-1)); + assertEquals(-1, buffer.seek(-1), "Can seek backwards now, making the buffer full again"); assertArrayEquals(new byte[] { 6 }, buffer.peek().getData()); assertEquals(new Chunk(new byte[] { 6 }, "", 0), buffer.peek()); assertTrue(buffer.full()); @@ -346,14 +337,14 @@ public void testSeekInFullBuffer() { assertEquals(9, buffer.size()); assertEquals(9, buffer.fill()); - assertEquals("Can seek forward up to empty() in full buffer", 9, buffer.seek(20)); - assertNull("Buffer is empty now as we forward up to head", buffer.peek()); + assertEquals(9, buffer.seek(20), "Can seek forward up to empty() in full buffer"); + assertNull(buffer.peek(), "Buffer is empty now as we forward up to head"); assertFalse(buffer.full()); assertTrue(buffer.empty()); assertEquals(0, buffer.size()); assertEquals(9, buffer.fill()); - assertEquals("Can seek backwards up to full() in full buffer", -9, buffer.seek(-20)); + assertEquals(-9, buffer.seek(-20), "Can seek backwards up to full() in full buffer"); assertArrayEquals(new byte[] { 6 }, buffer.peek().getData()); assertEquals(new Chunk(new byte[] { 6 }, "", 0), buffer.peek()); assertTrue(buffer.full()); diff --git a/src/test/java/org/dstadler/audio/buffer/BlockingSeekableRingBufferTest.java b/src/test/java/org/dstadler/audio/buffer/BlockingSeekableRingBufferTest.java index 495096c..5284d27 100644 --- a/src/test/java/org/dstadler/audio/buffer/BlockingSeekableRingBufferTest.java +++ b/src/test/java/org/dstadler/audio/buffer/BlockingSeekableRingBufferTest.java @@ -1,16 +1,11 @@ package org.dstadler.audio.buffer; import org.dstadler.audio.stream.Stream; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class BlockingSeekableRingBufferTest extends AbstractBlockingSeekableRingBufferTester { @Override @@ -71,10 +66,10 @@ public void testToStringBuffer() { try (BlockingSeekableRingBuffer localBuffer = new BlockingSeekableRingBuffer(10)) { assertTrue(localBuffer.empty()); assertFalse(localBuffer.full()); - assertTrue("Had: " + localBuffer, - localBuffer.toString().contains("empty=true")); - assertTrue("Had: " + localBuffer, - localBuffer.toString().contains("full=false")); + assertTrue(localBuffer.toString().contains("empty=true"), + "Had: " + localBuffer); + assertTrue(localBuffer.toString().contains("full=false"), + "Had: " + localBuffer); for (byte i = 0; i < 15; i++) { localBuffer.add(new Chunk(new byte[]{i}, "", 0)); @@ -82,10 +77,10 @@ public void testToStringBuffer() { assertFalse(localBuffer.empty()); assertTrue(localBuffer.full()); - assertTrue("Had: " + localBuffer, - localBuffer.toString().contains("empty=false")); - assertTrue("Had: " + localBuffer, - localBuffer.toString().contains("full=true")); + assertTrue(localBuffer.toString().contains("empty=false"), + "Had: " + localBuffer); + assertTrue(localBuffer.toString().contains("full=true"), + "Had: " + localBuffer); } } diff --git a/src/test/java/org/dstadler/audio/buffer/BufferPersistenceDTOTest.java b/src/test/java/org/dstadler/audio/buffer/BufferPersistenceDTOTest.java index 8072672..9f7ce0e 100644 --- a/src/test/java/org/dstadler/audio/buffer/BufferPersistenceDTOTest.java +++ b/src/test/java/org/dstadler/audio/buffer/BufferPersistenceDTOTest.java @@ -2,15 +2,11 @@ import org.dstadler.audio.stream.Stream; import org.dstadler.commons.testing.TestHelpers; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class BufferPersistenceDTOTest { @Test diff --git a/src/test/java/org/dstadler/audio/buffer/BufferPersistenceTest.java b/src/test/java/org/dstadler/audio/buffer/BufferPersistenceTest.java index d684fc3..60d9819 100644 --- a/src/test/java/org/dstadler/audio/buffer/BufferPersistenceTest.java +++ b/src/test/java/org/dstadler/audio/buffer/BufferPersistenceTest.java @@ -2,17 +2,14 @@ import org.dstadler.audio.stream.Stream; import org.dstadler.commons.logging.jdk.LoggerFactory; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; import java.util.logging.Logger; import static org.dstadler.audio.buffer.Chunk.CHUNK_SIZE; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class BufferPersistenceTest { private final static Logger log = LoggerFactory.make(); @@ -190,8 +187,7 @@ public void testInvalidStartPosition() throws IOException { BufferPersistenceDTO dtoBack = BufferPersistence.readBufferFromDisk(tempPersist); try (RangeDownloadingBuffer buffer = RangeDownloadingBuffer.fromPersistence(dtoBack, 100, Chunk.CHUNK_SIZE)) { - assertEquals("Zero expected here because we restored the buffer", - 0, buffer.bufferedBackward()); + assertEquals(0, buffer.bufferedBackward(), "Zero expected here because we restored the buffer"); buffer.next(); diff --git a/src/test/java/org/dstadler/audio/buffer/ChunkTest.java b/src/test/java/org/dstadler/audio/buffer/ChunkTest.java index fde3db5..bdbdbed 100644 --- a/src/test/java/org/dstadler/audio/buffer/ChunkTest.java +++ b/src/test/java/org/dstadler/audio/buffer/ChunkTest.java @@ -1,10 +1,10 @@ package org.dstadler.audio.buffer; import org.dstadler.commons.testing.TestHelpers; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class ChunkTest { @Test diff --git a/src/test/java/org/dstadler/audio/buffer/CountingSeekableRingBufferImplTest.java b/src/test/java/org/dstadler/audio/buffer/CountingSeekableRingBufferImplTest.java index 378ea2b..fd16fe4 100644 --- a/src/test/java/org/dstadler/audio/buffer/CountingSeekableRingBufferImplTest.java +++ b/src/test/java/org/dstadler/audio/buffer/CountingSeekableRingBufferImplTest.java @@ -3,14 +3,12 @@ import org.dstadler.commons.logging.jdk.LoggerFactory; import org.dstadler.commons.testing.TestHelpers; import org.dstadler.commons.testing.ThreadTestHelper; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.logging.Logger; import static org.dstadler.audio.buffer.CountingSeekableRingBufferImpl.DEFAULT_CHUNKS_PER_SECOND; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class CountingSeekableRingBufferImplTest extends AbstractBlockingSeekableRingBufferTester { private final static Logger log = LoggerFactory.make(); @@ -73,7 +71,7 @@ public void testGetChunksReadPerSec() throws InterruptedException { getBuffer().add(new Chunk(new byte[] { 1 }, "", tms)); final double writtenPerSecond = getBuffer().getChunksWrittenPerSecond(); - assertTrue("Had: " + writtenPerSecond, Double.isInfinite(writtenPerSecond)); + assertTrue(Double.isInfinite(writtenPerSecond), "Had: " + writtenPerSecond); assertEquals(0, getBuffer().getChunksReadPerSecond(), 0); assertEquals(DEFAULT_CHUNKS_PER_SECOND, getBuffer().getChunksPerSecond(), 0.01); @@ -96,13 +94,10 @@ public void testGetChunksReadPerSec() throws InterruptedException { "\n" + expected + "\n" + getBuffer().getChunksReadPerSecond()); - assertEquals("Having time: " + start + " - " + end + ": " + (end - start) + ": " + getBuffer(), - expected, getBuffer().getChunksReadPerSecond(), 0.01); - assertEquals("Having time: " + start + " - " + end + ": " + (end - start) + ": " + getBuffer(), - expected, getBuffer().getChunksPerSecond(), 0.01); + assertEquals(expected, getBuffer().getChunksReadPerSecond(), 0.01, "Having time: " + start + " - " + end + ": " + (end - start) + ": " + getBuffer()); + assertEquals(expected, getBuffer().getChunksPerSecond(), 0.01, "Having time: " + start + " - " + end + ": " + (end - start) + ": " + getBuffer()); - assertEquals("Having time: " + start + " - " + end + ": " + (end - start) + ": " + getBuffer(), - 4, ((CountingSeekableRingBufferImpl)getBuffer()).getChunksReadOverall()); + assertEquals(4, ((CountingSeekableRingBufferImpl)getBuffer()).getChunksReadOverall(), "Having time: " + start + " - " + end + ": " + (end - start) + ": " + getBuffer()); } @Test diff --git a/src/test/java/org/dstadler/audio/buffer/DiskBasedBlockingSeekableRingBufferTest.java b/src/test/java/org/dstadler/audio/buffer/DiskBasedBlockingSeekableRingBufferTest.java index 75fa704..841d2ad 100644 --- a/src/test/java/org/dstadler/audio/buffer/DiskBasedBlockingSeekableRingBufferTest.java +++ b/src/test/java/org/dstadler/audio/buffer/DiskBasedBlockingSeekableRingBufferTest.java @@ -7,25 +7,25 @@ import org.dstadler.commons.logging.jdk.LoggerFactory; import org.dstadler.commons.testing.TestHelpers; import org.dstadler.commons.testing.ThreadTestHelper; -import org.junit.After; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class DiskBasedBlockingSeekableRingBufferTest extends AbstractBlockingSeekableRingBufferTester { private static File DATA_DIR; - @BeforeClass + @BeforeAll public static void beforeClass() throws IOException { LoggerFactory.initLogging(); } - @After + @AfterEach public void tearDownDataDir() throws IOException { FileUtils.deleteDirectory(getDataDir()); } @@ -101,10 +101,10 @@ public void testToStringBuffer() throws IOException { assertTrue(localBuffer.empty()); assertFalse(localBuffer.full()); - assertTrue("Had: " + localBuffer, - localBuffer.toString().contains("empty=true")); - assertTrue("Had: " + localBuffer, - localBuffer.toString().contains("full=false")); + assertTrue(localBuffer.toString().contains("empty=true"), + "Had: " + localBuffer); + assertTrue(localBuffer.toString().contains("full=false"), + "Had: " + localBuffer); for (byte i = 0; i < 15; i++) { localBuffer.add(new Chunk(new byte[] { i }, "", 0)); @@ -112,24 +112,24 @@ public void testToStringBuffer() throws IOException { assertFalse(localBuffer.empty()); assertTrue(localBuffer.full()); - assertTrue("Had: " + localBuffer, - localBuffer.toString().contains("empty=false")); - assertTrue("Had: " + localBuffer, - localBuffer.toString().contains("full=true")); - assertTrue("Had: " + localBuffer, - localBuffer.toString().contains("isDirty=")); - assertTrue("Had: " + localBuffer, - localBuffer.toString().contains("diskBufferRead=")); - assertTrue("Had: " + localBuffer, - localBuffer.toString().contains("diskBufferWrite=")); - assertTrue("Had: " + localBuffer, - localBuffer.toString().contains("numberOfDiskChunks=")); - assertTrue("Had: " + localBuffer, - localBuffer.toString().contains("diskBufferReadPosition=")); - assertTrue("Had: " + localBuffer, - localBuffer.toString().contains("diskBufferWritePosition=")); - assertTrue("Had: " + localBuffer, - localBuffer.toString().contains("dataDir=")); + assertTrue(localBuffer.toString().contains("empty=false"), + "Had: " + localBuffer); + assertTrue(localBuffer.toString().contains("full=true"), + "Had: " + localBuffer); + assertTrue(localBuffer.toString().contains("isDirty="), + "Had: " + localBuffer); + assertTrue(localBuffer.toString().contains("diskBufferRead="), + "Had: " + localBuffer); + assertTrue(localBuffer.toString().contains("diskBufferWrite="), + "Had: " + localBuffer); + assertTrue(localBuffer.toString().contains("numberOfDiskChunks="), + "Had: " + localBuffer); + assertTrue(localBuffer.toString().contains("diskBufferReadPosition="), + "Had: " + localBuffer); + assertTrue(localBuffer.toString().contains("diskBufferWritePosition="), + "Had: " + localBuffer); + assertTrue(localBuffer.toString().contains("dataDir="), + "Had: " + localBuffer); } } @@ -137,23 +137,20 @@ public void testToStringBuffer() throws IOException { public void testAddDiskBuffer() throws IOException { String[] list = getDataDir().list(); assertNotNull(list); - assertEquals("Should not have disk-files before", - 0, list.length); + assertEquals(0, list.length, "Should not have disk-files before"); buffer.add(new Chunk(new byte[] { 1 }, "", 0)); list = getDataDir().list(); assertNotNull(list); - assertEquals("Should not have disk-files until first flush", - 0, list.length); + assertEquals(0, list.length, "Should not have disk-files until first flush"); buffer.add(new Chunk(new byte[] { 2 }, "", 0)); buffer.add(new Chunk(new byte[] { 3 }, "", 0)); list = getDataDir().list(); assertNotNull(list); - assertEquals("Should have disk files now", - 1, list.length); + assertEquals(1, list.length, "Should have disk files now"); assertTrue(list[0].startsWith(DiskBasedBlockingSeekableRingBuffer.FILE_PREFIX)); buffer.add(new Chunk(new byte[] { 4 }, "", 0)); @@ -162,8 +159,7 @@ public void testAddDiskBuffer() throws IOException { list = getDataDir().list(); assertNotNull(list); - assertEquals("Should have disk files now", - 2, list.length); + assertEquals(2, list.length, "Should have disk files now"); assertTrue(list[1].startsWith(DiskBasedBlockingSeekableRingBuffer.FILE_PREFIX)); buffer.add(new Chunk(new byte[] { 7 }, "", 0)); @@ -172,16 +168,14 @@ public void testAddDiskBuffer() throws IOException { list = getDataDir().list(); assertNotNull(list); - assertEquals("Should have disk files now", - 3, list.length); + assertEquals(3, list.length, "Should have disk files now"); assertTrue(list[2].startsWith(DiskBasedBlockingSeekableRingBuffer.FILE_PREFIX)); buffer.add(new Chunk(new byte[] { 10 }, "", 0)); list = getDataDir().list(); assertNotNull(list); - assertEquals("Should have disk files now", - 4, list.length); + assertEquals(4, list.length, "Should have disk files now"); assertTrue(list[3].startsWith(DiskBasedBlockingSeekableRingBuffer.FILE_PREFIX)); buffer.add(new Chunk(new byte[] { 11 }, "", 0)); @@ -190,8 +184,7 @@ public void testAddDiskBuffer() throws IOException { list = getDataDir().list(); assertNotNull(list); - assertEquals("Should have disk files now", - 4, list.length); + assertEquals(4, list.length, "Should have disk files now"); buffer.add(new Chunk(new byte[] { 14 }, "", 0)); buffer.add(new Chunk(new byte[] { 15 }, "", 0)); @@ -199,8 +192,7 @@ public void testAddDiskBuffer() throws IOException { list = getDataDir().list(); assertNotNull(list); - assertEquals("Should not end up with more disk files than 4", - 4, list.length); + assertEquals(4, list.length, "Should not end up with more disk files than 4"); } @Override @@ -222,8 +214,8 @@ public void testLargeBuffer() throws IOException { if (RandomUtils.nextBoolean()) { int seek = localBuffer.seek(RandomUtils.nextInt(0, 5000) - 2500); - assertTrue("Had: " + seek + " with " + buffer, - seek > -1000 && seek < 1000); + assertTrue(seek > -1000 && seek < 1000, + "Had: " + seek + " with " + buffer); } } } @@ -326,16 +318,16 @@ public void testFailingWrite() throws IOException { try { localBuffer.add(new Chunk(new byte[0], "", 1)); } catch (IllegalStateException e) { - assertTrue("Had: " + ExceptionUtils.getStackTrace(e), - e.getCause() instanceof FileNotFoundException); - assertTrue("Had: " + ExceptionUtils.getStackTrace(e), - e.getMessage().contains("Could not update current buffers for writing at position") || - e.getMessage().contains("Could not fetch buffer for reading at position")); - assertTrue("Had: " + ExceptionUtils.getStackTrace(e), - e.getMessage().contains("position 5 ") || + assertTrue(e.getCause() instanceof FileNotFoundException, + "Had: " + ExceptionUtils.getStackTrace(e)); + assertTrue(e.getMessage().contains("Could not update current buffers for writing at position") || + e.getMessage().contains("Could not fetch buffer for reading at position"), + "Had: " + ExceptionUtils.getStackTrace(e)); + assertTrue(e.getMessage().contains("position 5 ") || e.getMessage().contains("position 10 ") || e.getMessage().contains("position 25") || - e.getMessage().contains("position 30")); + e.getMessage().contains("position 30"), + "Had: " + ExceptionUtils.getStackTrace(e)); } } } diff --git a/src/test/java/org/dstadler/audio/buffer/MockHTTPTest.java b/src/test/java/org/dstadler/audio/buffer/MockHTTPTest.java index b365ed5..ee4942e 100644 --- a/src/test/java/org/dstadler/audio/buffer/MockHTTPTest.java +++ b/src/test/java/org/dstadler/audio/buffer/MockHTTPTest.java @@ -5,8 +5,8 @@ import org.dstadler.commons.http.NanoHTTPD; import org.dstadler.commons.testing.MockRESTServer; import org.dstadler.commons.testing.ThreadTestHelper; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; @@ -17,10 +17,7 @@ import java.util.logging.Level; import java.util.logging.Logger; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class MockHTTPTest { @Test @@ -49,8 +46,7 @@ public void testDownloadFails() throws IOException { } } - assertEquals("Expecting one call initially and 10 retries", - 10 + 1, httpCalls.get()); + assertEquals(10 + 1, httpCalls.get(), "Expecting one call initially and 10 retries"); } @Test @@ -80,8 +76,7 @@ public void testDownloadInvalidContentType() throws IOException { } } - assertEquals("Expecting one call initially and one call to fetch data", - 1 + 1, httpCalls.get()); + assertEquals(1 + 1, httpCalls.get(), "Expecting one call initially and one call to fetch data"); } @Test @@ -110,11 +105,10 @@ public void testDownloadSucceeds() throws IOException { } } - assertEquals("Expecting one call initially and one call to fetch data", - 1 + 1, httpCalls.get()); + assertEquals(1 + 1, httpCalls.get(), "Expecting one call initially and one call to fetch data"); } - @Ignore("URL is only temporary") + @Disabled("URL is only temporary") @Test public void testFM4Stream() throws IOException { try (RangeDownloadingBuffer buffer = new RangeDownloadingBuffer("https://loopstream01.apa.at/?channel=fm4&id=2020-11-30_1459_tl_54_7DaysMon12_109215.mp3", @@ -201,9 +195,9 @@ public void run(int threadNum, int itNum) throws Exception { capacity = buffer.capacity(); } assertTrue(size >= 0); - assertTrue("size: " + size + ", capacity: " + capacity + ", buffer: " + buffer, + assertTrue(size <= (capacity + BUFFERED_CHUNKS), // size can be a bit more as we compute it based on internal byte-position - size <= (capacity + BUFFERED_CHUNKS)); + "size: " + size + ", capacity: " + capacity + ", buffer: " + buffer); break; } case 5: @@ -215,13 +209,13 @@ public void run(int threadNum, int itNum) throws Exception { break; case 7: { int available = buffer.bufferedBackward(); - assertTrue("Had: " + available, available >= 0); + assertTrue(available >= 0, "Had: " + available); assertTrue(available <= buffer.capacity()); break; } case 8: { int available = buffer.bufferedForward(); - assertTrue("Had: " + available, available >= 0); + assertTrue(available >= 0, "Had: " + available); assertTrue(available <= buffer.capacity()); break; } @@ -258,13 +252,13 @@ public void run(int threadNum, int itNum) throws Exception { case 14: { // another test of size without synchronized block int size = buffer.size(); - assertTrue("Having size: " + size, size >= 0); + assertTrue(size >= 0, "Having size: " + size); break; } case 15: // another test of capacity without synchronized block int capacity = buffer.capacity(); - assertTrue("Having capacity: " + capacity, capacity >= 0); + assertTrue(capacity >= 0, "Having capacity: " + capacity); break; case 16: { final int fill; @@ -366,7 +360,6 @@ public void run() { } } - assertEquals("Expecting one call initially and first try", - 1 + 1, httpCalls.get()); + assertEquals(1 + 1, httpCalls.get(), "Expecting one call initially and first try"); } } diff --git a/src/test/java/org/dstadler/audio/buffer/RangeDownloadingBufferTest.java b/src/test/java/org/dstadler/audio/buffer/RangeDownloadingBufferTest.java index c4730d2..10aa8cf 100644 --- a/src/test/java/org/dstadler/audio/buffer/RangeDownloadingBufferTest.java +++ b/src/test/java/org/dstadler/audio/buffer/RangeDownloadingBufferTest.java @@ -8,12 +8,10 @@ import org.dstadler.commons.testing.MemoryLeakVerifier; import org.dstadler.commons.testing.MockRESTServer; import org.dstadler.commons.testing.TestHelpers; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import java.io.File; import java.io.IOException; @@ -24,16 +22,8 @@ import java.util.logging.Logger; import static org.dstadler.audio.buffer.Chunk.CHUNK_SIZE; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -@RunWith(Parameterized.class) +import static org.junit.jupiter.api.Assertions.*; + public class RangeDownloadingBufferTest { private final static Logger log = LoggerFactory.make(); @@ -53,7 +43,6 @@ public class RangeDownloadingBufferTest { private RangeDownloadingBuffer buffer; - @Parameterized.Parameters(name = "Sample: {0}, Chunks: {1}, Size: {2}/{3}, Meta: {4}") public static Collection data() { return Arrays.asList(new Object[][] { { SAMPLE_URL, 52, 841640, 841590, Pair.of("", 100L) }, @@ -75,19 +64,7 @@ public static Collection data() { }); } - @Parameterized.Parameter - public String sample; - @Parameterized.Parameter(1) - public int expectedChunks; - @Parameterized.Parameter(2) - public int fileSize; - @Parameterized.Parameter(3) - public int fileSize2; - @Parameterized.Parameter(4) - public Pair metaData; - - @Before - public void setUp() { + public void setUp(String sample, Pair metaData) { try { buffer = new RangeDownloadingBuffer(sample, "", null, 10, CHUNK_SIZE, p -> metaData); verifier.addObject(buffer); @@ -96,7 +73,7 @@ public void setUp() { } } - @After + @AfterEach public void tearDown() { if(buffer != null) { TestHelpers.ToStringTest(buffer); @@ -110,8 +87,10 @@ public void tearDown() { verifier.assertGarbageCollected(); } - @Test - public void testBuffered() { + @MethodSource("data") + @ParameterizedTest(name = "Sample: {0}, Chunks: {1}, Size: {2}/{3}, Meta: {4}") + public void testBuffered(String sample, int expectedChunks, int fileSize, int ignoredFileSize2, Pair metaData) { + setUp(sample, metaData); assertEquals(expectedChunks, buffer.fill()); assertEquals(expectedChunks, buffer.size()); assertEquals(expectedChunks, buffer.capacity()); @@ -160,14 +139,15 @@ public void testBuffered() { assertEquals(10, buffer.bufferedBackward()); assertNotNull(buffer.next()); - assertEquals("Having: " + buffer, 9, buffer.bufferedForward()); - assertEquals("internal buffer only stores 19 elements, thus one is already removed by adding 10 more", - 10, buffer.bufferedBackward()); + assertEquals(9, buffer.bufferedForward(), "Having: " + buffer); + assertEquals(10, buffer.bufferedBackward(), "internal buffer only stores 19 elements, thus one is already removed by adding 10 more"); } } - @Test - public void testInitialSize() { + @MethodSource("data") + @ParameterizedTest(name = "Sample: {0}, Chunks: {1}, Size: {2}/{3}, Meta: {4}") + public void testInitialSize(String sample, int expectedChunks, int fileSize, int ignoredFileSize2, Pair metaData) { + setUp(sample, metaData); TestHelpers.ToStringTest(buffer); if (fileSize == 0) { @@ -181,8 +161,10 @@ public void testInitialSize() { assertEquals(expectedChunks, buffer.fill()); } - @Test - public void testFillupBuffer() throws Exception { + @MethodSource("data") + @ParameterizedTest(name = "Sample: {0}, Chunks: {1}, Size: {2}/{3}, Meta: {4}") + public void testFillupBuffer(String sample, int expectedChunks, int fileSize, int ignoredFileSize2, Pair metaData) throws Exception { + setUp(sample, metaData); if (fileSize == 0) { assertEquals(0, buffer.fillupBuffer(-1, -1)); assertTrue(buffer.empty()); @@ -208,8 +190,10 @@ public void testFillupBuffer() throws Exception { assertEquals(expectedChunks, buffer.fill()); } - @Test - public void testFillupBufferMin() throws Exception { + @MethodSource("data") + @ParameterizedTest(name = "Sample: {0}, Chunks: {1}, Size: {2}/{3}, Meta: {4}") + public void testFillupBufferMin(String sample, int expectedChunks, int fileSize, int ignoredFileSize2, Pair metaData) throws Exception { + setUp(sample, metaData); assertEquals(0, buffer.fillupBuffer(1000, 10)); if (fileSize == 0) { @@ -236,15 +220,17 @@ public void testFillupBufferMin() throws Exception { assertEquals(expectedChunks, buffer.fill()); } - @Test - public void testFillupBufferWithBufferData() throws Exception { + @MethodSource("data") + @ParameterizedTest(name = "Sample: {0}, Chunks: {1}, Size: {2}/{3}, Meta: {4}") + public void testFillupBufferWithBufferData(String sample, int expectedChunks, int fileSize, int ignoredFileSize2, Pair metaData) throws Exception { + setUp(sample, metaData); // not useful for buffer without data if (fileSize == 0) { return; } for(int i = 0;i < 20;i++) { - assertNotNull("Having: " + buffer, buffer.next()); + assertNotNull(buffer.next(), "Having: " + buffer); } assertEquals(fileSize/CHUNK_SIZE + 1 - 20, buffer.size()); @@ -268,8 +254,10 @@ public void testFillupBufferWithBufferData() throws Exception { assertEquals(10, buffer.fillupBuffer(-1, -1)); } - @Test - public void testPeek() { + @MethodSource("data") + @ParameterizedTest(name = "Sample: {0}, Chunks: {1}, Size: {2}/{3}, Meta: {4}") + public void testPeek(String sample, int ignoredExpectedChunks, int fileSize, int ignoredFileSize2, Pair metaData) { + setUp(sample, metaData); Chunk peek = buffer.peek(); if (fileSize == 0) { assertNull(peek); @@ -292,8 +280,10 @@ public void testPeek() { } } - @Test - public void testPeekIOException() throws IOException { + @MethodSource("data") + @ParameterizedTest(name = "Sample: {0}, Chunks: {1}, Size: {2}/{3}, Meta: {4}") + public void testPeekIOException(String sample, int ignoredExpectedChunks, int ignoredFileSize, int ignoredFileSize2, Pair metaData) throws IOException { + setUp(sample, metaData); final AtomicInteger calls = new AtomicInteger(0); try (MockRESTServer server = new MockRESTServer(() -> { if (calls.incrementAndGet() == 1) { @@ -312,15 +302,17 @@ public void testPeekIOException() throws IOException { buffer.RETRY_SLEEP_TIME = 1; - assertNull("Should return null because fetching data fails internall", buffer.peek()); + assertNull(buffer.peek(), "Should return null because fetching data fails internall"); assertThrows(IllegalStateException.class, () -> buffer.next()); } } - @Test - public void testReadAtEnd() { + @MethodSource("data") + @ParameterizedTest(name = "Sample: {0}, Chunks: {1}, Size: {2}/{3}, Meta: {4}") + public void testReadAtEnd(String sample, int expectedChunks, int ignoredFileSize, int ignoredFileSize2, Pair metaData) { + setUp(sample, metaData); assertEquals(expectedChunks, buffer.seek(999999)); assertNull(buffer.peek()); @@ -332,8 +324,10 @@ public void testReadAtEnd() { assertTrue(buffer.empty()); } - @Test - public void testEmpty() throws IOException { + @MethodSource("data") + @ParameterizedTest(name = "Sample: {0}, Chunks: {1}, Size: {2}/{3}, Meta: {4}") + public void testEmpty(String sample, int expectedChunks, int fileSize, int ignoredFileSize2, Pair metaData) throws IOException { + setUp(sample, metaData); // not useful for buffer without data if (fileSize == 0) { return; @@ -352,8 +346,10 @@ public void testEmpty() throws IOException { assertFalse(buffer.empty()); } - @Test - public void testReadChunkAndSeek() { + @MethodSource("data") + @ParameterizedTest(name = "Sample: {0}, Chunks: {1}, Size: {2}/{3}, Meta: {4}") + public void testReadChunkAndSeek(String sample, int expectedChunks, int fileSize, int ignoredFileSize2, Pair metaData) { + setUp(sample, metaData); Chunk chunk = buffer.next(); if (fileSize == 0) { assertNull(chunk); @@ -375,8 +371,10 @@ public void testReadChunkAndSeek() { assertEquals(expectedChunks, buffer.fill()); } - @Test - public void testSeekOutside() { + @MethodSource("data") + @ParameterizedTest(name = "Sample: {0}, Chunks: {1}, Size: {2}/{3}, Meta: {4}") + public void testSeekOutside(String sample, int expectedChunks, int ignoredFileSize, int ignoredFileSize2, Pair metaData) { + setUp(sample, metaData); assertEquals(expectedChunks, buffer.size()); assertEquals(expectedChunks, buffer.capacity()); assertEquals(expectedChunks, buffer.fill()); @@ -384,8 +382,10 @@ public void testSeekOutside() { assertEquals(expectedChunks, buffer.seek(5000)); } - @Test - public void testSeekBackwards() throws IOException { + @MethodSource("data") + @ParameterizedTest(name = "Sample: {0}, Chunks: {1}, Size: {2}/{3}, Meta: {4}") + public void testSeekBackwards(String sample, int expectedChunks, int fileSize, int fileSize2, Pair metaData) throws IOException { + setUp(sample, metaData); // initialize with a chunk-size of 1 to have exact chunk-counts in the tests below buffer = new RangeDownloadingBuffer(sample, "", null, 10, 1, percentage -> Pair.of("", 0L)); @@ -428,21 +428,26 @@ public void testSeekBackwards() throws IOException { } } - @Test(expected = UnsupportedOperationException.class) - public void addFails() { - buffer.add(null); + @MethodSource("data") + @ParameterizedTest(name = "Sample: {0}, Chunks: {1}, Size: {2}/{3}, Meta: {4}") + public void addFails(String sample, int ignoredExpectedChunks, int ignoredFileSize, int ignoredFileSize2, Pair metaData) { + setUp(sample, metaData); + assertThrows(UnsupportedOperationException.class, () -> + buffer.add(null)); } - @Test - public void testPersistence() throws IOException { + @MethodSource("data") + @ParameterizedTest(name = "Sample: {0}, Chunks: {1}, Size: {2}/{3}, Meta: {4}") + public void testPersistence(String sample, int expectedChunks, int fileSize, int ignoredFileSize2, Pair metaData) throws IOException { + setUp(sample, metaData); buffer.next(); if (fileSize == 0) { - assertTrue("Had: " + buffer, buffer.empty()); + assertTrue(buffer.empty(), "Had: " + buffer); } else { - assertFalse("Had: " + buffer, buffer.empty()); + assertFalse(buffer.empty(), "Had: " + buffer); } - assertTrue("Had: " + buffer, buffer.full()); + assertTrue(buffer.full(), "Had: " + buffer); if (fileSize == 0) { assertEquals(0, buffer.size()); } else { @@ -503,25 +508,34 @@ private String toStringReplace(RangeDownloadingBuffer buffer) { .replaceAll("size=\\d+", ""); } - @Test - public void testWithUser() throws IOException { + @MethodSource("data") + @ParameterizedTest(name = "Sample: {0}, Chunks: {1}, Size: {2}/{3}, Meta: {4}") + public void testWithUser(String sample, int ignoredExpectedChunks, int ignoredFileSize, int ignoredFileSize2, Pair metaData) throws IOException { + setUp(sample, metaData); buffer = new RangeDownloadingBuffer(sample, "testuser", "testpass", 10, CHUNK_SIZE, percentage -> Pair.of("", 0L)); } - @Test(expected = IOException.class) - public void testWithUserAndAuthResponse() throws IOException { + @MethodSource("data") + @ParameterizedTest(name = "Sample: {0}, Chunks: {1}, Size: {2}/{3}, Meta: {4}") + public void testWithUserAndAuthResponse(String sample, int ignoredExpectedChunks, int ignoredFileSize, int ignoredFileSize2, Pair metaData) throws IOException { + setUp(sample, metaData); + try (MockRESTServer server = new MockRESTServer("404", "text/html", "")) { buffer.close(); - try (RangeDownloadingBuffer ignores = new RangeDownloadingBuffer("http://localhost:" + server.getPort(), - "testuser", "testpass", 10, CHUNK_SIZE, percentage -> Pair.of("", 0L))) { - fail("Should catch exception"); - } + assertThrows(IOException.class, () -> { + try (RangeDownloadingBuffer ignores = new RangeDownloadingBuffer("http://localhost:" + server.getPort(), + "testuser", "testpass", 10, CHUNK_SIZE, percentage -> Pair.of("", 0L))) { + fail("Should catch exception"); + } + }); } } - @Test - public void testToString() { + @MethodSource("data") + @ParameterizedTest(name = "Sample: {0}, Chunks: {1}, Size: {2}/{3}, Meta: {4}") + public void testToString(String sample, int ignoredExpectedChunks, int fileSize, int ignoredFileSize2, Pair metaData) { + setUp(sample, metaData); TestHelpers.ToStringTest(buffer); if (fileSize == 0) { assertNull(buffer.next()); @@ -530,15 +544,17 @@ public void testToString() { } TestHelpers.ToStringTest(buffer); - assertTrue("Had: " + buffer, - buffer.toString().contains("empty=" + (buffer.empty() ? "true" : "false"))); - assertTrue("Had: " + buffer, - buffer.toString().contains("full=" + (buffer.full() ? "true" : "false"))); + assertTrue(buffer.toString().contains("empty=" + (buffer.empty() ? "true" : "false")), + "Had: " + buffer); + assertTrue(buffer.toString().contains("full=" + (buffer.full() ? "true" : "false")), + "Had: " + buffer); } - @Ignore("Just used for testing download speed") - @Test - public void testSlowStartBenchmark() throws IOException, InterruptedException { + @Disabled("Just used for testing download speed") + @MethodSource("data") + @ParameterizedTest(name = "Sample: {0}, Chunks: {1}, Size: {2}/{3}, Meta: {4}") + public void testSlowStartBenchmark(String sample, int expectedChunks, int ignoredFileSize, int ignoredFileSize2, Pair metaData) throws IOException, InterruptedException { + setUp(sample, metaData); long start = System.currentTimeMillis(); log.info("Starting download: " + (System.currentTimeMillis() - start)); try (RangeDownloadingBuffer buffer = new RangeDownloadingBuffer("https://loopstream01.apa.at/?channel=fm4&id=2020-03-22_0959_tl_54_7DaysSun6_95352.mp3", @@ -559,34 +575,36 @@ public void testSlowStartBenchmark() throws IOException, InterruptedException { log.info("After fillup: " + (System.currentTimeMillis() - start)); } - @Test - public void testSeekNotEmpty() throws IOException { + @MethodSource("data") + @ParameterizedTest(name = "Sample: {0}, Chunks: {1}, Size: {2}/{3}, Meta: {4}") + public void testSeekNotEmpty(String sample, int ignoredExpectedChunks, int fileSize, int ignoredFileSize2, Pair metaData) throws IOException { + setUp(sample, metaData); if (fileSize == 0) { - assertTrue("Empty at the beginning", buffer.empty()); - assertEquals("Not able to read 10 chunks", 0, buffer.fillupBuffer(0, 10)); + assertTrue(buffer.empty(), "Empty at the beginning"); + assertEquals(0, buffer.fillupBuffer(0, 10), "Not able to read 10 chunks"); - assertTrue("Still empty after initial fill-up", buffer.empty()); + assertTrue(buffer.empty(), "Still empty after initial fill-up"); - assertEquals("Not able to seek 20 chunks", 0, buffer.seek(20)); + assertEquals(0, buffer.seek(20), "Not able to seek 20 chunks"); - assertTrue("Still empty after seeking", buffer.empty()); + assertTrue(buffer.empty(), "Still empty after seeking"); } else { - assertFalse("Not empty at the beginning", buffer.empty()); - assertEquals("Load 10 chunks", 10, buffer.fillupBuffer(0, 10)); + assertFalse(buffer.empty(), "Not empty at the beginning"); + assertEquals(10, buffer.fillupBuffer(0, 10), "Load 10 chunks"); - assertFalse("Not empty after initial fill-up", buffer.empty()); + assertFalse(buffer.empty(), "Not empty after initial fill-up"); - assertEquals("Able to seek 20 chunks", 20, buffer.seek(20)); + assertEquals(20, buffer.seek(20), "Able to seek 20 chunks"); - assertFalse("Not empty after seeking", buffer.empty()); + assertFalse(buffer.empty(), "Not empty after seeking"); } int seeked = buffer.seek(300); if (fileSize == 0) { - assertEquals("Had: " + seeked, 0, seeked); + assertEquals(0, seeked, "Had: " + seeked); } else { - assertTrue("Had: " + seeked, seeked >= 10); + assertTrue(seeked >= 10, "Had: " + seeked); } - assertTrue("Should be at the end now", buffer.empty()); + assertTrue(buffer.empty(), "Should be at the end now"); } } diff --git a/src/test/java/org/dstadler/audio/buffer/SynchronizingTest.java b/src/test/java/org/dstadler/audio/buffer/SynchronizingTest.java index 4c69d86..0b3d656 100644 --- a/src/test/java/org/dstadler/audio/buffer/SynchronizingTest.java +++ b/src/test/java/org/dstadler/audio/buffer/SynchronizingTest.java @@ -2,8 +2,8 @@ import org.dstadler.commons.logging.jdk.LoggerFactory; import org.dstadler.commons.testing.ThreadTestHelper; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import java.io.File; import java.util.concurrent.atomic.AtomicReference; @@ -21,7 +21,7 @@ public class SynchronizingTest { private static volatile boolean shouldStop = false; private final AtomicReference exc = new AtomicReference<>(); - @After + @AfterEach public void tearDown() throws Exception { if (exc.get() != null) { throw exc.get(); @@ -62,7 +62,7 @@ public void test() throws Exception { int fill = buffer.fill(); float maxChunksBackwards = (fill - size); if (maxChunksBackwards < 0) { - exc.set(new Exception(String.format("Had higher size '%d' than fill '%d' in the buffer, but this should not be possible: %s", + exc.set(new Exception("Had higher size '%d' than fill '%d' in the buffer, but this should not be possible: %s".formatted( size, fill, buffer))); } } diff --git a/src/test/java/org/dstadler/audio/download/RangeDownloadFileTest.java b/src/test/java/org/dstadler/audio/download/RangeDownloadFileTest.java index 590faab..c57860e 100644 --- a/src/test/java/org/dstadler/audio/download/RangeDownloadFileTest.java +++ b/src/test/java/org/dstadler/audio/download/RangeDownloadFileTest.java @@ -2,15 +2,14 @@ import org.dstadler.commons.testing.MemoryLeakVerifier; import org.dstadler.commons.testing.TestHelpers; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; import java.util.Arrays; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class RangeDownloadFileTest { private static final File SAMPLE_FILE = new File("src/test/resources/test.bin"); @@ -19,7 +18,7 @@ public class RangeDownloadFileTest { private final MemoryLeakVerifier verifier = new MemoryLeakVerifier(); - @After + @AfterEach public void tearDown() { verifier.assertGarbageCollected(); } @@ -43,14 +42,14 @@ public void testLengthClosed() throws IOException { verifier.addObject(download); } - @Test(expected = IllegalStateException.class) + @Test public void testClosed() throws IOException { RangeDownload download = new RangeDownloadFile(SAMPLE_FILE); download.close(); verifier.addObject(download); - download.readRange(0, 1); + assertThrows(IllegalStateException.class, () -> download.readRange(0, 1)); } @Test @@ -69,19 +68,19 @@ public void testToString() throws IOException { try (RangeDownload download = new RangeDownloadFile(SAMPLE_FILE)) { TestHelpers.ToStringTest(download); - assertTrue("Expected " + EXPECTED_LENGTH + ", but had: " + download, - download.toString().contains(Long.toString(EXPECTED_LENGTH))); + assertTrue(download.toString().contains(Long.toString(EXPECTED_LENGTH)), + "Expected " + EXPECTED_LENGTH + ", but had: " + download); verifier.addObject(download); } } - @Test(expected = IllegalArgumentException.class) + @Test public void readWithStartBeyondLength() throws IOException { try (RangeDownload download = new RangeDownloadFile(SAMPLE_FILE)) { verifier.addObject(download); - download.readRange(99999999L, 200); + assertThrows(IllegalArgumentException.class, () -> download.readRange(99999999L, 200)); } } @@ -95,30 +94,30 @@ public void readBeyondLength() throws IOException { } } - @Test(expected = IllegalArgumentException.class) + @Test public void readWithInvalidSizeAt0() throws IOException { try (RangeDownload download = new RangeDownloadFile(SAMPLE_FILE)) { verifier.addObject(download); - download.readRange(0, 0); + assertThrows(IllegalArgumentException.class, () -> download.readRange(0, 0)); } } - @Test(expected = IllegalArgumentException.class) + @Test public void readWithInvalidSizeAt100() throws IOException { try (RangeDownload download = new RangeDownloadFile(SAMPLE_FILE)) { verifier.addObject(download); - download.readRange(100, 0); + assertThrows(IllegalArgumentException.class, () -> download.readRange(100, 0)); } } - @Test(expected = IllegalArgumentException.class) + @Test public void readWithInvalidSizeAtMinus100() throws IOException { try (RangeDownload download = new RangeDownloadFile(SAMPLE_FILE)) { verifier.addObject(download); - download.readRange(-100, 10); + assertThrows(IllegalArgumentException.class, () -> download.readRange(-100, 10)); } } } diff --git a/src/test/java/org/dstadler/audio/download/RangeDownloadHTTPTest.java b/src/test/java/org/dstadler/audio/download/RangeDownloadHTTPTest.java index 2372e40..85ce00d 100644 --- a/src/test/java/org/dstadler/audio/download/RangeDownloadHTTPTest.java +++ b/src/test/java/org/dstadler/audio/download/RangeDownloadHTTPTest.java @@ -12,20 +12,15 @@ import org.dstadler.commons.testing.MemoryLeakVerifier; import org.dstadler.commons.testing.MockRESTServer; import org.dstadler.commons.testing.TestHelpers; -import org.junit.After; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; import java.util.Arrays; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class RangeDownloadHTTPTest { private static final String SAMPLE_URL = "https://www.dstadler.org/DominikStadler2013.png"; @@ -35,7 +30,7 @@ public class RangeDownloadHTTPTest { private final MemoryLeakVerifier verifier = new MemoryLeakVerifier(); - @After + @AfterEach public void tearDown() { verifier.assertGarbageCollected(); } @@ -59,22 +54,22 @@ public void testLengthClosed() throws IOException { verifier.addObject(download); } - @Test(expected = IllegalStateException.class) + @Test public void testClosed() throws IOException { RangeDownload download = new RangeDownloadHTTP(SAMPLE_URL, "", null); download.close(); verifier.addObject(download); - download.readRange(0, 1); + assertThrows(IllegalStateException.class, () -> download.readRange(0, 1)); } @Test public void testReadRangeDstadlerOrg() { //noinspection resource - assertThrows("Expect an exception because the endpoint does not support Accept-Range", - IllegalStateException.class, - () -> new RangeDownloadHTTP("https://www.dstadler.org/", "", null)); + assertThrows(IllegalStateException.class, + () -> new RangeDownloadHTTP("https://www.dstadler.org/", "", null), + "Expect an exception because the endpoint does not support Accept-Range"); } @Test @@ -88,7 +83,7 @@ public void testReadRange() throws Exception { } } - @Ignore("Depends on an URL that will become unavailable") + @Disabled("Depends on an URL that will become unavailable") @Test public void testFM4() throws Exception { try (RangeDownload download = new RangeDownloadHTTP(FM4_URL, "", null)) { @@ -106,7 +101,7 @@ public void testFM4() throws Exception { } } - @Ignore("Download URL will become unavailable soon") + @Disabled("Download URL will become unavailable soon") @Test public void testFM4Download() throws IOException { assertNotNull(Thread.currentThread().getContextClassLoader().getResource("log4j.properties")); @@ -118,7 +113,7 @@ public void testFM4Download() throws IOException { assertTrue(destination.exists()); } - @Ignore("Download URL will become unavailable soon") + @Disabled("Download URL will become unavailable soon") @Test public void testFM4DownloadRange() throws IOException { File destination = new File("/tmp/FM4.mp3"); @@ -142,7 +137,7 @@ public void testFM4DownloadRange() throws IOException { assertTrue(destination.exists()); } - @Ignore("Download URL will become unavailable soon") + @Disabled("Download URL will become unavailable soon") @Test public void testDownloadFM4Hangs() throws IOException { String url = FM4_URL; @@ -172,7 +167,7 @@ public void testToString() throws Exception { try (RangeDownload download = new RangeDownloadHTTP(SAMPLE_URL, "", null)) { TestHelpers.ToStringTest(download); - assertTrue("Had: " + download, download.toString().contains(Long.toString(EXPECTED_LENGTH))); + assertTrue(download.toString().contains(Long.toString(EXPECTED_LENGTH)), "Had: " + download); verifier.addObject(download); } @@ -196,12 +191,12 @@ public void testWithUserAndAuthResponse() throws IOException { } } - @Test(expected = IllegalArgumentException.class) + @Test public void readWithStartBeyondLength() throws IOException { try (RangeDownload download = new RangeDownloadHTTP(SAMPLE_URL, "", null)) { verifier.addObject(download); - download.readRange(99999999L, 200); + assertThrows(IllegalArgumentException.class, () -> download.readRange(99999999L, 200)); } } @@ -215,30 +210,30 @@ public void readBeyondLength() throws IOException { } } - @Test(expected = IllegalArgumentException.class) + @Test public void readWithInvalidSizeAt0() throws IOException { try (RangeDownload download = new RangeDownloadHTTP(SAMPLE_URL, "", null)) { verifier.addObject(download); - download.readRange(0, 0); + assertThrows(IllegalArgumentException.class, () -> download.readRange(0, 0)); } } - @Test(expected = IllegalArgumentException.class) + @Test public void readWithInvalidSizeAt100() throws IOException { try (RangeDownload download = new RangeDownloadHTTP(SAMPLE_URL, "", null)) { verifier.addObject(download); - download.readRange(100, 0); + assertThrows(IllegalArgumentException.class, () -> download.readRange(100, 0)); } } - @Test(expected = IllegalArgumentException.class) + @Test public void readWithInvalidSizeAtMinus100() throws IOException { try (RangeDownload download = new RangeDownloadHTTP(SAMPLE_URL, "", null)) { verifier.addObject(download); - download.readRange(-100, 10); + assertThrows(IllegalArgumentException.class, () -> download.readRange(-100, 10)); } } } diff --git a/src/test/java/org/dstadler/audio/fm4/FM4CacheTest.java b/src/test/java/org/dstadler/audio/fm4/FM4CacheTest.java index 03b5728..f2c4938 100644 --- a/src/test/java/org/dstadler/audio/fm4/FM4CacheTest.java +++ b/src/test/java/org/dstadler/audio/fm4/FM4CacheTest.java @@ -5,9 +5,9 @@ import org.dstadler.commons.testing.MemoryLeakVerifier; import org.dstadler.commons.testing.ThreadTestHelper; import org.dstadler.commons.util.ExecutorUtil; -import org.junit.After; -import org.junit.Assume; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Collection; @@ -16,19 +16,14 @@ import java.util.stream.Collectors; import static org.dstadler.audio.fm4.FM4Stream.FM4_STREAM_URL_BASE; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class FM4CacheTest { private static final ObjectMapper objectMapper = new ObjectMapper(); private final MemoryLeakVerifier verifier = new MemoryLeakVerifier(); - @After + @AfterEach public void tearDown() throws InterruptedException { // ensure no threads are left ThreadTestHelper.waitForThreadToFinishSubstring("FM4", 1_000); @@ -44,12 +39,12 @@ public void testCache() { assertEquals(0, cache.size()); cache.refresh(); - assertTrue("Cache should not be empty now, check stdout for error messages while fetching the data", - cache.size() > 0); + assertTrue(cache.size() > 0, + "Cache should not be empty now, check stdout for error messages while fetching the data"); - assertTrue("Did not get FM4 session with code '4SS' or '4LB', having: " + - cache.allStreams().stream().map(FM4Stream::getProgramKey).collect(Collectors.joining(",")), - cache.get("4SS") != null || cache.get("4LB") != null); + assertTrue(cache.get("4SS") != null || cache.get("4LB") != null, + "Did not get FM4 session with code '4SS' or '4LB', having: " + + cache.allStreams().stream().map(FM4Stream::getProgramKey).collect(Collectors.joining(","))); assertNull(cache.get("NOT EXISTING")); assertNotNull(cache.allStreams()); @@ -109,8 +104,8 @@ public List fetchStreams(int days) throws IOException { Collection fm4Streams = cache.allStreams(); - Assume.assumeTrue("Expecting some streams, but had: " + cache.allStreams(), - cache.allStreams().size() >= 2); + Assumptions.assumeTrue(cache.allStreams().size() >= 2, + "Expecting some streams, but had: " + cache.allStreams()); Iterator it = fm4Streams.iterator(); @@ -123,15 +118,15 @@ public List fetchStreams(int days) throws IOException { assertNotNull(next); assertEquals(stream1.getProgramKey(), next.getProgramKey()); - assertNull("Stream 1 should be the last one, had: " + fm4Streams, - cache.getNext(stream1)); + assertNull(cache.getNext(stream1), + "Stream 1 should be the last one, had: " + fm4Streams); } else { FM4Stream next = cache.getNext(stream1); assertNotNull(next); assertEquals(stream2.getProgramKey(), next.getProgramKey()); - assertNull("Stream 2 should be the last one, had: " + fm4Streams, - cache.getNext(stream2)); + assertNull(cache.getNext(stream2), + "Stream 2 should be the last one, had: " + fm4Streams); } verifier.addObject(cache); @@ -181,8 +176,8 @@ public List fetchStreams(int days) throws IOException { Collection fm4Streams = cache.allStreams(); - Assume.assumeTrue("Expecting some streams, but had: " + cache.allStreams(), - cache.allStreams().size() >= 2); + Assumptions.assumeTrue(cache.allStreams().size() >= 2, + "Expecting some streams, but had: " + cache.allStreams()); Iterator it = fm4Streams.iterator(); @@ -195,15 +190,15 @@ public List fetchStreams(int days) throws IOException { assertNotNull(previous); assertEquals(stream1.getProgramKey(), previous.getProgramKey()); - assertNull("Stream 1 should be the first one, had: " + fm4Streams, - cache.getPrevious(stream1)); + assertNull(cache.getPrevious(stream1), + "Stream 1 should be the first one, had: " + fm4Streams); } else { FM4Stream previous = cache.getPrevious(stream1); assertNotNull(previous); assertEquals(stream2.getProgramKey(), previous.getProgramKey()); - assertNull("Stream 2 should be the first one, had: " + fm4Streams, - cache.getPrevious(stream2)); + assertNull(cache.getPrevious(stream2), + "Stream 2 should be the first one, had: " + fm4Streams); } verifier.addObject(cache); @@ -244,8 +239,8 @@ public List fetchStreams(int days) throws IOException { Collection fm4Streams = cache.allStreams(); - Assume.assumeTrue("Expecting some streams, but had: " + cache.allStreams(), - cache.allStreams().size() >= 2); + Assumptions.assumeTrue(cache.allStreams().size() >= 2, + "Expecting some streams, but had: " + cache.allStreams()); Iterator it = fm4Streams.iterator(); @@ -260,15 +255,15 @@ public List fetchStreams(int days) throws IOException { assertNotNull(next); assertEquals(stream1.getProgramKey(), next.getProgramKey()); - assertNull("Stream 1 should be the last one, had: " + fm4Streams, - cache.getNextByStreamURL(url1)); + assertNull(cache.getNextByStreamURL(url1), + "Stream 1 should be the last one, had: " + fm4Streams); } else { FM4Stream next = cache.getNextByStreamURL(url1); assertNotNull(next); assertEquals(stream2.getProgramKey(), next.getProgramKey()); - assertNull("Stream 2 should be the last one, had: " + fm4Streams, - cache.getNextByStreamURL(url2)); + assertNull(cache.getNextByStreamURL(url2), + "Stream 2 should be the last one, had: " + fm4Streams); } verifier.addObject(cache); @@ -301,8 +296,8 @@ public void testThread() throws InterruptedException { } // we should have the thread started now - assertNotNull("Need a thread names 'FM4Cache' to be running now", - ExecutorUtil.lookupThread("FM4Cache")); + assertNotNull(ExecutorUtil.lookupThread("FM4Cache"), + "Need a thread names 'FM4Cache' to be running now"); assertNotNull(cache); diff --git a/src/test/java/org/dstadler/audio/fm4/FM4StreamTest.java b/src/test/java/org/dstadler/audio/fm4/FM4StreamTest.java index 4d78839..8cfcd58 100644 --- a/src/test/java/org/dstadler/audio/fm4/FM4StreamTest.java +++ b/src/test/java/org/dstadler/audio/fm4/FM4StreamTest.java @@ -5,8 +5,8 @@ import org.apache.commons.lang3.time.DateFormatUtils; import org.apache.commons.lang3.time.FastDateFormat; import org.dstadler.commons.testing.TestHelpers; -import org.junit.Assume; -import org.junit.Test; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.text.ParseException; @@ -14,10 +14,7 @@ import static org.dstadler.audio.fm4.FM4Stream.DATETIME_FORMAT; import static org.dstadler.audio.fm4.FM4Stream.FM4_STREAM_URL_BASE; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class FM4StreamTest { public static long MIN_START_TIME; @@ -43,8 +40,8 @@ public void testFM4Stream() throws IOException, ParseException { assertNotNull(DATETIME_FORMAT.parse(fm4Stream.getTime())); assertNotNull(fm4Stream.getTimeForREST()); - assertTrue("Failed for " + fm4Stream.getTimeForREST(), - fm4Stream.getTimeForREST().matches("\\d{4}-\\d{2}-\\d{2}")); + assertTrue(fm4Stream.getTimeForREST().matches("\\d{4}-\\d{2}-\\d{2}"), + "Failed for " + fm4Stream.getTimeForREST()); String time = DateFormatUtils.ISO_8601_EXTENDED_DATE_FORMAT.format( FM4Stream.DATETIME_FORMAT.parse(fm4Stream.getTime())); @@ -63,17 +60,17 @@ public void testFM4Stream() throws IOException, ParseException { assertTrue(fm4Stream.getSummary().contains(fm4Stream.getTitle())); assertNotNull(fm4Stream.getShortTime()); - assertTrue("Failed for " + fm4Stream.getShortTime(), - fm4Stream.getShortTime().matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}")); + assertTrue(fm4Stream.getShortTime().matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}"), + "Failed for " + fm4Stream.getShortTime()); assertNotNull(DateFormatUtils.ISO_8601_EXTENDED_DATE_FORMAT.parse(fm4Stream.getShortTime())); - assertTrue("Duration should be set, but had: " + fm4Stream.getDuration(), - fm4Stream.getDuration() > 0); - assertTrue("Duration should be below one day, but had: " + fm4Stream.getDuration(), - fm4Stream.getDuration() < 24*60*60*1000); - assertTrue("Start should be set, but had: " + fm4Stream.getStart(), - fm4Stream.getStart() > 0); - assertTrue("Start should be after 2019, but had: " + fm4Stream.getStart(), - fm4Stream.getStart() > MIN_START_TIME); + assertTrue(fm4Stream.getDuration() > 0, + "Duration should be set, but had: " + fm4Stream.getDuration()); + assertTrue(fm4Stream.getDuration() < 24*60*60*1000, + "Duration should be below one day, but had: " + fm4Stream.getDuration()); + assertTrue(fm4Stream.getStart() > 0, + "Start should be set, but had: " + fm4Stream.getStart()); + assertTrue(fm4Stream.getStart() > MIN_START_TIME, + "Start should be after 2019, but had: " + fm4Stream.getStart()); assertNotNull(fm4Stream.toString()); @@ -85,7 +82,7 @@ public void testStreams() throws IOException { FM4 fm4 = new FM4(); List fm4Streams = fm4.fetchStreams(7); - Assume.assumeFalse("Should get some streams", fm4Streams.isEmpty()); + Assumptions.assumeFalse(fm4Streams.isEmpty(), "Should get some streams"); List streams = fm4Streams.get(0).getStreams(); diff --git a/src/test/java/org/dstadler/audio/fm4/FM4Test.java b/src/test/java/org/dstadler/audio/fm4/FM4Test.java index 7c84e1a..b35b3af 100644 --- a/src/test/java/org/dstadler/audio/fm4/FM4Test.java +++ b/src/test/java/org/dstadler/audio/fm4/FM4Test.java @@ -1,5 +1,6 @@ package org.dstadler.audio.fm4; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.io.FileUtils; @@ -17,8 +18,8 @@ import org.dstadler.commons.logging.jdk.LoggerFactory; import org.dstadler.commons.net.UrlUtils; import org.dstadler.commons.testing.MockRESTServer; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import java.io.ByteArrayOutputStream; import java.io.File; @@ -34,12 +35,7 @@ import java.util.logging.Logger; import static org.dstadler.audio.fm4.FM4Stream.FM4_STREAM_URL_BASE; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class FM4Test { private final static Logger log = LoggerFactory.make(); @@ -71,8 +67,8 @@ public void testFetchNoDuplicates() throws IOException { List fm4Streams = fm4.fetchStreams(14); Set seenStreams = new HashSet<>(); for (FM4Stream stream : fm4Streams) { - assertTrue("Had duplicate for " + stream, - seenStreams.add(stream.getShortTime())); + assertTrue(seenStreams.add(stream.getShortTime()), + "Had duplicate for " + stream); } } @@ -101,7 +97,7 @@ public void testFetchForDate() throws IOException, ParseException { } } - @Ignore("Fetches streams for all programs, this runs for some time, so disable for CI") + @Disabled("Fetches streams for all programs, this runs for some time, so disable for CI") @Test public void testFetchAllStreams() throws IOException { List fm4Streams = fm4.fetchStreams(14); @@ -147,7 +143,7 @@ public void testFilterEmpty() throws IOException { assertTrue(fm4Streams.isEmpty()); } - @Ignore("This starts an actual download and thus should not run for every CI run") + @Disabled("This starts an actual download and thus should not run for every CI run") @Test public void testDownloadStream() throws IOException { List fm4Streams = fm4.filterStreams("4MO"); @@ -172,7 +168,7 @@ public void testDownloadStream() throws IOException { // template for the download-url Stream with replace-url private static final String STREAM_JSON = "{\"href\":\"$url\"}"; - @Ignore("This test is not finished, we could not inject the stream-URL properly here...") + @Disabled("This test is not finished, we could not inject the stream-URL properly here...") @Test public void testDownloadStreamOtherURL() throws IOException { // Mock the URL-stream download content on a local REST Server @@ -192,10 +188,11 @@ public void testDownloadStreamOtherURL() throws IOException { } } - @Test(expected = UnknownHostException.class) - public void testDownloadStreamInvalidURL() throws IOException { + @Test + public void testDownloadStreamInvalidURL() throws JsonProcessingException { JsonNode jsonNode = objectMapper.readTree(JSON.replace("$url", "http://invalid/url")); - fm4.downloadStream(new FM4Stream(jsonNode, FM4_STREAM_URL_BASE), new File("/tmp")); + assertThrows(UnknownHostException.class, () -> + fm4.downloadStream(new FM4Stream(jsonNode, FM4_STREAM_URL_BASE), new File("/tmp"))); } @Test @@ -228,7 +225,7 @@ public void testNotFoundIsHTTP200PlusMessage() throws IOException { HexDump.dump(bytes, 0, stream, 0); log.info(stream.toString(StandardCharsets.UTF_8)); - assertEquals("Could not find any loopchannels", + assertEquals("Could not find any loop-channels", new String(bytes, 0, 31, StandardCharsets.UTF_8)); } finally { // ensure all content is taken out to free resources diff --git a/src/test/java/org/dstadler/audio/player/AudioSPIPlayerTest.java b/src/test/java/org/dstadler/audio/player/AudioSPIPlayerTest.java index f38ffc0..2d13c48 100644 --- a/src/test/java/org/dstadler/audio/player/AudioSPIPlayerTest.java +++ b/src/test/java/org/dstadler/audio/player/AudioSPIPlayerTest.java @@ -1,8 +1,8 @@ package org.dstadler.audio.player; import org.apache.commons.lang3.exception.ExceptionUtils; -import org.junit.Assume; -import org.junit.Test; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.File; @@ -10,6 +10,8 @@ import java.io.IOException; import java.io.InputStream; +import static org.junit.jupiter.api.Assertions.assertThrows; + public class AudioSPIPlayerTest { private static final File SAMPLE_FILE = new File("src/test/resources/1-second-of-silence.mp3"); @@ -32,7 +34,7 @@ public void testPlay() throws IOException { } } catch (IllegalArgumentException e) { if(ExceptionUtils.getStackTrace(e).contains("No line matching interface SourceDataLine supporting format")) { - Assume.assumeNoException("No audio-device available", e); + Assumptions.abort("No audio-device available\n" + ExceptionUtils.getStackTrace(e)); } throw e; @@ -50,10 +52,12 @@ public void testCloseTwice() throws IOException { } } - @Test(expected = IOException.class) - public void testException() throws IOException { - try (AudioSPIPlayer player = new AudioSPIPlayer(new ByteArrayInputStream("test".getBytes()))) { - player.setOptions("-0.1"); - } + @Test + public void testException() { + assertThrows(IOException.class, () -> { + try (AudioSPIPlayer player = new AudioSPIPlayer(new ByteArrayInputStream("test".getBytes()))) { + player.setOptions("-0.1"); + } + }); } } diff --git a/src/test/java/org/dstadler/audio/player/BufferBasedTempoStrategyTest.java b/src/test/java/org/dstadler/audio/player/BufferBasedTempoStrategyTest.java index 5503076..723b883 100644 --- a/src/test/java/org/dstadler/audio/player/BufferBasedTempoStrategyTest.java +++ b/src/test/java/org/dstadler/audio/player/BufferBasedTempoStrategyTest.java @@ -3,13 +3,13 @@ import org.dstadler.audio.buffer.BlockingSeekableRingBuffer; import org.dstadler.audio.buffer.CountingSeekableRingBuffer; import org.dstadler.audio.buffer.CountingSeekableRingBufferImpl; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.concurrent.atomic.AtomicInteger; import static org.dstadler.audio.player.BufferBasedTempoStrategy.DEFAULT_KEEP_AREA_SECONDS; import static org.dstadler.audio.player.BufferBasedTempoStrategy.DEFAULT_SPEED_STEP; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class BufferBasedTempoStrategyTest { private final AtomicInteger fill = new AtomicInteger(); @@ -196,8 +196,7 @@ public void testWithDifferentKeepArea() { try (CountingSeekableRingBuffer buffer = new TestBufferImpl()) { BufferBasedTempoStrategy strategy = new BufferBasedTempoStrategy(() -> buffer, 600, DEFAULT_SPEED_STEP); - assertEquals("With larger keep area we should not apply any change in tempo here and thus should get back 1.0f", - 1f, strategy.calculateTempo(), 0.01); + assertEquals(1f, strategy.calculateTempo(), 0.01, "With larger keep area we should not apply any change in tempo here and thus should get back 1.0f"); } } @@ -207,8 +206,7 @@ public void testWithDifferentSpeedStep() { try (CountingSeekableRingBuffer buffer = new TestBufferImpl()) { BufferBasedTempoStrategy strategy = new BufferBasedTempoStrategy(() -> buffer, DEFAULT_KEEP_AREA_SECONDS, 0.01f); - assertEquals("With smaller speedStep we should get back a smaller slowdown value of 0.99f instead of default 0.95f", - 0.99f, strategy.calculateTempo(), 0.01); + assertEquals(0.99f, strategy.calculateTempo(), 0.01, "With smaller speedStep we should get back a smaller slowdown value of 0.99f instead of default 0.95f"); } } diff --git a/src/test/java/org/dstadler/audio/player/ConstantTempoStrategyTest.java b/src/test/java/org/dstadler/audio/player/ConstantTempoStrategyTest.java index 446eb72..fac4aa2 100644 --- a/src/test/java/org/dstadler/audio/player/ConstantTempoStrategyTest.java +++ b/src/test/java/org/dstadler/audio/player/ConstantTempoStrategyTest.java @@ -1,8 +1,8 @@ package org.dstadler.audio.player; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class ConstantTempoStrategyTest { diff --git a/src/test/java/org/dstadler/audio/player/JLayerPlayerTest.java b/src/test/java/org/dstadler/audio/player/JLayerPlayerTest.java index 6f3178f..9a84c33 100644 --- a/src/test/java/org/dstadler/audio/player/JLayerPlayerTest.java +++ b/src/test/java/org/dstadler/audio/player/JLayerPlayerTest.java @@ -1,8 +1,8 @@ package org.dstadler.audio.player; import org.apache.commons.lang3.exception.ExceptionUtils; -import org.junit.Assume; -import org.junit.Test; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.File; @@ -22,7 +22,7 @@ public void testSetOption() throws IOException { player.setOptions("1.0"); } catch (IOException e) { if(ExceptionUtils.getStackTrace(e).contains("Cannot create AudioDevice")) { - Assume.assumeNoException("No audio-device available", e); + Assumptions.abort("No audio-device available\n" + ExceptionUtils.getStackTrace(e)); } throw e; @@ -37,7 +37,7 @@ public void testPlay() throws IOException { player.play(); } catch (IOException e) { if(ExceptionUtils.getStackTrace(e).contains("Cannot create AudioDevice")) { - Assume.assumeNoException("No audio-device available", e); + Assumptions.abort("No audio-device available\n" + ExceptionUtils.getStackTrace(e)); } throw e; @@ -54,7 +54,7 @@ public void testCloseTwice() throws IOException { player.close(); } catch (IOException e) { if(ExceptionUtils.getStackTrace(e).contains("Cannot create AudioDevice")) { - Assume.assumeNoException("No audio-device available", e); + Assumptions.abort("No audio-device available\n" + ExceptionUtils.getStackTrace(e)); } throw e; @@ -69,7 +69,7 @@ public void testException() throws IOException { player.play(); } catch (IOException e) { if(ExceptionUtils.getStackTrace(e).contains("Cannot create AudioDevice")) { - Assume.assumeNoException("No audio-device available", e); + Assumptions.abort(("No audio-device available\n" + ExceptionUtils.getStackTrace(e))); } throw e; diff --git a/src/test/java/org/dstadler/audio/player/TarsosDSPPlayerTest.java b/src/test/java/org/dstadler/audio/player/TarsosDSPPlayerTest.java index 70955c5..036bae7 100644 --- a/src/test/java/org/dstadler/audio/player/TarsosDSPPlayerTest.java +++ b/src/test/java/org/dstadler/audio/player/TarsosDSPPlayerTest.java @@ -1,8 +1,8 @@ package org.dstadler.audio.player; import org.apache.commons.lang3.exception.ExceptionUtils; -import org.junit.Assume; -import org.junit.Test; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; @@ -14,8 +14,8 @@ import java.io.IOException; import java.io.InputStream; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; public class TarsosDSPPlayerTest { private static final File SAMPLE_FILE = new File("src/test/resources/1-second-of-silence.mp3"); @@ -39,7 +39,7 @@ public void testPlay() throws IOException, UnsupportedAudioFileException { player.setOptions("1.5"); } catch (IllegalArgumentException e) { if(ExceptionUtils.getStackTrace(e).contains("No line matching interface SourceDataLine supporting format")) { - Assume.assumeNoException("No audio-device available", e); + Assumptions.abort("No audio-device available\n" + ExceptionUtils.getStackTrace(e)); } throw e; @@ -56,11 +56,13 @@ public void testCloseTwice() throws IOException { } } - @Test(expected = IllegalStateException.class) - public void testException() throws IOException { - try (TarsosDSPPlayer player = new TarsosDSPPlayer(new ByteArrayInputStream("test".getBytes()))) { - player.setOptions("-0.1"); - } + @Test + public void testException() { + assertThrows(IllegalStateException.class, () -> { + try (TarsosDSPPlayer player = new TarsosDSPPlayer(new ByteArrayInputStream("test".getBytes()))) { + player.setOptions("-0.1"); + } + }); } @Test diff --git a/src/test/java/org/dstadler/audio/player/TempoStrategyTest.java b/src/test/java/org/dstadler/audio/player/TempoStrategyTest.java index 7ef74b4..1364e83 100644 --- a/src/test/java/org/dstadler/audio/player/TempoStrategyTest.java +++ b/src/test/java/org/dstadler/audio/player/TempoStrategyTest.java @@ -1,8 +1,7 @@ package org.dstadler.audio.player; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import java.util.Arrays; import java.util.Collection; @@ -10,15 +9,9 @@ import static org.dstadler.audio.player.BufferBasedTempoStrategy.DEFAULT_KEEP_AREA_SECONDS; import static org.dstadler.audio.player.BufferBasedTempoStrategy.DEFAULT_SPEED_STEP; import static org.dstadler.audio.player.TempoStrategy.ADAPTIVE_PARAMS_PATTERN; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; -@RunWith(Parameterized.class) public class TempoStrategyTest { - @Parameterized.Parameters(name = "Tempo-Strategy: {0}, isValid: {1}, isFailing: {2}") public static Collection data() { return Arrays.asList(new Object[][] { // only the ones without param are 'valid' @@ -40,17 +33,9 @@ public static Collection data() { }); } - @Parameterized.Parameter - public String tempoStrategy; - - @Parameterized.Parameter(1) - public boolean isValid; - - @Parameterized.Parameter(2) - public boolean isFailing; - - @Test - public void testCreate() { + @MethodSource("data") + @ParameterizedTest(name = "Tempo-Strategy: {0}, isValid: {1}, isFailing: {2}") + public void testCreate(String tempoStrategy, boolean ignoredIsValid, boolean isFailing) { try { assertNotNull(TempoStrategy.create(tempoStrategy, null)); if (isFailing) { @@ -64,8 +49,9 @@ public void testCreate() { } } - @Test - public void testValidate() { + @MethodSource("data") + @ParameterizedTest(name = "Tempo-Strategy: {0}, isValid: {1}, isFailing: {2}") + public void testValidate(String tempoStrategy, boolean isValid, boolean ignoredIsFailing) { try { TempoStrategy.validate(tempoStrategy); if (!isValid) { @@ -79,33 +65,44 @@ public void testValidate() { } } - @Test(expected = NullPointerException.class) - public void testValidateNull() { - TempoStrategy.validate(null); + @MethodSource("data") + @ParameterizedTest(name = "Tempo-Strategy: {0}, isValid: {1}, isFailing: {2}") + public void testValidateNull(String ignoredTempoStrategy, boolean ignoredIsValid, boolean ignoredIsFailing) { + assertThrows(NullPointerException.class, () -> + TempoStrategy.validate(null)); } - @Test(expected = IllegalStateException.class) - public void testValidateEmpty() { - TempoStrategy.validate(""); + @MethodSource("data") + @ParameterizedTest(name = "Tempo-Strategy: {0}, isValid: {1}, isFailing: {2}") + public void testValidateEmpty(String ignoredTempoStrategy, boolean ignoredIsValid, boolean ignoredIsFailing) { + assertThrows(IllegalStateException.class, () -> + TempoStrategy.validate("")); } - @Test(expected = IllegalStateException.class) - public void testValidateInvalid() { - TempoStrategy.validate("unknown"); + @MethodSource("data") + @ParameterizedTest(name = "Tempo-Strategy: {0}, isValid: {1}, isFailing: {2}") + public void testValidateInvalid(String ignoredTempoStrategy, boolean ignoredIsValid, boolean ignoredIsFailing) { + assertThrows(IllegalStateException.class, () -> + TempoStrategy.validate("unknown")); } - @Test(expected = IllegalStateException.class) - public void testValidateInvalid2() { - TempoStrategy.validate(TempoStrategy.CONSTANT_PREFIX + "a.b"); + @MethodSource("data") + @ParameterizedTest(name = "Tempo-Strategy: {0}, isValid: {1}, isFailing: {2}") + public void testValidateInvalid2(String ignoredTempoStrategy, boolean ignoredIsValid, boolean ignoredIsFailing) { + assertThrows(IllegalStateException.class, () -> + TempoStrategy.validate(TempoStrategy.CONSTANT_PREFIX + "a.b")); } - @Test(expected = IllegalStateException.class) - public void testValidateInvalid3() { - TempoStrategy.validate(" constant"); + @MethodSource("data") + @ParameterizedTest(name = "Tempo-Strategy: {0}, isValid: {1}, isFailing: {2}") + public void testValidateInvalid3(String ignoredTempoStrategy, boolean ignoredIsValid, boolean ignoredIsFailing) { + assertThrows(IllegalStateException.class, () -> + TempoStrategy.validate(" constant")); } - @Test - public void testConstants() { + @MethodSource("data") + @ParameterizedTest(name = "Tempo-Strategy: {0}, isValid: {1}, isFailing: {2}") + public void testConstants(String ignoredTempoStrategy, boolean ignoredIsValid, boolean ignoredIsFailing) { assertEquals("constant", TempoStrategy.CONSTANT); assertEquals("constant:", TempoStrategy.CONSTANT_PREFIX); assertEquals("constant:1.0", TempoStrategy.CONSTANT_1); @@ -114,8 +111,9 @@ public void testConstants() { assertEquals(TempoStrategy.ADAPTIVE, new BufferBasedTempoStrategy(() -> null, DEFAULT_KEEP_AREA_SECONDS, DEFAULT_SPEED_STEP).name()); } - @Test - public void testAdaptiveParamsPattern() { + @MethodSource("data") + @ParameterizedTest(name = "Tempo-Strategy: {0}, isValid: {1}, isFailing: {2}") + public void testAdaptiveParamsPattern(String ignoredTempoStrategy, boolean ignoredIsValid, boolean ignoredIsFailing) { assertFalse(ADAPTIVE_PARAMS_PATTERN.matcher("").matches()); assertFalse(ADAPTIVE_PARAMS_PATTERN.matcher(":").matches()); assertFalse(ADAPTIVE_PARAMS_PATTERN.matcher("-12:2.123").matches()); diff --git a/src/test/java/org/dstadler/audio/stream/StreamTest.java b/src/test/java/org/dstadler/audio/stream/StreamTest.java index cd7f4de..14380cd 100644 --- a/src/test/java/org/dstadler/audio/stream/StreamTest.java +++ b/src/test/java/org/dstadler/audio/stream/StreamTest.java @@ -1,22 +1,18 @@ package org.dstadler.audio.stream; import org.apache.commons.io.FileUtils; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.commons.lang3.tuple.Pair; import org.dstadler.audio.player.TempoStrategy; import org.dstadler.commons.testing.TestHelpers; -import org.junit.Assume; -import org.junit.Test; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; import java.util.function.Function; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; public class StreamTest { @Test @@ -47,7 +43,7 @@ public void test() throws IOException { TestHelpers.ToStringTest(stream); assertEquals("url1", stream.getUrl()); - assertEquals("Always lowercase", "default", stream.getTempoStrategy()); + assertEquals("default", stream.getTempoStrategy(), "Always lowercase"); assertEquals(1, stream.getTempo(), 0); assertNull(stream.getImageUrl()); assertNull(stream.getName()); @@ -63,7 +59,7 @@ public void test() throws IOException { stream.setUser("test"); assertEquals("url1", stream.getUrl()); - assertEquals("Always lowercase", TempoStrategy.CONSTANT, stream.getTempoStrategy()); + assertEquals(TempoStrategy.CONSTANT, stream.getTempoStrategy(), "Always lowercase"); assertEquals(1, stream.getTempo(), 0); assertEquals("imageUrl", stream.getImageUrl()); assertEquals("name1", stream.getName()); @@ -74,7 +70,7 @@ public void test() throws IOException { stream.validate(); assertEquals("url1", stream.getUrl()); - assertEquals("Always lowercase", TempoStrategy.CONSTANT, stream.getTempoStrategy()); + assertEquals(TempoStrategy.CONSTANT, stream.getTempoStrategy(), "Always lowercase"); assertEquals(1, stream.getTempo(), 0); assertEquals("imageUrl", stream.getImageUrl()); assertEquals("name1", stream.getName()); @@ -119,16 +115,16 @@ public void testCredentials() { TestHelpers.ToStringTest(stream); } catch (IOException e) { - Assume.assumeNoException("Credentials file not available, cannot test for password", - e); + Assumptions.abort("Credentials file not available, cannot test for password\n" + + ExceptionUtils.getStackTrace(e)); } } @Test public void testCredentialsDummyFile() throws IOException { final File credentialsFile = new File("credentials.properties"); - Assume.assumeFalse("Can only run this test when no credentials.properties exists before", - credentialsFile.exists()); + Assumptions.assumeFalse(credentialsFile.exists(), + "Can only run this test when no credentials.properties exists before"); Stream stream = new Stream(); stream.setUser("someuser"); @@ -140,8 +136,7 @@ public void testCredentialsDummyFile() throws IOException { try { FileUtils.writeStringToFile(credentialsFile, "password.someuser=pass1", "UTF-8"); - assertEquals("Should be able to read password now", - "pass1", stream.getPassword()); + assertEquals("pass1", stream.getPassword(), "Should be able to read password now"); } finally { assertTrue(credentialsFile.delete()); } diff --git a/src/test/java/org/dstadler/audio/util/ClearablePipedInputStreamTest.java b/src/test/java/org/dstadler/audio/util/ClearablePipedInputStreamTest.java index e34e971..549c64c 100644 --- a/src/test/java/org/dstadler/audio/util/ClearablePipedInputStreamTest.java +++ b/src/test/java/org/dstadler/audio/util/ClearablePipedInputStreamTest.java @@ -5,8 +5,8 @@ import org.dstadler.commons.testing.TestHelpers; import org.dstadler.commons.testing.ThreadTestHelper; import org.dstadler.commons.util.ThreadDump; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.PipedOutputStream; @@ -15,10 +15,7 @@ import java.util.logging.Logger; import static org.dstadler.audio.buffer.Chunk.CHUNK_SIZE; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; public class ClearablePipedInputStreamTest { private final static Logger log = LoggerFactory.make(); @@ -26,7 +23,7 @@ public class ClearablePipedInputStreamTest { private final PipedOutputStream out = new PipedOutputStream(); private ClearablePipedInputStream in; - @Before + @BeforeEach public void setUp() throws IOException { in = new ClearablePipedInputStream(out, 5 * CHUNK_SIZE); } @@ -195,7 +192,7 @@ public void run() { stop.set(true); th.join(); - assertNull("Expected no exception, but had: " + exc.get(), - exc.get()); + assertNull(exc.get(), + "Expected no exception, but had: " + exc.get()); } } diff --git a/src/test/java/org/dstadler/audio/util/DataPipeTest.java b/src/test/java/org/dstadler/audio/util/DataPipeTest.java index 5214525..dd69aa6 100644 --- a/src/test/java/org/dstadler/audio/util/DataPipeTest.java +++ b/src/test/java/org/dstadler/audio/util/DataPipeTest.java @@ -5,13 +5,13 @@ import org.apache.commons.rng.simple.RandomSource; import org.dstadler.commons.testing.TestHelpers; import org.dstadler.commons.testing.ThreadTestHelper; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.concurrent.atomic.AtomicReference; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; @SuppressWarnings("BusyWait") public class DataPipeTest { @@ -20,7 +20,7 @@ public class DataPipeTest { private final AtomicReference exc = new AtomicReference<>(); private final AtomicReference lastWrite = new AtomicReference<>(System.currentTimeMillis()); - @After + @AfterEach public void tearDown() throws IOException { if (exc.get() != null) { throw exc.get(); @@ -131,8 +131,7 @@ public void testReadAndWrite() throws IOException, InterruptedException { Thread reader = new Thread(() -> { for (int i = 0; i < 100000; i++) { try { - assertEquals("Failed at index " + i, - i % 256, pipe.getInput().read()); + assertEquals(i % 256, pipe.getInput().read(), "Failed at index " + i); } catch (IOException e) { exc.set(e); } diff --git a/src/test/java/org/dstadler/audio/util/RuntimeInterruptedExceptionTest.java b/src/test/java/org/dstadler/audio/util/RuntimeInterruptedExceptionTest.java index 44cc14b..b9bee97 100644 --- a/src/test/java/org/dstadler/audio/util/RuntimeInterruptedExceptionTest.java +++ b/src/test/java/org/dstadler/audio/util/RuntimeInterruptedExceptionTest.java @@ -1,8 +1,8 @@ package org.dstadler.audio.util; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class RuntimeInterruptedExceptionTest { @Test