Upgrade to Junit5 (#1050)

* chore: Update to junit5 for servlet package

* chore: Update to junit5 for contrib package

* chore: Update to junit5 for common-image package

* chore: Update to junit5 for common-lang package

* chore: Update to junit5 for entire project files

* fix: test case for JPEGImageReaderTest failed for java 8 and 11

assertEquals was using old signature of junit4.

* Update common/common-io/src/test/java/com/twelvemonkeys/io/InputStreamAbstractTest.java

Co-authored-by: Harald Kuhr <harald.kuhr@gmail.com>

* Update common/common-io/src/test/java/com/twelvemonkeys/io/InputStreamAbstractTest.java

Co-authored-by: Harald Kuhr <harald.kuhr@gmail.com>

* Update imageio/imageio-bmp/src/test/java/com/twelvemonkeys/imageio/plugins/bmp/BMPImageReaderTest.java

Co-authored-by: Harald Kuhr <harald.kuhr@gmail.com>

* Update imageio/imageio-jpeg/src/test/java/com/twelvemonkeys/imageio/plugins/jpeg/JPEGImageReaderTest.java

Co-authored-by: Harald Kuhr <harald.kuhr@gmail.com>

* Update imageio/imageio-tiff/src/test/java/com/twelvemonkeys/imageio/plugins/tiff/TIFFImageMetadataTest.java

Co-authored-by: Harald Kuhr <harald.kuhr@gmail.com>

* Update imageio/imageio-tiff/src/test/java/com/twelvemonkeys/imageio/plugins/tiff/TIFFImageReaderTest.java

Co-authored-by: Harald Kuhr <harald.kuhr@gmail.com>

* Update imageio/imageio-tiff/src/test/java/com/twelvemonkeys/imageio/plugins/tiff/TIFFImageWriterTest.java

Co-authored-by: Harald Kuhr <harald.kuhr@gmail.com>

* Update imageio/imageio-core/src/test/java/com/twelvemonkeys/imageio/stream/BufferedChannelImageInputStreamTest.java

Co-authored-by: Harald Kuhr <harald.kuhr@gmail.com>

* Update imageio/imageio-core/src/test/java/com/twelvemonkeys/imageio/stream/BufferedChannelImageInputStreamTest.java

Co-authored-by: Harald Kuhr <harald.kuhr@gmail.com>

* refactor: few indentation changes and missed test case

- review change related to missing test annotation
- unwanted new lines inside test case
- duplicate assertions

* refactor: moved the lambda expression to method reference

* review: testNotNullWithParameterNull catch block was never executed.

Added the suggested change

* Apply suggestions from code review

chore: adjust suggested indentation

Co-authored-by: Harald Kuhr <harald.kuhr@gmail.com>

* Update imageio/imageio-core/src/test/java/com/twelvemonkeys/imageio/util/ImageReaderAbstractTest.java

Co-authored-by: Harald Kuhr <harald.kuhr@gmail.com>

* Update imageio/imageio-core/src/test/java/com/twelvemonkeys/imageio/util/ImageReaderAbstractTest.java

Co-authored-by: Harald Kuhr <harald.kuhr@gmail.com>

* Update imageio/imageio-core/src/test/java/com/twelvemonkeys/imageio/util/ImageWriterAbstractTest.java

Co-authored-by: Harald Kuhr <harald.kuhr@gmail.com>

* refactor: using assertTimeout doesnot kill the execution, even if the timeout happens.

It is better to use assertTimeoutPreemptively in cases, where we really want to kill the execution after timeout.
https://stackoverflow.com/questions/57116801/how-to-fail-a-test-after-a-timeout-is-exceeded-in-junit-5/57116959#57116959

---------

Co-authored-by: Harald Kuhr <harald.kuhr@gmail.com>
This commit is contained in:
Vyshak Puthusseri
2024-11-12 14:43:15 +05:30
committed by GitHub
parent a67fdd4b80
commit 543acce8a3
194 changed files with 2554 additions and 3086 deletions
@@ -31,9 +31,7 @@
package com.twelvemonkeys.image; package com.twelvemonkeys.image;
import static java.lang.Math.min; import static java.lang.Math.min;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.*;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import java.awt.color.ColorSpace; import java.awt.color.ColorSpace;
import java.awt.geom.AffineTransform; import java.awt.geom.AffineTransform;
@@ -49,7 +47,7 @@ import java.util.List;
import javax.imageio.ImageTypeSpecifier; import javax.imageio.ImageTypeSpecifier;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* AffineTransformOpTest. * AffineTransformOpTest.
@@ -146,12 +144,12 @@ public class AffineTransformOpTest {
BufferedImage jreResult = jreOp.filter(image, null); BufferedImage jreResult = jreOp.filter(image, null);
BufferedImage tmResult = tmOp.filter(image, null); BufferedImage tmResult = tmOp.filter(image, null);
assertNotNull("No result!", tmResult); assertNotNull(tmResult, "No result!");
assertEquals("Bad type", jreResult.getType(), tmResult.getType()); assertEquals(jreResult.getType(), tmResult.getType(), "Bad type");
assertEquals("Incorrect color model", jreResult.getColorModel(), tmResult.getColorModel()); assertEquals(jreResult.getColorModel(), tmResult.getColorModel(), "Incorrect color model");
assertEquals("Incorrect width", jreResult.getWidth(), tmResult.getWidth()); assertEquals(jreResult.getWidth(), tmResult.getWidth(), "Incorrect width");
assertEquals("Incorrect height", jreResult.getHeight(), tmResult.getHeight()); assertEquals(jreResult.getHeight(), tmResult.getHeight(), "Incorrect height");
} }
} }
@@ -164,7 +162,7 @@ public class AffineTransformOpTest {
BufferedImage image = spec.createBufferedImage(width, height); BufferedImage image = spec.createBufferedImage(width, height);
BufferedImage tmResult = tmOp.filter(image, null); BufferedImage tmResult = tmOp.filter(image, null);
assertNotNull("No result!", tmResult); assertNotNull(tmResult, "No result!");
BufferedImage jreResult = null; BufferedImage jreResult = null;
@@ -176,18 +174,18 @@ public class AffineTransformOpTest {
} }
if (jreResult != null) { if (jreResult != null) {
assertEquals("Bad type", jreResult.getType(), tmResult.getType()); assertEquals(jreResult.getType(), tmResult.getType(), "Bad type");
assertEquals("Incorrect color model", jreResult.getColorModel(), tmResult.getColorModel()); assertEquals(jreResult.getColorModel(), tmResult.getColorModel(), "Incorrect color model");
assertEquals("Incorrect width", jreResult.getWidth(), tmResult.getWidth()); assertEquals(jreResult.getWidth(), tmResult.getWidth(), "Incorrect width");
assertEquals("Incorrect height", jreResult.getHeight(), tmResult.getHeight()); assertEquals(jreResult.getHeight(), tmResult.getHeight(), "Incorrect height");
} }
else { else {
assertEquals("Bad type", spec.getBufferedImageType(), tmResult.getType()); assertEquals(spec.getBufferedImageType(), tmResult.getType(), "Bad type");
assertEquals("Incorrect color model", spec.getColorModel(), tmResult.getColorModel()); assertEquals(spec.getColorModel(), tmResult.getColorModel(), "Incorrect color model");
assertEquals("Incorrect width", height, tmResult.getWidth()); assertEquals(height, tmResult.getWidth(), "Incorrect width");
assertEquals("Incorrect height", width, tmResult.getHeight()); assertEquals(width, tmResult.getHeight(), "Incorrect height");
} }
} }
} }
@@ -236,12 +234,12 @@ public class AffineTransformOpTest {
} }
if (jreResult != null) { if (jreResult != null) {
assertEquals("Incorrect width", jreResult.getWidth(), tmResult.getWidth()); assertEquals(jreResult.getWidth(), tmResult.getWidth(), "Incorrect width");
assertEquals("Incorrect height", jreResult.getHeight(), tmResult.getHeight()); assertEquals(jreResult.getHeight(), tmResult.getHeight(), "Incorrect height");
} }
else { else {
assertEquals("Incorrect width", height, tmResult.getWidth()); assertEquals(height, tmResult.getWidth(), "Incorrect width");
assertEquals("Incorrect height", width, tmResult.getHeight()); assertEquals(width, tmResult.getHeight(), "Incorrect height");
} }
} }
} }
@@ -277,12 +275,12 @@ public class AffineTransformOpTest {
} }
if (jreResult != null) { if (jreResult != null) {
assertEquals("Incorrect width", jreResult.getWidth(), tmResult.getWidth()); assertEquals(jreResult.getWidth(), tmResult.getWidth(), "Incorrect width");
assertEquals("Incorrect height", jreResult.getHeight(), tmResult.getHeight()); assertEquals(jreResult.getHeight(), tmResult.getHeight(), "Incorrect height");
} }
else { else {
assertEquals("Incorrect width", height, tmResult.getWidth()); assertEquals(height, tmResult.getWidth(), "Incorrect width");
assertEquals("Incorrect height", width, tmResult.getHeight()); assertEquals(width, tmResult.getHeight(), "Incorrect height");
} }
} }
} }
@@ -30,17 +30,16 @@
package com.twelvemonkeys.image; package com.twelvemonkeys.image;
import org.junit.Ignore; import org.junit.jupiter.api.Disabled;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.awt.*; import java.awt.*;
import java.awt.color.*; import java.awt.color.*;
import java.awt.image.*; import java.awt.image.*;
import java.net.URL; import java.net.URL;
import java.time.Duration;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.*;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/** /**
* BufferedImageFactoryTestCase * BufferedImageFactoryTestCase
@@ -50,50 +49,58 @@ import static org.junit.Assert.assertTrue;
* @version $Id: BufferedImageFactoryTestCase.java,v 1.0 May 7, 2010 12:40:08 PM haraldk Exp$ * @version $Id: BufferedImageFactoryTestCase.java,v 1.0 May 7, 2010 12:40:08 PM haraldk Exp$
*/ */
public class BufferedImageFactoryTest { public class BufferedImageFactoryTest {
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateNullImage() { public void testCreateNullImage() {
assertThrows(IllegalArgumentException.class, () -> {
new BufferedImageFactory((Image) null); new BufferedImageFactory((Image) null);
});
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateNullProducer() { public void testCreateNullProducer() {
assertThrows(IllegalArgumentException.class, () -> {
new BufferedImageFactory((ImageProducer) null); new BufferedImageFactory((ImageProducer) null);
});
} }
// NPE in Toolkit, ok // NPE in Toolkit, ok
@Test(expected = RuntimeException.class) @Test
public void testGetBufferedImageErrorSourceByteArray() { public void testGetBufferedImageErrorSourceByteArray() {
assertThrows(RuntimeException.class, () -> {
Image source = Toolkit.getDefaultToolkit().createImage((byte[]) null); Image source = Toolkit.getDefaultToolkit().createImage((byte[]) null);
new BufferedImageFactory(source); new BufferedImageFactory(source);
});
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testGetBufferedImageErrorSourceImageProducer() { public void testGetBufferedImageErrorSourceImageProducer() {
Image source = Toolkit.getDefaultToolkit().createImage((ImageProducer) null); Image source = Toolkit.getDefaultToolkit().createImage((ImageProducer) null);
assertThrows(IllegalArgumentException.class, () -> {
new BufferedImageFactory(source); new BufferedImageFactory(source);
});
} }
// TODO: This is a quite serious bug, however, the bug is in the Toolkit, allowing such images in the first place... // TODO: This is a quite serious bug, however, the bug is in the Toolkit, allowing such images in the first place...
// In any case, there's not much we can do, except until someone is bored and kills the app/thread... :-P // In any case, there's not much we can do, except until someone is bored and kills the app/thread... :-P
@Ignore("Bug in Toolkit") @Disabled("Bug in Toolkit")
@Test(timeout = 1000, expected = ImageConversionException.class) @Test
public void testGetBufferedImageErrorSourceString() { public void testGetBufferedImageErrorSourceString() {
assertTimeoutPreemptively(Duration.ofMillis(1000), () -> {
Image source = Toolkit.getDefaultToolkit().createImage((String) null); Image source = Toolkit.getDefaultToolkit().createImage((String) null);
BufferedImageFactory factory = new BufferedImageFactory(source); BufferedImageFactory factory = new BufferedImageFactory(source);
factory.getBufferedImage(); assertThrows(ImageConversionException.class, factory::getBufferedImage);
});
} }
// This is a little random, and it would be nicer if we could throw an IllegalArgumentException on create. // This is a little random, and it would be nicer if we could throw an IllegalArgumentException on create.
// Unfortunately, the API doesn't allow this... // Unfortunately, the API doesn't allow this...
@Test(timeout = 1000, expected = ImageConversionException.class) @Test
public void testGetBufferedImageErrorSourceURL() { public void testGetBufferedImageErrorSourceURL() {
Image source = Toolkit.getDefaultToolkit().createImage(getClass().getResource("/META-INF/MANIFEST.MF")); assertTimeoutPreemptively(Duration.ofMillis(1000), () -> {
Image source = Toolkit.getDefaultToolkit().createImage((String) null);
BufferedImageFactory factory = new BufferedImageFactory(source); BufferedImageFactory factory = new BufferedImageFactory(source);
factory.getBufferedImage(); assertThrows(ImageConversionException.class, factory::getBufferedImage);
});
} }
@Test @Test
@@ -165,7 +172,7 @@ public class BufferedImageFactoryTest {
assertEquals(3, colorModel.getNumColorComponents()); assertEquals(3, colorModel.getNumColorComponents());
assertEquals(ColorSpace.getInstance(ColorSpace.CS_sRGB), colorModel.getColorSpace()); assertEquals(ColorSpace.getInstance(ColorSpace.CS_sRGB), colorModel.getColorSpace());
assertTrue(colorModel instanceof IndexColorModel); assertInstanceOf(IndexColorModel.class, colorModel);
assertTrue(colorModel.hasAlpha()); assertTrue(colorModel.hasAlpha());
assertEquals(4, colorModel.getNumComponents()); assertEquals(4, colorModel.getNumComponents());
@@ -196,7 +203,7 @@ public class BufferedImageFactoryTest {
for (int y = 0; y < image.getHeight(); y++) { for (int y = 0; y < image.getHeight(); y++) {
for (int x = 0; x < image.getWidth(); x++) { for (int x = 0; x < image.getWidth(); x++) {
assertEquals("RGB[" + x + ", " + y + "]", original.getRGB(x * 2, y * 2), image.getRGB(x, y)); assertEquals(original.getRGB(x * 2, y * 2), image.getRGB(x, y), "RGB[" + x + ", " + y + "]");
} }
} }
} }
@@ -219,7 +226,7 @@ public class BufferedImageFactoryTest {
for (int y = 0; y < image.getHeight(); y++) { for (int y = 0; y < image.getHeight(); y++) {
for (int x = 0; x < image.getWidth(); x++) { for (int x = 0; x < image.getWidth(); x++) {
assertEquals("RGB[" + x + ", " + y + "]", original.getRGB(40 + x, 40 + y), image.getRGB(x, y)); assertEquals(original.getRGB(40 + x, 40 + y), image.getRGB(x, y), "RGB[" + x + ", " + y + "]");
} }
} }
} }
@@ -243,7 +250,7 @@ public class BufferedImageFactoryTest {
for (int y = 0; y < image.getHeight(); y++) { for (int y = 0; y < image.getHeight(); y++) {
for (int x = 0; x < image.getWidth(); x++) { for (int x = 0; x < image.getWidth(); x++) {
assertEquals("RGB[" + x + ", " + y + "]", original.getRGB(40 + x * 2, 40 + y * 2), image.getRGB(x, y)); assertEquals(original.getRGB(40 + x * 2, 40 + y * 2), image.getRGB(x, y), "RGB[" + x + ", " + y + "]");
} }
} }
} }
@@ -30,7 +30,7 @@
package com.twelvemonkeys.image; package com.twelvemonkeys.image;
import org.junit.Test; import org.junit.jupiter.api.Test;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import java.awt.*; import java.awt.*;
@@ -39,7 +39,7 @@ import java.awt.image.IndexColorModel;
import java.awt.image.RenderedImage; import java.awt.image.RenderedImage;
import java.io.InputStream; import java.io.InputStream;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
public class ImageUtilTest { public class ImageUtilTest {
@@ -116,8 +116,8 @@ public class ImageUtilTest {
public void testImageIsNotBufferedImage() { public void testImageIsNotBufferedImage() {
// Should not be a buffered image // Should not be a buffered image
assertFalse( assertFalse(
"FOR SOME IMPLEMENTATIONS THIS MIGHT FAIL!\nIn that case, testToBufferedImage() will fail too.", scaled instanceof BufferedImage,
scaled instanceof BufferedImage "FOR SOME IMPLEMENTATIONS THIS MIGHT FAIL!\nIn that case, testToBufferedImage() will fail too."
); );
} }
@@ -247,7 +247,7 @@ public class ImageUtilTest {
if (original != notContrasted) { // Don't care to test if images are same if (original != notContrasted) { // Don't care to test if images are same
for (int y = 0; y < original.getHeight(); y++) { for (int y = 0; y < original.getHeight(); y++) {
for (int x = 0; x < original.getWidth(); x++) { for (int x = 0; x < original.getWidth(); x++) {
assertEquals("0 constrast should not change image", original.getRGB(x, y), notContrasted.getRGB(x, y)); assertEquals(original.getRGB(x, y), notContrasted.getRGB(x, y), "0 constrast should not change image");
} }
} }
} }
@@ -275,24 +275,24 @@ public class ImageUtilTest {
// RED // RED
if (oR < 127) { if (oR < 127) {
assertTrue("Contrast should be decreased or same", oR >= cR && cR >= dR); assertTrue(oR >= cR && cR >= dR, "Contrast should be decreased or same");
} }
else { else {
assertTrue("Contrast should be increased or same", oR <= cR && cR <= dR); assertTrue(oR <= cR && cR <= dR, "Contrast should be increased or same");
} }
// GREEN // GREEN
if (oG < 127) { if (oG < 127) {
assertTrue("Contrast should be decreased or same", oG >= cG && cG >= dG); assertTrue(oG >= cG && cG >= dG, "Contrast should be decreased or same");
} }
else { else {
assertTrue("Contrast should be increased or same", oG <= cG && cG <= dG); assertTrue(oG <= cG && cG <= dG, "Contrast should be increased or same");
} }
// BLUE // BLUE
if (oB < 127) { if (oB < 127) {
assertTrue("Contrast should be decreased or same", oB >= cB && cB >= dB); assertTrue(oB >= cB && cB >= dB, "Contrast should be decreased or same");
} }
else { else {
assertTrue("Contrast should be increased or same", oB <= cB && cB <= dB); assertTrue(oB <= cB && cB <= dB, "Contrast should be increased or same");
} }
} }
} }
@@ -304,9 +304,9 @@ public class ImageUtilTest {
int r = rgb >> 16 & 0xFF; int r = rgb >> 16 & 0xFF;
int g = rgb >> 8 & 0xFF; int g = rgb >> 8 & 0xFF;
int b = rgb & 0xFF; int b = rgb & 0xFF;
assertTrue("Max contrast should only produce primary colors", r == 0 || r == 255); assertTrue(r == 0 || r == 255, "Max contrast should only produce primary colors");
assertTrue("Max contrast should only produce primary colors", g == 0 || g == 255); assertTrue(g == 0 || g == 255, "Max contrast should only produce primary colors");
assertTrue("Max contrast should only produce primary colors", b == 0 || b == 255); assertTrue(b == 0 || b == 255, "Max contrast should only produce primary colors");
} }
} }
@@ -327,24 +327,24 @@ public class ImageUtilTest {
// RED // RED
if (oR >= 127) { if (oR >= 127) {
assertTrue("Contrast should be decreased or same", oR >= cR); assertTrue(oR >= cR, "Contrast should be decreased or same");
} }
else { else {
assertTrue("Contrast should be increased or same", oR <= cR); assertTrue(oR <= cR, "Contrast should be increased or same");
} }
// GREEN // GREEN
if (oG >= 127) { if (oG >= 127) {
assertTrue("Contrast should be decreased or same", oG >= cG); assertTrue(oG >= cG, "Contrast should be decreased or same");
} }
else { else {
assertTrue("Contrast should be increased or same", oG <= cG); assertTrue(oG <= cG, "Contrast should be increased or same");
} }
// BLUE // BLUE
if (oB >= 127) { if (oB >= 127) {
assertTrue("Contrast should be decreased or same", oB >= cB); assertTrue(oB >= cB, "Contrast should be decreased or same");
} }
else { else {
assertTrue("Contrast should be increased or same", oB <= cB); assertTrue(oB <= cB, "Contrast should be increased or same");
} }
} }
} }
@@ -357,7 +357,7 @@ public class ImageUtilTest {
int r = rgb >> 16 & 0xFF; int r = rgb >> 16 & 0xFF;
int g = rgb >> 8 & 0xFF; int g = rgb >> 8 & 0xFF;
int b = rgb & 0xFF; int b = rgb & 0xFF;
assertTrue("Minimum contrast should be all gray", r == 127 && g == 127 && b == 127); assertTrue(r == 127 && g == 127 && b == 127, "Minimum contrast should be all gray");
} }
} }
@@ -400,7 +400,7 @@ public class ImageUtilTest {
if (original != notSharpened) { // Don't care to test if images are same if (original != notSharpened) { // Don't care to test if images are same
for (int y = 0; y < original.getHeight(); y++) { for (int y = 0; y < original.getHeight(); y++) {
for (int x = 0; x < original.getWidth(); x++) { for (int x = 0; x < original.getWidth(); x++) {
assertEquals("0 sharpen should not change image", original.getRGB(x, y), notSharpened.getRGB(x, y)); assertEquals(original.getRGB(x, y), notSharpened.getRGB(x, y), "0 sharpen should not change image");
} }
} }
} }
@@ -446,13 +446,13 @@ public class ImageUtilTest {
} }
// assertEquals("Difference should not change", diffOriginal, diffSharpened); // assertEquals("Difference should not change", diffOriginal, diffSharpened);
assertTrue("Abs difference should increase", absDiffOriginal < absDiffSharpened); assertTrue(absDiffOriginal < absDiffSharpened, "Abs difference should increase");
// assertEquals("Difference should not change", diffOriginal, diffDefault); // assertEquals("Difference should not change", diffOriginal, diffDefault);
assertTrue("Abs difference should increase", absDiffOriginal < absDiffDefault); assertTrue(absDiffOriginal < absDiffDefault, "Abs difference should increase");
// assertEquals("Difference should not change", diffOriginal, diffMore); // assertEquals("Difference should not change", diffOriginal, diffMore);
assertTrue("Abs difference should increase", absDiffOriginal < absDiffMore); assertTrue(absDiffOriginal < absDiffMore, "Abs difference should increase");
// assertEquals("Difference should not change", diffSharpened, diffMore); // assertEquals("Difference should not change", diffSharpened, diffMore);
assertTrue("Abs difference should increase", absDiffSharpened < absDiffMore); assertTrue(absDiffSharpened < absDiffMore, "Abs difference should increase");
} }
@Test @Test
@@ -466,7 +466,7 @@ public class ImageUtilTest {
if (original != notBlurred) { // Don't care to test if images are same if (original != notBlurred) { // Don't care to test if images are same
for (int y = 0; y < original.getHeight(); y++) { for (int y = 0; y < original.getHeight(); y++) {
for (int x = 0; x < original.getWidth(); x++) { for (int x = 0; x < original.getWidth(); x++) {
assertEquals("0 blur should not change image", original.getRGB(x, y), notBlurred.getRGB(x, y)); assertEquals(original.getRGB(x, y), notBlurred.getRGB(x, y), "0 blur should not change image");
} }
} }
} }
@@ -512,13 +512,13 @@ public class ImageUtilTest {
} }
// assertEquals("Difference should not change", diffOriginal, diffBlurred); // assertEquals("Difference should not change", diffOriginal, diffBlurred);
assertTrue(String.format("Abs difference should decrease: %s <= %s", absDiffOriginal, absDiffBlurred), absDiffOriginal > absDiffBlurred); assertTrue(absDiffOriginal > absDiffBlurred, String.format("Abs difference should decrease: %s <= %s", absDiffOriginal, absDiffBlurred));
// assertEquals("Difference should not change", diffOriginal, diffDefault); // assertEquals("Difference should not change", diffOriginal, diffDefault);
assertTrue("Abs difference should decrease", absDiffOriginal > absDiffDefault); assertTrue(absDiffOriginal > absDiffDefault, "Abs difference should decrease");
// assertEquals("Difference should not change", diffOriginal, diffMore); // assertEquals("Difference should not change", diffOriginal, diffMore);
assertTrue("Abs difference should decrease", absDiffOriginal > absDiffMore); assertTrue(absDiffOriginal > absDiffMore, "Abs difference should decrease");
// assertEquals("Difference should not change", diffBlurred, diffMore); // assertEquals("Difference should not change", diffBlurred, diffMore);
assertTrue("Abs difference should decrease", absDiffBlurred > absDiffMore); assertTrue(absDiffBlurred > absDiffMore, "Abs difference should decrease");
} }
@Test @Test
@@ -528,7 +528,7 @@ public class ImageUtilTest {
assertNotNull(sunflower); assertNotNull(sunflower);
BufferedImage image = ImageUtil.createIndexed(sunflower); BufferedImage image = ImageUtil.createIndexed(sunflower);
assertNotNull("Image was null", image); assertNotNull(image, "Image was null");
assertTrue(image.getColorModel() instanceof IndexColorModel); assertInstanceOf(IndexColorModel.class, image.getColorModel());
} }
} }
@@ -30,8 +30,8 @@
package com.twelvemonkeys.image; package com.twelvemonkeys.image;
import org.junit.Ignore; import org.junit.jupiter.api.Disabled;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.awt.*; import java.awt.*;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
@@ -40,7 +40,7 @@ import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
/** /**
* ResampleOpTestCase * ResampleOpTestCase
@@ -124,7 +124,7 @@ public class ResampleOpTest {
} }
} }
assertEquals("Filter threw exceptions: ", Collections.EMPTY_LIST, exceptions); assertEquals(Collections.EMPTY_LIST, exceptions, "Filter threw exceptions: ");
} }
// 1x1 // 1x1
@@ -358,7 +358,7 @@ public class ResampleOpTest {
} }
} }
@Ignore("Not for general unit testing") @Disabled("Not for general unit testing")
@Test @Test
public void testTime() { public void testTime() {
int iterations = 1000; int iterations = 1000;
@@ -32,7 +32,6 @@ package com.twelvemonkeys.io;
import com.twelvemonkeys.lang.StringUtil; import com.twelvemonkeys.lang.StringUtil;
import com.twelvemonkeys.util.CollectionUtil; import com.twelvemonkeys.util.CollectionUtil;
import org.junit.Test;
import java.io.IOException; import java.io.IOException;
import java.io.Reader; import java.io.Reader;
@@ -40,7 +39,8 @@ import java.io.StringReader;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import static org.junit.Assert.*; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* CompoundReaderTestCase * CompoundReaderTestCase
@@ -30,12 +30,11 @@
package com.twelvemonkeys.io; package com.twelvemonkeys.io;
import org.junit.Test;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import static org.junit.Assert.assertEquals; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* FastByteArrayOutputStreamTestCase * FastByteArrayOutputStreamTestCase
@@ -30,11 +30,10 @@
package com.twelvemonkeys.io; package com.twelvemonkeys.io;
import org.junit.Test;
import java.io.*; import java.io.*;
import static org.junit.Assert.*; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* MemoryCacheSeekableStreamTestCase * MemoryCacheSeekableStreamTestCase
@@ -92,13 +91,13 @@ public class FileSeekableStreamTest extends SeekableInputStreamAbstractTest {
try { try {
FileUtil.read(stream); // Read until EOF FileUtil.read(stream); // Read until EOF
assertEquals("EOF not reached (test case broken)", -1, stream.read()); assertEquals(-1, stream.read(), "EOF not reached (test case broken)");
assertFalse("Underlying stream closed before close", closed[0]); assertFalse(closed[0], "Underlying stream closed before close");
} }
finally { finally {
stream.close(); stream.close();
} }
assertTrue("Underlying stream not closed", closed[0]); assertTrue(closed[0], "Underlying stream not closed");
} }
} }
@@ -46,14 +46,14 @@
package com.twelvemonkeys.io; package com.twelvemonkeys.io;
import com.twelvemonkeys.lang.ObjectAbstractTest; import com.twelvemonkeys.lang.ObjectAbstractTest;
import org.junit.Test;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.Random; import java.util.Random;
import static org.junit.Assert.*; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* InputStreamAbstractTestCase * InputStreamAbstractTestCase
@@ -104,15 +104,15 @@ public abstract class InputStreamAbstractTest extends ObjectAbstractTest {
int size = 5; int size = 5;
InputStream input = makeInputStream(makeOrderedArray(size)); InputStream input = makeInputStream(makeOrderedArray(size));
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
assertTrue("Check Size [" + i + "]", (size - i) >= input.available()); assertTrue((size - i) >= input.available(), "Check Size [" + i + "]");
assertEquals("Check Value [" + i + "]", i, input.read()); assertEquals(i, input.read(), "Check Value [" + i + "]");
} }
assertEquals("Available after contents all read", 0, input.available()); assertEquals(0, input.available(), "Available after contents all read");
// Test reading after the end of file // Test reading after the end of file
try { try {
int result = input.read(); int result = input.read();
assertEquals("Wrong value read after end of file", -1, result); assertEquals( -1, result, "Wrong value read after end of file");
} }
catch (IOException e) { catch (IOException e) {
fail("Should not have thrown an IOException: " + e.getMessage()); fail("Should not have thrown an IOException: " + e.getMessage());
@@ -122,12 +122,12 @@ public abstract class InputStreamAbstractTest extends ObjectAbstractTest {
@Test @Test
public void testAvailable() throws Exception { public void testAvailable() throws Exception {
InputStream input = makeInputStream(1); InputStream input = makeInputStream(1);
assertFalse("Unexpected EOF", input.read() < 0); assertFalse(input.read() < 0, "Unexpected EOF");
assertEquals("Available after contents all read", 0, input.available()); assertEquals(0, input.available(), "Available after contents all read");
// Check availbale is zero after End of file // Check availbale is zero after End of file
assertEquals("End of File", -1, input.read()); assertEquals(-1, input.read(), "End of File");
assertEquals("Available after End of File", 0, input.available()); assertEquals( 0, input.available(), "Available after End of File");
} }
@Test @Test
@@ -138,26 +138,26 @@ public abstract class InputStreamAbstractTest extends ObjectAbstractTest {
// Read into array // Read into array
int count1 = input.read(bytes); int count1 = input.read(bytes);
assertEquals("Read 1", bytes.length, count1); assertEquals(bytes.length, count1, "Read 1");
for (int i = 0; i < count1; i++) { for (int i = 0; i < count1; i++) {
assertEquals("Check Bytes 1", i, bytes[i]); assertEquals(i, bytes[i], "Check Bytes 1");
} }
// Read into array // Read into array
int count2 = input.read(bytes); int count2 = input.read(bytes);
assertEquals("Read 2", 5, count2); assertEquals(5, count2, "Read 2");
for (int i = 0; i < count2; i++) { for (int i = 0; i < count2; i++) {
assertEquals("Check Bytes 2", count1 + i, bytes[i]); assertEquals(count1 + i, bytes[i], "Check Bytes 2");
} }
// End of File // End of File
int count3 = input.read(bytes); int count3 = input.read(bytes);
assertEquals("Read 3 (EOF)", -1, count3); assertEquals(-1, count3, "Read 3 (EOF)");
// Test reading after the end of file // Test reading after the end of file
try { try {
int result = input.read(bytes); int result = input.read(bytes);
assertEquals("Wrong value read after end of file", -1, result); assertEquals(-1, result, "Wrong value read after end of file");
} }
catch (IOException e) { catch (IOException e) {
fail("Should not have thrown an IOException: " + e.getMessage()); fail("Should not have thrown an IOException: " + e.getMessage());
@@ -170,20 +170,20 @@ public abstract class InputStreamAbstractTest extends ObjectAbstractTest {
int offset = 2; int offset = 2;
int lth = 4; int lth = 4;
int count5 = input.read(bytes, offset, lth); int count5 = input.read(bytes, offset, lth);
assertEquals("Read 5", lth, count5); assertEquals(lth, count5, "Read 5");
for (int i = offset; i < lth; i++) { for (int i = offset; i < lth; i++) {
assertEquals("Check Bytes 2", i - offset, bytes[i]); assertEquals(i - offset, bytes[i], "Check Bytes 2");
} }
} }
@Test @Test
public void testEOF() throws Exception { public void testEOF() throws Exception {
InputStream input = makeInputStream(makeOrderedArray(2)); InputStream input = makeInputStream(makeOrderedArray(2));
assertEquals("Read 1", 0, input.read()); assertEquals(0, input.read(), "Read 1");
assertEquals("Read 2", 1, input.read()); assertEquals(1, input.read(), "Read 2");
assertEquals("Read 3", -1, input.read()); assertEquals(-1, input.read(), "Read 3");
assertEquals("Read 4", -1, input.read()); assertEquals(-1, input.read(), "Read 4");
assertEquals("Read 5", -1, input.read()); assertEquals(-1, input.read(), "Read 5");
} }
@Test @Test
@@ -205,7 +205,7 @@ public abstract class InputStreamAbstractTest extends ObjectAbstractTest {
fail("Should throw IOException"); fail("Should throw IOException");
} }
catch (IOException e) { catch (IOException e) {
assertTrue("Wrong messge: " + e.getMessage(), e.getMessage().contains("reset")); assertTrue(e.getMessage().contains("reset"), "Wrong messge: " + e.getMessage());
} }
} }
@@ -223,10 +223,10 @@ public abstract class InputStreamAbstractTest extends ObjectAbstractTest {
// No mark may either throw exception, or reset to beginning of stream. // No mark may either throw exception, or reset to beginning of stream.
try { try {
input.reset(); input.reset();
assertEquals("Re-read of reset data should be same", 0, input.read()); assertEquals(0, input.read(), "Re-read of reset data should be same");
} }
catch (Exception e) { catch (Exception e) {
assertTrue("Wrong no mark IOException message", e.getMessage().contains("mark")); assertTrue(e.getMessage().contains("mark"), "Wrong no mark IOException message");
} }
} }
@@ -249,7 +249,7 @@ public abstract class InputStreamAbstractTest extends ObjectAbstractTest {
// Read further // Read further
for (int i = 0; i < 3; i++) { for (int i = 0; i < 3; i++) {
assertEquals("Read After Mark [" + i + "]", (position + i), input.read()); assertEquals((position + i), input.read(), "Read After Mark [" + i + "]");
} }
// Reset // Reset
@@ -257,7 +257,7 @@ public abstract class InputStreamAbstractTest extends ObjectAbstractTest {
// Read from marked position // Read from marked position
for (int i = 0; i < readlimit + 1; i++) { for (int i = 0; i < readlimit + 1; i++) {
assertEquals("Read After Reset [" + i + "]", (position + i), input.read()); assertEquals((position + i), input.read(), "Read After Reset [" + i + "]");
} }
} }
@@ -280,16 +280,16 @@ public abstract class InputStreamAbstractTest extends ObjectAbstractTest {
// Read past marked position // Read past marked position
for (int i = 0; i < readlimit + 1; i++) { for (int i = 0; i < readlimit + 1; i++) {
assertEquals("Read After Reset [" + i + "]", (position + i), input.read()); assertEquals((position + i), input.read(), "Read After Reset [" + i + "]");
} }
// Reset after read limit passed, may either throw exception, or reset to last mark // Reset after read limit passed, may either throw exception, or reset to last mark
try { try {
input.reset(); input.reset();
assertEquals("Re-read of reset data should be same", 1, input.read()); assertEquals(1, input.read(), "Re-read of reset data should be same");
} }
catch (Exception e) { catch (Exception e) {
assertTrue("Wrong read-limit IOException message", e.getMessage().contains("mark")); assertTrue(e.getMessage().contains("mark"), "Wrong read-limit IOException message");
} }
} }
@@ -302,29 +302,29 @@ public abstract class InputStreamAbstractTest extends ObjectAbstractTest {
} }
int first = input.read(); int first = input.read();
assertTrue("Expected to read positive value", first >= 0); assertTrue(first >= 0, "Expected to read positive value");
int readlimit = 5; int readlimit = 5;
// Mark // Mark
input.mark(readlimit); input.mark(readlimit);
int read = input.read(); int read = input.read();
assertTrue("Expected to read positive value", read >= 0); assertTrue(read >= 0, "Expected to read positive value");
assertTrue(input.read() >= 0); assertTrue(input.read() >= 0);
assertTrue(input.read() >= 0); assertTrue(input.read() >= 0);
input.reset(); input.reset();
assertEquals("Expected value read differs from actual", read, input.read()); assertEquals(read, input.read(), "Expected value read differs from actual");
// Reset after read limit passed, may either throw exception, or reset to last good mark // Reset after read limit passed, may either throw exception, or reset to last good mark
try { try {
input.reset(); input.reset();
int reRead = input.read(); int reRead = input.read();
assertTrue("Re-read of reset data should be same as initially marked or first", reRead == read || reRead == first); assertTrue(reRead == read || reRead == first, "Re-read of reset data should be same as initially marked or first");
} }
catch (Exception e) { catch (Exception e) {
assertTrue("Wrong read-limit IOException message", e.getMessage().contains("mark")); assertTrue(e.getMessage().contains("mark"), "Wrong read-limit IOException message");
} }
} }
@@ -332,17 +332,17 @@ public abstract class InputStreamAbstractTest extends ObjectAbstractTest {
public void testSkip() throws Exception { public void testSkip() throws Exception {
InputStream input = makeInputStream(makeOrderedArray(10)); InputStream input = makeInputStream(makeOrderedArray(10));
assertEquals("Unexpected value read", 0, input.read()); assertEquals(0, input.read(), "Unexpected value read");
assertEquals("Unexpected value read", 1, input.read()); assertEquals(1, input.read(), "Unexpected value read");
assertEquals("Unexpected number of bytes skipped", 5, input.skip(5)); assertEquals(5, input.skip(5), "Unexpected number of bytes skipped");
assertEquals("Unexpected value read", 7, input.read()); assertEquals(7, input.read(), "Unexpected value read");
assertEquals("Unexpected number of bytes skipped", 2, input.skip(5)); // only 2 left to skip assertEquals(2, input.skip(5), "Unexpected number of bytes skipped"); // only 2 left to skip
assertEquals("Unexpected value read after EOF", -1, input.read()); assertEquals(-1, input.read(), "Unexpected value read after EOF");
// Spec says skip might return 0 or negative after EOF... // Spec says skip might return 0 or negative after EOF...
assertTrue("Positive value skipped after EOF", input.skip(5) <= 0); // End of file assertTrue(input.skip(5) <= 0, "Positive value skipped after EOF"); // End of file
assertEquals("Unexpected value read after EOF", -1, input.read()); assertEquals(-1, input.read(), "Unexpected value read after EOF");
} }
@Test @Test
@@ -30,12 +30,11 @@
package com.twelvemonkeys.io; package com.twelvemonkeys.io;
import org.junit.Test;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import static org.junit.Assert.*; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* LittleEndianDataInputStreamTest * LittleEndianDataInputStreamTest
@@ -31,13 +31,12 @@
package com.twelvemonkeys.io; package com.twelvemonkeys.io;
import com.twelvemonkeys.lang.ObjectAbstractTest; import com.twelvemonkeys.lang.ObjectAbstractTest;
import org.junit.Test;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import static org.junit.Assert.assertNotNull; import org.junit.jupiter.api.Test;
import static org.junit.Assert.fail; import static org.junit.jupiter.api.Assertions.*;
/** /**
* InputStreamAbstractTestCase * InputStreamAbstractTestCase
@@ -31,12 +31,12 @@
package com.twelvemonkeys.io; package com.twelvemonkeys.io;
import com.twelvemonkeys.lang.ObjectAbstractTest; import com.twelvemonkeys.lang.ObjectAbstractTest;
import org.junit.Test;
import java.io.IOException; import java.io.IOException;
import java.io.Reader; import java.io.Reader;
import static org.junit.Assert.*; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* ReaderAbstractTestCase * ReaderAbstractTestCase
@@ -112,7 +112,7 @@ public abstract class ReaderAbstractTest extends ObjectAbstractTest {
int toSkip = mInput.length(); int toSkip = mInput.length();
while (toSkip > 0) { while (toSkip > 0) {
long skipped = reader.skip(toSkip); long skipped = reader.skip(toSkip);
assertFalse("Skipped < 0", skipped < 0); assertFalse(skipped < 0, "Skipped < 0");
toSkip -= skipped; toSkip -= skipped;
} }
@@ -30,10 +30,8 @@
package com.twelvemonkeys.io; package com.twelvemonkeys.io;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/** /**
* SeekableAbstractTestCase * SeekableAbstractTestCase
@@ -30,14 +30,13 @@
package com.twelvemonkeys.io; package com.twelvemonkeys.io;
import org.junit.Test;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.EOFException; import java.io.EOFException;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import static org.junit.Assert.*; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* SeekableInputStreamAbstractTest * SeekableInputStreamAbstractTest
@@ -79,25 +78,25 @@ public abstract class SeekableInputStreamAbstractTest extends InputStreamAbstrac
return; // Not supported, skip test return; // Not supported, skip test
} }
assertTrue("Expected to read positive value", input.read() >= 0); assertTrue(input.read() >= 0, "Expected to read positive value");
int readlimit = 5; int readlimit = 5;
// Mark // Mark
input.mark(readlimit); input.mark(readlimit);
int read = input.read(); int read = input.read();
assertTrue("Expected to read positive value", read >= 0); assertTrue(read >= 0, "Expected to read positive value");
input.reset(); input.reset();
assertEquals("Expected value read differs from actual", read, input.read()); assertEquals(read, input.read(), "Expected value read differs from actual");
// Reset after read limit passed, may either throw exception, or reset to last good mark // Reset after read limit passed, may either throw exception, or reset to last good mark
try { try {
input.reset(); input.reset();
assertEquals("Re-read of reset data should be first", 0, input.read()); assertEquals(0, input.read(), "Re-read of reset data should be first");
} }
catch (Exception e) { catch (Exception e) {
assertTrue("Wrong read-limit IOException message", e.getMessage().contains("mark")); assertTrue(e.getMessage().contains("mark"), "Wrong read-limit IOException message");
} }
} }
@@ -127,7 +126,7 @@ public abstract class SeekableInputStreamAbstractTest extends InputStreamAbstrac
seekable.seek(pos); seekable.seek(pos);
long streamPos = seekable.getStreamPosition(); long streamPos = seekable.getStreamPosition();
assertEquals("Stream positon should match seeked position", pos, streamPos); assertEquals(pos, streamPos, "Stream positon should match seeked position");
} }
@Test @Test
@@ -137,7 +136,7 @@ public abstract class SeekableInputStreamAbstractTest extends InputStreamAbstrac
seekable.seek(pos); seekable.seek(pos);
seekable.flushBefore(pos); seekable.flushBefore(pos);
long flushedPos = seekable.getFlushedPosition(); long flushedPos = seekable.getFlushedPosition();
assertEquals("Flushed positon should match position", pos, flushedPos); assertEquals(pos, flushedPos, "Flushed positon should match position");
try { try {
seekable.seek(pos - 1); seekable.seek(pos - 1);
@@ -382,13 +381,13 @@ public abstract class SeekableInputStreamAbstractTest extends InputStreamAbstrac
int val; int val;
val = stream.read(); val = stream.read();
assertFalse("Unexepected EOF", val == -1); assertFalse(val == -1, "Unexepected EOF");
val = stream.read(); val = stream.read();
assertFalse("Unexepected EOF", val == -1); assertFalse(val == -1, "Unexepected EOF");
val = stream.read(); val = stream.read();
assertFalse("Unexepected EOF", val == -1); assertFalse(val == -1, "Unexepected EOF");
val = stream.read(); val = stream.read();
assertFalse("Unexepected EOF", val == -1); assertFalse(val == -1, "Unexepected EOF");
stream.seek(0); stream.seek(0);
@@ -422,19 +421,19 @@ public abstract class SeekableInputStreamAbstractTest extends InputStreamAbstrac
stream.seek(0); stream.seek(0);
for (int i = 0; i < bytes.length; i += 2) { for (int i = 0; i < bytes.length; i += 2) {
assertEquals("Wrong stream position", i, stream.getStreamPosition()); assertEquals(i, stream.getStreamPosition(), "Wrong stream position");
int count = stream.read(buffer, 0, 2); int count = stream.read(buffer, 0, 2);
assertEquals(2, count); assertEquals(2, count);
assertEquals(String.format("Wrong value read at pos %d", stream.getStreamPosition()), bytes[i], buffer[0]); assertEquals(bytes[i], buffer[0], String.format("Wrong value read at pos %d", stream.getStreamPosition()));
assertEquals(String.format("Wrong value read at pos %d", stream.getStreamPosition()), bytes[i + 1], buffer[1]); assertEquals(bytes[i + 1], buffer[1], String.format("Wrong value read at pos %d", stream.getStreamPosition()));
} }
stream.seek(0); stream.seek(0);
for (int i = 0; i < bytes.length; i++) { for (int i = 0; i < bytes.length; i++) {
assertEquals("Wrong stream position", i, stream.getStreamPosition()); assertEquals(i, stream.getStreamPosition(), "Wrong stream position");
int actual = stream.read(); int actual = stream.read();
assertEquals(String.format("Wrong value read at pos %d", stream.getStreamPosition()), bytes[i] & 0xff, actual); assertEquals(bytes[i] & 0xff, actual, String.format("Wrong value read at pos %d", stream.getStreamPosition()));
assertEquals(String.format("Wrong value read at pos %d", stream.getStreamPosition()), bytes[i], (byte) actual); assertEquals(bytes[i], (byte) actual, String.format("Wrong value read at pos %d", stream.getStreamPosition()));
} }
} }
@@ -456,14 +455,14 @@ public abstract class SeekableInputStreamAbstractTest extends InputStreamAbstrac
try { try {
FileUtil.read(stream); // Read until EOF FileUtil.read(stream); // Read until EOF
assertEquals("EOF not reached (test case broken)", -1, stream.read()); assertEquals(-1, stream.read(), "EOF not reached (test case broken)");
assertFalse("Underlying stream closed before close", closed[0]); assertFalse(closed[0], "Underlying stream closed before close");
} }
finally { finally {
stream.close(); stream.close();
} }
assertTrue("Underlying stream not closed", closed[0]); assertTrue(closed[0], "Underlying stream not closed");
} }
@@ -31,12 +31,12 @@
package com.twelvemonkeys.io; package com.twelvemonkeys.io;
import com.twelvemonkeys.lang.StringUtil; import com.twelvemonkeys.lang.StringUtil;
import org.junit.Test;
import java.io.IOException; import java.io.IOException;
import java.io.Reader; import java.io.Reader;
import static org.junit.Assert.*; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* StringArrayReaderTestCase * StringArrayReaderTestCase
@@ -1,15 +1,14 @@
package com.twelvemonkeys.io; package com.twelvemonkeys.io;
import org.junit.Test;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.time.Duration;
import java.util.Arrays; import java.util.Arrays;
import java.util.Random; import java.util.Random;
import static org.junit.Assert.assertArrayEquals; import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.*;
/** /**
* SubStreamTest. * SubStreamTest.
@@ -23,14 +22,18 @@ public class SubStreamTest {
private final Random rng = new Random(2918475687L); private final Random rng = new Random(2918475687L);
@SuppressWarnings("resource") @SuppressWarnings("resource")
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateNullStream() { public void testCreateNullStream() {
assertThrows(IllegalArgumentException.class, () -> {
new SubStream(null, 42); new SubStream(null, 42);
});
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateNegativeLength() { public void testCreateNegativeLength() {
assertThrows(IllegalArgumentException.class, () -> {
new SubStream(new ByteArrayInputStream(new byte[1]), -1); new SubStream(new ByteArrayInputStream(new byte[1]), -1);
});
} }
@Test @Test
@@ -100,8 +103,9 @@ public class SubStreamTest {
} }
@SuppressWarnings("EmptyTryBlock") @SuppressWarnings("EmptyTryBlock")
@Test(timeout = 500L) @Test
public void testCloseConsumesAllShortStream() throws IOException { public void testCloseConsumesAllShortStream() throws IOException {
assertTimeoutPreemptively(Duration.ofMillis(500), () -> {
ByteArrayInputStream stream = new ByteArrayInputStream(new byte[13]); ByteArrayInputStream stream = new ByteArrayInputStream(new byte[13]);
try (InputStream ignore = new SubStream(stream, 42)) { try (InputStream ignore = new SubStream(stream, 42)) {
@@ -110,5 +114,6 @@ public class SubStreamTest {
assertEquals(0, stream.available()); assertEquals(0, stream.available());
assertEquals(-1, stream.read()); assertEquals(-1, stream.read());
});
} }
} }
@@ -31,15 +31,13 @@
package com.twelvemonkeys.io.enc; package com.twelvemonkeys.io.enc;
import com.twelvemonkeys.io.FileUtil; import com.twelvemonkeys.io.FileUtil;
import org.junit.Test;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.*;
/** /**
* Base64DecoderTest * Base64DecoderTest
* <p/> * <p/>
@@ -66,7 +64,7 @@ public class Base64DecoderTest extends DecoderAbstractTest {
FileUtil.copy(in, bytes); FileUtil.copy(in, bytes);
assertEquals("Strings does not match", "", new String(bytes.toByteArray())); assertEquals("", new String(bytes.toByteArray()), "Strings does not match");
} }
@Test @Test
@@ -78,7 +76,7 @@ public class Base64DecoderTest extends DecoderAbstractTest {
FileUtil.copy(in, bytes); FileUtil.copy(in, bytes);
assertEquals("Strings does not match", "test", new String(bytes.toByteArray())); assertEquals("test", new String(bytes.toByteArray()), "Strings does not match");
} }
@Test @Test
@@ -93,11 +91,12 @@ public class Base64DecoderTest extends DecoderAbstractTest {
FileUtil.copy(in, bytes); FileUtil.copy(in, bytes);
assertEquals("Strings does not match", assertEquals(
"Lorem ipsum dolor sit amet, consectetuer adipiscing " + "Lorem ipsum dolor sit amet, consectetuer adipiscing " +
"elit. Fusce est. Morbi luctus consectetuer justo. Vivamus " + "elit. Fusce est. Morbi luctus consectetuer justo. Vivamus " +
"dapibus laoreet purus. Nunc viverra dictum nisl. Integer " + "dapibus laoreet purus. Nunc viverra dictum nisl. Integer " +
"ullamcorper, nisi in dictum amet.", "ullamcorper, nisi in dictum amet.",
new String(bytes.toByteArray())); new String(bytes.toByteArray()),
"Strings does not match");
} }
} }
@@ -30,13 +30,12 @@
package com.twelvemonkeys.io.enc; package com.twelvemonkeys.io.enc;
import org.junit.Test;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.*;
/** /**
* Base64EncoderTest * Base64EncoderTest
@@ -63,7 +62,7 @@ public class Base64EncoderTest extends EncoderAbstractTest {
OutputStream out = new EncoderStream(bytes, createEncoder(), true); OutputStream out = new EncoderStream(bytes, createEncoder(), true);
out.write(data.getBytes()); out.write(data.getBytes());
assertEquals("Strings does not match", "", new String(bytes.toByteArray())); assertEquals("", new String(bytes.toByteArray()), "Strings does not match");
} }
@Test @Test
@@ -74,7 +73,7 @@ public class Base64EncoderTest extends EncoderAbstractTest {
OutputStream out = new EncoderStream(bytes, createEncoder(), true); OutputStream out = new EncoderStream(bytes, createEncoder(), true);
out.write(data.getBytes()); out.write(data.getBytes());
assertEquals("Strings does not match", "dGVzdA==", new String(bytes.toByteArray())); assertEquals("dGVzdA==", new String(bytes.toByteArray()), "Strings does not match");
} }
@Test @Test
@@ -88,11 +87,12 @@ public class Base64EncoderTest extends EncoderAbstractTest {
OutputStream out = new EncoderStream(bytes, createEncoder(), true); OutputStream out = new EncoderStream(bytes, createEncoder(), true);
out.write(data.getBytes()); out.write(data.getBytes());
assertEquals("Strings does not match", assertEquals(
"TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVlciBhZGlwaXNjaW5nIGVsaXQuIEZ1" + "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVlciBhZGlwaXNjaW5nIGVsaXQuIEZ1" +
"c2NlIGVzdC4gTW9yYmkgbHVjdHVzIGNvbnNlY3RldHVlciBqdXN0by4gVml2YW11cyBkYXBpYnVzIGxh" + "c2NlIGVzdC4gTW9yYmkgbHVjdHVzIGNvbnNlY3RldHVlciBqdXN0by4gVml2YW11cyBkYXBpYnVzIGxh" +
"b3JlZXQgcHVydXMuIE51bmMgdml2ZXJyYSBkaWN0dW0gbmlzbC4gSW50ZWdlciB1bGxhbWNvcnBlciwg" + "b3JlZXQgcHVydXMuIE51bmMgdml2ZXJyYSBkaWN0dW0gbmlzbC4gSW50ZWdlciB1bGxhbWNvcnBlciwg" +
"bmlzaSBpbiBkaWN0dW0gYW1ldC4=", "bmlzaSBpbiBkaWN0dW0gYW1ldC4=",
new String(bytes.toByteArray())); new String(bytes.toByteArray()),
"Strings does not match");
} }
} }
@@ -32,12 +32,13 @@ package com.twelvemonkeys.io.enc;
import com.twelvemonkeys.io.FileUtil; import com.twelvemonkeys.io.FileUtil;
import com.twelvemonkeys.lang.ObjectAbstractTest; import com.twelvemonkeys.lang.ObjectAbstractTest;
import org.junit.Test;
import java.awt.image.ImageProducer;
import java.io.*; import java.io.*;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import static org.junit.Assert.*; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* AbstractDecoderTest * AbstractDecoderTest
@@ -55,13 +56,13 @@ public abstract class DecoderAbstractTest extends ObjectAbstractTest {
return createDecoder(); return createDecoder();
} }
@Test(expected = NullPointerException.class) @Test
public final void testNullDecode() throws IOException { public final void testNullDecode() throws IOException {
Decoder decoder = createDecoder(); Decoder decoder = createDecoder();
ByteArrayInputStream bytes = new ByteArrayInputStream(new byte[20]); ByteArrayInputStream bytes = new ByteArrayInputStream(new byte[20]);
assertThrows(NullPointerException.class, () -> {
decoder.decode(bytes, null); decoder.decode(bytes, null);
fail("null should throw NullPointerException"); });
} }
@Test @Test
@@ -71,7 +72,7 @@ public abstract class DecoderAbstractTest extends ObjectAbstractTest {
try { try {
int count = decoder.decode(bytes, ByteBuffer.allocate(128)); int count = decoder.decode(bytes, ByteBuffer.allocate(128));
assertEquals("Should not be able to read any bytes", 0, count); assertEquals( 0, count, "Should not be able to read any bytes");
} }
catch (EOFException allowed) { catch (EOFException allowed) {
// Okay // Okay
@@ -94,7 +95,7 @@ public abstract class DecoderAbstractTest extends ObjectAbstractTest {
byte[] encoded = outBytes.toByteArray(); byte[] encoded = outBytes.toByteArray();
byte[] decoded = FileUtil.read(new DecoderStream(new ByteArrayInputStream(encoded), createDecoder())); byte[] decoded = FileUtil.read(new DecoderStream(new ByteArrayInputStream(encoded), createDecoder()));
assertArrayEquals(String.format("Data %d", pLength), data, decoded); assertArrayEquals(data, decoded, String.format("Data %d", pLength));
InputStream in = new DecoderStream(new ByteArrayInputStream(encoded), createDecoder()); InputStream in = new DecoderStream(new ByteArrayInputStream(encoded), createDecoder());
outBytes = new ByteArrayOutputStream(); outBytes = new ByteArrayOutputStream();
@@ -103,7 +104,7 @@ public abstract class DecoderAbstractTest extends ObjectAbstractTest {
in.close(); in.close();
decoded = outBytes.toByteArray(); decoded = outBytes.toByteArray();
assertArrayEquals(String.format("Data %d", pLength), data, decoded); assertArrayEquals(data, decoded, String.format("Data %d", pLength));
} }
@Test @Test
@@ -30,7 +30,6 @@
package com.twelvemonkeys.io.enc; package com.twelvemonkeys.io.enc;
import org.junit.Test;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
@@ -39,7 +38,8 @@ import java.nio.ByteBuffer;
import java.util.Arrays; import java.util.Arrays;
import java.util.Random; import java.util.Random;
import static org.junit.Assert.*; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class DecoderStreamTest { public class DecoderStreamTest {
@@ -33,13 +33,12 @@ package com.twelvemonkeys.io.enc;
import com.twelvemonkeys.io.FileUtil; import com.twelvemonkeys.io.FileUtil;
import com.twelvemonkeys.lang.ObjectAbstractTest; import com.twelvemonkeys.lang.ObjectAbstractTest;
import org.junit.Test;
import java.io.*; import java.io.*;
import java.util.Random; import java.util.Random;
import static org.junit.Assert.assertArrayEquals; import org.junit.jupiter.api.Test;
import static org.junit.Assert.fail; import static org.junit.jupiter.api.Assertions.*;
/** /**
* AbstractEncoderTest * AbstractEncoderTest
@@ -30,8 +30,6 @@
package com.twelvemonkeys.io.enc; package com.twelvemonkeys.io.enc;
import org.junit.Test;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
@@ -39,7 +37,8 @@ import java.nio.ByteBuffer;
import java.util.Arrays; import java.util.Arrays;
import java.util.Random; import java.util.Random;
import static org.junit.Assert.assertArrayEquals; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class EncoderStreamTest { public class EncoderStreamTest {
@@ -31,9 +31,9 @@
package com.twelvemonkeys.io.ole2; package com.twelvemonkeys.io.ole2;
import com.twelvemonkeys.io.MemoryCacheSeekableStream; import com.twelvemonkeys.io.MemoryCacheSeekableStream;
import org.junit.Test;
import javax.imageio.stream.MemoryCacheImageInputStream; import javax.imageio.stream.MemoryCacheImageInputStream;
import java.awt.image.ImageProducer;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@@ -43,8 +43,8 @@ import java.nio.ByteOrder;
import java.util.SortedSet; import java.util.SortedSet;
import java.util.TreeSet; import java.util.TreeSet;
import static org.junit.Assert.*; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* CompoundDocumentTestCase * CompoundDocumentTestCase
* *
@@ -59,8 +59,8 @@ public class CompoundDocumentTest {
protected final CompoundDocument createTestDocument() throws IOException { protected final CompoundDocument createTestDocument() throws IOException {
URL input = getClass().getResource(SAMPLE_DATA); URL input = getClass().getResource(SAMPLE_DATA);
assertNotNull("Missing test resource!", input); assertNotNull(input, "Missing test resource!");
assertEquals("Test resource not a file:// resource", "file", input.getProtocol()); assertEquals( "file", input.getProtocol(), "Test resource not a file:// resource");
try { try {
return new CompoundDocument(new File(input.toURI())); return new CompoundDocument(new File(input.toURI()));
@@ -103,7 +103,7 @@ public class CompoundDocumentTest {
} }
} }
@Test(expected = UnsupportedOperationException.class) @Test
public void testChildEntriesUnmodifiable() throws IOException { public void testChildEntriesUnmodifiable() throws IOException {
try (CompoundDocument document = createTestDocument()) { try (CompoundDocument document = createTestDocument()) {
Entry root = document.getRootEntry(); Entry root = document.getRootEntry();
@@ -111,9 +111,10 @@ public class CompoundDocumentTest {
assertNotNull(root); assertNotNull(root);
SortedSet<Entry> children = root.getChildEntries(); SortedSet<Entry> children = root.getChildEntries();
assertThrows(UnsupportedOperationException.class, () -> {
// Should not be allowed, as it modifies the internal structure // Should not be allowed, as it modifies the internal structure
children.remove(children.first()); children.remove(children.first());
});
} }
} }
@@ -128,7 +129,7 @@ public class CompoundDocumentTest {
Entry catalog = root.getChildEntry("Catalog"); Entry catalog = root.getChildEntry("Catalog");
assertNotNull(catalog); assertNotNull(catalog);
assertNotNull("Input stream may not be null", catalog.getInputStream()); assertNotNull(catalog.getInputStream(), "Input stream may not be null");
} }
} }
@@ -136,7 +137,7 @@ public class CompoundDocumentTest {
public void testReadCatalogInputStream() throws IOException { public void testReadCatalogInputStream() throws IOException {
InputStream input = getClass().getResourceAsStream(SAMPLE_DATA); InputStream input = getClass().getResourceAsStream(SAMPLE_DATA);
assertNotNull("Missing test resource!", input); assertNotNull(input, "Missing test resource!");
CompoundDocument document = new CompoundDocument(input); CompoundDocument document = new CompoundDocument(input);
Entry root = document.getRootEntry(); Entry root = document.getRootEntry();
@@ -145,14 +146,14 @@ public class CompoundDocumentTest {
Entry catalog = root.getChildEntry("Catalog"); Entry catalog = root.getChildEntry("Catalog");
assertNotNull(catalog); assertNotNull(catalog);
assertNotNull("Input stream may not be null", catalog.getInputStream()); assertNotNull(catalog.getInputStream(), "Input stream may not be null");
} }
@Test @Test
public void testReadCatalogSeekableStream() throws IOException { public void testReadCatalogSeekableStream() throws IOException {
InputStream input = getClass().getResourceAsStream(SAMPLE_DATA); InputStream input = getClass().getResourceAsStream(SAMPLE_DATA);
assertNotNull("Missing test resource!", input); assertNotNull(input, "Missing test resource!");
CompoundDocument document = new CompoundDocument(new MemoryCacheSeekableStream(input)); CompoundDocument document = new CompoundDocument(new MemoryCacheSeekableStream(input));
Entry root = document.getRootEntry(); Entry root = document.getRootEntry();
@@ -161,14 +162,14 @@ public class CompoundDocumentTest {
Entry catalog = root.getChildEntry("Catalog"); Entry catalog = root.getChildEntry("Catalog");
assertNotNull(catalog); assertNotNull(catalog);
assertNotNull("Input stream may not be null", catalog.getInputStream()); assertNotNull(catalog.getInputStream(), "Input stream may not be null");
} }
@Test @Test
public void testReadCatalogImageInputStream() throws IOException { public void testReadCatalogImageInputStream() throws IOException {
InputStream input = getClass().getResourceAsStream(SAMPLE_DATA); InputStream input = getClass().getResourceAsStream(SAMPLE_DATA);
assertNotNull("Missing test resource!", input); assertNotNull(input, "Missing test resource!");
MemoryCacheImageInputStream stream = new MemoryCacheImageInputStream(input); MemoryCacheImageInputStream stream = new MemoryCacheImageInputStream(input);
stream.setByteOrder(ByteOrder.LITTLE_ENDIAN); stream.setByteOrder(ByteOrder.LITTLE_ENDIAN);
@@ -183,6 +184,6 @@ public class CompoundDocumentTest {
Entry catalog = root.getChildEntry("Catalog"); Entry catalog = root.getChildEntry("Catalog");
assertNotNull(catalog); assertNotNull(catalog);
assertNotNull("Input stream may not be null", catalog.getInputStream()); assertNotNull(catalog.getInputStream(), "Input stream may not be null");
} }
} }
@@ -31,7 +31,7 @@
package com.twelvemonkeys.io.ole2; package com.twelvemonkeys.io.ole2;
import com.twelvemonkeys.io.*; import com.twelvemonkeys.io.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
@@ -33,7 +33,6 @@ package com.twelvemonkeys.io.ole2;
import com.twelvemonkeys.io.InputStreamAbstractTest; import com.twelvemonkeys.io.InputStreamAbstractTest;
import com.twelvemonkeys.io.LittleEndianDataOutputStream; import com.twelvemonkeys.io.LittleEndianDataOutputStream;
import com.twelvemonkeys.io.MemoryCacheSeekableStream; import com.twelvemonkeys.io.MemoryCacheSeekableStream;
import org.junit.Test;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
@@ -42,7 +41,8 @@ import java.io.InputStream;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.util.Arrays; import java.util.Arrays;
import static org.junit.Assert.*; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* CompoundDocument_StreamTestCase * CompoundDocument_StreamTestCase
@@ -165,8 +165,8 @@ public class CompoundDocument_StreamTest extends InputStreamAbstractTest {
count++; count++;
} }
assertFalse("Short stream", count < 32); assertFalse(count < 32, "Short stream");
assertFalse("Stream overrun", count > 32); assertFalse(count > 32, "Stream overrun");
} }
@Test @Test
@@ -30,9 +30,8 @@
package com.twelvemonkeys.net; package com.twelvemonkeys.net;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.Assert.assertEquals;
/** /**
* HTTPUtilTest * HTTPUtilTest
@@ -30,14 +30,13 @@
package com.twelvemonkeys.lang; package com.twelvemonkeys.lang;
import org.junit.Test;
import java.io.Serializable; import java.io.Serializable;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import static org.junit.Assert.*; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* BeanUtilTestCase * BeanUtilTestCase
@@ -161,10 +160,8 @@ public class BeanUtilTest {
} }
assertNotNull(bean.getAmbiguous()); assertNotNull(bean.getAmbiguous());
assertEquals("String converted rather than invoking setAmbiguous(String), ordering not predictable", assertEquals("one", bean.getAmbiguous(), "String converted rather than invoking setAmbiguous(String), ordering not predictable");
"one", bean.getAmbiguous()); assertSame(value, bean.getAmbiguous(), "String converted rather than invoking setAmbiguous(String), ordering not predictable");
assertSame("String converted rather than invoking setAmbiguous(String), ordering not predictable",
value, bean.getAmbiguous());
} }
@Test @Test
@@ -184,10 +181,10 @@ public class BeanUtilTest {
} }
assertNotNull(bean.getAmbiguous()); assertNotNull(bean.getAmbiguous());
assertEquals("Integer converted rather than invoking setAmbiguous(Integer), ordering not predictable", assertEquals(2, bean.getAmbiguous(),
2, bean.getAmbiguous()); "Integer converted rather than invoking setAmbiguous(Integer), ordering not predictable");
assertSame("Integer converted rather than invoking setAmbiguous(Integer), ordering not predictable", assertSame(value, bean.getAmbiguous(),
value, bean.getAmbiguous()); "Integer converted rather than invoking setAmbiguous(Integer), ordering not predictable");
} }
@Test @Test
@@ -207,10 +204,8 @@ public class BeanUtilTest {
} }
assertNotNull(bean.getAmbiguous()); assertNotNull(bean.getAmbiguous());
assertEquals("Object converted rather than invoking setAmbiguous(Object), ordering not predictable", assertEquals(value.getClass(), bean.getAmbiguous().getClass(), "Object converted rather than invoking setAmbiguous(Object), ordering not predictable");
value.getClass(), bean.getAmbiguous().getClass()); assertSame(value, bean.getAmbiguous(), "Object converted rather than invoking setAmbiguous(Object), ordering not predictable");
assertSame("Object converted rather than invoking setAmbiguous(Object), ordering not predictable",
value, bean.getAmbiguous());
} }
static class TestBean { static class TestBean {
@@ -30,16 +30,16 @@
package com.twelvemonkeys.lang; package com.twelvemonkeys.lang;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays; import java.util.Arrays;
import java.util.Calendar; import java.util.Calendar;
import java.util.List; import java.util.List;
import java.util.TimeZone; import java.util.TimeZone;
import static org.junit.Assert.assertEquals; import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* DateUtilTest * DateUtilTest
@@ -48,12 +48,9 @@ import static org.junit.Assert.assertEquals;
* @author last modified by $Author: haraldk$ * @author last modified by $Author: haraldk$
* @version $Id: DateUtilTest.java,v 1.0 11.04.12 16:21 haraldk Exp$ * @version $Id: DateUtilTest.java,v 1.0 11.04.12 16:21 haraldk Exp$
*/ */
@RunWith(Parameterized.class)
public class DateUtilTest { public class DateUtilTest {
private final TimeZone timeZone;
@Parameterized.Parameters
public static List<Object[]> timeZones() { public static List<Object[]> timeZones() {
return Arrays.asList(new Object[][] { return Arrays.asList(new Object[][] {
{TimeZone.getTimeZone("UTC")}, {TimeZone.getTimeZone("UTC")},
@@ -62,10 +59,6 @@ public class DateUtilTest {
}); });
} }
public DateUtilTest(final TimeZone timeZone) {
this.timeZone = timeZone;
}
private Calendar getCalendar(long time) { private Calendar getCalendar(long time) {
return getCalendar(time, TimeZone.getDefault()); return getCalendar(time, TimeZone.getDefault());
} }
@@ -101,8 +94,9 @@ public class DateUtilTest {
assertEquals(0, calendar.get(Calendar.MINUTE)); assertEquals(0, calendar.get(Calendar.MINUTE));
} }
@Test @ParameterizedTest
public void testRoundToHourTZ() { @MethodSource("timeZones")
public void testRoundToHourTZ(TimeZone timeZone) {
Calendar calendar = getCalendar(DateUtil.roundToHour(System.currentTimeMillis(), timeZone), timeZone); Calendar calendar = getCalendar(DateUtil.roundToHour(System.currentTimeMillis(), timeZone), timeZone);
assertEquals(0, calendar.get(Calendar.MILLISECOND)); assertEquals(0, calendar.get(Calendar.MILLISECOND));
@@ -120,8 +114,9 @@ public class DateUtilTest {
assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY)); assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY));
} }
@Test @ParameterizedTest
public void testRoundToDayTZ() { @MethodSource("timeZones")
public void testRoundToDayTZ(TimeZone timeZone) {
Calendar calendar = getCalendar(DateUtil.roundToDay(System.currentTimeMillis(), timeZone), timeZone); Calendar calendar = getCalendar(DateUtil.roundToDay(System.currentTimeMillis(), timeZone), timeZone);
assertEquals(0, calendar.get(Calendar.MILLISECOND)); assertEquals(0, calendar.get(Calendar.MILLISECOND));
@@ -30,12 +30,11 @@
package com.twelvemonkeys.lang; package com.twelvemonkeys.lang;
import org.junit.Test;
import java.io.*; import java.io.*;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import static org.junit.Assert.*; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* AbstractObjectTestCase * AbstractObjectTestCase
@@ -79,10 +78,10 @@ public abstract class ObjectAbstractTest {
Class cl = obj.getClass(); Class cl = obj.getClass();
if (isEqualsOverriden(cl)) { if (isEqualsOverriden(cl)) {
assertTrue("Class " + cl.getName() + " implements equals but not hashCode", isHashCodeOverriden(cl)); assertTrue(isHashCodeOverriden(cl), "Class " + cl.getName() + " implements equals but not hashCode");
} }
else if (isHashCodeOverriden(cl)) { else if (isHashCodeOverriden(cl)) {
assertTrue("Class " + cl.getName() + " implements hashCode but not equals", isEqualsOverriden(cl)); assertTrue(isEqualsOverriden(cl), "Class " + cl.getName() + " implements hashCode but not equals");
} }
} }
@@ -107,7 +106,7 @@ public abstract class ObjectAbstractTest {
@Test @Test
public void testObjectEqualsSelf() { public void testObjectEqualsSelf() {
Object obj = makeObject(); Object obj = makeObject();
assertEquals("An Object should equal itself", obj, obj); assertEquals(obj, obj, "An Object should equal itself");
} }
@Test @Test
@@ -115,32 +114,26 @@ public abstract class ObjectAbstractTest {
Object obj = makeObject(); Object obj = makeObject();
// NOTE: Makes sure this doesn't throw NPE either // NOTE: Makes sure this doesn't throw NPE either
//noinspection ObjectEqualsNull //noinspection ObjectEqualsNull
assertFalse("An object should never equal null", obj.equals(null)); assertFalse(obj.equals(null), "An object should never equal null");
} }
@Test @Test
public void testObjectHashCodeEqualsSelfHashCode() { public void testObjectHashCodeEqualsSelfHashCode() {
Object obj = makeObject(); Object obj = makeObject();
assertEquals("hashCode should be repeatable", obj.hashCode(), obj.hashCode()); assertEquals(obj.hashCode(), obj.hashCode(), "hashCode should be repeatable");
} }
@Test @Test
public void testObjectHashCodeEqualsContract() { public void testObjectHashCodeEqualsContract() {
Object obj1 = makeObject(); Object obj1 = makeObject();
if (obj1.equals(obj1)) { if (obj1.equals(obj1)) {
assertEquals( assertEquals(obj1.hashCode(), obj1.hashCode(), "[1] When two objects are equal, their hashCodes should be also.");
"[1] When two objects are equal, their hashCodes should be also.",
obj1.hashCode(), obj1.hashCode());
} }
// TODO: Make sure we create at least one equal object, and one different object // TODO: Make sure we create at least one equal object, and one different object
Object obj2 = makeObject(); Object obj2 = makeObject();
if (obj1.equals(obj2)) { if (obj1.equals(obj2)) {
assertEquals( assertEquals(obj1.hashCode(), obj2.hashCode(), "[2] When two objects are equal, their hashCodes should be also.");
"[2] When two objects are equal, their hashCodes should be also.", assertTrue(obj2.equals(obj1), "When obj1.equals(obj2) is true, then obj2.equals(obj1) should also be true");
obj1.hashCode(), obj2.hashCode());
assertTrue(
"When obj1.equals(obj2) is true, then obj2.equals(obj1) should also be true",
obj2.equals(obj1));
} }
} }
@@ -169,14 +162,14 @@ public abstract class ObjectAbstractTest {
Object cloned = clone.invoke(obj); Object cloned = clone.invoke(obj);
assertNotNull("Cloned object should never be null", cloned); assertNotNull(cloned, "Cloned object should never be null");
// TODO: This can only be asserted if equals() test is based on // TODO: This can only be asserted if equals() test is based on
// value equality, not reference (identity) equality // value equality, not reference (identity) equality
// Maybe it's possible to do a reflective introspection of // Maybe it's possible to do a reflective introspection of
// the objects fields? // the objects fields?
if (isHashCodeOverriden(cl)) { if (isHashCodeOverriden(cl)) {
assertEquals("Cloned object not equal", obj, cloned); assertEquals(obj, cloned, "Cloned object not equal");
} }
} }
} }
@@ -235,7 +228,7 @@ public abstract class ObjectAbstractTest {
// Maybe it's possible to do a reflective introspection of // Maybe it's possible to do a reflective introspection of
// the objects fields? // the objects fields?
if (isEqualsOverriden(obj.getClass())) { if (isEqualsOverriden(obj.getClass())) {
assertEquals("obj != deserialize(serialize(obj))", obj, dest); assertEquals(obj, dest, "obj != deserialize(serialize(obj))");
} }
} }
} }
@@ -30,13 +30,11 @@
package com.twelvemonkeys.lang; package com.twelvemonkeys.lang;
import org.junit.Ignore;
import org.junit.Test;
import java.util.Properties; import java.util.Properties;
import static org.junit.Assert.assertEquals; import org.junit.jupiter.api.Disabled;
import static org.junit.Assert.assertNotNull; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* PlatformTest * PlatformTest
@@ -121,7 +119,7 @@ public class PlatformTest {
assertEquals(Platform.Architecture.X86, platform.getArchitecture()); assertEquals(Platform.Architecture.X86, platform.getArchitecture());
} }
@Ignore("Known issue, needs resolve") @Disabled("Known issue, needs resolve")
@Test @Test
public void testCreateWindows686() { public void testCreateWindows686() {
Platform platform = new Platform(createProperties("Windows", "5.1", "686")); Platform platform = new Platform(createProperties("Windows", "5.1", "686"));
@@ -129,7 +127,7 @@ public class PlatformTest {
assertEquals(Platform.Architecture.X86, platform.getArchitecture()); assertEquals(Platform.Architecture.X86, platform.getArchitecture());
} }
@Ignore("Known issue, needs resolve") @Disabled("Known issue, needs resolve")
@Test @Test
public void testCreateLinuxX86() { public void testCreateLinuxX86() {
Platform platform = new Platform(createProperties("Linux", "3.0.18", "x86")); Platform platform = new Platform(createProperties("Linux", "3.0.18", "x86"));
@@ -30,8 +30,6 @@
package com.twelvemonkeys.lang; package com.twelvemonkeys.lang;
import static org.junit.Assert.*;
import java.awt.*; import java.awt.*;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.text.DateFormat; import java.text.DateFormat;
@@ -41,8 +39,8 @@ import java.util.Date;
import java.util.GregorianCalendar; import java.util.GregorianCalendar;
import java.util.Locale; import java.util.Locale;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* StringUtilTestCase * StringUtilTestCase
* *
@@ -165,10 +163,10 @@ public class StringUtilTest {
// Test all alpha-chars // Test all alpha-chars
for (int i = 'a'; i < 'z'; i++) { for (int i = 'a'; i < 'z'; i++) {
if (TEST_STRING.indexOf(i) < 0) { if (TEST_STRING.indexOf(i) < 0) {
assertFalse(TEST_STRING + " seems to contain '" + (char) i + "', at index " + TEST_STRING.indexOf(i), StringUtil.contains(TEST_STRING, i)); assertFalse(StringUtil.contains(TEST_STRING, i), TEST_STRING + " seems to contain '" + (char) i + "', at index " + TEST_STRING.indexOf(i));
} }
else { else {
assertTrue(TEST_STRING + " seems to not contain '" + (char) i + "', at index " + TEST_STRING.indexOf(i), StringUtil.contains(TEST_STRING, i)); assertTrue(StringUtil.contains(TEST_STRING, i), TEST_STRING + " seems to not contain '" + (char) i + "', at index " + TEST_STRING.indexOf(i));
} }
} }
} }
@@ -199,10 +197,10 @@ public class StringUtilTest {
// Test all alpha-chars // Test all alpha-chars
for (int i = 'a'; i < 'z'; i++) { for (int i = 'a'; i < 'z'; i++) {
if ((TEST_STRING.indexOf(i) < 0) && (TEST_STRING.indexOf(Character.toUpperCase((char) i)) < 0)) { if ((TEST_STRING.indexOf(i) < 0) && (TEST_STRING.indexOf(Character.toUpperCase((char) i)) < 0)) {
assertFalse(TEST_STRING + " seems to contain '" + (char) i + "', at index " + Math.max(TEST_STRING.indexOf(i), TEST_STRING.indexOf(Character.toUpperCase((char) i))), StringUtil.containsIgnoreCase(TEST_STRING, i)); assertFalse(StringUtil.containsIgnoreCase(TEST_STRING, i), TEST_STRING + " seems to contain '" + (char) i + "', at index " + Math.max(TEST_STRING.indexOf(i), TEST_STRING.indexOf(Character.toUpperCase((char) i))));
} }
else { else {
assertTrue(TEST_STRING + " seems to not contain '" + (char) i + "', at index " + TEST_STRING.indexOf(i), StringUtil.containsIgnoreCase(TEST_STRING, i)); assertTrue(StringUtil.containsIgnoreCase(TEST_STRING, i), TEST_STRING + " seems to not contain '" + (char) i + "', at index " + TEST_STRING.indexOf(i));
} }
} }
} }
@@ -350,10 +348,10 @@ public class StringUtilTest {
// Test all alpha-chars // Test all alpha-chars
for (int i = 'a'; i < 'z'; i++) { for (int i = 'a'; i < 'z'; i++) {
if ((TEST_STRING.indexOf(i) < 0) && (TEST_STRING.indexOf(Character.toUpperCase((char) i)) < 0)) { if ((TEST_STRING.indexOf(i) < 0) && (TEST_STRING.indexOf(Character.toUpperCase((char) i)) < 0)) {
assertEquals(TEST_STRING + " seems to contain '" + (char) i + "', at index " + Math.max(TEST_STRING.indexOf(i), TEST_STRING.indexOf(Character.toUpperCase((char) i))), -1, StringUtil.indexOfIgnoreCase(TEST_STRING, i)); assertEquals(-1, StringUtil.indexOfIgnoreCase(TEST_STRING, i), TEST_STRING + " seems to contain '" + (char) i + "', at index " + Math.max(TEST_STRING.indexOf(i), TEST_STRING.indexOf(Character.toUpperCase((char) i))));
} }
else { else {
assertTrue(TEST_STRING + " seems to not contain '" + (char) i + "', at index " + TEST_STRING.indexOf(i), 0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, i)); assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, i), TEST_STRING + " seems to not contain '" + (char) i + "', at index " + TEST_STRING.indexOf(i));
} }
} }
} }
@@ -385,10 +383,10 @@ public class StringUtilTest {
// Test all alpha-chars // Test all alpha-chars
for (int i = 'a'; i < 'z'; i++) { for (int i = 'a'; i < 'z'; i++) {
if ((TEST_STRING.indexOf(i) < 0) && (TEST_STRING.indexOf(Character.toUpperCase((char) i)) < 0)) { if ((TEST_STRING.indexOf(i) < 0) && (TEST_STRING.indexOf(Character.toUpperCase((char) i)) < 0)) {
assertEquals(TEST_STRING + " seems to contain '" + (char) i + "', at index " + Math.max(TEST_STRING.indexOf(i), TEST_STRING.indexOf(Character.toUpperCase((char) i))), -1, StringUtil.indexOfIgnoreCase(TEST_STRING, i, 0)); assertEquals(-1, StringUtil.indexOfIgnoreCase(TEST_STRING, i, 0), TEST_STRING + " seems to contain '" + (char) i + "', at index " + Math.max(TEST_STRING.indexOf(i), TEST_STRING.indexOf(Character.toUpperCase((char) i))));
} }
else { else {
assertTrue(TEST_STRING + " seems to not contain '" + (char) i + "', at index " + TEST_STRING.indexOf(i), 0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, i, 0)); assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, i, 0), TEST_STRING + " seems to not contain '" + (char) i + "', at index " + TEST_STRING.indexOf(i));
} }
} }
} }
@@ -420,10 +418,10 @@ public class StringUtilTest {
// Test all alpha-chars // Test all alpha-chars
for (int i = 'a'; i < 'z'; i++) { for (int i = 'a'; i < 'z'; i++) {
if ((TEST_STRING.indexOf(i) < 0) && (TEST_STRING.indexOf(Character.toUpperCase((char) i)) < 0)) { if ((TEST_STRING.indexOf(i) < 0) && (TEST_STRING.indexOf(Character.toUpperCase((char) i)) < 0)) {
assertEquals(TEST_STRING + " seems to contain '" + (char) i + "', at index " + Math.max(TEST_STRING.indexOf(i), TEST_STRING.indexOf(Character.toUpperCase((char) i))), -1, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, i)); assertEquals(-1, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, i), TEST_STRING + " seems to contain '" + (char) i + "', at index " + Math.max(TEST_STRING.indexOf(i), TEST_STRING.indexOf(Character.toUpperCase((char) i))));
} }
else { else {
assertTrue(TEST_STRING + " seems to not contain '" + (char) i + "', at index " + TEST_STRING.indexOf(i), 0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, i)); assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, i), TEST_STRING + " seems to not contain '" + (char) i + "', at index " + TEST_STRING.indexOf(i));
} }
} }
} }
@@ -455,10 +453,10 @@ public class StringUtilTest {
// Test all alpha-chars // Test all alpha-chars
for (int i = 'a'; i < 'z'; i++) { for (int i = 'a'; i < 'z'; i++) {
if ((TEST_STRING.indexOf(i) < 0) && (TEST_STRING.indexOf(Character.toUpperCase((char) i)) < 0)) { if ((TEST_STRING.indexOf(i) < 0) && (TEST_STRING.indexOf(Character.toUpperCase((char) i)) < 0)) {
assertEquals(TEST_STRING + " seems to contain '" + (char) i + "', at index " + Math.max(TEST_STRING.indexOf(i), TEST_STRING.indexOf(Character.toUpperCase((char) i))), -1, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, i, TEST_STRING.length())); assertEquals(-1, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, i, TEST_STRING.length()), TEST_STRING + " seems to contain '" + (char) i + "', at index " + Math.max(TEST_STRING.indexOf(i), TEST_STRING.indexOf(Character.toUpperCase((char) i))));
} }
else { else {
assertTrue(TEST_STRING + " seems to not contain '" + (char) i + "', at index " + TEST_STRING.indexOf(i), 0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, i, TEST_STRING.length())); assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, i, TEST_STRING.length()), TEST_STRING + " seems to not contain '" + (char) i + "', at index " + TEST_STRING.indexOf(i));
} }
} }
} }
@@ -30,7 +30,7 @@
package com.twelvemonkeys.lang; package com.twelvemonkeys.lang;
import org.junit.Ignore; import org.junit.jupiter.api.Disabled;
/** /**
* SystemUtilTest * SystemUtilTest
@@ -39,6 +39,6 @@ import org.junit.Ignore;
* @author last modified by $Author: haraldk$ * @author last modified by $Author: haraldk$
* @version $Id: SystemUtilTest.java,v 1.0 11.04.12 16:21 haraldk Exp$ * @version $Id: SystemUtilTest.java,v 1.0 11.04.12 16:21 haraldk Exp$
*/ */
@Ignore @Disabled
public class SystemUtilTest { public class SystemUtilTest {
} }
File diff suppressed because it is too large Load Diff
@@ -45,12 +45,11 @@
package com.twelvemonkeys.util; package com.twelvemonkeys.util;
import org.junit.Test;
import java.lang.reflect.Array; import java.lang.reflect.Array;
import java.util.*; import java.util.*;
import static org.junit.Assert.*; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* Abstract test class for {@link java.util.Collection} methods and contracts. * Abstract test class for {@link java.util.Collection} methods and contracts.
@@ -251,11 +250,8 @@ public abstract class CollectionAbstractTest extends ObjectAbstractTest {
*/ */
public void verifyAll() { public void verifyAll() {
int confirmedSize = confirmed.size(); int confirmedSize = confirmed.size();
assertEquals("Collection size should match confirmed collection's", assertEquals(confirmedSize, collection.size(), "Collection size should match confirmed collection's");
confirmedSize, collection.size()); assertEquals(confirmed.isEmpty(), collection.isEmpty(), "Collection isEmpty() result should match confirmed collection's");
assertEquals("Collection isEmpty() result should match confirmed " +
" collection's",
confirmed.isEmpty(), collection.isEmpty());
// verify the collections are the same by attempting to match each // verify the collections are the same by attempting to match each
// object in the collection and confirmed collection. To account for // object in the collection and confirmed collection. To account for
@@ -521,8 +517,8 @@ public abstract class CollectionAbstractTest extends ObjectAbstractTest {
boolean r = collection.add(elements[i]); boolean r = collection.add(elements[i]);
confirmed.add(elements[i]); confirmed.add(elements[i]);
verifyAll(); verifyAll();
assertTrue("Empty collection changed after add", r); assertTrue(r, "Empty collection changed after add");
assertEquals("Collection size is 1 after first add", 1, collection.size()); assertEquals(1, collection.size(), "Collection size is 1 after first add");
} }
resetEmpty(); resetEmpty();
@@ -532,10 +528,8 @@ public abstract class CollectionAbstractTest extends ObjectAbstractTest {
confirmed.add(elements[i]); confirmed.add(elements[i]);
verifyAll(); verifyAll();
if (r) size++; if (r) size++;
assertEquals("Collection size should grow after add", assertEquals(size, collection.size(), "Collection size should grow after add");
size, collection.size()); assertTrue(collection.contains(elements[i]), "Collection should contain added element");
assertTrue("Collection should contain added element",
collection.contains(elements[i]));
} }
} }
@@ -552,10 +546,9 @@ public abstract class CollectionAbstractTest extends ObjectAbstractTest {
boolean r = collection.addAll(Arrays.asList(elements)); boolean r = collection.addAll(Arrays.asList(elements));
confirmed.addAll(Arrays.asList(elements)); confirmed.addAll(Arrays.asList(elements));
verifyAll(); verifyAll();
assertTrue("Empty collection should change after addAll", r); assertTrue(r, "Empty collection should change after addAll");
for (int i = 0; i < elements.length; i++) { for (int i = 0; i < elements.length; i++) {
assertTrue("Collection should contain added element", assertTrue(collection.contains(elements[i]), "Collection should contain added element");
collection.contains(elements[i]));
} }
resetFull(); resetFull();
@@ -564,13 +557,11 @@ public abstract class CollectionAbstractTest extends ObjectAbstractTest {
r = collection.addAll(Arrays.asList(elements)); r = collection.addAll(Arrays.asList(elements));
confirmed.addAll(Arrays.asList(elements)); confirmed.addAll(Arrays.asList(elements));
verifyAll(); verifyAll();
assertTrue("Full collection should change after addAll", r); assertTrue(r, "Full collection should change after addAll");
for (int i = 0; i < elements.length; i++) { for (int i = 0; i < elements.length; i++) {
assertTrue("Full collection should contain added element", assertTrue(collection.contains(elements[i]), "Full collection should contain added element");
collection.contains(elements[i]));
} }
assertEquals("Size should increase after addAll", assertEquals(size + elements.length, collection.size(), "Size should increase after addAll");
size + elements.length, collection.size());
resetFull(); resetFull();
size = collection.size(); size = collection.size();
@@ -578,11 +569,9 @@ public abstract class CollectionAbstractTest extends ObjectAbstractTest {
confirmed.addAll(Arrays.asList(getFullElements())); confirmed.addAll(Arrays.asList(getFullElements()));
verifyAll(); verifyAll();
if (r) { if (r) {
assertTrue("Size should increase if addAll returns true", assertTrue(size < collection.size(), "Size should increase if addAll returns true");
size < collection.size());
} else { } else {
assertEquals("Size should not change if addAll returns false", assertEquals(size, collection.size(), "Size should not change if addAll returns false");
size, collection.size());
} }
} }
@@ -666,16 +655,14 @@ public abstract class CollectionAbstractTest extends ObjectAbstractTest {
resetEmpty(); resetEmpty();
elements = getFullElements(); elements = getFullElements();
for(int i = 0; i < elements.length; i++) { for(int i = 0; i < elements.length; i++) {
assertTrue("Empty collection shouldn't contain element[" + i + "]", assertTrue(!collection.contains(elements[i]), "Empty collection shouldn't contain element[" + i + "]");
!collection.contains(elements[i]));
} }
// make sure calls to "contains" don't change anything // make sure calls to "contains" don't change anything
verifyAll(); verifyAll();
elements = getOtherElements(); elements = getOtherElements();
for(int i = 0; i < elements.length; i++) { for(int i = 0; i < elements.length; i++) {
assertTrue("Empty collection shouldn't contain element[" + i + "]", assertTrue(!collection.contains(elements[i]), "Empty collection shouldn't contain element[" + i + "]");
!collection.contains(elements[i]));
} }
// make sure calls to "contains" don't change anything // make sure calls to "contains" don't change anything
verifyAll(); verifyAll();
@@ -683,8 +670,7 @@ public abstract class CollectionAbstractTest extends ObjectAbstractTest {
resetFull(); resetFull();
elements = getFullElements(); elements = getFullElements();
for(int i = 0; i < elements.length; i++) { for(int i = 0; i < elements.length; i++) {
assertTrue("Full collection should contain element[" + i + "]", assertTrue(collection.contains(elements[i]), "Full collection should contain element[" + i + "]");
collection.contains(elements[i]));
} }
// make sure calls to "contains" don't change anything // make sure calls to "contains" don't change anything
verifyAll(); verifyAll();
@@ -692,8 +678,7 @@ public abstract class CollectionAbstractTest extends ObjectAbstractTest {
resetFull(); resetFull();
elements = getOtherElements(); elements = getOtherElements();
for(int i = 0; i < elements.length; i++) { for(int i = 0; i < elements.length; i++) {
assertTrue("Full collection shouldn't contain element", assertTrue(!collection.contains(elements[i]), "Full collection shouldn't contain element");
!collection.contains(elements[i]));
} }
} }
@@ -705,22 +690,22 @@ public abstract class CollectionAbstractTest extends ObjectAbstractTest {
public void testCollectionContainsAll() { public void testCollectionContainsAll() {
resetEmpty(); resetEmpty();
Collection col = new HashSet(); Collection col = new HashSet();
assertTrue("Every Collection should contain all elements of an " + assertTrue(collection.containsAll(col),
"empty Collection.", collection.containsAll(col)); "Every Collection should contain all elements of an " +
"empty Collection.");
col.addAll(Arrays.asList(getOtherElements())); col.addAll(Arrays.asList(getOtherElements()));
assertTrue("Empty Collection shouldn't contain all elements of " + assertTrue(!collection.containsAll(col),
"a non-empty Collection.", !collection.containsAll(col)); "Empty Collection shouldn't contain all elements of " +
"a non-empty Collection.");
// make sure calls to "containsAll" don't change anything // make sure calls to "containsAll" don't change anything
verifyAll(); verifyAll();
resetFull(); resetFull();
assertTrue("Full collection shouldn't contain other elements", assertTrue(!collection.containsAll(col), "Full collection shouldn't contain other elements");
!collection.containsAll(col));
col.clear(); col.clear();
col.addAll(Arrays.asList(getFullElements())); col.addAll(Arrays.asList(getFullElements()));
assertTrue("Full collection should containAll full elements", assertTrue(collection.containsAll(col), "Full collection should containAll full elements");
collection.containsAll(col));
// make sure calls to "containsAll" don't change anything // make sure calls to "containsAll" don't change anything
verifyAll(); verifyAll();
@@ -728,18 +713,17 @@ public abstract class CollectionAbstractTest extends ObjectAbstractTest {
int max = (getFullElements().length == 1 ? 1 : int max = (getFullElements().length == 1 ? 1 :
(getFullElements().length <= 5 ? getFullElements().length - 1 : 5)); (getFullElements().length <= 5 ? getFullElements().length - 1 : 5));
col = Arrays.asList(getFullElements()).subList(min, max); col = Arrays.asList(getFullElements()).subList(min, max);
assertTrue("Full collection should containAll partial full " + assertTrue(collection.containsAll(col), "Full collection should containAll partial full " +
"elements", collection.containsAll(col)); "elements");
assertTrue("Full collection should containAll itself", assertTrue(collection.containsAll(collection), "Full collection should containAll itself");
collection.containsAll(collection));
// make sure calls to "containsAll" don't change anything // make sure calls to "containsAll" don't change anything
verifyAll(); verifyAll();
col = new ArrayList(); col = new ArrayList();
col.addAll(Arrays.asList(getFullElements())); col.addAll(Arrays.asList(getFullElements()));
col.addAll(Arrays.asList(getFullElements())); col.addAll(Arrays.asList(getFullElements()));
assertTrue("Full collection should containAll duplicate full " + assertTrue(collection.containsAll(col), "Full collection should containAll duplicate full " +
"elements", collection.containsAll(col)); "elements");
// make sure calls to "containsAll" don't change anything // make sure calls to "containsAll" don't change anything
verifyAll(); verifyAll();
@@ -751,14 +735,12 @@ public abstract class CollectionAbstractTest extends ObjectAbstractTest {
@Test @Test
public void testCollectionIsEmpty() { public void testCollectionIsEmpty() {
resetEmpty(); resetEmpty();
assertEquals("New Collection should be empty.", assertEquals(true, collection.isEmpty(), "New Collection should be empty.");
true, collection.isEmpty());
// make sure calls to "isEmpty() don't change anything // make sure calls to "isEmpty() don't change anything
verifyAll(); verifyAll();
resetFull(); resetFull();
assertEquals("Full collection shouldn't be empty", assertEquals(false, collection.isEmpty(), "Full collection shouldn't be empty");
false, collection.isEmpty());
// make sure calls to "isEmpty() don't change anything // make sure calls to "isEmpty() don't change anything
verifyAll(); verifyAll();
} }
@@ -771,8 +753,7 @@ public abstract class CollectionAbstractTest extends ObjectAbstractTest {
public void testCollectionIterator() { public void testCollectionIterator() {
resetEmpty(); resetEmpty();
Iterator it1 = collection.iterator(); Iterator it1 = collection.iterator();
assertEquals("Iterator for empty Collection shouldn't have next.", assertEquals(false, it1.hasNext(), "Iterator for empty Collection shouldn't have next.");
false, it1.hasNext());
try { try {
it1.next(); it1.next();
fail("Iterator at end of Collection should throw " + fail("Iterator at end of Collection should throw " +
@@ -786,18 +767,17 @@ public abstract class CollectionAbstractTest extends ObjectAbstractTest {
resetFull(); resetFull();
it1 = collection.iterator(); it1 = collection.iterator();
for (int i = 0; i < collection.size(); i++) { for (int i = 0; i < collection.size(); i++) {
assertTrue("Iterator for full collection should haveNext", assertTrue(it1.hasNext(), "Iterator for full collection should haveNext");
it1.hasNext());
it1.next(); it1.next();
} }
assertTrue("Iterator should be finished", !it1.hasNext()); assertTrue(!it1.hasNext(), "Iterator should be finished");
ArrayList list = new ArrayList(); ArrayList list = new ArrayList();
it1 = collection.iterator(); it1 = collection.iterator();
for (int i = 0; i < collection.size(); i++) { for (int i = 0; i < collection.size(); i++) {
Object next = it1.next(); Object next = it1.next();
assertTrue("Collection should contain element returned by " + assertTrue(collection.contains(next), "Collection should contain element returned by " +
"its iterator", collection.contains(next)); "its iterator");
list.add(next); list.add(next);
} }
try { try {
@@ -865,11 +845,10 @@ public abstract class CollectionAbstractTest extends ObjectAbstractTest {
} }
size--; size--;
assertEquals("Collection should shrink by one after " + assertEquals(size, collection.size(), "Collection should shrink by one after " +
"iterator.remove", size, collection.size()); "iterator.remove");
} }
assertTrue("Collection should be empty after iterator purge", assertTrue(collection.isEmpty(), "Collection should be empty after iterator purge");
collection.isEmpty());
resetFull(); resetFull();
iter = collection.iterator(); iter = collection.iterator();
@@ -894,8 +873,7 @@ public abstract class CollectionAbstractTest extends ObjectAbstractTest {
resetEmpty(); resetEmpty();
Object[] elements = getFullElements(); Object[] elements = getFullElements();
for (int i = 0; i < elements.length; i++) { for (int i = 0; i < elements.length; i++) {
assertTrue("Shouldn't remove nonexistent element", assertTrue(!collection.remove(elements[i]), "Shouldn't remove nonexistent element");
!collection.remove(elements[i]));
verifyAll(); verifyAll();
} }
@@ -903,16 +881,14 @@ public abstract class CollectionAbstractTest extends ObjectAbstractTest {
resetFull(); resetFull();
for (int i = 0; i < other.length; i++) { for (int i = 0; i < other.length; i++) {
assertTrue("Shouldn't remove nonexistent other element", assertTrue(!collection.remove(other[i]), "Shouldn't remove nonexistent other element");
!collection.remove(other[i]));
verifyAll(); verifyAll();
} }
int size = collection.size(); int size = collection.size();
for (int i = 0; i < elements.length; i++) { for (int i = 0; i < elements.length; i++) {
resetFull(); resetFull();
assertTrue("Collection should remove extant element: " + elements[i], assertTrue(collection.remove(elements[i]), "Collection should remove extant element: " + elements[i]);
collection.remove(elements[i]));
// if the elements aren't distinguishable, we can just remove a // if the elements aren't distinguishable, we can just remove a
// matching element from the confirmed collection and verify // matching element from the confirmed collection and verify
@@ -927,8 +903,7 @@ public abstract class CollectionAbstractTest extends ObjectAbstractTest {
verifyAll(); verifyAll();
} }
assertEquals("Collection should shrink after remove", assertEquals(size - 1, collection.size(), "Collection should shrink after remove");
size - 1, collection.size());
} }
} }
@@ -941,28 +916,28 @@ public abstract class CollectionAbstractTest extends ObjectAbstractTest {
if (!isRemoveSupported()) return; if (!isRemoveSupported()) return;
resetEmpty(); resetEmpty();
assertTrue("Emtpy collection removeAll should return false for " + assertTrue(!collection.removeAll(Collections.EMPTY_SET),
"empty input", "Emtpy collection removeAll should return false for " +
!collection.removeAll(Collections.EMPTY_SET)); "empty input");
verifyAll(); verifyAll();
assertTrue("Emtpy collection removeAll should return false for " + assertTrue(!collection.removeAll(new ArrayList(collection)),
"nonempty input", "Emtpy collection removeAll should return false for " +
!collection.removeAll(new ArrayList(collection))); "nonempty input");
verifyAll(); verifyAll();
resetFull(); resetFull();
assertTrue("Full collection removeAll should return false for " + assertTrue(!collection.removeAll(Collections.EMPTY_SET),
"empty input", "Full collection removeAll should return false for " +
!collection.removeAll(Collections.EMPTY_SET)); "empty input");
verifyAll(); verifyAll();
assertTrue("Full collection removeAll should return false for other elements", assertTrue(!collection.removeAll(Arrays.asList(getOtherElements())),
!collection.removeAll(Arrays.asList(getOtherElements()))); "Full collection removeAll should return false for other elements");
verifyAll(); verifyAll();
assertTrue("Full collection removeAll should return true for full elements", assertTrue(collection.removeAll(new HashSet(collection)),
collection.removeAll(new HashSet(collection))); "Full collection removeAll should return true for full elements");
confirmed.removeAll(new HashSet(confirmed)); confirmed.removeAll(new HashSet(confirmed));
verifyAll(); verifyAll();
@@ -972,17 +947,14 @@ public abstract class CollectionAbstractTest extends ObjectAbstractTest {
int max = (getFullElements().length == 1 ? 1 : int max = (getFullElements().length == 1 ? 1 :
(getFullElements().length <= 5 ? getFullElements().length - 1 : 5)); (getFullElements().length <= 5 ? getFullElements().length - 1 : 5));
Collection all = Arrays.asList(getFullElements()).subList(min, max); Collection all = Arrays.asList(getFullElements()).subList(min, max);
assertTrue("Full collection removeAll should work", assertTrue(collection.removeAll(all), "Full collection removeAll should work");
collection.removeAll(all));
confirmed.removeAll(all); confirmed.removeAll(all);
verifyAll(); verifyAll();
assertTrue("Collection should shrink after removeAll", assertTrue(collection.size() < size, "Collection should shrink after removeAll");
collection.size() < size);
Iterator iter = all.iterator(); Iterator iter = all.iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
assertTrue("Collection shouldn't contain removed element", assertTrue(!collection.contains(iter.next()), "Collection shouldn't contain removed element");
!collection.contains(iter.next()));
} }
} }
@@ -998,59 +970,51 @@ public abstract class CollectionAbstractTest extends ObjectAbstractTest {
List elements = Arrays.asList(getFullElements()); List elements = Arrays.asList(getFullElements());
List other = Arrays.asList(getOtherElements()); List other = Arrays.asList(getOtherElements());
assertTrue("Empty retainAll() should return false", assertTrue(!collection.retainAll(Collections.EMPTY_SET), "Empty retainAll() should return false");
!collection.retainAll(Collections.EMPTY_SET));
verifyAll(); verifyAll();
assertTrue("Empty retainAll() should return false", assertTrue(!collection.retainAll(elements), "Empty retainAll() should return false");
!collection.retainAll(elements));
verifyAll(); verifyAll();
resetFull(); resetFull();
assertTrue("Collection should change from retainAll empty", assertTrue(collection.retainAll(Collections.EMPTY_SET), "Collection should change from retainAll empty");
collection.retainAll(Collections.EMPTY_SET));
confirmed.retainAll(Collections.EMPTY_SET); confirmed.retainAll(Collections.EMPTY_SET);
verifyAll(); verifyAll();
resetFull(); resetFull();
assertTrue("Collection changed from retainAll other", assertTrue(collection.retainAll(other), "Collection changed from retainAll other");
collection.retainAll(other));
confirmed.retainAll(other); confirmed.retainAll(other);
verifyAll(); verifyAll();
resetFull(); resetFull();
int size = collection.size(); int size = collection.size();
assertTrue("Collection shouldn't change from retainAll elements", assertTrue(!collection.retainAll(elements), "Collection shouldn't change from retainAll elements");
!collection.retainAll(elements));
verifyAll(); verifyAll();
assertEquals("Collection size shouldn't change", size, assertEquals(size, collection.size(), "Collection size shouldn't change");
collection.size());
if (getFullElements().length > 1) { if (getFullElements().length > 1) {
resetFull(); resetFull();
size = collection.size(); size = collection.size();
int min = (getFullElements().length < 2 ? 0 : 2); int min = (getFullElements().length < 2 ? 0 : 2);
int max = (getFullElements().length <= 5 ? getFullElements().length - 1 : 5); int max = (getFullElements().length <= 5 ? getFullElements().length - 1 : 5);
assertTrue("Collection should changed by partial retainAll", assertTrue(collection.retainAll(elements.subList(min, max)), "Collection should changed by partial retainAll");
collection.retainAll(elements.subList(min, max)));
confirmed.retainAll(elements.subList(min, max)); confirmed.retainAll(elements.subList(min, max));
verifyAll(); verifyAll();
Iterator iter = collection.iterator(); Iterator iter = collection.iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
assertTrue("Collection only contains retained element", assertTrue(elements.subList(min, max).contains(iter.next()), "Collection only contains retained element");
elements.subList(min, max).contains(iter.next()));
} }
} }
resetFull(); resetFull();
HashSet set = new HashSet(elements); HashSet set = new HashSet(elements);
size = collection.size(); size = collection.size();
assertTrue("Collection shouldn't change from retainAll without " + assertTrue(!collection.retainAll(set),
"duplicate elements", !collection.retainAll(set)); "Collection shouldn't change from retainAll without duplicate elements");
verifyAll(); verifyAll();
assertEquals("Collection size didn't change from nonduplicate " + assertEquals( size, collection.size(),
"retainAll", size, collection.size()); "Collection size didn't change from nonduplicate retainAll");
} }
@@ -1060,11 +1024,10 @@ public abstract class CollectionAbstractTest extends ObjectAbstractTest {
@Test @Test
public void testCollectionSize() { public void testCollectionSize() {
resetEmpty(); resetEmpty();
assertEquals("Size of new Collection is 0.", 0, collection.size()); assertEquals(0, collection.size(), "Size of new Collection is 0.");
resetFull(); resetFull();
assertTrue("Size of full collection should be greater than zero", assertTrue(collection.size() > 0, "Size of full collection should be greater than zero");
collection.size() > 0);
} }
@@ -1073,22 +1036,18 @@ public abstract class CollectionAbstractTest extends ObjectAbstractTest {
*/ */
public void testCollectionToArray() { public void testCollectionToArray() {
resetEmpty(); resetEmpty();
assertEquals("Empty Collection should return empty array for toArray", assertEquals(0, collection.toArray().length, "Empty Collection should return empty array for toArray");
0, collection.toArray().length);
resetFull(); resetFull();
Object[] array = collection.toArray(); Object[] array = collection.toArray();
assertEquals("Full collection toArray should be same size as " + assertEquals(array.length, collection.size(), "Full collection toArray should be same size as collection");
"collection", array.length, collection.size());
Object[] confirmedArray = confirmed.toArray(); Object[] confirmedArray = confirmed.toArray();
assertEquals("length of array from confirmed collection should " + assertEquals(confirmedArray.length, array.length,
"match the length of the collection's array", "length of array from confirmed collection should match the length of the collection's array");
confirmedArray.length, array.length);
boolean[] matched = new boolean[array.length]; boolean[] matched = new boolean[array.length];
for (int i = 0; i < array.length; i++) { for (int i = 0; i < array.length; i++) {
assertTrue("Collection should contain element in toArray", assertTrue(collection.contains(array[i]), "Collection should contain element in toArray");
collection.contains(array[i]));
boolean match = false; boolean match = false;
// find a match in the confirmed array // find a match in the confirmed array
@@ -1108,8 +1067,7 @@ public abstract class CollectionAbstractTest extends ObjectAbstractTest {
} }
} }
for(int i = 0; i < matched.length; i++) { for(int i = 0; i < matched.length; i++) {
assertEquals("Collection should return all its elements in " + assertEquals(true, matched[i], "Collection should return all its elements in toArray");
"toArray", true, matched[i]);
} }
} }
@@ -1123,8 +1081,8 @@ public abstract class CollectionAbstractTest extends ObjectAbstractTest {
resetEmpty(); resetEmpty();
Object[] a = new Object[] { new Object(), null, null }; Object[] a = new Object[] { new Object(), null, null };
Object[] array = collection.toArray(a); Object[] array = collection.toArray(a);
assertArrayEquals("Given array shouldn't shrink", array, a); assertArrayEquals(array, a, "Given array shouldn't shrink");
assertNull("Last element should be set to null", a[0]); assertNull(a[0], "Last element should be set to null");
verifyAll(); verifyAll();
resetFull(); resetFull();
@@ -1146,8 +1104,7 @@ public abstract class CollectionAbstractTest extends ObjectAbstractTest {
array = collection.toArray(new Object[0]); array = collection.toArray(new Object[0]);
a = collection.toArray(); a = collection.toArray();
assertEquals("toArrays should be equal", assertEquals(Arrays.asList(array), Arrays.asList(a), "toArrays should be equal");
Arrays.asList(array), Arrays.asList(a));
// Figure out if they're all the same class // Figure out if they're all the same class
// TODO: It'd be nicer to detect a common superclass // TODO: It'd be nicer to detect a common superclass
@@ -1163,11 +1120,10 @@ public abstract class CollectionAbstractTest extends ObjectAbstractTest {
} }
a = (Object[])Array.newInstance(cl, 0); a = (Object[])Array.newInstance(cl, 0);
array = collection.toArray(a); array = collection.toArray(a);
assertEquals("toArray(Object[]) should return correct array type", assertEquals(a.getClass(), array.getClass(), "toArray(Object[]) should return correct array type");
a.getClass(), array.getClass()); assertEquals(Arrays.asList(array),
assertEquals("type-specific toArrays should be equal", Arrays.asList(collection.toArray()),
Arrays.asList(array), "type-specific toArrays should be equal");
Arrays.asList(collection.toArray()));
verifyAll(); verifyAll();
} }
@@ -1178,12 +1134,10 @@ public abstract class CollectionAbstractTest extends ObjectAbstractTest {
@Test @Test
public void testCollectionToString() { public void testCollectionToString() {
resetEmpty(); resetEmpty();
assertTrue("toString shouldn't return null", assertTrue(collection.toString() != null, "toString shouldn't return null");
collection.toString() != null);
resetFull(); resetFull();
assertTrue("toString shouldn't return null", assertTrue(collection.toString() != null, "toString shouldn't return null");
collection.toString() != null);
} }
@@ -30,13 +30,11 @@
package com.twelvemonkeys.util; package com.twelvemonkeys.util;
import org.junit.Ignore;
import org.junit.Test;
import java.util.*; import java.util.*;
import static org.junit.Assert.*; import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* CollectionUtilTest * CollectionUtilTest
* *
@@ -61,44 +59,60 @@ public class CollectionUtilTest {
assertArrayEquals(new Object[] {"bar", "baz", 3}, merged); assertArrayEquals(new Object[] {"bar", "baz", 3}, merged);
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
public void testMergeArraysObjectBadOffset() { public void testMergeArraysObjectBadOffset() {
assertThrows(IndexOutOfBoundsException.class, () -> {
CollectionUtil.mergeArrays(stringObjects, 4, 2, integerObjects, 2, 1); CollectionUtil.mergeArrays(stringObjects, 4, 2, integerObjects, 2, 1);
});
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
public void testMergeArraysObjectBadSecondOffset() { public void testMergeArraysObjectBadSecondOffset() {
assertThrows(IndexOutOfBoundsException.class, () -> {
CollectionUtil.mergeArrays(stringObjects, 1, 2, integerObjects, 4, 1); CollectionUtil.mergeArrays(stringObjects, 1, 2, integerObjects, 4, 1);
});
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
public void testMergeArraysObjectBadLength() { public void testMergeArraysObjectBadLength() {
assertThrows(IndexOutOfBoundsException.class, () -> {
CollectionUtil.mergeArrays(stringObjects, 1, 4, integerObjects, 2, 1); CollectionUtil.mergeArrays(stringObjects, 1, 4, integerObjects, 2, 1);
});
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
public void testMergeArraysObjectBadSecondLength() { public void testMergeArraysObjectBadSecondLength() {
assertThrows(IndexOutOfBoundsException.class, () -> {
CollectionUtil.mergeArrays(stringObjects, 1, 2, integerObjects, 2, 2); CollectionUtil.mergeArrays(stringObjects, 1, 2, integerObjects, 2, 2);
});
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
public void testMergeArraysObjectNegativeOffset() { public void testMergeArraysObjectNegativeOffset() {
assertThrows(IndexOutOfBoundsException.class, () -> {
CollectionUtil.mergeArrays(stringObjects, -1, 2, integerObjects, 2, 1); CollectionUtil.mergeArrays(stringObjects, -1, 2, integerObjects, 2, 1);
});
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
public void testMergeArraysObjectNegativeSecondOffset() { public void testMergeArraysObjectNegativeSecondOffset() {
assertThrows(IndexOutOfBoundsException.class, () -> {
CollectionUtil.mergeArrays(stringObjects, 1, 2, integerObjects, -1, 1); CollectionUtil.mergeArrays(stringObjects, 1, 2, integerObjects, -1, 1);
});
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
public void testMergeArraysObjectNegativeLength() { public void testMergeArraysObjectNegativeLength() {
assertThrows(IndexOutOfBoundsException.class, () -> {
CollectionUtil.mergeArrays(stringObjects, 1, -1, integerObjects, 2, 1); CollectionUtil.mergeArrays(stringObjects, 1, -1, integerObjects, 2, 1);
});
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
public void testMergeArraysObjectNegativeSecondLength() { public void testMergeArraysObjectNegativeSecondLength() {
assertThrows(IndexOutOfBoundsException.class, () -> {
CollectionUtil.mergeArrays(stringObjects, 1, 2, integerObjects, 2, -1); CollectionUtil.mergeArrays(stringObjects, 1, 2, integerObjects, 2, -1);
});
} }
@Test @Test
@@ -109,20 +123,24 @@ public class CollectionUtilTest {
assertArrayEquals(new Object[] {"foo", "bar", "baz", 1, 2, 3}, merged); assertArrayEquals(new Object[] {"foo", "bar", "baz", 1, 2, 3}, merged);
} }
@Test(expected = ArrayStoreException.class) @Test
public void testMergeArraysObjectIllegalType() { public void testMergeArraysObjectIllegalType() {
String[] strings = {"foo", "bar", "baz"}; String[] strings = {"foo", "bar", "baz"};
Integer[] integers = {1, 2, 3}; // Integer not assignable to String Integer[] integers = {1, 2, 3}; // Integer not assignable to String
assertThrows(ArrayStoreException.class, () -> {
CollectionUtil.mergeArrays(strings, integers); CollectionUtil.mergeArrays(strings, integers);
});
} }
@Test(expected = ArrayStoreException.class) @Test
public void testMergeArraysNativeIllegalType() { public void testMergeArraysNativeIllegalType() {
char[] chars = {'a', 'b', 'c'}; char[] chars = {'a', 'b', 'c'};
int[] integers = {1, 2, 3}; // Integer not assignable to String int[] integers = {1, 2, 3}; // Integer not assignable to String
assertThrows(ArrayStoreException.class, () -> {
CollectionUtil.mergeArrays(chars, integers); CollectionUtil.mergeArrays(chars, integers);
});
} }
@@ -147,9 +165,11 @@ public class CollectionUtilTest {
assertArrayEquals(new int[] {2, 3, 4}, numbers); assertArrayEquals(new int[] {2, 3, 4}, numbers);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testEnumIteratorNull() { public void testEnumIteratorNull() {
assertThrows(IllegalArgumentException.class, () -> {
CollectionUtil.iterator((Enumeration<Object>) null); CollectionUtil.iterator((Enumeration<Object>) null);
});
} }
@Test @Test
@@ -183,9 +203,11 @@ public class CollectionUtilTest {
} }
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testArrayIteratorNull() { public void testArrayIteratorNull() {
assertThrows(IllegalArgumentException.class, () -> {
CollectionUtil.iterator((Object[]) null); CollectionUtil.iterator((Object[]) null);
});
} }
@Test @Test
@@ -262,7 +284,7 @@ public class CollectionUtilTest {
int count = 0; int count = 0;
for (Object element : elements) { for (Object element : elements) {
assertTrue("No next element for element '" + element + "' at index: " + count, iterator.hasNext()); assertTrue(iterator.hasNext(), "No next element for element '" + element + "' at index: " + count);
assertEquals(count > 0, iterator.hasPrevious()); assertEquals(count > 0, iterator.hasPrevious());
assertEquals(count, iterator.nextIndex()); assertEquals(count, iterator.nextIndex());
assertEquals(count - 1, iterator.previousIndex()); assertEquals(count - 1, iterator.previousIndex());
@@ -318,7 +340,7 @@ public class CollectionUtilTest {
assertEquals(elements.length, iterator.nextIndex()); assertEquals(elements.length, iterator.nextIndex());
for (int i = count; i > 0; i--) { for (int i = count; i > 0; i--) {
assertTrue("No previous element for element '" + elements[i - 1] + "' at index: " + (i - 1), iterator.hasPrevious()); assertTrue(iterator.hasPrevious(), "No previous element for element '" + elements[i - 1] + "' at index: " + (i - 1));
assertEquals(i < elements.length, iterator.hasNext()); assertEquals(i < elements.length, iterator.hasNext());
assertEquals(i - 1, iterator.previousIndex()); assertEquals(i - 1, iterator.previousIndex());
assertEquals(i, iterator.nextIndex()); assertEquals(i, iterator.nextIndex());
@@ -339,18 +361,24 @@ public class CollectionUtilTest {
} }
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testArrayIteratorRangeNull() { public void testArrayIteratorRangeNull() {
assertThrows(IllegalArgumentException.class, () -> {
CollectionUtil.iterator(null, 0, 0); CollectionUtil.iterator(null, 0, 0);
});
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testArrayIteratorRangeBadStart() { public void testArrayIteratorRangeBadStart() {
assertThrows(IllegalArgumentException.class, () -> {
CollectionUtil.iterator(stringObjects, stringObjects.length + 1, 2); CollectionUtil.iterator(stringObjects, stringObjects.length + 1, 2);
});
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testArrayIteratorRangeBadLength() { public void testArrayIteratorRangeBadLength() {
assertThrows(IllegalArgumentException.class, () -> {
CollectionUtil.iterator(stringObjects, 1, stringObjects.length); CollectionUtil.iterator(stringObjects, 1, stringObjects.length);
});
} }
@Test @Test
@@ -379,9 +407,11 @@ public class CollectionUtilTest {
} }
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testReverseOrderNull() { public void testReverseOrderNull() {
assertThrows(IllegalArgumentException.class, () -> {
CollectionUtil.reverseOrder(null); CollectionUtil.reverseOrder(null);
});
} }
@Test @Test
@@ -431,7 +461,7 @@ public class CollectionUtilTest {
} }
} }
@Ignore("For development only") @Disabled("For development only")
@Test @Test
@SuppressWarnings({"UnusedDeclaration"}) @SuppressWarnings({"UnusedDeclaration"})
public void testGenerify() { public void testGenerify() {
@@ -45,11 +45,10 @@
package com.twelvemonkeys.util; package com.twelvemonkeys.util;
import org.junit.Test;
import java.util.*; import java.util.*;
import static org.junit.Assert.assertTrue; import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* Tests LRUMap. * Tests LRUMap.
@@ -81,8 +80,8 @@ public class LRUMapTest extends LinkedMapTest {
map2.put(4,"foo"); // removes 1 since max size exceeded map2.put(4,"foo"); // removes 1 since max size exceeded
map2.removeLRU(); // should be Integer(2) map2.removeLRU(); // should be Integer(2)
assertTrue("Second to last value should exist",map2.get(new Integer(3)).equals("foo")); assertTrue(map2.get(new Integer(3)).equals("foo"), "Second to last value should exist");
assertTrue("First value inserted should not exist", map2.get(new Integer(1)) == null); assertTrue(map2.get(new Integer(1)) == null, "First value inserted should not exist");
} }
@Test @Test
@@ -93,8 +92,8 @@ public class LRUMapTest extends LinkedMapTest {
map2.put(3,"foo"); map2.put(3,"foo");
map2.put(4,"bar"); map2.put(4,"bar");
assertTrue("last value should exist",map2.get(new Integer(4)).equals("bar")); assertTrue(map2.get(new Integer(4)).equals("bar"), "last value should exist");
assertTrue("LRU should not exist", map2.get(new Integer(1)) == null); assertTrue(map2.get(new Integer(1)) == null, "LRU should not exist");
} }
/** /**
@@ -113,10 +112,8 @@ public class LRUMapTest extends LinkedMapTest {
map2.putAll(hashMap); map2.putAll(hashMap);
assertTrue("max size is 3, but actual size is " + map2.size(), assertTrue(map2.size() == 3, "max size is 3, but actual size is " + map2.size());
map2.size() == 3); assertTrue(map2.containsKey(new Integer(4)), "map should contain the Integer(4) object");
assertTrue("map should contain the Integer(4) object",
map2.containsKey(new Integer(4)));
} }
/** /**
@@ -134,8 +131,7 @@ public class LRUMapTest extends LinkedMapTest {
map.put("6","6"); map.put("6","6");
map.setMaxSize(3); map.setMaxSize(3);
assertTrue("map should have size = 3, but actually = " + map.size(), assertTrue(map.size() == 3, "map should have size = 3, but actually = " + map.size());
map.size() == 3);
} }
@Test @Test
@@ -160,9 +156,9 @@ public class LRUMapTest extends LinkedMapTest {
keys[i] = keyIterator.next(); keys[i] = keyIterator.next();
} }
assertTrue("first evicted should be 3, was " + keys[0], keys[0].equals("3")); assertTrue(keys[0].equals("3"), "first evicted should be 3, was " + keys[0]);
assertTrue("second evicted should be 1, was " + keys[1], keys[1].equals("1")); assertTrue(keys[1].equals("1"), "second evicted should be 1, was " + keys[1]);
assertTrue("third evicted should be 4, was " + keys[2], keys[2].equals("4")); assertTrue(keys[2].equals("4"), "third evicted should be 4, was " + keys[2]);
} }
@@ -192,13 +188,12 @@ public class LRUMapTest extends LinkedMapTest {
// 4 2 // 4 2
counter.remove("5"); counter.remove("5");
assertTrue("size should be 2, but was " + counter.size(), counter.size() == 2); assertTrue(counter.size() == 2, "size should be 2, but was " + counter.size());
assertTrue("removedCount should be 3 but was " + counter.removedCount, assertTrue(counter.removedCount == 3, "removedCount should be 3 but was " + counter.removedCount);
counter.removedCount == 3);
assertTrue("first removed was '2'",counter.list.get(0).equals("2")); assertTrue(counter.list.get(0).equals("2"), "first removed was '2'");
assertTrue("second removed was '3'",counter.list.get(1).equals("3")); assertTrue(counter.list.get(1).equals("3"), "second removed was '3'");
assertTrue("third removed was '1'",counter.list.get(2).equals("1")); assertTrue(counter.list.get(2).equals("1"), "third removed was '1'");
//assertTrue("oldest key is '4'",counter.get(0).equals("4")); //assertTrue("oldest key is '4'",counter.get(0).equals("4"));
//assertTrue("newest key is '2'",counter.get(1).equals("2")); //assertTrue("newest key is '2'",counter.get(1).equals("2"));
@@ -45,15 +45,11 @@
package com.twelvemonkeys.util; package com.twelvemonkeys.util;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
import static org.junit.Assert.assertEquals; import org.junit.jupiter.api.*;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.*;
/** /**
* Unit tests * Unit tests
@@ -74,7 +70,7 @@ public class LinkedMapTest extends MapAbstractTest {
*/ */
protected LinkedMap labRat; protected LinkedMap labRat;
@Before @BeforeEach
public void setUp() throws Exception { public void setUp() throws Exception {
// use makeMap and cast the result to a SeqHashMap // use makeMap and cast the result to a SeqHashMap
// so that subclasses of SeqHashMap can share these tests // so that subclasses of SeqHashMap can share these tests
@@ -103,27 +99,21 @@ public class LinkedMapTest extends MapAbstractTest {
} }
// Test size(). // Test size().
assertEquals("size() does not match expected size", assertEquals(expectedSize, labRat.size(), "size() does not match expected size");
expectedSize, labRat.size());
// Test clone(), iterator(), and get(Object). // Test clone(), iterator(), and get(Object).
LinkedMap clone = (LinkedMap) labRat.clone(); LinkedMap clone = (LinkedMap) labRat.clone();
assertEquals("Size of clone does not match original", assertEquals(labRat.size(), clone.size(), "Size of clone does not match original");
labRat.size(), clone.size());
Iterator origEntries = labRat.entrySet().iterator(); Iterator origEntries = labRat.entrySet().iterator();
Iterator copiedEntries = clone.entrySet().iterator(); Iterator copiedEntries = clone.entrySet().iterator();
while (origEntries.hasNext()) { while (origEntries.hasNext()) {
Map.Entry origEntry = (Map.Entry)origEntries.next(); Map.Entry origEntry = (Map.Entry)origEntries.next();
Map.Entry copiedEntry = (Map.Entry)copiedEntries.next(); Map.Entry copiedEntry = (Map.Entry)copiedEntries.next();
assertEquals("Cloned key does not match original", assertEquals(origEntry.getKey(), copiedEntry.getKey(), "Cloned key does not match original");
origEntry.getKey(), copiedEntry.getKey()); assertEquals(origEntry.getValue(), copiedEntry.getValue(), "Cloned value does not match original");
assertEquals("Cloned value does not match original", assertEquals(origEntry, copiedEntry, "Cloned entry does not match original");
origEntry.getValue(), copiedEntry.getValue());
assertEquals("Cloned entry does not match original",
origEntry, copiedEntry);
} }
assertTrue("iterator() returned different number of elements than keys()", assertTrue(!copiedEntries.hasNext(), "iterator() returned different number of elements than keys()");
!copiedEntries.hasNext());
// Test sequence() // Test sequence()
/* /*
@@ -207,7 +197,7 @@ public class LinkedMapTest extends MapAbstractTest {
} }
*/ */
@After @AfterEach
public void tearDown() throws Exception { public void tearDown() throws Exception {
labRat = null; labRat = null;
} }
@@ -45,12 +45,10 @@
package com.twelvemonkeys.util; package com.twelvemonkeys.util;
import org.junit.After;
import org.junit.Test;
import java.util.*; import java.util.*;
import static org.junit.Assert.*; import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* Abstract test class for {@link java.util.Map} methods and contracts. * Abstract test class for {@link java.util.Map} methods and contracts.
@@ -390,19 +388,19 @@ public abstract class MapAbstractTest extends ObjectAbstractTest {
m.put(keys[i], values[i]); m.put(keys[i], values[i]);
} }
catch (NullPointerException exception) { catch (NullPointerException exception) {
assertTrue("NullPointerException only allowed to be thrown if either the key or value is null.", assertTrue(keys[i] == null || values[i] == null,
keys[i] == null || values[i] == null); "NullPointerException only allowed to be thrown if either the key or value is null.");
assertTrue("NullPointerException on null key, but isAllowNullKey is not overridden to return false.", assertTrue(keys[i] == null || !isAllowNullKey(),
keys[i] == null || !isAllowNullKey()); "NullPointerException on null key, but isAllowNullKey is not overridden to return false.");
assertTrue("NullPointerException on null value, but isAllowNullValue is not overridden to return false.", assertTrue(values[i] == null || !isAllowNullValue(),
values[i] == null || !isAllowNullValue()); "NullPointerException on null value, but isAllowNullValue is not overridden to return false.");
assertTrue("Unknown reason for NullPointer.", false); fail("Unknown reason for NullPointer.");
} }
} }
assertEquals("size must reflect number of mappings added.", keys.length, m.size()); assertEquals(keys.length, m.size(), "size must reflect number of mappings added.");
} }
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
@@ -481,27 +479,26 @@ public abstract class MapAbstractTest extends ObjectAbstractTest {
Object[] values = getSampleValues(); Object[] values = getSampleValues();
Object[] newValues = getNewSampleValues(); Object[] newValues = getNewSampleValues();
assertTrue("failure in test: Must have keys returned from getSampleKeys.", keys != null); assertTrue(keys != null, "failure in test: Must have keys returned from getSampleKeys.");
assertTrue("failure in test: Must have values returned from getSampleValues.", values != null); assertTrue(values != null, "failure in test: Must have values returned from getSampleValues.");
// verify keys and values have equivalent lengths (in case getSampleX are // verify keys and values have equivalent lengths (in case getSampleX are
// overridden) // overridden)
assertEquals("failure in test: not the same number of sample keys and values.", keys.length, values.length); assertEquals(keys.length, values.length, "failure in test: not the same number of sample keys and values.");
assertEquals("failure in test: not the same number of values and new values.", values.length, newValues.length); assertEquals(values.length, newValues.length, "failure in test: not the same number of values and new values.");
// verify there aren't duplicate keys, and check values // verify there aren't duplicate keys, and check values
for (int i = 0; i < keys.length - 1; i++) { for (int i = 0; i < keys.length - 1; i++) {
for (int j = i + 1; j < keys.length; j++) { for (int j = i + 1; j < keys.length; j++) {
assertTrue("failure in test: duplicate null keys.", (keys[i] != null || keys[j] != null)); assertTrue((keys[i] != null || keys[j] != null), "failure in test: duplicate null keys.");
assertTrue("failure in test: duplicate non-null key.", assertTrue((keys[i] == null || keys[j] == null || (!keys[i].equals(keys[j]) && !keys[j].equals(keys[i]))),
(keys[i] == null || keys[j] == null || (!keys[i].equals(keys[j]) && !keys[j].equals(keys[i])))); "failure in test: duplicate non-null key.");
} }
assertTrue("failure in test: found null key, but isNullKeySupported is false.", keys[i] != null || isAllowNullKey()); assertTrue(keys[i] != null || isAllowNullKey(),"failure in test: found null key, but isNullKeySupported is false.");
assertTrue("failure in test: found null value, but isNullValueSupported is false.", values[i] != null || isAllowNullValue()); assertTrue(values[i] != null || isAllowNullValue(),"failure in test: found null value, but isNullValueSupported is false.");
assertTrue("failure in test: found null new value, but isNullValueSupported is false.", newValues[i] != null || isAllowNullValue()); assertTrue(newValues[i] != null || isAllowNullValue(), "failure in test: found null new value, but isNullValueSupported is false.");
assertTrue("failure in test: values should not be the same as new value", assertTrue(values[i] != newValues[i] && (values[i] == null || !values[i].equals(newValues[i])), "failure in test: values should not be the same as new value");
values[i] != newValues[i] && (values[i] == null || !values[i].equals(newValues[i])));
} }
} }
@@ -517,18 +514,18 @@ public abstract class MapAbstractTest extends ObjectAbstractTest {
@Test @Test
public void testMakeMap() { public void testMakeMap() {
Map em = makeEmptyMap(); Map em = makeEmptyMap();
assertTrue("failure in test: makeEmptyMap must return a non-null map.", em != null); assertTrue(em != null, "failure in test: makeEmptyMap must return a non-null map.");
Map em2 = makeEmptyMap(); Map em2 = makeEmptyMap();
assertTrue("failure in test: makeEmptyMap must return a non-null map.", em2 != null); assertTrue(em2 != null, "failure in test: makeEmptyMap must return a non-null map.");
assertTrue("failure in test: makeEmptyMap must return a new map with each invocation.", em != em2); assertTrue(em != em2, "failure in test: makeEmptyMap must return a new map with each invocation.");
Map fm = makeFullMap(); Map fm = makeFullMap();
assertTrue("failure in test: makeFullMap must return a non-null map.", fm != null); assertTrue(fm != null, "failure in test: makeFullMap must return a non-null map.");
Map fm2 = makeFullMap(); Map fm2 = makeFullMap();
assertTrue("failure in test: makeFullMap must return a non-null map.", fm2 != null); assertTrue(fm2 != null, "failure in test: makeFullMap must return a non-null map.");
assertTrue("failure in test: makeFullMap must return a new map with each invocation.", fm != fm2); assertTrue(fm != fm2, "failure in test: makeFullMap must return a new map with each invocation.");
} }
/** /**
@@ -537,11 +534,11 @@ public abstract class MapAbstractTest extends ObjectAbstractTest {
@Test @Test
public void testMapIsEmpty() { public void testMapIsEmpty() {
resetEmpty(); resetEmpty();
assertEquals("Map.isEmpty() should return true with an empty map", true, map.isEmpty()); assertEquals(true, map.isEmpty(), "Map.isEmpty() should return true with an empty map");
verifyAll(); verifyAll();
resetFull(); resetFull();
assertEquals("Map.isEmpty() should return false with a non-empty map", false, map.isEmpty()); assertEquals(false, map.isEmpty(), "Map.isEmpty() should return false with a non-empty map");
verifyAll(); verifyAll();
} }
@@ -551,11 +548,11 @@ public abstract class MapAbstractTest extends ObjectAbstractTest {
@Test @Test
public void testMapSize() { public void testMapSize() {
resetEmpty(); resetEmpty();
assertEquals("Map.size() should be 0 with an empty map", 0, map.size()); assertEquals(0, map.size(), "Map.size() should be 0 with an empty map");
verifyAll(); verifyAll();
resetFull(); resetFull();
assertEquals("Map.size() should equal the number of entries in the map", getSampleKeys().length, map.size()); assertEquals(getSampleKeys().length, map.size(), "Map.size() should equal the number of entries in the map");
verifyAll(); verifyAll();
} }
@@ -602,13 +599,13 @@ public abstract class MapAbstractTest extends ObjectAbstractTest {
resetEmpty(); resetEmpty();
for (Object key : keys) { for (Object key : keys) {
assertTrue("Map must not contain key when map is empty", !map.containsKey(key)); assertTrue(!map.containsKey(key), "Map must not contain key when map is empty");
} }
verifyAll(); verifyAll();
resetFull(); resetFull();
for (Object key : keys) { for (Object key : keys) {
assertTrue("Map must contain key for a mapping in the map. Missing: " + key, map.containsKey(key)); assertTrue(map.containsKey(key), "Map must contain key for a mapping in the map. Missing: " + key);
} }
verifyAll(); verifyAll();
} }
@@ -624,13 +621,13 @@ public abstract class MapAbstractTest extends ObjectAbstractTest {
resetEmpty(); resetEmpty();
for (Object value : values) { for (Object value : values) {
assertTrue("Empty map must not contain value", !map.containsValue(value)); assertTrue(!map.containsValue(value), "Empty map must not contain value");
} }
verifyAll(); verifyAll();
resetFull(); resetFull();
for (Object value : values) { for (Object value : values) {
assertTrue("Map must contain value for a mapping in the map.", map.containsValue(value)); assertTrue(map.containsValue(value), "Map must contain value for a mapping in the map.");
} }
verifyAll(); verifyAll();
} }
@@ -641,11 +638,11 @@ public abstract class MapAbstractTest extends ObjectAbstractTest {
@Test @Test
public void testMapEquals() { public void testMapEquals() {
resetEmpty(); resetEmpty();
assertTrue("Empty maps unequal.", map.equals(confirmed)); assertTrue(map.equals(confirmed), "Empty maps unequal.");
verifyAll(); verifyAll();
resetFull(); resetFull();
assertTrue("Full maps unequal.", map.equals(confirmed)); assertTrue(map.equals(confirmed), "Full maps unequal.");
verifyAll(); verifyAll();
resetFull(); resetFull();
@@ -654,11 +651,11 @@ public abstract class MapAbstractTest extends ObjectAbstractTest {
Iterator iter = confirmed.keySet().iterator(); Iterator iter = confirmed.keySet().iterator();
iter.next(); iter.next();
iter.remove(); iter.remove();
assertTrue("Different maps equal.", !map.equals(confirmed)); assertTrue(!map.equals(confirmed), "Different maps equal.");
resetFull(); resetFull();
assertTrue("equals(null) returned true.", !map.equals(null)); assertTrue(!map.equals(null), "equals(null) returned true.");
assertTrue("equals(new Object()) returned true.", !map.equals(new Object())); assertTrue(!map.equals(new Object()), "equals(new Object()) returned true.");
verifyAll(); verifyAll();
} }
@@ -673,14 +670,14 @@ public abstract class MapAbstractTest extends ObjectAbstractTest {
Object[] values = getSampleValues(); Object[] values = getSampleValues();
for (Object key : keys) { for (Object key : keys) {
assertTrue("Empty map.get() should return null.", map.get(key) == null); assertTrue(map.get(key) == null, "Empty map.get() should return null.");
} }
verifyAll(); verifyAll();
resetFull(); resetFull();
for (int i = 0; i < keys.length; i++) { for (int i = 0; i < keys.length; i++) {
assertEquals("Full map.get() should return value from mapping.", values[i], map.get(keys[i])); assertEquals(values[i], map.get(keys[i]), "Full map.get() should return value from mapping.");
} }
} }
@@ -690,10 +687,10 @@ public abstract class MapAbstractTest extends ObjectAbstractTest {
@Test @Test
public void testMapHashCode() { public void testMapHashCode() {
resetEmpty(); resetEmpty();
assertTrue("Empty maps have different hashCodes.", map.hashCode() == confirmed.hashCode()); assertTrue(map.hashCode() == confirmed.hashCode(), "Empty maps have different hashCodes.");
resetFull(); resetFull();
assertTrue("Equal maps have different hashCodes.", map.hashCode() == confirmed.hashCode()); assertTrue(map.hashCode() == confirmed.hashCode(), "Equal maps have different hashCodes.");
} }
/** /**
@@ -708,11 +705,11 @@ public abstract class MapAbstractTest extends ObjectAbstractTest {
@Test @Test
public void testMapToString() { public void testMapToString() {
resetEmpty(); resetEmpty();
assertTrue("Empty map toString() should not return null", map.toString() != null); assertTrue(map.toString() != null, "Empty map toString() should not return null");
verifyAll(); verifyAll();
resetFull(); resetFull();
assertTrue("Empty map toString() should not return null", map.toString() != null); assertTrue(map.toString() != null, "Empty map toString() should not return null");
verifyAll(); verifyAll();
} }
@@ -776,29 +773,23 @@ public abstract class MapAbstractTest extends ObjectAbstractTest {
Object o = map.put(keys[i], values[i]); Object o = map.put(keys[i], values[i]);
confirmed.put(keys[i], values[i]); confirmed.put(keys[i], values[i]);
verifyAll(); verifyAll();
assertTrue("First map.put should return null", o == null); assertTrue(o == null, "First map.put should return null");
assertTrue("Map should contain key after put", assertTrue(map.containsKey(keys[i]), "Map should contain key after put");
map.containsKey(keys[i])); assertTrue(map.containsValue(values[i]), "Map should contain value after put");
assertTrue("Map should contain value after put",
map.containsValue(values[i]));
} }
if (isPutChangeSupported()) { if (isPutChangeSupported()) {
for (int i = 0; i < keys.length; i++) { for (int i = 0; i < keys.length; i++) {
Object o = map.put(keys[i], newValues[i]); Object o = map.put(keys[i], newValues[i]);
confirmed.put(keys[i], newValues[i]); confirmed.put(keys[i], newValues[i]);
verifyAll(); verifyAll();
assertEquals("Map.put should return previous value when changed", assertEquals(values[i], o, "Map.put should return previous value when changed");
values[i], o); assertTrue(map.containsKey(keys[i]), "Map should still contain key after put when changed");
assertTrue("Map should still contain key after put when changed", assertTrue(map.containsValue(newValues[i]), "Map should contain new value after put when changed");
map.containsKey(keys[i]));
assertTrue("Map should contain new value after put when changed",
map.containsValue(newValues[i]));
// if duplicates are allowed, we're not guaranteed that the value // if duplicates are allowed, we're not guaranteed that the value
// no longer exists, so don't try checking that. // no longer exists, so don't try checking that.
if (!isAllowDuplicateValues()) { if (!isAllowDuplicateValues()) {
assertTrue("Map should not contain old value after put when changed", assertTrue(!map.containsValue(values[i]), "Map should not contain old value after put when changed");
!map.containsValue(values[i]));
} }
} }
} }
@@ -832,18 +823,14 @@ public abstract class MapAbstractTest extends ObjectAbstractTest {
Object o = map.put(key, newValues[i]); Object o = map.put(key, newValues[i]);
Object value = confirmed.put(key, newValues[i]); Object value = confirmed.put(key, newValues[i]);
verifyAll(); verifyAll();
assertEquals("Map.put should return previous value when changed", assertEquals(value, o, "Map.put should return previous value when changed");
value, o); assertTrue(map.containsKey(key), "Map should still contain key after put when changed");
assertTrue("Map should still contain key after put when changed", assertTrue(map.containsValue(newValues[i]), "Map should contain new value after put when changed");
map.containsKey(key));
assertTrue("Map should contain new value after put when changed",
map.containsValue(newValues[i]));
// if duplicates are allowed, we're not guaranteed that the value // if duplicates are allowed, we're not guaranteed that the value
// no longer exists, so don't try checking that. // no longer exists, so don't try checking that.
if (!isAllowDuplicateValues()) { if (!isAllowDuplicateValues()) {
assertTrue("Map should not contain old value after put when changed", assertTrue(!map.containsValue(values[i]), "Map should not contain old value after put when changed");
!map.containsValue(values[i]));
} }
} }
} }
@@ -970,7 +957,7 @@ public abstract class MapAbstractTest extends ObjectAbstractTest {
Object[] values = getSampleValues(); Object[] values = getSampleValues();
for (int i = 0; i < keys.length; i++) { for (int i = 0; i < keys.length; i++) {
Object o = map.remove(keys[i]); Object o = map.remove(keys[i]);
assertTrue("First map.remove should return null", o == null); assertTrue(o == null, "First map.remove should return null");
} }
verifyAll(); verifyAll();
@@ -981,8 +968,7 @@ public abstract class MapAbstractTest extends ObjectAbstractTest {
confirmed.remove(keys[i]); confirmed.remove(keys[i]);
verifyAll(); verifyAll();
assertEquals("map.remove with valid key should return value", assertEquals(values[i], o, "map.remove with valid key should return value");
values[i], o);
} }
Object[] other = getOtherKeys(); Object[] other = getOtherKeys();
@@ -991,10 +977,8 @@ public abstract class MapAbstractTest extends ObjectAbstractTest {
int size = map.size(); int size = map.size();
for (int i = 0; i < other.length; i++) { for (int i = 0; i < other.length; i++) {
Object o = map.remove(other[i]); Object o = map.remove(other[i]);
assertEquals("map.remove for nonexistent key should return null", assertEquals(o, null, "map.remove for nonexistent key should return null");
o, null); assertEquals(size, map.size(), "map.remove for nonexistent key should not shrink map");
assertEquals("map.remove for nonexistent key should not " +
"shrink map", size, map.size());
} }
verifyAll(); verifyAll();
} }
@@ -1204,10 +1188,9 @@ public abstract class MapAbstractTest extends ObjectAbstractTest {
} }
j++; j++;
} }
assertTrue("values().remove(obj) is broken", j < 10000); assertTrue(j < 10000, "values().remove(obj) is broken");
assertTrue( assertTrue(!map.containsValue(sampleValues[i]),
"Value should have been removed from the underlying map.", "Value should have been removed from the underlying map.");
!map.containsValue(sampleValues[i]));
} }
} }
} }
@@ -1230,9 +1213,8 @@ public abstract class MapAbstractTest extends ObjectAbstractTest {
// if key.remove is unsupported, just skip this test // if key.remove is unsupported, just skip this test
return; return;
} }
assertTrue( assertTrue(!map.containsKey(sampleKeys[i]),
"Key should have been removed from the underlying map.", "Key should have been removed from the underlying map.");
!map.containsKey(sampleKeys[i]));
} }
} }
@@ -1413,7 +1395,7 @@ public abstract class MapAbstractTest extends ObjectAbstractTest {
break; break;
} }
} }
assertNotNull("No matching entry in map for key '" + key + "'", entry); assertNotNull(entry, "No matching entry in map for key '" + key + "'");
return entry; return entry;
} }
@@ -1638,14 +1620,14 @@ public abstract class MapAbstractTest extends ObjectAbstractTest {
public void verifyMap() { public void verifyMap() {
int size = confirmed.size(); int size = confirmed.size();
boolean empty = confirmed.isEmpty(); boolean empty = confirmed.isEmpty();
assertEquals("Map should be same size as HashMap", size, map.size()); assertEquals(size, map.size(), "Map should be same size as HashMap");
assertEquals("Map should be empty if HashMap is", empty, map.isEmpty()); assertEquals(empty, map.isEmpty(), "Map should be empty if HashMap is");
assertEquals("hashCodes should be the same", confirmed.hashCode(), map.hashCode()); assertEquals(confirmed.hashCode(), map.hashCode(), "hashCodes should be the same");
// this fails for LRUMap because confirmed.equals() somehow modifies // this fails for LRUMap because confirmed.equals() somehow modifies
// map, causing concurrent modification exceptions. // map, causing concurrent modification exceptions.
//assertEquals("Map should still equal HashMap", confirmed, map); //assertEquals("Map should still equal HashMap", confirmed, map);
// this works though and performs the same verification: // this works though and performs the same verification:
assertTrue("Map should still equal HashMap", map.equals(confirmed)); assertTrue(map.equals(confirmed), "Map should still equal HashMap");
// TODO: this should really be reexamined to figure out why LRU map // TODO: this should really be reexamined to figure out why LRU map
// behaves like it does (the equals shouldn't modify since all accesses // behaves like it does (the equals shouldn't modify since all accesses
// by the confirmed collection should be through an iterator, thus not // by the confirmed collection should be through an iterator, thus not
@@ -1655,29 +1637,29 @@ public abstract class MapAbstractTest extends ObjectAbstractTest {
public void verifyEntrySet() { public void verifyEntrySet() {
int size = confirmed.size(); int size = confirmed.size();
boolean empty = confirmed.isEmpty(); boolean empty = confirmed.isEmpty();
assertEquals("entrySet should be same size as HashMap's\nTest: " + entrySet + "\nReal: " + confirmed.entrySet(), assertEquals(size, entrySet.size(),
size, entrySet.size()); "entrySet should be same size as HashMap's\nTest: " + entrySet + "\nReal: " + confirmed.entrySet());
assertEquals("entrySet should be empty if HashMap is\nTest: " + entrySet + "\nReal: " + confirmed.entrySet(), assertEquals(empty, entrySet.isEmpty(),
empty, entrySet.isEmpty()); "entrySet should be empty if HashMap is\nTest: " + entrySet + "\nReal: " + confirmed.entrySet());
assertTrue("entrySet should contain all HashMap's elements\nTest: " + entrySet + "\nReal: " + confirmed.entrySet(), assertTrue(entrySet.containsAll(confirmed.entrySet()),
entrySet.containsAll(confirmed.entrySet())); "entrySet should contain all HashMap's elements\nTest: " + entrySet + "\nReal: " + confirmed.entrySet());
assertEquals("entrySet hashCodes should be the same\nTest: " + entrySet + "\nReal: " + confirmed.entrySet(), assertEquals(confirmed.entrySet().hashCode(), entrySet.hashCode(),
confirmed.entrySet().hashCode(), entrySet.hashCode()); "entrySet hashCodes should be the same\nTest: " + entrySet + "\nReal: " + confirmed.entrySet());
assertEquals("Map's entry set should still equal HashMap's", confirmed.entrySet(), entrySet); assertEquals(confirmed.entrySet(), entrySet,"Map's entry set should still equal HashMap's");
} }
public void verifyKeySet() { public void verifyKeySet() {
int size = confirmed.size(); int size = confirmed.size();
boolean empty = confirmed.isEmpty(); boolean empty = confirmed.isEmpty();
assertEquals("keySet should be same size as HashMap's\nTest: " + keySet + "\nReal: " + confirmed.keySet(), assertEquals(size, keySet.size(),
size, keySet.size()); "keySet should be same size as HashMap's\nTest: " + keySet + "\nReal: " + confirmed.keySet());
assertEquals("keySet should be empty if HashMap is\nTest: " + keySet + "\nReal: " + confirmed.keySet(), assertEquals(empty, keySet.isEmpty(),
empty, keySet.isEmpty()); "keySet should be empty if HashMap is\nTest: " + keySet + "\nReal: " + confirmed.keySet());
assertTrue("keySet should contain all HashMap's elements\nTest: " + keySet + "\nReal: " + confirmed.keySet(), assertTrue(keySet.containsAll(confirmed.keySet()),
keySet.containsAll(confirmed.keySet())); "keySet should contain all HashMap's elements\nTest: " + keySet + "\nReal: " + confirmed.keySet());
assertEquals("keySet hashCodes should be the same\nTest: " + keySet + "\nReal: " + confirmed.keySet(), assertEquals(confirmed.keySet().hashCode(), keySet.hashCode(),
confirmed.keySet().hashCode(), keySet.hashCode()); "keySet hashCodes should be the same\nTest: " + keySet + "\nReal: " + confirmed.keySet());
assertEquals("Map's key set should still equal HashMap's", confirmed.keySet(), keySet); assertEquals(confirmed.keySet(), keySet, "Map's key set should still equal HashMap's");
} }
public void verifyValues() { public void verifyValues() {
@@ -1687,23 +1669,23 @@ public abstract class MapAbstractTest extends ObjectAbstractTest {
int size = confirmed.size(); int size = confirmed.size();
boolean empty = confirmed.isEmpty(); boolean empty = confirmed.isEmpty();
assertEquals("values should be same size as HashMap's\nTest: " + test + "\nReal: " + known, size, values.size()); assertEquals(size, values.size(), "values should be same size as HashMap's\nTest: " + test + "\nReal: " + known);
assertEquals("values should be empty if HashMap is\nTest: " + test + "\nReal: " + known, empty, values.isEmpty()); assertEquals(empty, values.isEmpty(), "values should be empty if HashMap is\nTest: " + test + "\nReal: " + known);
assertTrue("values should contain all HashMap's elements\nTest: " + test + "\nReal: " + known, test.containsAll(known)); assertTrue(test.containsAll(known), "values should contain all HashMap's elements\nTest: " + test + "\nReal: " + known);
assertTrue("values should contain all HashMap's elements\nTest: " + test + "\nReal: " + known, known.containsAll(test)); assertTrue(known.containsAll(test), "values should contain all HashMap's elements\nTest: " + test + "\nReal: " + known);
for (Object aKnown : known) { for (Object aKnown : known) {
boolean removed = test.remove(aKnown); boolean removed = test.remove(aKnown);
assertTrue("Map's values should still equal HashMap's", removed); assertTrue(removed, "Map's values should still equal HashMap's");
} }
assertTrue("Map's values should still equal HashMap's", test.isEmpty()); assertTrue(test.isEmpty(), "Map's values should still equal HashMap's");
} }
/** /**
* Erases any leftover instance variables by setting them to null. * Erases any leftover instance variables by setting them to null.
*/ */
@After @AfterEach
public void tearDown() throws Exception { public void tearDown() throws Exception {
map = null; map = null;
keySet = null; keySet = null;
@@ -30,13 +30,11 @@
package com.twelvemonkeys.util; package com.twelvemonkeys.util;
import org.junit.Test;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import static org.junit.Assert.assertEquals; import org.junit.jupiter.api.*;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.*;
/** /**
* NOTE: This TestCase is written especially for NullMap, and is full of dirty * NOTE: This TestCase is written especially for NullMap, and is full of dirty
@@ -83,12 +81,12 @@ public class NullMapTest extends MapAbstractTest {
@Override @Override
public void testMapIsEmpty() { public void testMapIsEmpty() {
resetEmpty(); resetEmpty();
assertEquals("Map.isEmpty() should return true with an empty map", assertEquals(true, map.isEmpty(),
true, map.isEmpty()); "Map.isEmpty() should return true with an empty map");
verifyAll(); verifyAll();
resetFull(); resetFull();
assertEquals("Map.isEmpty() should return true with a full map", assertEquals(true, map.isEmpty(),
true, map.isEmpty()); "Map.isEmpty() should return true with a full map");
} }
// Overriden, as this map is always empty // Overriden, as this map is always empty
@@ -96,13 +94,13 @@ public class NullMapTest extends MapAbstractTest {
@Override @Override
public void testMapSize() { public void testMapSize() {
resetEmpty(); resetEmpty();
assertEquals("Map.size() should be 0 with an empty map", assertEquals(0, map.size(),
0, map.size()); "Map.size() should be 0 with an empty map");
verifyAll(); verifyAll();
resetFull(); resetFull();
assertEquals("Map.size() should equal the number of entries " + assertEquals(0, map.size(),
"in the map", 0, map.size()); "Map.size() should equal the number of entries in the map");
} }
@Test @Test
@@ -112,7 +110,7 @@ public class NullMapTest extends MapAbstractTest {
resetEmpty(); resetEmpty();
for (Object key : keys) { for (Object key : keys) {
assertTrue("Map must not contain key when map is empty", !map.containsKey(key)); assertTrue(!map.containsKey(key),"Map must not contain key when map is empty");
} }
verifyAll(); verifyAll();
} }
@@ -124,7 +122,7 @@ public class NullMapTest extends MapAbstractTest {
resetEmpty(); resetEmpty();
for (Object value : values) { for (Object value : values) {
assertTrue("Empty map must not contain value", !map.containsValue(value)); assertTrue(!map.containsValue(value), "Empty map must not contain value");
} }
verifyAll(); verifyAll();
} }
@@ -133,7 +131,7 @@ public class NullMapTest extends MapAbstractTest {
@Override @Override
public void testMapEquals() { public void testMapEquals() {
resetEmpty(); resetEmpty();
assertTrue("Empty maps unequal.", map.equals(confirmed)); assertTrue(map.equals(confirmed), "Empty maps unequal.");
verifyAll(); verifyAll();
} }
@@ -141,8 +139,7 @@ public class NullMapTest extends MapAbstractTest {
@Override @Override
public void testMapHashCode() { public void testMapHashCode() {
resetEmpty(); resetEmpty();
assertTrue("Empty maps have different hashCodes.", assertTrue(map.hashCode() == confirmed.hashCode(), "Empty maps have different hashCodes.");
map.hashCode() == confirmed.hashCode());
} }
@Test @Test
@@ -153,7 +150,7 @@ public class NullMapTest extends MapAbstractTest {
Object[] keys = getSampleKeys(); Object[] keys = getSampleKeys();
for (Object key : keys) { for (Object key : keys) {
assertTrue("Empty map.get() should return null.", map.get(key) == null); assertTrue(map.get(key) == null, "Empty map.get() should return null.");
} }
verifyAll(); verifyAll();
} }
@@ -170,7 +167,7 @@ public class NullMapTest extends MapAbstractTest {
Object o = map.put(keys[i], values[i]); Object o = map.put(keys[i], values[i]);
//confirmed.put(keys[i], values[i]); //confirmed.put(keys[i], values[i]);
verifyAll(); verifyAll();
assertTrue("First map.put should return null", o == null); assertTrue(o == null, "First map.put should return null");
} }
for (int i = 0; i < keys.length; i++) { for (int i = 0; i < keys.length; i++) {
map.put(keys[i], newValues[i]); map.put(keys[i], newValues[i]);
@@ -183,8 +180,8 @@ public class NullMapTest extends MapAbstractTest {
@Override @Override
public void testMapToString() { public void testMapToString() {
resetEmpty(); resetEmpty();
assertTrue("Empty map toString() should not return null", assertTrue(map.toString() != null,
map.toString() != null); "Empty map toString() should not return null");
verifyAll(); verifyAll();
} }
@@ -202,7 +199,7 @@ public class NullMapTest extends MapAbstractTest {
Object[] keys = getSampleKeys(); Object[] keys = getSampleKeys();
for(int i = 0; i < keys.length; i++) { for(int i = 0; i < keys.length; i++) {
Object o = map.remove(keys[i]); Object o = map.remove(keys[i]);
assertTrue("First map.remove should return null", o == null); assertTrue(o == null, "First map.remove should return null");
} }
verifyAll(); verifyAll();
} }
@@ -44,12 +44,10 @@
*/ */
package com.twelvemonkeys.util; package com.twelvemonkeys.util;
import org.junit.Test;
import java.io.*; import java.io.*;
import static org.junit.Assert.assertEquals; import org.junit.jupiter.api.*;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.*;
/** /**
* Abstract test class for {@link Object} methods and contracts. * Abstract test class for {@link Object} methods and contracts.
@@ -119,7 +117,7 @@ public abstract class ObjectAbstractTest {
@Test @Test
public void testObjectEqualsSelf() { public void testObjectEqualsSelf() {
Object obj = makeObject(); Object obj = makeObject();
assertEquals("A Object should equal itself", obj, obj); assertEquals(obj, obj, "A Object should equal itself");
} }
@Test @Test
@@ -131,25 +129,24 @@ public abstract class ObjectAbstractTest {
@Test @Test
public void testObjectHashCodeEqualsSelfHashCode() { public void testObjectHashCodeEqualsSelfHashCode() {
Object obj = makeObject(); Object obj = makeObject();
assertEquals("hashCode should be repeatable", obj.hashCode(), obj.hashCode()); assertEquals(obj.hashCode(), obj.hashCode(), "hashCode should be repeatable");
} }
@Test @Test
public void testObjectHashCodeEqualsContract() { public void testObjectHashCodeEqualsContract() {
Object obj1 = makeObject(); Object obj1 = makeObject();
if (obj1.equals(obj1)) { if (obj1.equals(obj1)) {
assertEquals( assertEquals(obj1.hashCode(), obj1.hashCode(),
"[1] When two objects are equal, their hashCodes should be also.", "[1] When two objects are equal, their hashCodes should be also.");
obj1.hashCode(), obj1.hashCode());
} }
Object obj2 = makeObject(); Object obj2 = makeObject();
if (obj1.equals(obj2)) { if (obj1.equals(obj2)) {
assertEquals( assertEquals(
"[2] When two objects are equal, their hashCodes should be also.", obj1.hashCode(), obj2.hashCode(),
obj1.hashCode(), obj2.hashCode()); "[2] When two objects are equal, their hashCodes should be also.");
assertTrue( assertTrue(
"When obj1.equals(obj2) is true, then obj2.equals(obj1) should also be true", obj2.equals(obj1),
obj2.equals(obj1)); "When obj1.equals(obj2) is true, then obj2.equals(obj1) should also be true");
} }
} }
@@ -166,7 +163,7 @@ public abstract class ObjectAbstractTest {
Object dest = in.readObject(); Object dest = in.readObject();
in.close(); in.close();
if (isEqualsCheckable()) { if (isEqualsCheckable()) {
assertEquals("obj != deserialize(serialize(obj))", obj, dest); assertEquals(obj, dest, "obj != deserialize(serialize(obj))");
} }
} }
} }
@@ -199,8 +196,8 @@ public abstract class ObjectAbstractTest {
if (object instanceof Serializable) { if (object instanceof Serializable) {
String name = getCanonicalEmptyCollectionName(object); String name = getCanonicalEmptyCollectionName(object);
assertTrue( assertTrue(
"Canonical empty collection (" + name + ") is not in CVS", new File(name).exists(),
new File(name).exists()); "Canonical empty collection (" + name + ") is not in CVS");
} }
} }
} }
@@ -216,8 +213,8 @@ public abstract class ObjectAbstractTest {
if (object instanceof Serializable) { if (object instanceof Serializable) {
String name = getCanonicalFullCollectionName(object); String name = getCanonicalFullCollectionName(object);
assertTrue( assertTrue(
"Canonical full collection (" + name + ") is not in CVS", new File(name).exists(),
new File(name).exists()); "Canonical full collection (" + name + ") is not in CVS");
} }
} }
} }
@@ -44,12 +44,10 @@
*/ */
package com.twelvemonkeys.util; package com.twelvemonkeys.util;
import org.junit.Test;
import java.util.*; import java.util.*;
import static org.junit.Assert.assertEquals; import org.junit.jupiter.api.*;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.*;
/** /**
* Abstract test class for {@link Set} methods and contracts. * Abstract test class for {@link Set} methods and contracts.
@@ -79,14 +77,12 @@ public abstract class SetAbstractTest extends CollectionAbstractTest {
public void verifyAll() { public void verifyAll() {
super.verifyAll(); super.verifyAll();
assertEquals("Sets should be equal", confirmed, collection); assertEquals(confirmed, collection, "Sets should be equal");
assertEquals("Sets should have equal hashCodes", assertEquals(confirmed.hashCode(), collection.hashCode(), "Sets should have equal hashCodes");
confirmed.hashCode(), collection.hashCode());
Collection set = makeConfirmedCollection(); Collection set = makeConfirmedCollection();
Iterator iterator = collection.iterator(); Iterator iterator = collection.iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
assertTrue("Set.iterator should only return unique elements", assertTrue(set.add(iterator.next()), "Set.iterator should only return unique elements");
set.add(iterator.next()));
} }
} }
@@ -180,23 +176,20 @@ public abstract class SetAbstractTest extends CollectionAbstractTest {
@Test @Test
public void testSetEquals() { public void testSetEquals() {
resetEmpty(); resetEmpty();
assertEquals("Empty sets should be equal", assertEquals(getSet(), getConfirmedSet(), "Empty sets should be equal");
getSet(), getConfirmedSet());
verifyAll(); verifyAll();
Collection set2 = makeConfirmedCollection(); Collection set2 = makeConfirmedCollection();
set2.add("foo"); set2.add("foo");
assertTrue("Empty set shouldn't equal nonempty set", assertTrue(!getSet().equals(set2), "Empty set shouldn't equal nonempty set");
!getSet().equals(set2));
resetFull(); resetFull();
assertEquals("Full sets should be equal", getSet(), getConfirmedSet()); assertEquals(getSet(), getConfirmedSet(), "Full sets should be equal");
verifyAll(); verifyAll();
set2.clear(); set2.clear();
set2.addAll(Arrays.asList(getOtherElements())); set2.addAll(Arrays.asList(getOtherElements()));
assertTrue("Sets with different contents shouldn't be equal", assertTrue(!getSet().equals(set2), "Sets with different contents shouldn't be equal");
!getSet().equals(set2));
} }
/** /**
@@ -205,11 +198,9 @@ public abstract class SetAbstractTest extends CollectionAbstractTest {
@Test @Test
public void testSetHashCode() { public void testSetHashCode() {
resetEmpty(); resetEmpty();
assertEquals("Empty sets have equal hashCodes", assertEquals(getSet().hashCode(), getConfirmedSet().hashCode(), "Empty sets have equal hashCodes");
getSet().hashCode(), getConfirmedSet().hashCode());
resetFull(); resetFull();
assertEquals("Equal sets have equal hashCodes", assertEquals(getSet().hashCode(), getConfirmedSet().hashCode(), "Equal sets have equal hashCodes");
getSet().hashCode(), getConfirmedSet().hashCode());
} }
} }
@@ -30,12 +30,10 @@
package com.twelvemonkeys.util; package com.twelvemonkeys.util;
import org.junit.Test;
import java.util.Iterator; import java.util.Iterator;
import static org.junit.Assert.*; import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* StringTokenIteratorTestCase * StringTokenIteratorTestCase
@@ -56,88 +54,88 @@ public class StringTokenIteratorTest extends TokenIteratorAbstractTest {
@Test @Test
public void testEmptyDelimiter() { public void testEmptyDelimiter() {
Iterator iterator = createTokenIterator("", ""); Iterator iterator = createTokenIterator("", "");
assertFalse("Empty string has elements", iterator.hasNext()); assertFalse(iterator.hasNext(), "Empty string has elements");
} }
@Test @Test
public void testSingleToken() { public void testSingleToken() {
Iterator iterator = createTokenIterator("A"); Iterator iterator = createTokenIterator("A");
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("A", iterator.next()); assertEquals("A", iterator.next());
assertFalse("String has more than one element", iterator.hasNext()); assertFalse(iterator.hasNext(), "String has more than one element");
} }
@Test @Test
public void testSingleTokenEmptyDelimiter() { public void testSingleTokenEmptyDelimiter() {
Iterator iterator = createTokenIterator("A", ""); Iterator iterator = createTokenIterator("A", "");
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("A", iterator.next()); assertEquals("A", iterator.next());
assertFalse("String has more than one element", iterator.hasNext()); assertFalse(iterator.hasNext(), "String has more than one element");
} }
@Test @Test
public void testSingleTokenSingleDelimiter() { public void testSingleTokenSingleDelimiter() {
Iterator iterator = createTokenIterator("A", ","); Iterator iterator = createTokenIterator("A", ",");
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("A", iterator.next()); assertEquals("A", iterator.next());
assertFalse("String has more than one element", iterator.hasNext()); assertFalse(iterator.hasNext(), "String has more than one element");
} }
@Test @Test
public void testSingleSeparatorDefaultDelimiter() { public void testSingleSeparatorDefaultDelimiter() {
Iterator iterator = createTokenIterator("A B C D"); Iterator iterator = createTokenIterator("A B C D");
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("A", iterator.next()); assertEquals("A", iterator.next());
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("B", iterator.next()); assertEquals("B", iterator.next());
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("C", iterator.next()); assertEquals("C", iterator.next());
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("D", iterator.next()); assertEquals("D", iterator.next());
assertFalse("String has more than one element", iterator.hasNext()); assertFalse(iterator.hasNext(), "String has more than one element");
} }
@Test @Test
public void testSingleSeparator() { public void testSingleSeparator() {
Iterator iterator = createTokenIterator("A,B,C", ","); Iterator iterator = createTokenIterator("A,B,C", ",");
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("A", iterator.next()); assertEquals("A", iterator.next());
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("B", iterator.next()); assertEquals("B", iterator.next());
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("C", iterator.next()); assertEquals("C", iterator.next());
assertFalse("String has more than one element", iterator.hasNext()); assertFalse(iterator.hasNext(), "String has more than one element");
} }
@Test @Test
public void testMultipleSeparatorDefaultDelimiter() { public void testMultipleSeparatorDefaultDelimiter() {
Iterator iterator = createTokenIterator("A B C\nD\t\t \nE"); Iterator iterator = createTokenIterator("A B C\nD\t\t \nE");
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("A", iterator.next()); assertEquals("A", iterator.next());
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("B", iterator.next()); assertEquals("B", iterator.next());
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("C", iterator.next()); assertEquals("C", iterator.next());
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("D", iterator.next()); assertEquals("D", iterator.next());
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("E", iterator.next()); assertEquals("E", iterator.next());
assertFalse("String has more than one element", iterator.hasNext()); assertFalse(iterator.hasNext(), "String has more than one element");
} }
@Test @Test
public void testMultipleSeparator() { public void testMultipleSeparator() {
Iterator iterator = createTokenIterator("A,B,;,C...D, ., ,E", " ,.;:"); Iterator iterator = createTokenIterator("A,B,;,C...D, ., ,E", " ,.;:");
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("A", iterator.next()); assertEquals("A", iterator.next());
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("B", iterator.next()); assertEquals("B", iterator.next());
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("C", iterator.next()); assertEquals("C", iterator.next());
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("D", iterator.next()); assertEquals("D", iterator.next());
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("E", iterator.next()); assertEquals("E", iterator.next());
assertFalse("String has more than one element", iterator.hasNext()); assertFalse(iterator.hasNext(), "String has more than one element");
} }
} }
@@ -30,12 +30,10 @@
package com.twelvemonkeys.util; package com.twelvemonkeys.util;
import org.junit.Test;
import java.util.*; import java.util.*;
import static org.junit.Assert.*; import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* TimeoutMapTest * TimeoutMapTest
* <p/> * <p/>
@@ -541,7 +539,7 @@ public class TimeoutMapTest extends MapAbstractTest {
} }
} }
assertTrue("Elements expired too early, test did not run as expected.", count > 0); assertTrue(count > 0, "Elements expired too early, test did not run as expected.");
//assertEquals("Elements did not expire as expected.", 1, count); //assertEquals("Elements did not expire as expected.", 1, count);
} }
@@ -573,7 +571,7 @@ public class TimeoutMapTest extends MapAbstractTest {
} }
} }
assertTrue("Elements expired too early, test did not run as expected.", count > 0); assertTrue(count > 0, "Elements expired too early, test did not run as expected.");
//assertEquals("Elements did not expire as expected.", 1, count); //assertEquals("Elements did not expire as expected.", 1, count);
} }
@@ -613,7 +611,7 @@ public class TimeoutMapTest extends MapAbstractTest {
} }
} }
assertTrue("Elements expired too early, test did not run as expected.", count > 0); assertTrue(count > 0, "Elements expired too early, test did not run as expected.");
//assertEquals("Elements did not expire as expected.", 1, count); //assertEquals("Elements did not expire as expected.", 1, count);
} }
@@ -630,7 +628,7 @@ public class TimeoutMapTest extends MapAbstractTest {
Object removedKey = null; Object removedKey = null;
Object otherKey = null; Object otherKey = null;
Iterator iterator = map.entrySet().iterator(); Iterator iterator = map.entrySet().iterator();
assertTrue("Iterator was empty", iterator.hasNext()); assertTrue(iterator.hasNext(), "Iterator was empty");
try { try {
Map.Entry entry = (Map.Entry) iterator.next(); Map.Entry entry = (Map.Entry) iterator.next();
assertNotNull(entry); assertNotNull(entry);
@@ -648,8 +646,8 @@ public class TimeoutMapTest extends MapAbstractTest {
fail("Elements expired between Interator.hasNext() and Iterator.remove()"); fail("Elements expired between Interator.hasNext() and Iterator.remove()");
} }
assertTrue("Wrong entry removed, keySet().iterator() is broken.", !map.containsKey(removedKey)); assertTrue(!map.containsKey(removedKey), "Wrong entry removed, keySet().iterator() is broken.");
assertTrue("Wrong entry removed, keySet().iterator() is broken.", map.containsKey(otherKey)); assertTrue(map.containsKey(otherKey), "Wrong entry removed, keySet().iterator() is broken.");
} }
@@ -30,12 +30,10 @@
package com.twelvemonkeys.util; package com.twelvemonkeys.util;
import org.junit.Test;
import java.util.Iterator; import java.util.Iterator;
import static org.junit.Assert.assertFalse; import org.junit.jupiter.api.*;
import static org.junit.Assert.fail; import static org.junit.jupiter.api.Assertions.*;
/** /**
* TokenIteratorAbstractTestCase * TokenIteratorAbstractTestCase
@@ -80,7 +78,7 @@ public abstract class TokenIteratorAbstractTest {
@Test @Test
public void testEmptyString() { public void testEmptyString() {
Iterator iterator = createTokenIterator(""); Iterator iterator = createTokenIterator("");
assertFalse("Empty string has elements", iterator.hasNext()); assertFalse(iterator.hasNext(), "Empty string has elements");
} }
} }
@@ -30,8 +30,8 @@
package com.twelvemonkeys.util.convert; package com.twelvemonkeys.util.convert;
import org.junit.Ignore; import org.junit.jupiter.api.Disabled;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* ConverterTest * ConverterTest
@@ -43,7 +43,7 @@ import org.junit.Test;
*/ */
public class ConverterTest { public class ConverterTest {
@Ignore("Not implemented") @Disabled("Not implemented")
@Test @Test
public void testMe() { public void testMe() {
// TODO: Implement tests // TODO: Implement tests
@@ -31,7 +31,7 @@
package com.twelvemonkeys.util.convert; package com.twelvemonkeys.util.convert;
import com.twelvemonkeys.lang.DateUtil; import com.twelvemonkeys.lang.DateUtil;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.text.DateFormat; import java.text.DateFormat;
import java.util.Date; import java.util.Date;
@@ -31,13 +31,13 @@
package com.twelvemonkeys.util.convert; package com.twelvemonkeys.util.convert;
import com.twelvemonkeys.lang.Validate; import com.twelvemonkeys.lang.Validate;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File; import java.io.File;
import java.net.URI; import java.net.URI;
import static org.junit.Assert.*; import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* DefaultConverterTest * DefaultConverterTest
@@ -138,7 +138,7 @@ public class DefaultConverterTest extends PropertyConverterAbstractTest {
assertEquals(-2.3456, (Double) converter.toObject("-2.3456", Double.TYPE, null), 0); assertEquals(-2.3456, (Double) converter.toObject("-2.3456", Double.TYPE, null), 0);
} }
@Ignore("Known issue. Why would anyone do something like this?") @Disabled("Known issue. Why would anyone do something like this?")
@Test @Test
public void testConvertCharPrimitive() { public void testConvertCharPrimitive() {
PropertyConverter converter = makePropertyConverter(); PropertyConverter converter = makePropertyConverter();
@@ -32,11 +32,11 @@ package com.twelvemonkeys.util.convert;
import com.twelvemonkeys.lang.ObjectAbstractTest; import com.twelvemonkeys.lang.ObjectAbstractTest;
import com.twelvemonkeys.lang.Validate; import com.twelvemonkeys.lang.Validate;
import org.junit.Test;
import java.util.Arrays; import java.util.Arrays;
import static org.junit.Assert.*; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* PropertyConverterAbstractTest * PropertyConverterAbstractTest
@@ -66,26 +66,26 @@ public abstract class PropertyConverterAbstractTest extends ObjectAbstractTest {
try { try {
obj = converter.toObject(test.original(), test.type(), test.format()); obj = converter.toObject(test.original(), test.type(), test.format());
assertEquals(String.format("'%s' converted to incorrect type", test.original()), test.type(), obj.getClass()); assertEquals(test.type(), obj.getClass(), String.format("'%s' converted to incorrect type", test.original()));
if (test.type().isArray()) { if (test.type().isArray()) {
assertArrayEquals0(String.format("'%s' not converted", test.original()), test.value(), obj); assertArrayEquals0(String.format("'%s' not converted", test.original()), test.value(), obj);
} }
else { else {
assertEquals(String.format("'%s' not converted", test.original()), test.value(), obj); assertEquals(test.value(), obj, String.format("'%s' not converted", test.original()));
} }
String result = converter.toString(test.value(), test.format()); String result = converter.toString(test.value(), test.format());
assertEquals(String.format("'%s' does not match", test.converted()), test.converted(), result); assertEquals(test.converted(), result, String.format("'%s' does not match", test.converted()));
obj = converter.toObject(result, test.type(), test.format()); obj = converter.toObject(result, test.type(), test.format());
assertEquals(String.format("'%s' converted to incorrect type", test.original()), test.type(), obj.getClass()); assertEquals(test.type(), obj.getClass(), String.format("'%s' converted to incorrect type", test.original()));
if (test.type().isArray()) { if (test.type().isArray()) {
assertArrayEquals0(String.format("'%s' did not survive round trip conversion", test.original()), test.value(), obj); assertArrayEquals0(String.format("'%s' did not survive round trip conversion", test.original()), test.value(), obj);
} }
else { else {
assertEquals(String.format("'%s' did not survive round trip conversion", test.original()), test.value(), obj); assertEquals(test.value(), obj, String.format("'%s' did not survive round trip conversion", test.original()));
} }
} }
catch (ConversionException e) { catch (ConversionException e) {
@@ -98,35 +98,35 @@ public abstract class PropertyConverterAbstractTest extends ObjectAbstractTest {
Class<?> componentType = left.getClass().getComponentType(); Class<?> componentType = left.getClass().getComponentType();
if (componentType.isPrimitive()) { if (componentType.isPrimitive()) {
if (int.class == componentType) { if (int.class == componentType) {
assertArrayEquals(message, (int[]) left, (int[]) right); assertArrayEquals((int[]) left, (int[]) right, message);
} }
else if (short.class == componentType) { else if (short.class == componentType) {
assertArrayEquals(message, (short[]) left, (short[]) right); assertArrayEquals((short[]) left, (short[]) right, message);
} }
else if (long.class == componentType) { else if (long.class == componentType) {
assertArrayEquals(message, (long[]) left, (long[]) right); assertArrayEquals((long[]) left, (long[]) right, message);
} }
else if (float.class == componentType) { else if (float.class == componentType) {
assertArrayEquals(message, (float[]) left, (float[]) right, 0f); assertArrayEquals((float[]) left, (float[]) right, 0f, message);
} }
else if (double.class == componentType) { else if (double.class == componentType) {
assertArrayEquals(message, (double[]) left, (double[]) right, 0d); assertArrayEquals((double[]) left, (double[]) right, 0d, message);
} }
else if (boolean.class == componentType) { else if (boolean.class == componentType) {
assertTrue(message, Arrays.equals((boolean[]) left, (boolean[]) right)); assertTrue(Arrays.equals((boolean[]) left, (boolean[]) right), message);
} }
else if (byte.class == componentType) { else if (byte.class == componentType) {
assertArrayEquals(message, (byte[]) left, (byte[]) right); assertArrayEquals((byte[]) left, (byte[]) right, message);
} }
else if (char.class == componentType) { else if (char.class == componentType) {
assertArrayEquals(message, (char[]) left, (char[]) right); assertArrayEquals((char[]) left, (char[]) right, message);
} }
else { else {
fail(String.format("Unknown primitive type: %s", componentType)); fail(String.format("Unknown primitive type: %s", componentType));
} }
} }
else { else {
assertArrayEquals(message, (Object[]) left, (Object[]) right); assertArrayEquals((Object[]) left, (Object[]) right, message);
} }
} }
@@ -32,12 +32,11 @@ package com.twelvemonkeys.util.regex;
import com.twelvemonkeys.util.TokenIterator; import com.twelvemonkeys.util.TokenIterator;
import com.twelvemonkeys.util.TokenIteratorAbstractTest; import com.twelvemonkeys.util.TokenIteratorAbstractTest;
import org.junit.Test;
import java.util.Iterator; import java.util.Iterator;
import static org.junit.Assert.*; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* StringTokenIteratorTestCase * StringTokenIteratorTestCase
* <p/> * <p/>
@@ -68,9 +67,9 @@ public class RegExTokenIteratorTest extends TokenIteratorAbstractTest {
@Test @Test
public void testSingleToken() { public void testSingleToken() {
Iterator iterator = createTokenIterator("A"); Iterator iterator = createTokenIterator("A");
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("A", iterator.next()); assertEquals("A", iterator.next());
assertFalse("String has more than one element", iterator.hasNext()); assertFalse(iterator.hasNext(), "String has more than one element");
} }
@Test @Test
@@ -87,67 +86,67 @@ public class RegExTokenIteratorTest extends TokenIteratorAbstractTest {
@Test @Test
public void testSingleTokenSingleDelimiter() { public void testSingleTokenSingleDelimiter() {
Iterator iterator = createTokenIterator("A", "[^,]+"); Iterator iterator = createTokenIterator("A", "[^,]+");
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("A", iterator.next()); assertEquals("A", iterator.next());
assertFalse("String has more than one element", iterator.hasNext()); assertFalse(iterator.hasNext(), "String has more than one element");
} }
@Test @Test
public void testSingleSeparatorDefaultDelimiter() { public void testSingleSeparatorDefaultDelimiter() {
Iterator iterator = createTokenIterator("A B C D"); Iterator iterator = createTokenIterator("A B C D");
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("A", iterator.next()); assertEquals("A", iterator.next());
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("B", iterator.next()); assertEquals("B", iterator.next());
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("C", iterator.next()); assertEquals("C", iterator.next());
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("D", iterator.next()); assertEquals("D", iterator.next());
assertFalse("String has more than one element", iterator.hasNext()); assertFalse(iterator.hasNext(), "String has more than one element");
} }
@Test @Test
public void testSingleSeparator() { public void testSingleSeparator() {
Iterator iterator = createTokenIterator("A,B,C", "[^,]+"); Iterator iterator = createTokenIterator("A,B,C", "[^,]+");
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("A", iterator.next()); assertEquals("A", iterator.next());
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("B", iterator.next()); assertEquals("B", iterator.next());
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("C", iterator.next()); assertEquals("C", iterator.next());
assertFalse("String has more than one element", iterator.hasNext()); assertFalse(iterator.hasNext(), "String has more than one element");
} }
@Test @Test
public void testMultipleSeparatorDefaultDelimiter() { public void testMultipleSeparatorDefaultDelimiter() {
Iterator iterator = createTokenIterator("A B C\nD\t\t \nE"); Iterator iterator = createTokenIterator("A B C\nD\t\t \nE");
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("A", iterator.next()); assertEquals("A", iterator.next());
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("B", iterator.next()); assertEquals("B", iterator.next());
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("C", iterator.next()); assertEquals("C", iterator.next());
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("D", iterator.next()); assertEquals("D", iterator.next());
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("E", iterator.next()); assertEquals("E", iterator.next());
assertFalse("String has more than one element", iterator.hasNext()); assertFalse(iterator.hasNext(), "String has more than one element");
} }
@Test @Test
public void testMultipleSeparator() { public void testMultipleSeparator() {
Iterator iterator = createTokenIterator("A,B,;,C...D, ., ,E", "[^ ,.;:]+"); Iterator iterator = createTokenIterator("A,B,;,C...D, ., ,E", "[^ ,.;:]+");
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
Object o = iterator.next(); Object o = iterator.next();
assertEquals("A", o); assertEquals("A", o);
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("B", iterator.next()); assertEquals("B", iterator.next());
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("C", iterator.next()); assertEquals("C", iterator.next());
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("D", iterator.next()); assertEquals("D", iterator.next());
assertTrue("String has no elements", iterator.hasNext()); assertTrue(iterator.hasNext(), "String has no elements");
assertEquals("E", iterator.next()); assertEquals("E", iterator.next());
assertFalse("String has more than one element", iterator.hasNext()); assertFalse(iterator.hasNext(), "String has more than one element");
} }
} }
@@ -30,12 +30,13 @@
package com.twelvemonkeys.util.service; package com.twelvemonkeys.util.service;
import com.twelvemonkeys.lang.Validate;
import com.twelvemonkeys.util.CollectionUtil; import com.twelvemonkeys.util.CollectionUtil;
import org.junit.Test;
import java.util.*; import java.util.*;
import static org.junit.Assert.*; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* ServiceRegistryTest * ServiceRegistryTest
@@ -48,9 +49,11 @@ public class ServiceRegistryTest {
private final TestRegistry registry = new TestRegistry(); private final TestRegistry registry = new TestRegistry();
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateNull() { public void testCreateNull() {
assertThrows(IllegalArgumentException.class, () -> {
new ServiceRegistry(null); new ServiceRegistry(null);
});
} }
@Test @Test
@@ -64,11 +67,12 @@ public class ServiceRegistryTest {
} }
} }
@Test(expected = ServiceConfigurationError.class) @Test
public void testCreateBadConfig() { public void testCreateBadConfig() {
@SuppressWarnings("unchecked") assertThrows(ServiceConfigurationError.class, () -> {
ServiceRegistry registry = new ServiceRegistry(Arrays.asList(BadSPI.class).iterator()); ServiceRegistry registry = new ServiceRegistry(Arrays.asList(BadSPI.class).iterator());
registry.registerApplicationClasspathSPIs(); registry.registerApplicationClasspathSPIs();
});
// DONE: Test non-class // DONE: Test non-class
+9 -3
View File
@@ -45,9 +45,15 @@
</dependencyManagement> </dependencyManagement>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>org.junit.jupiter</groupId>
<artifactId>junit</artifactId> <artifactId>junit-jupiter-api</artifactId>
<version>4.13.2</version> <version>5.11.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>5.11.3</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
+9 -4
View File
@@ -61,11 +61,16 @@
<type>test-jar</type> <type>test-jar</type>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>org.junit.jupiter</groupId>
<artifactId>junit</artifactId> <artifactId>junit-jupiter-engine</artifactId>
<version>4.13.2</version> <version>5.11.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.11.3</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
@@ -1,9 +1,9 @@
package com.twelvemonkeys.contrib.exif; package com.twelvemonkeys.contrib.exif;
import org.junit.Test;
import static com.twelvemonkeys.contrib.exif.Orientation.*; import static com.twelvemonkeys.contrib.exif.Orientation.*;
import static org.junit.Assert.assertEquals;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/** /**
* OrientationTest. * OrientationTest.
@@ -34,8 +34,6 @@ import com.twelvemonkeys.contrib.tiff.TIFFUtilities.TIFFExtension;
import com.twelvemonkeys.imageio.plugins.tiff.TIFFImageMetadataFormat; import com.twelvemonkeys.imageio.plugins.tiff.TIFFImageMetadataFormat;
import com.twelvemonkeys.io.FileUtil; import com.twelvemonkeys.io.FileUtil;
import org.junit.Assert;
import org.junit.Test;
import org.w3c.dom.Node; import org.w3c.dom.Node;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
@@ -54,6 +52,9 @@ import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* TIFFUtilitiesTest * TIFFUtilitiesTest
* *
@@ -95,7 +96,7 @@ public class TIFFUtilitiesTest {
ImageInputStream iis = ImageIO.createImageInputStream(output); ImageInputStream iis = ImageIO.createImageInputStream(output);
ImageReader reader = ImageIO.getImageReaders(iis).next(); ImageReader reader = ImageIO.getImageReaders(iis).next();
reader.setInput(iis); reader.setInput(iis);
Assert.assertEquals(3, reader.getNumImages(true)); assertEquals(3, reader.getNumImages(true));
iis.close(); iis.close();
output.delete(); output.delete();
@@ -119,11 +120,11 @@ public class TIFFUtilitiesTest {
ImageReader reader = ImageIO.getImageReadersByFormatName("TIF").next(); ImageReader reader = ImageIO.getImageReadersByFormatName("TIF").next();
File[] outputFiles = outputDirectory.listFiles(); File[] outputFiles = outputDirectory.listFiles();
Assert.assertEquals(3, outputFiles.length); assertEquals(3, outputFiles.length);
for (File outputFile : outputFiles) { for (File outputFile : outputFiles) {
ImageInputStream iis = ImageIO.createImageInputStream(outputFile); ImageInputStream iis = ImageIO.createImageInputStream(outputFile);
reader.setInput(iis); reader.setInput(iis);
Assert.assertEquals(1, reader.getNumImages(true)); assertEquals(1, reader.getNumImages(true));
iis.close(); iis.close();
outputFile.delete(); outputFile.delete();
} }
@@ -157,7 +158,7 @@ public class TIFFUtilitiesTest {
Node metaData = reader.getImageMetadata(i) Node metaData = reader.getImageMetadata(i)
.getAsTree(TIFFImageMetadataFormat.SUN_NATIVE_IMAGE_METADATA_FORMAT_NAME); .getAsTree(TIFFImageMetadataFormat.SUN_NATIVE_IMAGE_METADATA_FORMAT_NAME);
short orientation = ((Number) expression.evaluate(metaData, XPathConstants.NUMBER)).shortValue(); short orientation = ((Number) expression.evaluate(metaData, XPathConstants.NUMBER)).shortValue();
Assert.assertEquals(orientation, TIFFExtension.ORIENTATION_RIGHTTOP); assertEquals(orientation, TIFFExtension.ORIENTATION_RIGHTTOP);
} }
checkTest1.close(); checkTest1.close();
@@ -174,7 +175,7 @@ public class TIFFUtilitiesTest {
Node metaData = reader.getImageMetadata(i) Node metaData = reader.getImageMetadata(i)
.getAsTree(TIFFImageMetadataFormat.SUN_NATIVE_IMAGE_METADATA_FORMAT_NAME); .getAsTree(TIFFImageMetadataFormat.SUN_NATIVE_IMAGE_METADATA_FORMAT_NAME);
short orientation = ((Number) expression.evaluate(metaData, XPathConstants.NUMBER)).shortValue(); short orientation = ((Number) expression.evaluate(metaData, XPathConstants.NUMBER)).shortValue();
Assert.assertEquals(orientation, i == 1 assertEquals(orientation, i == 1
? TIFFExtension.ORIENTATION_BOTRIGHT ? TIFFExtension.ORIENTATION_BOTRIGHT
: TIFFExtension.ORIENTATION_RIGHTTOP); : TIFFExtension.ORIENTATION_RIGHTTOP);
} }
@@ -199,7 +200,7 @@ public class TIFFUtilitiesTest {
byte[] original = ((DataBufferByte) image.getData().getDataBuffer()).getData(); byte[] original = ((DataBufferByte) image.getData().getDataBuffer()).getData();
byte[] rotated = ((DataBufferByte) image360.getData().getDataBuffer()).getData(); byte[] rotated = ((DataBufferByte) image360.getData().getDataBuffer()).getData();
Assert.assertArrayEquals(original, rotated); assertArrayEquals(original, rotated);
} }
@Test @Test
@@ -32,16 +32,16 @@ package com.twelvemonkeys.imageio.plugins.svg;
import com.twelvemonkeys.imageio.stream.ByteArrayImageInputStream; import com.twelvemonkeys.imageio.stream.ByteArrayImageInputStream;
import com.twelvemonkeys.imageio.stream.URLImageInputStreamSpi; import com.twelvemonkeys.imageio.stream.URLImageInputStreamSpi;
import org.junit.Test;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import javax.imageio.spi.IIORegistry; import javax.imageio.spi.IIORegistry;
import javax.imageio.spi.ImageReaderSpi; import javax.imageio.spi.ImageReaderSpi;
import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageInputStream;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.time.Duration;
import static org.junit.Assert.assertFalse; import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.*;
/** /**
* SVGImageReaderSpiTest. * SVGImageReaderSpiTest.
@@ -83,18 +83,20 @@ public class SVGImageReaderSpiTest {
public void canDecodeInput() throws Exception { public void canDecodeInput() throws Exception {
for (String validInput : VALID_INPUTS) { for (String validInput : VALID_INPUTS) {
try (ImageInputStream input = ImageIO.createImageInputStream(getClass().getResource(validInput))) { try (ImageInputStream input = ImageIO.createImageInputStream(getClass().getResource(validInput))) {
assertTrue("Can't read valid input: " + validInput, provider.canDecodeInput(input)); assertTrue(provider.canDecodeInput(input), "Can't read valid input: " + validInput);
} }
} }
} }
// Test will time out, if EOFs are not properly detected, see #275 // Test will time out, if EOFs are not properly detected, see #275
@Test(timeout = 5000) @Test
public void canDecodeInputInvalid() throws Exception { public void canDecodeInputInvalid() throws Exception {
assertTimeoutPreemptively(Duration.ofMillis(5000), () -> {
for (String invalidInput : INVALID_INPUTS) { for (String invalidInput : INVALID_INPUTS) {
try (ImageInputStream input = new ByteArrayImageInputStream(invalidInput.getBytes(StandardCharsets.UTF_8))) { try (ImageInputStream input = new ByteArrayImageInputStream(invalidInput.getBytes(StandardCharsets.UTF_8))) {
assertFalse("Claims to read invalid input:" + invalidInput, provider.canDecodeInput(input)); assertFalse(provider.canDecodeInput(input), "Claims to read invalid input:" + invalidInput);
} }
} }
});
} }
} }
@@ -32,9 +32,6 @@ package com.twelvemonkeys.imageio.plugins.svg;
import com.twelvemonkeys.imageio.util.ImageReaderAbstractTest; import com.twelvemonkeys.imageio.util.ImageReaderAbstractTest;
import org.junit.Ignore;
import org.junit.Test;
import javax.imageio.IIOException; import javax.imageio.IIOException;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam; import javax.imageio.ImageReadParam;
@@ -52,10 +49,9 @@ import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static org.junit.Assert.assertEquals; import org.junit.jupiter.api.Disabled;
import static org.junit.Assert.assertNotNull; import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.*;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
/** /**
@@ -128,18 +124,18 @@ public class SVGImageReaderTest extends ImageReaderAbstractTest<SVGImageReader>
int current = image.getRGB(x, y); int current = image.getRGB(x, y);
if (x < quadPoint) { if (x < quadPoint) {
if (y < quadPoint) { if (y < quadPoint) {
assertEquals("x=" + x + " y=" + y + " q=" + quadPoint, 0xFF0000FF, current); assertEquals( 0xFF0000FF, current, "x=" + x + " y=" + y + " q=" + quadPoint);
} }
else { else {
assertEquals("x=" + x + " y=" + y + " q=" + quadPoint, 0xFFFF0000, current); assertEquals(0xFFFF0000, current, "x=" + x + " y=" + y + " q=" + quadPoint);
} }
} }
else { else {
if (y < quadPoint) { if (y < quadPoint) {
assertEquals("x=" + x + " y=" + y + " q=" + quadPoint, 0xFF00FF00, current); assertEquals(0xFF00FF00, current, "x=" + x + " y=" + y + " q=" + quadPoint);
} }
else { else {
assertEquals("x=" + x + " y=" + y + " q=" + quadPoint, 0xFF000000, current); assertEquals(0xFF000000, current, "x=" + x + " y=" + y + " q=" + quadPoint);
} }
} }
} }
@@ -171,14 +167,14 @@ public class SVGImageReaderTest extends ImageReaderAbstractTest<SVGImageReader>
} }
@Test @Test
@Ignore("Known issue: Source region reading not supported") @Disabled("Known issue: Source region reading not supported")
@Override @Override
public void testReadWithSourceRegionParamEqualImage() throws IOException { public void testReadWithSourceRegionParamEqualImage() throws IOException {
super.testReadWithSourceRegionParamEqualImage(); super.testReadWithSourceRegionParamEqualImage();
} }
@Test @Test
@Ignore("Known issue: Subsampled reading not supported") @Disabled("Known issue: Subsampled reading not supported")
@Override @Override
public void testReadWithSubsampleParamPixels() throws IOException { public void testReadWithSubsampleParamPixels() throws IOException {
super.testReadWithSubsampleParamPixels(); super.testReadWithSubsampleParamPixels();
@@ -316,7 +312,7 @@ public class SVGImageReaderTest extends ImageReaderAbstractTest<SVGImageReader>
} }
} }
@Test(expected = SecurityException.class) @Test
public void testDisallowedExternalResources() throws URISyntaxException, IOException { public void testDisallowedExternalResources() throws URISyntaxException, IOException {
// system-property set to true in surefire-plugin-settings in the pom // system-property set to true in surefire-plugin-settings in the pom
URL resource = getClassLoaderResource("/svg/barChart.svg"); URL resource = getClassLoaderResource("/svg/barChart.svg");
@@ -333,7 +329,9 @@ public class SVGImageReaderTest extends ImageReaderAbstractTest<SVGImageReader>
// `reader.read` for `/svg/barChart.svg` should raise // `reader.read` for `/svg/barChart.svg` should raise
// a SecurityException when External Resources are blocked // a SecurityException when External Resources are blocked
// because the API invocation gets preference // because the API invocation gets preference
assertThrows(SecurityException.class, () -> {
reader.read(0, param); reader.read(0, param);
});
} }
finally { finally {
reader.dispose(); reader.dispose();
@@ -32,9 +32,6 @@ package com.twelvemonkeys.imageio.plugins.wmf;
import com.twelvemonkeys.imageio.util.ImageReaderAbstractTest; import com.twelvemonkeys.imageio.util.ImageReaderAbstractTest;
import org.junit.Ignore;
import org.junit.Test;
import javax.imageio.spi.ImageReaderSpi; import javax.imageio.spi.ImageReaderSpi;
import java.awt.*; import java.awt.*;
import java.io.IOException; import java.io.IOException;
@@ -42,6 +39,8 @@ import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
/** /**
* WMFImageReaderTest * WMFImageReaderTest
* *
@@ -77,14 +76,14 @@ public class WMFImageReaderTest extends ImageReaderAbstractTest<WMFImageReader>
} }
@Test @Test
@Ignore("Known issue: Source region reading not supported") @Disabled("Known issue: Source region reading not supported")
@Override @Override
public void testReadWithSourceRegionParamEqualImage() throws IOException { public void testReadWithSourceRegionParamEqualImage() throws IOException {
super.testReadWithSourceRegionParamEqualImage(); super.testReadWithSourceRegionParamEqualImage();
} }
@Test @Test
@Ignore("Known issue: Subsampled reading not supported") @Disabled("Known issue: Subsampled reading not supported")
@Override @Override
public void testReadWithSubsampleParamPixels() throws IOException { public void testReadWithSubsampleParamPixels() throws IOException {
super.testReadWithSubsampleParamPixels(); super.testReadWithSubsampleParamPixels();
@@ -33,8 +33,8 @@ package com.twelvemonkeys.imageio.plugins.bmp;
import com.twelvemonkeys.imageio.util.ImageReaderAbstractTest; import com.twelvemonkeys.imageio.util.ImageReaderAbstractTest;
import com.twelvemonkeys.xml.XMLSerializer; import com.twelvemonkeys.xml.XMLSerializer;
import org.junit.Ignore; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.Disabled;
import org.mockito.InOrder; import org.mockito.InOrder;
import org.w3c.dom.Node; import org.w3c.dom.Node;
import org.w3c.dom.NodeList; import org.w3c.dom.NodeList;
@@ -59,8 +59,8 @@ import java.util.Collections;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
import static org.junit.Assume.assumeNoException; import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.mockito.ArgumentMatchers.anyFloat; import static org.mockito.ArgumentMatchers.anyFloat;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.atLeastOnce;
@@ -204,11 +204,11 @@ public class BMPImageReaderTest extends ImageReaderAbstractTest<BMPImageReader>
} }
} }
assertTrue("ImageTypeSepcifier from getRawImageType should be in the iterator from getImageTypes", rawFound); assertTrue(rawFound, "ImageTypeSepcifier from getRawImageType should be in the iterator from getImageTypes");
} }
} }
@Ignore("Known issue: Subsampled reading is currently broken") @Disabled("Known issue: Subsampled reading is currently broken")
@Test @Test
public void testReadWithSubsampleParamPixelsIndexed8() throws IOException { public void testReadWithSubsampleParamPixelsIndexed8() throws IOException {
ImageReader reader = createReader(); ImageReader reader = createReader();
@@ -235,7 +235,7 @@ public class BMPImageReaderTest extends ImageReaderAbstractTest<BMPImageReader>
// TODO: 1. Subsampling is currently broken, should fix it. // TODO: 1. Subsampling is currently broken, should fix it.
// 2. BMPs are (normally) stored bottom/up, meaning y subsampling offsets will differ from normal // 2. BMPs are (normally) stored bottom/up, meaning y subsampling offsets will differ from normal
// subsampling of the same data with an offset... Should we deal with this in the reader? Yes? // subsampling of the same data with an offset... Should we deal with this in the reader? Yes?
@Ignore("Known issue: Subsampled reading is currently broken") @Disabled("Known issue: Subsampled reading is currently broken")
@Test @Test
@Override @Override
public void testReadWithSubsampleParamPixels() throws IOException { public void testReadWithSubsampleParamPixels() throws IOException {
@@ -260,7 +260,7 @@ public class BMPImageReaderTest extends ImageReaderAbstractTest<BMPImageReader>
assertSubsampledImageDataEquals("Subsampled image data does not match expected", image, subsampled, param); assertSubsampledImageDataEquals("Subsampled image data does not match expected", image, subsampled, param);
} }
@Test(expected = IIOException.class) @Test
public void testReadCorruptCausesIIOException() throws IOException { public void testReadCorruptCausesIIOException() throws IOException {
// See https://bugs.openjdk.java.net/browse/JDK-8066904 // See https://bugs.openjdk.java.net/browse/JDK-8066904
// NullPointerException when calling ImageIO.read(InputStream) with corrupt BMP // NullPointerException when calling ImageIO.read(InputStream) with corrupt BMP
@@ -268,7 +268,9 @@ public class BMPImageReaderTest extends ImageReaderAbstractTest<BMPImageReader>
try { try {
reader.setInput(ImageIO.createImageInputStream(getClassLoaderResource("/broken-bmp/corrupted-bmp.bmp"))); reader.setInput(ImageIO.createImageInputStream(getClassLoaderResource("/broken-bmp/corrupted-bmp.bmp")));
assertThrows(IIOException.class, () -> {
reader.read(0); reader.read(0);
});
} }
finally { finally {
reader.dispose(); reader.dispose();
@@ -331,7 +333,7 @@ public class BMPImageReaderTest extends ImageReaderAbstractTest<BMPImageReader>
catch (Exception e) { catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
// Ignore this test if not on an Oracle JRE (com.sun...BMPImageReader not available) // Ignore this test if not on an Oracle JRE (com.sun...BMPImageReader not available)
assumeNoException(e); assumeTrue(false, "Skipping test: BMPImageReaderSpi not available on non-Oracle JREs");
return; return;
} }
@@ -383,7 +385,7 @@ public class BMPImageReaderTest extends ImageReaderAbstractTest<BMPImageReader>
new XMLSerializer(expected, "UTF-8").serialize(expectedTree, false); new XMLSerializer(expected, "UTF-8").serialize(expectedTree, false);
new XMLSerializer(actual, "UTF-8").serialize(actualTree, false); new XMLSerializer(actual, "UTF-8").serialize(actualTree, false);
assertEquals(e.getMessage(), new String(expected.toByteArray(), StandardCharsets.UTF_8), new String(actual.toByteArray(), StandardCharsets.UTF_8)); assertEquals(new String(expected.toByteArray(), StandardCharsets.UTF_8), new String(actual.toByteArray(), StandardCharsets.UTF_8), e.getMessage());
throw e; throw e;
} }
@@ -392,24 +394,24 @@ public class BMPImageReaderTest extends ImageReaderAbstractTest<BMPImageReader>
} }
private void assertNodeEquals(final String message, final Node expected, final Node actual) { private void assertNodeEquals(final String message, final Node expected, final Node actual) {
assertEquals(message + " class differs", expected.getClass(), actual.getClass()); assertEquals(expected.getClass(), actual.getClass(), message + " class differs");
if (!excludeEqualValueTest(expected)) { if (!excludeEqualValueTest(expected)) {
assertEquals(message, expected.getNodeValue(), actual.getNodeValue()); assertEquals(expected.getNodeValue(), actual.getNodeValue(), message);
if (expected instanceof IIOMetadataNode) { if (expected instanceof IIOMetadataNode) {
IIOMetadataNode expectedIIO = (IIOMetadataNode) expected; IIOMetadataNode expectedIIO = (IIOMetadataNode) expected;
IIOMetadataNode actualIIO = (IIOMetadataNode) actual; IIOMetadataNode actualIIO = (IIOMetadataNode) actual;
assertEquals(message, expectedIIO.getUserObject(), actualIIO.getUserObject()); assertEquals(expectedIIO.getUserObject(), actualIIO.getUserObject(), message);
} }
} }
NodeList expectedChildNodes = expected.getChildNodes(); NodeList expectedChildNodes = expected.getChildNodes();
NodeList actualChildNodes = actual.getChildNodes(); NodeList actualChildNodes = actual.getChildNodes();
assertTrue(message + " child length differs: " + toString(expectedChildNodes) + " != " + toString(actualChildNodes), assertTrue(expectedChildNodes.getLength() <= actualChildNodes.getLength(),
expectedChildNodes.getLength() <= actualChildNodes.getLength()); message + " child length differs: " + toString(expectedChildNodes) + " != " + toString(actualChildNodes));
for (int i = 0; i < expectedChildNodes.getLength(); i++) { for (int i = 0; i < expectedChildNodes.getLength(); i++) {
Node expectedChild = expectedChildNodes.item(i); Node expectedChild = expectedChildNodes.item(i);
@@ -423,7 +425,7 @@ public class BMPImageReaderTest extends ImageReaderAbstractTest<BMPImageReader>
} }
} }
assertEquals(message + " node name differs", expectedChild.getLocalName(), actualChild.getLocalName()); assertEquals(expectedChild.getLocalName(), actualChild.getLocalName(), message + " node name differs");
assertNodeEquals(message + "/" + expectedChild.getLocalName(), expectedChild, actualChild); assertNodeEquals(message + "/" + expectedChild.getLocalName(), expectedChild, actualChild);
} }
} }
@@ -32,9 +32,6 @@ package com.twelvemonkeys.imageio.plugins.bmp;
import com.twelvemonkeys.imageio.util.ImageReaderAbstractTest; import com.twelvemonkeys.imageio.util.ImageReaderAbstractTest;
import org.junit.Ignore;
import org.junit.Test;
import javax.imageio.ImageReadParam; import javax.imageio.ImageReadParam;
import javax.imageio.spi.ImageReaderSpi; import javax.imageio.spi.ImageReaderSpi;
import java.awt.*; import java.awt.*;
@@ -44,7 +41,9 @@ import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static org.junit.Assert.*; import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* CURImageReaderTest * CURImageReaderTest
@@ -93,16 +92,16 @@ public class CURImageReaderTest extends ImageReaderAbstractTest<CURImageReader>
if (hotspot != Image.UndefinedProperty || pParam == null) { if (hotspot != Image.UndefinedProperty || pParam == null) {
// Typically never happens, because of weirdness with UndefinedProperty // Typically never happens, because of weirdness with UndefinedProperty
assertNotNull("Hotspot for cursor not present", hotspot); assertNotNull(hotspot, "Hotspot for cursor not present");
// Image weirdness // Image weirdness
assertNotSame("Hotspot for cursor undefined (java.awt.Image.UndefinedProperty)", Image.UndefinedProperty, hotspot); assertNotSame(Image.UndefinedProperty, hotspot, "Hotspot for cursor undefined (java.awt.Image.UndefinedProperty)");
assertTrue(String.format("Hotspot not a java.awt.Point: %s", hotspot.getClass()), hotspot instanceof Point); assertTrue(hotspot instanceof Point, String.format("Hotspot not a java.awt.Point: %s", hotspot.getClass()));
assertEquals(pExpected, hotspot); assertEquals(pExpected, hotspot);
} }
assertNotNull("Hotspot for cursor not present", reader.getHotSpot(0)); assertNotNull(reader.getHotSpot(0), "Hotspot for cursor not present");
assertEquals(pExpected, reader.getHotSpot(0)); assertEquals(pExpected, reader.getHotSpot(0));
} }
@@ -141,14 +140,14 @@ public class CURImageReaderTest extends ImageReaderAbstractTest<CURImageReader>
// TODO: Test cursor is transparent // TODO: Test cursor is transparent
@Test @Test
@Ignore("Known issue") @Disabled("Known issue")
@Override @Override
public void testNotBadCaching() throws IOException { public void testNotBadCaching() throws IOException {
super.testNotBadCaching(); super.testNotBadCaching();
} }
@Test @Test
@Ignore("Known issue: Subsampled reading currently not supported") @Disabled("Known issue: Subsampled reading currently not supported")
@Override @Override
public void testReadWithSubsampleParamPixels() throws IOException { public void testReadWithSubsampleParamPixels() throws IOException {
super.testReadWithSubsampleParamPixels(); super.testReadWithSubsampleParamPixels();
@@ -32,9 +32,6 @@ package com.twelvemonkeys.imageio.plugins.bmp;
import com.twelvemonkeys.imageio.util.ImageReaderAbstractTest; import com.twelvemonkeys.imageio.util.ImageReaderAbstractTest;
import org.junit.Ignore;
import org.junit.Test;
import javax.imageio.spi.ImageReaderSpi; import javax.imageio.spi.ImageReaderSpi;
import java.awt.*; import java.awt.*;
import java.io.IOException; import java.io.IOException;
@@ -42,6 +39,9 @@ import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
/** /**
* ICOImageReaderTest * ICOImageReaderTest
* *
@@ -98,14 +98,14 @@ public class ICOImageReaderTest extends ImageReaderAbstractTest<ICOImageReader>
} }
@Test @Test
@Ignore("Known issue") @Disabled("Known issue")
@Override @Override
public void testNotBadCaching() throws IOException { public void testNotBadCaching() throws IOException {
super.testNotBadCaching(); super.testNotBadCaching();
} }
@Test @Test
@Ignore("Known issue: Subsampled reading currently not supported") @Disabled("Known issue: Subsampled reading currently not supported")
@Override @Override
public void testReadWithSubsampleParamPixels() throws IOException { public void testReadWithSubsampleParamPixels() throws IOException {
super.testReadWithSubsampleParamPixels(); super.testReadWithSubsampleParamPixels();
@@ -32,7 +32,6 @@ package com.twelvemonkeys.imageio.plugins.bmp;
import com.twelvemonkeys.io.enc.Decoder; import com.twelvemonkeys.io.enc.Decoder;
import com.twelvemonkeys.io.enc.DecoderStream; import com.twelvemonkeys.io.enc.DecoderStream;
import org.junit.Test;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
@@ -42,8 +41,8 @@ import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel; import java.nio.channels.ReadableByteChannel;
import java.util.Arrays; import java.util.Arrays;
import static org.junit.Assert.assertArrayEquals; import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.*;
public class RLE4DecoderTest { public class RLE4DecoderTest {
@@ -82,8 +81,8 @@ public class RLE4DecoderTest {
int r = channel.read(plain); int r = channel.read(plain);
plain.rewind(); plain.rewind();
assertEquals("Difference at line " + i, r, d); assertEquals(r, d, "Difference at line " + i);
assertArrayEquals("Difference at line " + i, plain.array(), decoded.array()); assertArrayEquals(plain.array(), decoded.array(), "Difference at line " + i);
} }
} }
@@ -104,7 +103,7 @@ public class RLE4DecoderTest {
int pos = 0; int pos = 0;
while (true) { while (true) {
int expected = plainSream.read(); int expected = plainSream.read();
assertEquals("Differs at " + pos, expected, decoded.read()); assertEquals(expected, decoded.read(), "Differs at " + pos);
if (expected < 0) { if (expected < 0) {
break; break;
@@ -32,7 +32,6 @@ package com.twelvemonkeys.imageio.plugins.bmp;
import com.twelvemonkeys.io.enc.Decoder; import com.twelvemonkeys.io.enc.Decoder;
import com.twelvemonkeys.io.enc.DecoderStream; import com.twelvemonkeys.io.enc.DecoderStream;
import org.junit.Test;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
@@ -42,8 +41,8 @@ import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel; import java.nio.channels.ReadableByteChannel;
import java.util.Arrays; import java.util.Arrays;
import static org.junit.Assert.assertArrayEquals; import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.*;
public class RLE8DecoderTest { public class RLE8DecoderTest {
@@ -108,7 +107,7 @@ public class RLE8DecoderTest {
while (true) { while (true) {
int expected = plainSream.read(); int expected = plainSream.read();
assertEquals("Differs at " + pos, expected, decoded.read()); assertEquals(expected, decoded.read(), "Differs at " + pos);
if (expected < 0) { if (expected < 0) {
break; break;
@@ -30,8 +30,6 @@
package com.twelvemonkeys.imageio.path; package com.twelvemonkeys.imageio.path;
import org.junit.Test;
import javax.imageio.IIOException; import javax.imageio.IIOException;
import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageInputStream;
import java.awt.geom.Path2D; import java.awt.geom.Path2D;
@@ -39,36 +37,39 @@ import java.io.DataInput;
import java.io.IOException; import java.io.IOException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static com.twelvemonkeys.imageio.path.PathsTest.assertPathEquals; import static com.twelvemonkeys.imageio.path.PathsTest.assertPathEquals;
import static com.twelvemonkeys.imageio.path.PathsTest.readExpectedPath; import static com.twelvemonkeys.imageio.path.PathsTest.readExpectedPath;
import static org.junit.Assert.assertNotNull;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public class AdobePathBuilderTest { public class AdobePathBuilderTest {
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateNullBytes() { public void testCreateNullBytes() {
new AdobePathBuilder((byte[]) null); assertThrows(IllegalArgumentException.class, () -> new AdobePathBuilder((byte[]) null));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateNull() { public void testCreateNull() {
new AdobePathBuilder((DataInput) null); assertThrows(IllegalArgumentException.class, () -> new AdobePathBuilder((DataInput) null));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateEmpty() { public void testCreateEmpty() {
new AdobePathBuilder(new byte[0]); assertThrows(IllegalArgumentException.class, () -> new AdobePathBuilder(new byte[0]));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateShortPath() { public void testCreateShortPath() {
new AdobePathBuilder(new byte[3]); assertThrows(IllegalArgumentException.class, () -> new AdobePathBuilder(new byte[3]));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateImpossiblePath() { public void testCreateImpossiblePath() {
new AdobePathBuilder(new byte[7]); assertThrows(IllegalArgumentException.class, () -> new AdobePathBuilder(new byte[7]));
} }
@Test @Test
@@ -82,18 +83,20 @@ public class AdobePathBuilderTest {
assertNotNull(path); assertNotNull(path);
} }
@Test(expected = IIOException.class) @Test
public void testShortPath() throws IOException { public void testShortPath() throws IOException {
byte[] data = new byte[26]; byte[] data = new byte[26];
ByteBuffer buffer = ByteBuffer.wrap(data); ByteBuffer buffer = ByteBuffer.wrap(data);
buffer.putShort((short) AdobePathSegment.CLOSED_SUBPATH_LENGTH_RECORD); buffer.putShort((short) AdobePathSegment.CLOSED_SUBPATH_LENGTH_RECORD);
buffer.putShort((short) 1); buffer.putShort((short) 1);
assertThrows(IIOException.class, () -> {
Path2D path = new AdobePathBuilder(data).path(); Path2D path = new AdobePathBuilder(data).path();
assertNotNull(path); assertNotNull(path);
});
} }
@Test(expected = IIOException.class) @Test
public void testShortPathToo() throws IOException { public void testShortPathToo() throws IOException {
byte[] data = new byte[52]; byte[] data = new byte[52];
ByteBuffer buffer = ByteBuffer.wrap(data); ByteBuffer buffer = ByteBuffer.wrap(data);
@@ -102,11 +105,13 @@ public class AdobePathBuilderTest {
buffer.position(buffer.position() + 22); buffer.position(buffer.position() + 22);
buffer.putShort((short) AdobePathSegment.CLOSED_SUBPATH_BEZIER_LINKED); buffer.putShort((short) AdobePathSegment.CLOSED_SUBPATH_BEZIER_LINKED);
assertThrows(IIOException.class, () -> {
Path2D path = new AdobePathBuilder(data).path(); Path2D path = new AdobePathBuilder(data).path();
assertNotNull(path); assertNotNull(path);
});
} }
@Test(expected = IIOException.class) @Test
public void testLongPath() throws IOException { public void testLongPath() throws IOException {
byte[] data = new byte[78]; byte[] data = new byte[78];
ByteBuffer buffer = ByteBuffer.wrap(data); ByteBuffer buffer = ByteBuffer.wrap(data);
@@ -117,18 +122,22 @@ public class AdobePathBuilderTest {
buffer.position(buffer.position() + 24); buffer.position(buffer.position() + 24);
buffer.putShort((short) AdobePathSegment.CLOSED_SUBPATH_BEZIER_LINKED); buffer.putShort((short) AdobePathSegment.CLOSED_SUBPATH_BEZIER_LINKED);
assertThrows(IIOException.class, () -> {
Path2D path = new AdobePathBuilder(data).path(); Path2D path = new AdobePathBuilder(data).path();
assertNotNull(path); assertNotNull(path);
});
} }
@Test(expected = IIOException.class) @Test
public void testPathMissingLength() throws IOException { public void testPathMissingLength() throws IOException {
byte[] data = new byte[26]; byte[] data = new byte[26];
ByteBuffer buffer = ByteBuffer.wrap(data); ByteBuffer buffer = ByteBuffer.wrap(data);
buffer.putShort((short) AdobePathSegment.CLOSED_SUBPATH_BEZIER_LINKED); buffer.putShort((short) AdobePathSegment.CLOSED_SUBPATH_BEZIER_LINKED);
assertThrows(IIOException.class, () -> {
Path2D path = new AdobePathBuilder(data).path(); Path2D path = new AdobePathBuilder(data).path();
assertNotNull(path); assertNotNull(path);
});
} }
@Test @Test
@@ -31,7 +31,6 @@
package com.twelvemonkeys.imageio.path; package com.twelvemonkeys.imageio.path;
import org.junit.Test;
import javax.imageio.IIOException; import javax.imageio.IIOException;
import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageInputStream;
@@ -39,36 +38,37 @@ import java.awt.geom.Path2D;
import java.io.DataInput; import java.io.DataInput;
import java.io.IOException; import java.io.IOException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static com.twelvemonkeys.imageio.path.PathsTest.assertPathEquals; import static com.twelvemonkeys.imageio.path.PathsTest.assertPathEquals;
import static com.twelvemonkeys.imageio.path.PathsTest.readExpectedPath; import static com.twelvemonkeys.imageio.path.PathsTest.readExpectedPath;
import static org.junit.Assert.assertNotNull;
public class AdobePathReaderTest { public class AdobePathReaderTest {
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateNullBytes() { public void testCreateNullBytes() {
new AdobePathReader((byte[]) null); assertThrows(IllegalArgumentException.class, () -> new AdobePathReader((byte[]) null));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateNull() { public void testCreateNull() {
new AdobePathReader((DataInput) null); assertThrows(IllegalArgumentException.class, () -> new AdobePathReader((DataInput) null));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateEmpty() { public void testCreateEmpty() {
new AdobePathReader(new byte[0]); assertThrows(IllegalArgumentException.class, () -> new AdobePathReader(new byte[0]));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateShortPath() { public void testCreateShortPath() {
new AdobePathReader(new byte[3]); assertThrows(IllegalArgumentException.class, () -> new AdobePathReader(new byte[3]));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateImpossiblePath() { public void testCreateImpossiblePath() {
new AdobePathReader(new byte[7]); assertThrows(IllegalArgumentException.class, () -> new AdobePathReader(new byte[7]));
} }
@Test @Test
@@ -82,18 +82,20 @@ public class AdobePathReaderTest {
assertNotNull(path); assertNotNull(path);
} }
@Test(expected = IIOException.class) @Test
public void testShortPath() throws IOException { public void testShortPath() throws IOException {
byte[] data = new byte[26]; byte[] data = new byte[26];
ByteBuffer buffer = ByteBuffer.wrap(data); ByteBuffer buffer = ByteBuffer.wrap(data);
buffer.putShort((short) AdobePathSegment.CLOSED_SUBPATH_LENGTH_RECORD); buffer.putShort((short) AdobePathSegment.CLOSED_SUBPATH_LENGTH_RECORD);
buffer.putShort((short) 1); buffer.putShort((short) 1);
assertThrows(IIOException.class, () -> {
Path2D path = new AdobePathReader(data).readPath(); Path2D path = new AdobePathReader(data).readPath();
assertNotNull(path); assertNotNull(path);
});
} }
@Test(expected = IIOException.class) @Test
public void testShortPathToo() throws IOException { public void testShortPathToo() throws IOException {
byte[] data = new byte[52]; byte[] data = new byte[52];
ByteBuffer buffer = ByteBuffer.wrap(data); ByteBuffer buffer = ByteBuffer.wrap(data);
@@ -102,11 +104,13 @@ public class AdobePathReaderTest {
buffer.position(buffer.position() + 22); buffer.position(buffer.position() + 22);
buffer.putShort((short) AdobePathSegment.CLOSED_SUBPATH_BEZIER_LINKED); buffer.putShort((short) AdobePathSegment.CLOSED_SUBPATH_BEZIER_LINKED);
assertThrows(IIOException.class, () -> {
Path2D path = new AdobePathReader(data).readPath(); Path2D path = new AdobePathReader(data).readPath();
assertNotNull(path); assertNotNull(path);
});
} }
@Test(expected = IIOException.class) @Test
public void testLongPath() throws IOException { public void testLongPath() throws IOException {
byte[] data = new byte[78]; byte[] data = new byte[78];
ByteBuffer buffer = ByteBuffer.wrap(data); ByteBuffer buffer = ByteBuffer.wrap(data);
@@ -117,18 +121,22 @@ public class AdobePathReaderTest {
buffer.position(buffer.position() + 24); buffer.position(buffer.position() + 24);
buffer.putShort((short) AdobePathSegment.CLOSED_SUBPATH_BEZIER_LINKED); buffer.putShort((short) AdobePathSegment.CLOSED_SUBPATH_BEZIER_LINKED);
assertThrows(IIOException.class, () -> {
Path2D path = new AdobePathReader(data).readPath(); Path2D path = new AdobePathReader(data).readPath();
assertNotNull(path); assertNotNull(path);
});
} }
@Test(expected = IIOException.class) @Test
public void testPathMissingLength() throws IOException { public void testPathMissingLength() throws IOException {
byte[] data = new byte[26]; byte[] data = new byte[26];
ByteBuffer buffer = ByteBuffer.wrap(data); ByteBuffer buffer = ByteBuffer.wrap(data);
buffer.putShort((short) AdobePathSegment.CLOSED_SUBPATH_BEZIER_LINKED); buffer.putShort((short) AdobePathSegment.CLOSED_SUBPATH_BEZIER_LINKED);
assertThrows(IIOException.class, () -> {
Path2D path = new AdobePathReader(data).readPath(); Path2D path = new AdobePathReader(data).readPath();
assertNotNull(path); assertNotNull(path);
});
} }
@Test @Test
@@ -30,9 +30,9 @@
package com.twelvemonkeys.imageio.path; package com.twelvemonkeys.imageio.path;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
/** /**
* AdobePathSegmentTest. * AdobePathSegmentTest.
@@ -42,20 +42,19 @@ import static org.junit.Assert.*;
* @version $Id: AdobePathSegmentTest.java,v 1.0 13/12/14 harald.kuhr Exp$ * @version $Id: AdobePathSegmentTest.java,v 1.0 13/12/14 harald.kuhr Exp$
*/ */
public class AdobePathSegmentTest { public class AdobePathSegmentTest {
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateBadSelectorNegative() { public void testCreateBadSelectorNegative() {
new AdobePathSegment(-1, 1); assertThrows(IllegalArgumentException.class, () -> new AdobePathSegment(-1, 1));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateBadSelector() { public void testCreateBadSelector() {
new AdobePathSegment(9, 2); assertThrows(IllegalArgumentException.class, () -> new AdobePathSegment(9, 2));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateOpenLengthRecordNegative() { public void testCreateOpenLengthRecordNegative() {
new AdobePathSegment(AdobePathSegment.OPEN_SUBPATH_LENGTH_RECORD, -1); assertThrows(IllegalArgumentException.class, () -> new AdobePathSegment(AdobePathSegment.OPEN_SUBPATH_LENGTH_RECORD, -1));
} }
@Test @Test
@@ -72,9 +71,9 @@ public class AdobePathSegmentTest {
assertEquals(-1, segment.cply, 0); assertEquals(-1, segment.cply, 0);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateClosedLengthRecordNegative() { public void testCreateClosedLengthRecordNegative() {
new AdobePathSegment(AdobePathSegment.CLOSED_SUBPATH_LENGTH_RECORD, -42); assertThrows(IllegalArgumentException.class, () -> new AdobePathSegment(AdobePathSegment.CLOSED_SUBPATH_LENGTH_RECORD, -42));
} }
@Test @Test
@@ -107,19 +106,19 @@ public class AdobePathSegmentTest {
assertEquals(1, segment.cply, 0); assertEquals(1, segment.cply, 0);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateOpenLinkedRecordBad() { public void testCreateOpenLinkedRecordBad() {
new AdobePathSegment(AdobePathSegment.OPEN_SUBPATH_BEZIER_LINKED, 44); assertThrows(IllegalArgumentException.class, () -> new AdobePathSegment(AdobePathSegment.OPEN_SUBPATH_BEZIER_LINKED, 44));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateOpenLinkedRecordOutOfRangeNegative() { public void testCreateOpenLinkedRecordOutOfRangeNegative() {
new AdobePathSegment(AdobePathSegment.OPEN_SUBPATH_BEZIER_LINKED, -16.1, -16.1, 0, 0, 1, 1); assertThrows(IllegalArgumentException.class, () -> new AdobePathSegment(AdobePathSegment.OPEN_SUBPATH_BEZIER_LINKED, -16.1, -16.1, 0, 0, 1, 1));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateOpenLinkedRecordOutOfRangePositive() { public void testCreateOpenLinkedRecordOutOfRangePositive() {
new AdobePathSegment(AdobePathSegment.OPEN_SUBPATH_BEZIER_LINKED, 16.1, 16.1, 0, 0, 1, 1); assertThrows(IllegalArgumentException.class, () -> new AdobePathSegment(AdobePathSegment.OPEN_SUBPATH_BEZIER_LINKED, 16.1, 16.1, 0, 0, 1, 1));
} }
@Test @Test
@@ -136,20 +135,20 @@ public class AdobePathSegmentTest {
assertEquals(1, segment.cply, 0); assertEquals(1, segment.cply, 0);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateOpenUnlinkedRecordBad() { public void testCreateOpenUnlinkedRecordBad() {
new AdobePathSegment(AdobePathSegment.OPEN_SUBPATH_BEZIER_UNLINKED, 44); assertThrows(IllegalArgumentException.class, () -> new AdobePathSegment(AdobePathSegment.OPEN_SUBPATH_BEZIER_UNLINKED, 44));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateOpenUnlinkedRecordOutOfRangeNegative() { public void testCreateOpenUnlinkedRecordOutOfRangeNegative() {
new AdobePathSegment(AdobePathSegment.OPEN_SUBPATH_BEZIER_UNLINKED, -16.5, 0, 0, 0, 1, 1); assertThrows(IllegalArgumentException.class, () -> new AdobePathSegment(AdobePathSegment.OPEN_SUBPATH_BEZIER_UNLINKED, -16.5, 0, 0, 0, 1, 1));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateOpenUnlinkedRecorOutOfRangePositive() { public void testCreateOpenUnlinkedRecorOutOfRangePositive() {
new AdobePathSegment(AdobePathSegment.OPEN_SUBPATH_BEZIER_UNLINKED, 0, -17, 0, 0, 16.5, 1); assertThrows(IllegalArgumentException.class, () -> new AdobePathSegment(AdobePathSegment.OPEN_SUBPATH_BEZIER_UNLINKED, 0, -17, 0, 0, 16.5, 1));
} }
/// Closed subpath /// Closed subpath
@@ -168,19 +167,19 @@ public class AdobePathSegmentTest {
assertEquals(1, segment.cply, 0); assertEquals(1, segment.cply, 0);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateClosedLinkedRecordBad() { public void testCreateClosedLinkedRecordBad() {
new AdobePathSegment(AdobePathSegment.CLOSED_SUBPATH_BEZIER_LINKED, 44); assertThrows(IllegalArgumentException.class, () -> new AdobePathSegment(AdobePathSegment.CLOSED_SUBPATH_BEZIER_LINKED, 44));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateClosedLinkedRecordOutOfRangeNegative() { public void testCreateClosedLinkedRecordOutOfRangeNegative() {
new AdobePathSegment(AdobePathSegment.CLOSED_SUBPATH_BEZIER_LINKED, -16.5, -.5, 0, 0, 1, 1); assertThrows(IllegalArgumentException.class, () -> new AdobePathSegment(AdobePathSegment.CLOSED_SUBPATH_BEZIER_LINKED, -16.5, -.5, 0, 0, 1, 1));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateClosedLinkedRecordOutOfRangePositive() { public void testCreateClosedLinkedRecordOutOfRangePositive() {
new AdobePathSegment(AdobePathSegment.CLOSED_SUBPATH_BEZIER_LINKED, .5, 16.5, 0, 0, 1, 1); assertThrows(IllegalArgumentException.class, () -> new AdobePathSegment(AdobePathSegment.CLOSED_SUBPATH_BEZIER_LINKED, .5, 16.5, 0, 0, 1, 1));
} }
@Test @Test
@@ -197,59 +196,59 @@ public class AdobePathSegmentTest {
assertEquals(1, segment.cply, 0); assertEquals(1, segment.cply, 0);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateClosedUnlinkedRecordBad() { public void testCreateClosedUnlinkedRecordBad() {
new AdobePathSegment(AdobePathSegment.CLOSED_SUBPATH_BEZIER_UNLINKED, 44); assertThrows(IllegalArgumentException.class, () -> new AdobePathSegment(AdobePathSegment.CLOSED_SUBPATH_BEZIER_UNLINKED, 44));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateClosedUnlinkedRecordOutOfRangeNegative() { public void testCreateClosedUnlinkedRecordOutOfRangeNegative() {
new AdobePathSegment(AdobePathSegment.CLOSED_SUBPATH_BEZIER_UNLINKED, -.5, -16.5, 0, 0, 1, 1); assertThrows(IllegalArgumentException.class, () -> new AdobePathSegment(AdobePathSegment.CLOSED_SUBPATH_BEZIER_UNLINKED, -.5, -16.5, 0, 0, 1, 1));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateClosedUnlinkedRecordOutOfRangePositive() { public void testCreateClosedUnlinkedRecordOutOfRangePositive() {
new AdobePathSegment(AdobePathSegment.CLOSED_SUBPATH_BEZIER_UNLINKED, 16.5, .5, 0, 0, 1, 1); assertThrows(IllegalArgumentException.class, () -> new AdobePathSegment(AdobePathSegment.CLOSED_SUBPATH_BEZIER_UNLINKED, 16.5, .5, 0, 0, 1, 1));
} }
@Test @Test
public void testToStringRule() { public void testToStringRule() {
String string = new AdobePathSegment(AdobePathSegment.INITIAL_FILL_RULE_RECORD, 0).toString(); String string = new AdobePathSegment(AdobePathSegment.INITIAL_FILL_RULE_RECORD, 0).toString();
assertTrue(string, string.startsWith("Rule")); assertTrue(string.startsWith("Rule"), string);
assertTrue(string, string.contains("Initial")); assertTrue(string.contains("Initial"), string);
assertTrue(string, string.contains("fill")); assertTrue(string.contains("fill"), string);
assertTrue(string, string.contains("rule=0")); assertTrue(string.contains("rule=0"), string);
} }
@Test @Test
public void testToStringLength() { public void testToStringLength() {
String string = new AdobePathSegment(AdobePathSegment.CLOSED_SUBPATH_LENGTH_RECORD, 2).toString(); String string = new AdobePathSegment(AdobePathSegment.CLOSED_SUBPATH_LENGTH_RECORD, 2).toString();
assertTrue(string, string.startsWith("Len")); assertTrue(string.startsWith("Len"), string);
assertTrue(string, string.contains("Closed")); assertTrue(string.contains("Closed"), string);
assertTrue(string, string.contains("subpath")); assertTrue(string.contains("subpath"), string);
assertTrue(string, string.contains("length=2")); assertTrue(string.contains("length=2"), string);
string = new AdobePathSegment(AdobePathSegment.OPEN_SUBPATH_LENGTH_RECORD, 42).toString(); string = new AdobePathSegment(AdobePathSegment.OPEN_SUBPATH_LENGTH_RECORD, 42).toString();
assertTrue(string, string.startsWith("Len")); assertTrue(string.startsWith("Len"), string);
assertTrue(string, string.contains("Open")); assertTrue(string.contains("Open"), string);
assertTrue(string, string.contains("subpath")); assertTrue(string.contains("subpath"), string);
assertTrue(string, string.contains("length=42")); assertTrue(string.contains("length=42"), string);
} }
@Test @Test
public void testToStringOther() { public void testToStringOther() {
String string = new AdobePathSegment(AdobePathSegment.OPEN_SUBPATH_BEZIER_LINKED, 0, 0, 1, 1, 0, 0).toString(); String string = new AdobePathSegment(AdobePathSegment.OPEN_SUBPATH_BEZIER_LINKED, 0, 0, 1, 1, 0, 0).toString();
assertTrue(string, string.startsWith("Pt")); assertTrue(string.startsWith("Pt"), string);
assertTrue(string, string.contains("Open")); assertTrue(string.contains("Open"), string);
assertTrue(string, string.contains("Bezier")); assertTrue(string.contains("Bezier"), string);
assertTrue(string, string.contains("linked")); assertTrue(string.contains("linked"), string);
string = new AdobePathSegment(AdobePathSegment.CLOSED_SUBPATH_BEZIER_LINKED, 0, 0, 1, 1, 0, 0).toString(); string = new AdobePathSegment(AdobePathSegment.CLOSED_SUBPATH_BEZIER_LINKED, 0, 0, 1, 1, 0, 0).toString();
assertTrue(string, string.startsWith("Pt")); assertTrue(string.startsWith("Pt"), string);
assertTrue(string, string.contains("Closed")); assertTrue(string.contains("Closed"), string);
assertTrue(string, string.contains("Bezier")); assertTrue(string.contains("Bezier"), string);
assertTrue(string, string.contains("linked")); assertTrue(string.contains("linked"), string);
} }
@Test @Test
@@ -31,7 +31,6 @@
package com.twelvemonkeys.imageio.path; package com.twelvemonkeys.imageio.path;
import com.twelvemonkeys.imageio.stream.ByteArrayImageInputStream; import com.twelvemonkeys.imageio.stream.ByteArrayImageInputStream;
import org.junit.Test;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageInputStream;
@@ -41,11 +40,11 @@ import java.awt.geom.*;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
import org.junit.jupiter.api.Test;
import static com.twelvemonkeys.imageio.path.AdobePathSegment.*; import static com.twelvemonkeys.imageio.path.AdobePathSegment.*;
import static com.twelvemonkeys.imageio.path.PathsTest.assertPathEquals; import static com.twelvemonkeys.imageio.path.PathsTest.assertPathEquals;
import static org.junit.Assert.assertArrayEquals; import static org.junit.jupiter.api.Assertions.*;
import static org.junit.Assert.assertEquals;
/** /**
* AdobePathWriterTest. * AdobePathWriterTest.
@@ -56,22 +55,22 @@ import static org.junit.Assert.assertEquals;
*/ */
public class AdobePathWriterTest { public class AdobePathWriterTest {
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateWriterNull() { public void testCreateWriterNull() {
new AdobePathWriter(null); assertThrows(IllegalArgumentException.class, () -> new AdobePathWriter(null));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateWriterInvalid() { public void testCreateWriterInvalid() {
new AdobePathWriter(new Path2D.Double(Path2D.WIND_NON_ZERO)); assertThrows(IllegalArgumentException.class, () -> new AdobePathWriter(new Path2D.Double(Path2D.WIND_NON_ZERO)));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateWriterOutOfBounds() { public void testCreateWriterOutOfBounds() {
Path2D path = new Path2D.Float(Path2D.WIND_EVEN_ODD); Path2D path = new Path2D.Float(Path2D.WIND_EVEN_ODD);
path.append(new Ellipse2D.Double(.5, 0.5, 2, 2), false); path.append(new Ellipse2D.Double(.5, 0.5, 2, 2), false);
new AdobePathWriter(path); assertThrows(IllegalArgumentException.class, () -> new AdobePathWriter(path));
} }
@Test @Test
@@ -93,14 +92,14 @@ public class AdobePathWriterTest {
new AdobePathWriter(path); new AdobePathWriter(path);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateNotClosed() { public void testCreateNotClosed() {
GeneralPath path = new GeneralPath(Path2D.WIND_EVEN_ODD); GeneralPath path = new GeneralPath(Path2D.WIND_EVEN_ODD);
path.moveTo(.5, .5); path.moveTo(.5, .5);
path.lineTo(1, .5); path.lineTo(1, .5);
path.curveTo(1, 1, 1, 1, .5, 1); path.curveTo(1, 1, 1, 1, .5, 1);
new AdobePathWriter(path).writePath(); assertThrows(IllegalArgumentException.class, () -> new AdobePathWriter(path).writePath());
} }
@Test @Test
@@ -33,7 +33,6 @@ package com.twelvemonkeys.imageio.path;
import com.twelvemonkeys.imageio.stream.ByteArrayImageInputStream; import com.twelvemonkeys.imageio.stream.ByteArrayImageInputStream;
import com.twelvemonkeys.imageio.stream.SubImageInputStream; import com.twelvemonkeys.imageio.stream.SubImageInputStream;
import com.twelvemonkeys.imageio.stream.URLImageInputStreamSpi; import com.twelvemonkeys.imageio.stream.URLImageInputStreamSpi;
import org.junit.Test;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import javax.imageio.spi.IIORegistry; import javax.imageio.spi.IIORegistry;
@@ -48,8 +47,9 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.ObjectInputStream; import java.io.ObjectInputStream;
import static org.junit.Assert.*; import org.junit.jupiter.api.Test;
import static org.junit.Assume.assumeTrue; import static org.junit.jupiter.api.Assumptions.*;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* PathsTest. * PathsTest.
@@ -63,9 +63,9 @@ public class PathsTest {
IIORegistry.getDefaultInstance().registerServiceProvider(new URLImageInputStreamSpi()); IIORegistry.getDefaultInstance().registerServiceProvider(new URLImageInputStreamSpi());
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testReadPathNull() throws IOException { public void testReadPathNull() throws IOException {
Paths.readPath(null); assertThrows(IllegalArgumentException.class, () -> Paths.readPath(null));
} }
@Test @Test
@@ -127,14 +127,14 @@ public class PathsTest {
assertPathEquals(readExpectedPath("/ser/grape-path.ser"), path); assertPathEquals(readExpectedPath("/ser/grape-path.ser"), path);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testApplyClippingPathNullPath() { public void testApplyClippingPathNullPath() {
Paths.applyClippingPath(null, new BufferedImage(1, 1, BufferedImage.TYPE_BYTE_GRAY)); assertThrows(IllegalArgumentException.class, () -> Paths.applyClippingPath(null, new BufferedImage(1, 1, BufferedImage.TYPE_BYTE_GRAY)));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testApplyClippingPathNullSource() { public void testApplyClippingPathNullSource() {
Paths.applyClippingPath(new GeneralPath(), null); assertThrows(IllegalArgumentException.class, () -> Paths.applyClippingPath(new GeneralPath(), null));
} }
@Test @Test
@@ -165,9 +165,9 @@ public class PathsTest {
} }
@SuppressWarnings("ConstantConditions") @SuppressWarnings("ConstantConditions")
@Test(expected = IllegalArgumentException.class) @Test
public void testApplyClippingPathNullDestination() { public void testApplyClippingPathNullDestination() {
Paths.applyClippingPath(new GeneralPath(), new BufferedImage(1, 1, BufferedImage.TYPE_BYTE_GRAY), null); assertThrows(IllegalArgumentException.class, () -> Paths.applyClippingPath(new GeneralPath(), new BufferedImage(1, 1, BufferedImage.TYPE_BYTE_GRAY), null));
} }
@Test @Test
@@ -199,9 +199,9 @@ public class PathsTest {
// TODO: Mor sophisticated test that tests all pixels outside path... // TODO: Mor sophisticated test that tests all pixels outside path...
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testReadClippedNull() throws IOException { public void testReadClippedNull() throws IOException {
Paths.readClipped(null); assertThrows(IllegalArgumentException.class, () -> Paths.readClipped(null));
} }
@Test @Test
@@ -243,7 +243,7 @@ public class PathsTest {
} }
static void assertPathEquals(final Path2D expectedPath, final Path2D actualPath) { static void assertPathEquals(final Path2D expectedPath, final Path2D actualPath) {
assertNotNull("Expected path is null, check your tests...", expectedPath); assertNotNull(expectedPath, "Expected path is null, check your tests...");
assertNotNull(actualPath); assertNotNull(actualPath);
PathIterator expectedIterator = expectedPath.getPathIterator(null); PathIterator expectedIterator = expectedPath.getPathIterator(null);
@@ -253,19 +253,19 @@ public class PathsTest {
float[] actualCoords = new float[6]; float[] actualCoords = new float[6];
while(!expectedIterator.isDone()) { while(!expectedIterator.isDone()) {
assertFalse("Less points than expected", actualIterator.isDone()); assertFalse(actualIterator.isDone(), "Less points than expected");
int expectedType = expectedIterator.currentSegment(expectedCoords); int expectedType = expectedIterator.currentSegment(expectedCoords);
int actualType = actualIterator.currentSegment(actualCoords); int actualType = actualIterator.currentSegment(actualCoords);
assertEquals("Unexpected segment type", expectedType, actualType); assertEquals( expectedType, actualType, "Unexpected segment type");
assertArrayEquals("Unexpected coordinates", expectedCoords, actualCoords, 0); assertArrayEquals(expectedCoords, actualCoords, 0, "Unexpected coordinates");
actualIterator.next(); actualIterator.next();
expectedIterator.next(); expectedIterator.next();
} }
assertTrue("More points than expected", actualIterator.isDone()); assertTrue( actualIterator.isDone(), "More points than expected");
} }
@Test @Test
@@ -30,11 +30,9 @@
package com.twelvemonkeys.imageio; package com.twelvemonkeys.imageio;
import static java.util.Collections.singleton;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static java.util.Collections.singleton;
import static org.junit.jupiter.api.Assertions.*;
import java.awt.*; import java.awt.*;
import java.awt.color.ColorSpace; import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
@@ -48,7 +46,7 @@ import javax.imageio.IIOException;
import javax.imageio.ImageReadParam; import javax.imageio.ImageReadParam;
import javax.imageio.ImageTypeSpecifier; import javax.imageio.ImageTypeSpecifier;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* ImageReaderBaseTest * ImageReaderBaseTest
@@ -64,36 +62,36 @@ public class ImageReaderBaseTest {
ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_ARGB) ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_ARGB)
); );
@Test(expected = IllegalArgumentException.class) @Test
public void testGetDestinationZeroWidth() throws IIOException { public void testGetDestinationZeroWidth() throws IIOException {
ImageReaderBase.getDestination(null, TYPES.iterator(), 0, 42); assertThrows(IllegalArgumentException.class, () -> ImageReaderBase.getDestination(null, TYPES.iterator(), 0, 42));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testGetDestinationNegativeWidth() throws IIOException { public void testGetDestinationNegativeWidth() throws IIOException {
ImageReaderBase.getDestination(null, TYPES.iterator(), -1, 42); assertThrows(IllegalArgumentException.class, () -> ImageReaderBase.getDestination(null, TYPES.iterator(), -1, 42));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testGetDestinationZeroHeight() throws IIOException { public void testGetDestinationZeroHeight() throws IIOException {
ImageReaderBase.getDestination(null, TYPES.iterator(), 42, 0); assertThrows(IllegalArgumentException.class, () -> ImageReaderBase.getDestination(null, TYPES.iterator(), 42, 0));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testGetDestinationNegativeHeight() throws IIOException { public void testGetDestinationNegativeHeight() throws IIOException {
ImageReaderBase.getDestination(null, TYPES.iterator(), 42, -1); assertThrows(IllegalArgumentException.class, () -> ImageReaderBase.getDestination(null, TYPES.iterator(), 42, -1));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testGetDestinationNullTypes() throws IIOException { public void testGetDestinationNullTypes() throws IIOException {
ImageReaderBase.getDestination(null, null, 42, 42); assertThrows(IllegalArgumentException.class, () -> ImageReaderBase.getDestination(null, null, 42, 42));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testGetDestinationNoTypes() throws IIOException { public void testGetDestinationNoTypes() throws IIOException {
ImageReaderBase.getDestination(null, Collections.<ImageTypeSpecifier>emptyList().iterator(), 42, 42); assertThrows(IllegalArgumentException.class, () -> ImageReaderBase.getDestination(null, Collections.<ImageTypeSpecifier>emptyList().iterator(), 42, 42));
} }
@Test @Test
@@ -162,11 +160,11 @@ public class ImageReaderBaseTest {
assertEquals(1, destination.getHeight()); assertEquals(1, destination.getHeight());
} }
@Test(expected = IIOException.class) @Test
public void testGetDestinationParamIllegalDestination() throws IIOException { public void testGetDestinationParamIllegalDestination() throws IIOException {
ImageReadParam param = new ImageReadParam(); ImageReadParam param = new ImageReadParam();
param.setDestination(new BufferedImage(21, 1, BufferedImage.TYPE_USHORT_565_RGB)); param.setDestination(new BufferedImage(21, 1, BufferedImage.TYPE_USHORT_565_RGB));
ImageReaderBase.getDestination(param, TYPES.iterator(), 42, 1); assertThrows(IIOException.class, () -> ImageReaderBase.getDestination(param, TYPES.iterator(), 42, 1));
} }
@Test @Test
@@ -191,18 +189,18 @@ public class ImageReaderBaseTest {
assertEquals(7, destination.getHeight()); assertEquals(7, destination.getHeight());
} }
@Test(expected = IIOException.class) @Test
public void testGetDestinationParamIllegalDestinationType() throws IIOException { public void testGetDestinationParamIllegalDestinationType() throws IIOException {
ImageReadParam param = new ImageReadParam(); ImageReadParam param = new ImageReadParam();
param.setDestinationType(ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_BYTE_GRAY)); param.setDestinationType(ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_BYTE_GRAY));
ImageReaderBase.getDestination(param, TYPES.iterator(), 6, 7); assertThrows(IIOException.class, () -> ImageReaderBase.getDestination(param, TYPES.iterator(), 6, 7));
} }
@Test(expected = IIOException.class) @Test
public void testGetDestinationParamIllegalDestinationTypeAlt() throws IIOException { public void testGetDestinationParamIllegalDestinationTypeAlt() throws IIOException {
ImageReadParam param = new ImageReadParam(); ImageReadParam param = new ImageReadParam();
param.setDestinationType(ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_BGR)); param.setDestinationType(ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_BGR));
ImageReaderBase.getDestination(param, TYPES.iterator(), 6, 7); assertThrows(IIOException.class, () -> ImageReaderBase.getDestination(param, TYPES.iterator(), 6, 7));
} }
@Test @Test
@@ -215,22 +213,22 @@ public class ImageReaderBaseTest {
assertEquals(TYPES.get(0).getBufferedImageType(), destination.getType()); assertEquals(TYPES.get(0).getBufferedImageType(), destination.getType());
} }
@Test(expected = IIOException.class) @Test
public void testGetDestinationParamDestinationExceedsIntegerMax() throws IIOException { public void testGetDestinationParamDestinationExceedsIntegerMax() throws IIOException {
ImageReadParam param = new ImageReadParam(); ImageReadParam param = new ImageReadParam();
param.setSourceRegion(new Rectangle(3 * Short.MAX_VALUE, 2 * Short.MAX_VALUE)); // 6 442 057 734 pixels param.setSourceRegion(new Rectangle(3 * Short.MAX_VALUE, 2 * Short.MAX_VALUE)); // 6 442 057 734 pixels
ImageReaderBase.getDestination(param, TYPES.iterator(), 6 * Short.MAX_VALUE, 4 * Short.MAX_VALUE); // 25 768 230 936 pixels assertThrows(IIOException.class, () -> ImageReaderBase.getDestination(param, TYPES.iterator(), 6 * Short.MAX_VALUE, 4 * Short.MAX_VALUE)); // 25 768 230 936 pixels
} }
@Test(expected = IIOException.class) @Test
public void testGetDestinationDimensionExceedsIntegerMax() throws IIOException { public void testGetDestinationDimensionExceedsIntegerMax() throws IIOException {
ImageReaderBase.getDestination(null, TYPES.iterator(), 3 * Short.MAX_VALUE, 2 * Short.MAX_VALUE); // 6 442 057 734 pixels assertThrows(IIOException.class, () -> ImageReaderBase.getDestination(null, TYPES.iterator(), 3 * Short.MAX_VALUE, 2 * Short.MAX_VALUE)); // 6 442 057 734 pixels
} }
@Test(expected = IIOException.class) @Test
public void testGetDestinationStorageExceedsIntegerMax() throws IIOException { public void testGetDestinationStorageExceedsIntegerMax() throws IIOException {
Set<ImageTypeSpecifier> byteTypes = singleton(ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_3BYTE_BGR)); Set<ImageTypeSpecifier> byteTypes = singleton(ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_3BYTE_BGR));
ImageReaderBase.getDestination(null, byteTypes.iterator(), Short.MAX_VALUE, Short.MAX_VALUE); // 1 073 676 289 pixels assertThrows(IIOException.class, () -> ImageReaderBase.getDestination(null, byteTypes.iterator(), Short.MAX_VALUE, Short.MAX_VALUE)); // 1 073 676 289 pixels
// => 3 221 028 867 bytes needed in continuous array, not possible // => 3 221 028 867 bytes needed in continuous array, not possible
} }
@@ -7,9 +7,9 @@ import com.twelvemonkeys.imageio.StandardImageMetadataSupport.SubimageInterpreta
import com.twelvemonkeys.imageio.StandardImageMetadataSupport.TextEntry; import com.twelvemonkeys.imageio.StandardImageMetadataSupport.TextEntry;
import com.twelvemonkeys.imageio.util.ImageTypeSpecifiers; import com.twelvemonkeys.imageio.util.ImageTypeSpecifiers;
import org.junit.Test;
import org.w3c.dom.NodeList; import org.w3c.dom.NodeList;
import javax.imageio.IIOException;
import javax.imageio.metadata.IIOMetadata; import javax.imageio.metadata.IIOMetadata;
import javax.imageio.metadata.IIOMetadataNode; import javax.imageio.metadata.IIOMetadataNode;
import java.awt.image.*; import java.awt.image.*;
@@ -23,22 +23,23 @@ import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import static com.twelvemonkeys.imageio.StandardImageMetadataSupport.builder; import static com.twelvemonkeys.imageio.StandardImageMetadataSupport.builder;
import static org.junit.Assert.*; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class StandardImageMetadataSupportTest { public class StandardImageMetadataSupportTest {
@Test(expected = IllegalArgumentException.class) @Test
public void createNullBuilder() { public void createNullBuilder() {
new StandardImageMetadataSupport(null); assertThrows(IllegalArgumentException.class, () -> new StandardImageMetadataSupport(null));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void createNullType() { public void createNullType() {
new StandardImageMetadataSupport(builder(null)); assertThrows(IllegalArgumentException.class, () -> new StandardImageMetadataSupport(builder(null)));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void builderNullType() { public void builderNullType() {
builder(null).build(); assertThrows(IllegalArgumentException.class, () -> builder(null).build());
} }
@Test @Test
@@ -89,10 +90,10 @@ public class StandardImageMetadataSupportTest {
assertEquals("TRUE", compressionLossless.getAttribute("value")); assertEquals("TRUE", compressionLossless.getAttribute("value"));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void withCompressionLossyIllegal() { public void withCompressionLossyIllegal() {
builder(ImageTypeSpecifiers.createFromBufferedImageType(BufferedImage.TYPE_BYTE_GRAY)) assertThrows(IllegalArgumentException.class, () -> builder(ImageTypeSpecifiers.createFromBufferedImageType(BufferedImage.TYPE_BYTE_GRAY))
.withCompressionLossless(false); .withCompressionLossless(false));
} }
@Test @Test
@@ -31,9 +31,9 @@
package com.twelvemonkeys.imageio.color; package com.twelvemonkeys.imageio.color;
import com.twelvemonkeys.imageio.color.CIELabColorConverter.Illuminant; import com.twelvemonkeys.imageio.color.CIELabColorConverter.Illuminant;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* CIELabColorConverterTest. * CIELabColorConverterTest.
@@ -43,9 +43,9 @@ import static org.junit.Assert.assertArrayEquals;
* @version $Id: CIELabColorConverterTest.java,v 1.0 22/10/15 harald.kuhr Exp$ * @version $Id: CIELabColorConverterTest.java,v 1.0 22/10/15 harald.kuhr Exp$
*/ */
public class CIELabColorConverterTest { public class CIELabColorConverterTest {
@Test(expected = IllegalArgumentException.class) @Test
public void testNoIllumninant() { public void testNoIllumninant() {
new CIELabColorConverter(null); assertThrows(IllegalArgumentException.class, () -> new CIELabColorConverter(null));
} }
@Test @Test
@@ -1,7 +1,5 @@
package com.twelvemonkeys.imageio.color; package com.twelvemonkeys.imageio.color;
import org.junit.Test;
import java.awt.color.ColorSpace; import java.awt.color.ColorSpace;
import java.awt.color.ICC_ColorSpace; import java.awt.color.ICC_ColorSpace;
import java.awt.color.ICC_Profile; import java.awt.color.ICC_Profile;
@@ -9,7 +7,8 @@ import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
import static org.junit.Assert.*; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class ColorProfilesTest { public class ColorProfilesTest {
@Test @Test
@@ -53,9 +52,9 @@ public class ColorProfilesTest {
assertFalse(ColorProfiles.isCS_sRGB(ICC_Profile.getInstance(ColorSpace.CS_PYCC))); assertFalse(ColorProfiles.isCS_sRGB(ICC_Profile.getInstance(ColorSpace.CS_PYCC)));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testIsCS_sRGBNull() { public void testIsCS_sRGBNull() {
ColorProfiles.isCS_sRGB(null); assertThrows(IllegalArgumentException.class, () -> ColorProfiles.isCS_sRGB(null));
} }
@Test @Test
@@ -71,29 +70,29 @@ public class ColorProfilesTest {
assertFalse(ColorProfiles.isCS_GRAY(ICC_Profile.getInstance(ColorSpace.CS_PYCC))); assertFalse(ColorProfiles.isCS_GRAY(ICC_Profile.getInstance(ColorSpace.CS_PYCC)));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testIsCS_GRAYNull() { public void testIsCS_GRAYNull() {
ColorProfiles.isCS_GRAY(null); assertThrows(IllegalArgumentException.class, () -> ColorProfiles.isCS_GRAY(null));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateProfileNull() { public void testCreateProfileNull() {
ColorProfiles.createProfile(null); assertThrows(IllegalArgumentException.class, () -> ColorProfiles.createProfile(null));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testReadProfileNull() throws IOException { public void testReadProfileNull() throws IOException {
ColorProfiles.readProfile(null); assertThrows(IllegalArgumentException.class, () -> ColorProfiles.readProfile(null));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateProfileRawNull() { public void testCreateProfileRawNull() {
ColorProfiles.createProfileRaw(null); assertThrows(IllegalArgumentException.class, () -> ColorProfiles.createProfileRaw(null));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testReadProfileRawNull() throws IOException { public void testReadProfileRawNull() throws IOException {
ColorProfiles.readProfileRaw(null); assertThrows(IllegalArgumentException.class, () -> ColorProfiles.readProfileRaw(null));
} }
@Test @Test
@@ -110,74 +109,74 @@ public class ColorProfilesTest {
assertArrayEquals(data, profileRaw.getData()); assertArrayEquals(data, profileRaw.getData());
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateProfileRawBadData() { public void testCreateProfileRawBadData() {
ColorProfiles.createProfileRaw(new byte[5]); assertThrows(IllegalArgumentException.class, () -> ColorProfiles.createProfileRaw(new byte[5]));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testReadProfileRawBadData() throws IOException { public void testReadProfileRawBadData() throws IOException {
// NOTE: The array here is larger, as there's a bug in OpenJDK 15 & 16, that throws // NOTE: The array here is larger, as there's a bug in OpenJDK 15 & 16, that throws
// ArrayIndexOutOfBoundsException if the stream is shorter than the profile signature... // ArrayIndexOutOfBoundsException if the stream is shorter than the profile signature...
ColorProfiles.readProfileRaw(new ByteArrayInputStream(new byte[40])); assertThrows(IllegalArgumentException.class, () -> ColorProfiles.readProfileRaw(new ByteArrayInputStream(new byte[40])));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateProfileBadData() { public void testCreateProfileBadData() {
ColorProfiles.createProfile(new byte[5]); assertThrows(IllegalArgumentException.class, () -> ColorProfiles.createProfile(new byte[5]));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testReadProfileBadData() throws IOException { public void testReadProfileBadData() throws IOException {
ColorProfiles.readProfile(new ByteArrayInputStream(new byte[5])); assertThrows(IllegalArgumentException.class, () -> ColorProfiles.readProfile(new ByteArrayInputStream(new byte[5])));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateProfileRawTruncated() throws IOException { public void testCreateProfileRawTruncated() throws IOException {
byte[] data = ICC_Profile.getInstance(getClass().getResourceAsStream("/profiles/adobe_rgb_1998.icc")).getData(); byte[] data = ICC_Profile.getInstance(getClass().getResourceAsStream("/profiles/adobe_rgb_1998.icc")).getData();
ColorProfiles.createProfileRaw(Arrays.copyOf(data, 200)); assertThrows(IllegalArgumentException.class, () -> ColorProfiles.createProfileRaw(Arrays.copyOf(data, 200)));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testReadProfileRawTruncated() throws IOException { public void testReadProfileRawTruncated() throws IOException {
byte[] data = ICC_Profile.getInstance(getClass().getResourceAsStream("/profiles/adobe_rgb_1998.icc")).getData(); byte[] data = ICC_Profile.getInstance(getClass().getResourceAsStream("/profiles/adobe_rgb_1998.icc")).getData();
ColorProfiles.readProfileRaw(new ByteArrayInputStream(data, 0, 200)); assertThrows(IllegalArgumentException.class, () -> ColorProfiles.readProfileRaw(new ByteArrayInputStream(data, 0, 200)));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateProfileTruncated() throws IOException { public void testCreateProfileTruncated() throws IOException {
byte[] data = ICC_Profile.getInstance(getClass().getResourceAsStream("/profiles/adobe_rgb_1998.icc")).getData(); byte[] data = ICC_Profile.getInstance(getClass().getResourceAsStream("/profiles/adobe_rgb_1998.icc")).getData();
ColorProfiles.createProfile(Arrays.copyOf(data, 200)); assertThrows(IllegalArgumentException.class, () -> ColorProfiles.createProfile(Arrays.copyOf(data, 200)));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testReadProfileTruncated() throws IOException { public void testReadProfileTruncated() throws IOException {
byte[] data = ICC_Profile.getInstance(getClass().getResourceAsStream("/profiles/adobe_rgb_1998.icc")).getData(); byte[] data = ICC_Profile.getInstance(getClass().getResourceAsStream("/profiles/adobe_rgb_1998.icc")).getData();
ColorProfiles.readProfile(new ByteArrayInputStream(data, 0, 200)); assertThrows(IllegalArgumentException.class, () -> ColorProfiles.readProfile(new ByteArrayInputStream(data, 0, 200)));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateProfileRawTruncatedHeader() throws IOException { public void testCreateProfileRawTruncatedHeader() throws IOException {
byte[] data = ICC_Profile.getInstance(getClass().getResourceAsStream("/profiles/adobe_rgb_1998.icc")).getData(); byte[] data = ICC_Profile.getInstance(getClass().getResourceAsStream("/profiles/adobe_rgb_1998.icc")).getData();
ColorProfiles.createProfileRaw(Arrays.copyOf(data, 125)); assertThrows(IllegalArgumentException.class, () -> ColorProfiles.createProfileRaw(Arrays.copyOf(data, 125)));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testReadProfileRawTruncatedHeader() throws IOException { public void testReadProfileRawTruncatedHeader() throws IOException {
byte[] data = ICC_Profile.getInstance(getClass().getResourceAsStream("/profiles/adobe_rgb_1998.icc")).getData(); byte[] data = ICC_Profile.getInstance(getClass().getResourceAsStream("/profiles/adobe_rgb_1998.icc")).getData();
ColorProfiles.readProfileRaw(new ByteArrayInputStream(data, 0, 125)); assertThrows(IllegalArgumentException.class, () -> ColorProfiles.readProfileRaw(new ByteArrayInputStream(data, 0, 125)));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateProfileTruncatedHeader() throws IOException { public void testCreateProfileTruncatedHeader() throws IOException {
byte[] data = ICC_Profile.getInstance(getClass().getResourceAsStream("/profiles/adobe_rgb_1998.icc")).getData(); byte[] data = ICC_Profile.getInstance(getClass().getResourceAsStream("/profiles/adobe_rgb_1998.icc")).getData();
ColorProfiles.createProfile(Arrays.copyOf(data, 125)); assertThrows(IllegalArgumentException.class, () -> ColorProfiles.createProfile(Arrays.copyOf(data, 125)));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testReadProfileTruncatedHeader() throws IOException { public void testReadProfileTruncatedHeader() throws IOException {
byte[] data = ICC_Profile.getInstance(getClass().getResourceAsStream("/profiles/adobe_rgb_1998.icc")).getData(); byte[] data = ICC_Profile.getInstance(getClass().getResourceAsStream("/profiles/adobe_rgb_1998.icc")).getData();
ColorProfiles.readProfile(new ByteArrayInputStream(data, 0, 125)); assertThrows(IllegalArgumentException.class, () -> ColorProfiles.readProfile(new ByteArrayInputStream(data, 0, 125)));
} }
@Test @Test
@@ -30,15 +30,16 @@
package com.twelvemonkeys.imageio.color; package com.twelvemonkeys.imageio.color;
import org.junit.Test;
import java.awt.color.ColorSpace; import java.awt.color.ColorSpace;
import java.awt.color.ICC_ColorSpace; import java.awt.color.ICC_ColorSpace;
import java.awt.color.ICC_Profile; import java.awt.color.ICC_Profile;
import java.io.IOException; import java.io.IOException;
import static org.junit.Assert.*; import org.junit.jupiter.api.Test;
import static org.junit.Assume.assumeTrue; import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assumptions.*;
/** /**
* ColorSpacesTest * ColorSpacesTest
@@ -154,9 +155,9 @@ public class ColorSpacesTest {
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@Test(expected = IllegalArgumentException.class) @Test
public void testIsCS_sRGBNull() { public void testIsCS_sRGBNull() {
ColorSpaces.isCS_sRGB(null); assertThrows(IllegalArgumentException.class, () -> ColorSpaces.isCS_sRGB(null));
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@@ -175,9 +176,9 @@ public class ColorSpacesTest {
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@Test(expected = IllegalArgumentException.class) @Test
public void testIsCS_GRAYNull() { public void testIsCS_GRAYNull() {
ColorSpaces.isCS_GRAY(null); assertThrows(IllegalArgumentException.class, () -> ColorSpaces.isCS_GRAY(null));
} }
@Test @Test
@@ -31,21 +31,20 @@
package com.twelvemonkeys.imageio.color; package com.twelvemonkeys.imageio.color;
import org.hamcrest.CoreMatchers; import org.hamcrest.CoreMatchers;
import org.junit.Test;
import java.awt.image.*; import java.awt.image.*;
import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.*;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class DiscreteAlphaIndexColorModelTest { public class DiscreteAlphaIndexColorModelTest {
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateNull() { public void testCreateNull() {
new DiscreteAlphaIndexColorModel(null); assertThrows(IllegalArgumentException.class, () -> new DiscreteAlphaIndexColorModel(null));
} }
@Test @Test
@@ -202,7 +201,7 @@ public class DiscreteAlphaIndexColorModelTest {
assertEquals(2, raster.getHeight()); assertEquals(2, raster.getHeight());
assertTrue(colorModel.isCompatibleRaster(raster)); assertTrue(colorModel.isCompatibleRaster(raster));
assertThat(raster, CoreMatchers.is(WritableRaster.class)); // Specific subclasses are in sun.awt package assertThat(raster, instanceOf(WritableRaster.class)); // Checks if raster is an instance of WritableRaster or its subclass
assertThat(raster.getTransferType(), CoreMatchers.equalTo(DataBuffer.TYPE_BYTE)); assertThat(raster.getTransferType(), CoreMatchers.equalTo(DataBuffer.TYPE_BYTE));
} }
@@ -30,8 +30,6 @@
package com.twelvemonkeys.imageio.color; package com.twelvemonkeys.imageio.color;
import org.junit.Test;
import java.awt.color.ColorSpace; import java.awt.color.ColorSpace;
import java.awt.color.ICC_ColorSpace; import java.awt.color.ICC_ColorSpace;
import java.awt.color.ICC_Profile; import java.awt.color.ICC_Profile;
@@ -39,16 +37,18 @@ import java.io.IOException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.Arrays; import java.util.Arrays;
import static org.junit.Assert.assertArrayEquals; import org.junit.jupiter.api.Test;
import static org.junit.Assume.assumeFalse; import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assumptions.*;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
public class KCMSSanitizerStrategyTest { public class KCMSSanitizerStrategyTest {
private static final byte[] XYZ = new byte[] {'X', 'Y', 'Z', ' '}; private static final byte[] XYZ = new byte[] {'X', 'Y', 'Z', ' '};
@Test(expected = IllegalArgumentException.class) @Test
public void testFixProfileNullProfile() throws Exception { public void testFixProfileNullProfile() throws Exception {
new KCMSSanitizerStrategy().fixProfile(null); assertThrows(IllegalArgumentException.class, () -> new KCMSSanitizerStrategy().fixProfile(null));
} }
@Test @Test
@@ -77,7 +77,7 @@ public class KCMSSanitizerStrategyTest {
try { try {
Method isSealed = Class.class.getMethod("isSealed"); Method isSealed = Class.class.getMethod("isSealed");
Boolean result = (Boolean) isSealed.invoke(ICC_Profile.class); Boolean result = (Boolean) isSealed.invoke(ICC_Profile.class);
assumeFalse("Can't mock ICC_Profile, class is sealed (as of JDK 19).", result); assumeFalse(result, "Can't mock ICC_Profile, class is sealed (as of JDK 19).");
} }
catch (ReflectiveOperationException ignore) { catch (ReflectiveOperationException ignore) {
// We can't have sealed classes if we don't have the isSealed method... // We can't have sealed classes if we don't have the isSealed method...
@@ -30,19 +30,19 @@
package com.twelvemonkeys.imageio.color; package com.twelvemonkeys.imageio.color;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.awt.color.ICC_Profile; import java.awt.color.ICC_Profile;
import static com.twelvemonkeys.imageio.color.KCMSSanitizerStrategyTest.assumeICC_ProfileNotSealed; import static com.twelvemonkeys.imageio.color.KCMSSanitizerStrategyTest.assumeICC_ProfileNotSealed;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions;
public class LCMSSanitizerStrategyTest { public class LCMSSanitizerStrategyTest {
@Test(expected = IllegalArgumentException.class) @Test
public void testFixProfileNullProfile() throws Exception { public void testFixProfileNullProfile() throws Exception {
new LCMSSanitizerStrategy().fixProfile(null); assertThrows(IllegalArgumentException.class, () -> new LCMSSanitizerStrategy().fixProfile(null));
} }
@Test @Test
@@ -1,6 +1,6 @@
package com.twelvemonkeys.imageio.color; package com.twelvemonkeys.imageio.color;
import org.junit.Test; import org.junit.jupiter.api.Test;
import javax.imageio.spi.ImageInputStreamSpi; import javax.imageio.spi.ImageInputStreamSpi;
import javax.imageio.spi.ServiceRegistry; import javax.imageio.spi.ServiceRegistry;
@@ -30,12 +30,11 @@
package com.twelvemonkeys.imageio.color; package com.twelvemonkeys.imageio.color;
import org.junit.Test;
import java.awt.color.ColorSpace; import java.awt.color.ColorSpace;
import java.awt.image.ComponentColorModel; import java.awt.image.ComponentColorModel;
import static org.junit.Assert.assertEquals; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class UInt32ColorModelTest { public class UInt32ColorModelTest {
@@ -30,11 +30,11 @@
package com.twelvemonkeys.imageio.spi; package com.twelvemonkeys.imageio.spi;
import org.junit.Test;
import java.net.URL; import java.net.URL;
import static org.junit.Assert.*; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* ProviderInfoTest * ProviderInfoTest
@@ -30,9 +30,9 @@
package com.twelvemonkeys.imageio.spi; package com.twelvemonkeys.imageio.spi;
import org.junit.jupiter.api.Test;
import org.hamcrest.Description; import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher; import org.hamcrest.TypeSafeMatcher;
import org.junit.Test;
import javax.imageio.ImageReader; import javax.imageio.ImageReader;
import javax.imageio.ImageWriter; import javax.imageio.ImageWriter;
@@ -43,7 +43,7 @@ import java.util.List;
import static java.util.Arrays.asList; import static java.util.Arrays.asList;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
/** /**
* ReaderWriterProviderInfoTest. * ReaderWriterProviderInfoTest.
@@ -30,8 +30,8 @@
package com.twelvemonkeys.imageio.stream; package com.twelvemonkeys.imageio.stream;
import org.junit.Test;
import org.junit.function.ThrowingRunnable; import org.junit.jupiter.api.Test;
import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageInputStream;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
@@ -44,7 +44,8 @@ import java.nio.channels.ReadableByteChannel;
import java.util.Random; import java.util.Random;
import static com.twelvemonkeys.imageio.stream.BufferedImageInputStreamTest.rangeEquals; import static com.twelvemonkeys.imageio.stream.BufferedImageInputStreamTest.rangeEquals;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.only; import static org.mockito.Mockito.only;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
@@ -69,7 +70,7 @@ public class BufferedChannelImageInputStreamFileCacheTest {
@Test @Test
public void testCreate() throws IOException { public void testCreate() throws IOException {
try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new FileCache(new ByteArrayInputStream(new byte[0]), null))) { try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new FileCache(new ByteArrayInputStream(new byte[0]), null))) {
assertEquals("Stream length should be unknown", -1, stream.length()); assertEquals(-1, stream.length(), "Stream length should be unknown");
} }
} }
@@ -82,8 +83,8 @@ public class BufferedChannelImageInputStreamFileCacheTest {
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
assertNotNull("Null exception message", expected.getMessage()); assertNotNull("Null exception message", expected.getMessage());
String message = expected.getMessage().toLowerCase(); String message = expected.getMessage().toLowerCase();
assertTrue("Exception message does not contain parameter name", message.contains("stream")); assertTrue(message.contains("stream"), "Exception message does not contain parameter name");
assertTrue("Exception message does not contain null", message.contains("null")); assertTrue(message.contains("null"), "Exception message does not contain null");
} }
} }
@@ -96,8 +97,8 @@ public class BufferedChannelImageInputStreamFileCacheTest {
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
assertNotNull("Null exception message", expected.getMessage()); assertNotNull("Null exception message", expected.getMessage());
String message = expected.getMessage().toLowerCase(); String message = expected.getMessage().toLowerCase();
assertTrue("Exception message does not contain parameter name", message.contains("channel")); assertTrue(message.contains("channel"), "Exception message does not contain parameter name");
assertTrue("Exception message does not contain null", message.contains("null")); assertTrue(message.contains("null"), "Exception message does not contain null");
} }
} }
@@ -107,13 +108,13 @@ public class BufferedChannelImageInputStreamFileCacheTest {
InputStream input = randomDataToInputStream(data); InputStream input = randomDataToInputStream(data);
try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new FileCache(input, null))) { try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new FileCache(input, null))) {
assertEquals("Stream length should be unknown", -1, stream.length()); assertEquals(-1, stream.length(), "Stream length should be unknown");
for (byte value : data) { for (byte value : data) {
assertEquals("Wrong data read", value & 0xff, stream.read()); assertEquals(value & 0xff, stream.read(), "Wrong data read");
} }
assertEquals("Wrong data read", -1, stream.read()); assertEquals(-1, stream.read(), "Wrong data read");
} }
} }
@@ -123,16 +124,16 @@ public class BufferedChannelImageInputStreamFileCacheTest {
InputStream input = randomDataToInputStream(data); InputStream input = randomDataToInputStream(data);
try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new FileCache(input, null))) { try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new FileCache(input, null))) {
assertEquals("Stream length should be unknown", -1, stream.length()); assertEquals(-1, stream.length(), "Stream length should be unknown");
byte[] result = new byte[1024]; byte[] result = new byte[1024];
for (int i = 0; i < data.length / result.length; i++) { for (int i = 0; i < data.length / result.length; i++) {
stream.readFully(result); stream.readFully(result);
assertTrue("Wrong data read: " + i, rangeEquals(data, i * result.length, result, 0, result.length)); assertTrue(rangeEquals(data, i * result.length, result, 0, result.length), "Wrong data read: " + i);
} }
assertEquals("Wrong data read", -1, stream.read()); assertEquals(-1, stream.read(), "Wrong data read");
} }
} }
@@ -142,14 +143,14 @@ public class BufferedChannelImageInputStreamFileCacheTest {
InputStream input = randomDataToInputStream(data); InputStream input = randomDataToInputStream(data);
try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new FileCache(input, null))) { try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new FileCache(input, null))) {
assertEquals("Stream length should be unknown", -1, stream.length()); assertEquals(-1, stream.length(), "Stream length should be unknown");
byte[] result = new byte[7]; byte[] result = new byte[7];
for (int i = 0; i < data.length / result.length; i += 2) { for (int i = 0; i < data.length / result.length; i += 2) {
stream.readFully(result); stream.readFully(result);
stream.skipBytes(result.length); stream.skipBytes(result.length);
assertTrue("Wrong data read: " + i, rangeEquals(data, i * result.length, result, 0, result.length)); assertTrue(rangeEquals(data, i * result.length, result, 0, result.length), "Wrong data read: " + i);
} }
} }
} }
@@ -160,7 +161,7 @@ public class BufferedChannelImageInputStreamFileCacheTest {
InputStream input = randomDataToInputStream(data); InputStream input = randomDataToInputStream(data);
try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new FileCache(input, null))) { try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new FileCache(input, null))) {
assertEquals("Stream length should be unknown", -1, stream.length()); assertEquals(-1, stream.length(), "Stream length should be unknown");
byte[] result = new byte[9]; byte[] result = new byte[9];
@@ -168,9 +169,9 @@ public class BufferedChannelImageInputStreamFileCacheTest {
// Read backwards // Read backwards
long newPos = data.length - result.length - i * result.length; long newPos = data.length - result.length - i * result.length;
stream.seek(newPos); stream.seek(newPos);
assertEquals("Wrong stream position", newPos, stream.getStreamPosition()); assertEquals(newPos, stream.getStreamPosition(), "Wrong stream position");
stream.readFully(result); stream.readFully(result);
assertTrue("Wrong data read: " + i, rangeEquals(data, (int) newPos, result, 0, result.length)); assertTrue(rangeEquals(data, (int) newPos, result, 0, result.length), "Wrong data read: " + i);
} }
} }
} }
@@ -181,7 +182,7 @@ public class BufferedChannelImageInputStreamFileCacheTest {
InputStream input = randomDataToInputStream(data); InputStream input = randomDataToInputStream(data);
try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new FileCache(input, null))) { try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new FileCache(input, null))) {
assertEquals("Stream length should be unknown", -1, stream.length()); assertEquals(-1, stream.length(), "Stream length should be unknown");
byte[] buffer = new byte[data.length * 2]; byte[] buffer = new byte[data.length * 2];
stream.read(buffer); stream.read(buffer);
@@ -200,7 +201,7 @@ public class BufferedChannelImageInputStreamFileCacheTest {
// Create stream // Create stream
try (ImageInputStream stream = new BufferedChannelImageInputStream(new FileCache(input, null))) { try (ImageInputStream stream = new BufferedChannelImageInputStream(new FileCache(input, null))) {
for (int i = 1; i <= 64; i++) { for (int i = 1; i <= 64; i++) {
assertEquals(String.format("bit %d differ", i), (value << (i - 1L)) >>> 63L, stream.readBit()); assertEquals((value << (i - 1L)) >>> 63L, stream.readBit(), String.format("bit %d differ", i));
} }
} }
} }
@@ -215,7 +216,7 @@ public class BufferedChannelImageInputStreamFileCacheTest {
try (ImageInputStream stream = new BufferedChannelImageInputStream(new FileCache(input, null))) { try (ImageInputStream stream = new BufferedChannelImageInputStream(new FileCache(input, null))) {
for (int i = 1; i <= 64; i++) { for (int i = 1; i <= 64; i++) {
stream.seek(0); stream.seek(0);
assertEquals(String.format("bit %d differ", i), value >>> (64L - i), stream.readBits(i)); assertEquals(value >>> (64L - i), stream.readBits(i), String.format("bit %d differ", i));
assertEquals(i % 8, stream.getBitOffset()); assertEquals(i % 8, stream.getBitOffset());
} }
} }
@@ -232,7 +233,7 @@ public class BufferedChannelImageInputStreamFileCacheTest {
for (int i = 1; i <= 60; i++) { for (int i = 1; i <= 60; i++) {
stream.seek(0); stream.seek(0);
stream.setBitOffset(i % 8); stream.setBitOffset(i % 8);
assertEquals(String.format("bit %d differ", i), (value << (i % 8)) >>> (64L - i), stream.readBits(i)); assertEquals((value << (i % 8)) >>> (64L - i), stream.readBits(i), String.format("bit %d differ", i));
assertEquals(i * 2 % 8, stream.getBitOffset()); assertEquals(i * 2 % 8, stream.getBitOffset());
} }
} }
@@ -251,12 +252,7 @@ public class BufferedChannelImageInputStreamFileCacheTest {
assertEquals(buffer.getShort(), stream.readShort()); assertEquals(buffer.getShort(), stream.readShort());
} }
assertThrows(EOFException.class, new ThrowingRunnable() { assertThrows(EOFException.class, stream::readShort);
@Override
public void run() throws Throwable {
stream.readShort();
}
});
stream.seek(0); stream.seek(0);
stream.setByteOrder(ByteOrder.LITTLE_ENDIAN); stream.setByteOrder(ByteOrder.LITTLE_ENDIAN);
@@ -267,12 +263,7 @@ public class BufferedChannelImageInputStreamFileCacheTest {
assertEquals(buffer.getShort(), stream.readShort()); assertEquals(buffer.getShort(), stream.readShort());
} }
assertThrows(EOFException.class, new ThrowingRunnable() { assertThrows(EOFException.class, stream::readShort);
@Override
public void run() throws Throwable {
stream.readShort();
}
});
} }
} }
@@ -289,12 +280,7 @@ public class BufferedChannelImageInputStreamFileCacheTest {
assertEquals(buffer.getInt(), stream.readInt()); assertEquals(buffer.getInt(), stream.readInt());
} }
assertThrows(EOFException.class, new ThrowingRunnable() { assertThrows(EOFException.class, stream::readInt);
@Override
public void run() throws Throwable {
stream.readInt();
}
});
stream.seek(0); stream.seek(0);
stream.setByteOrder(ByteOrder.LITTLE_ENDIAN); stream.setByteOrder(ByteOrder.LITTLE_ENDIAN);
@@ -305,12 +291,7 @@ public class BufferedChannelImageInputStreamFileCacheTest {
assertEquals(buffer.getInt(), stream.readInt()); assertEquals(buffer.getInt(), stream.readInt());
} }
assertThrows(EOFException.class, new ThrowingRunnable() { assertThrows(EOFException.class, stream::readInt);
@Override
public void run() throws Throwable {
stream.readInt();
}
});
} }
} }
@@ -327,12 +308,7 @@ public class BufferedChannelImageInputStreamFileCacheTest {
assertEquals(buffer.getLong(), stream.readLong()); assertEquals(buffer.getLong(), stream.readLong());
} }
assertThrows(EOFException.class, new ThrowingRunnable() { assertThrows(EOFException.class, stream::readLong);
@Override
public void run() throws Throwable {
stream.readLong();
}
});
stream.seek(0); stream.seek(0);
stream.setByteOrder(ByteOrder.LITTLE_ENDIAN); stream.setByteOrder(ByteOrder.LITTLE_ENDIAN);
@@ -343,12 +319,7 @@ public class BufferedChannelImageInputStreamFileCacheTest {
assertEquals(buffer.getLong(), stream.readLong()); assertEquals(buffer.getLong(), stream.readLong());
} }
assertThrows(EOFException.class, new ThrowingRunnable() { assertThrows(EOFException.class, stream::readLong);
@Override
public void run() throws Throwable {
stream.readLong();
}
});
} }
} }
@@ -363,36 +334,12 @@ public class BufferedChannelImageInputStreamFileCacheTest {
assertEquals(-1, stream.read()); assertEquals(-1, stream.read());
assertEquals(-1, stream.read(new byte[1], 0, 1)); assertEquals(-1, stream.read(new byte[1], 0, 1));
assertThrows(EOFException.class, new ThrowingRunnable() {
@Override assertThrows(EOFException.class, () -> stream.readFully(new byte[1]));
public void run() throws Throwable { assertThrows(EOFException.class, stream::readByte);
stream.readFully(new byte[1]); assertThrows(EOFException.class, stream::readShort);
} assertThrows(EOFException.class, stream::readInt);
}); assertThrows(EOFException.class, stream::readLong);
assertThrows(EOFException.class, new ThrowingRunnable() {
@Override
public void run() throws Throwable {
stream.readByte();
}
});
assertThrows(EOFException.class, new ThrowingRunnable() {
@Override
public void run() throws Throwable {
stream.readShort();
}
});
assertThrows(EOFException.class, new ThrowingRunnable() {
@Override
public void run() throws Throwable {
stream.readInt();
}
});
assertThrows(EOFException.class, new ThrowingRunnable() {
@Override
public void run() throws Throwable {
stream.readLong();
}
});
stream.seek(0); stream.seek(0);
for (byte value : bytes) { for (byte value : bytes) {
@@ -30,9 +30,6 @@
package com.twelvemonkeys.imageio.stream; package com.twelvemonkeys.imageio.stream;
import org.junit.Test;
import org.junit.function.ThrowingRunnable;
import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageInputStream;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.EOFException; import java.io.EOFException;
@@ -43,8 +40,10 @@ import java.nio.ByteOrder;
import java.nio.channels.ReadableByteChannel; import java.nio.channels.ReadableByteChannel;
import java.util.Random; import java.util.Random;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static com.twelvemonkeys.imageio.stream.BufferedImageInputStreamTest.rangeEquals; import static com.twelvemonkeys.imageio.stream.BufferedImageInputStreamTest.rangeEquals;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.only; import static org.mockito.Mockito.only;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
@@ -69,7 +68,7 @@ public class BufferedChannelImageInputStreamMemoryCacheTest {
@Test @Test
public void testCreate() throws IOException { public void testCreate() throws IOException {
try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new MemoryCache(new ByteArrayInputStream(new byte[0])))) { try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new MemoryCache(new ByteArrayInputStream(new byte[0])))) {
assertEquals("Stream length should be unknown", -1, stream.length()); assertEquals(-1, stream.length(), "Stream length should be unknown");
} }
} }
@@ -82,8 +81,8 @@ public class BufferedChannelImageInputStreamMemoryCacheTest {
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
assertNotNull("Null exception message", expected.getMessage()); assertNotNull("Null exception message", expected.getMessage());
String message = expected.getMessage().toLowerCase(); String message = expected.getMessage().toLowerCase();
assertTrue("Exception message does not contain parameter name", message.contains("stream")); assertTrue(message.contains("stream"), "Exception message does not contain parameter name");
assertTrue("Exception message does not contain null", message.contains("null")); assertTrue(message.contains("null"), "Exception message does not contain null");
} }
} }
@@ -96,8 +95,8 @@ public class BufferedChannelImageInputStreamMemoryCacheTest {
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
assertNotNull("Null exception message", expected.getMessage()); assertNotNull("Null exception message", expected.getMessage());
String message = expected.getMessage().toLowerCase(); String message = expected.getMessage().toLowerCase();
assertTrue("Exception message does not contain parameter name", message.contains("channel")); assertTrue(message.contains("channel"), "Exception message does not contain parameter name");
assertTrue("Exception message does not contain null", message.contains("null")); assertTrue(message.contains("null"), "Exception message does not contain null");
} }
} }
@@ -107,13 +106,13 @@ public class BufferedChannelImageInputStreamMemoryCacheTest {
InputStream input = randomDataToInputStream(data); InputStream input = randomDataToInputStream(data);
try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new MemoryCache(input))) { try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new MemoryCache(input))) {
assertEquals("Stream length should be unknown", -1, stream.length()); assertEquals(-1, stream.length(), "Stream length should be unknown");
for (byte value : data) { for (byte value : data) {
assertEquals("Wrong data read", value & 0xff, stream.read()); assertEquals(value & 0xff, stream.read(), "Wrong data read");
} }
assertEquals("Wrong data read", -1, stream.read()); assertEquals(-1, stream.read(), "Wrong data read");
} }
} }
@@ -123,16 +122,16 @@ public class BufferedChannelImageInputStreamMemoryCacheTest {
InputStream input = randomDataToInputStream(data); InputStream input = randomDataToInputStream(data);
try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new MemoryCache(input))) { try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new MemoryCache(input))) {
assertEquals("Stream length should be unknown", -1, stream.length()); assertEquals(-1, stream.length(), "Stream length should be unknown");
byte[] result = new byte[1024]; byte[] result = new byte[1024];
for (int i = 0; i < data.length / result.length; i++) { for (int i = 0; i < data.length / result.length; i++) {
stream.readFully(result); stream.readFully(result);
assertTrue("Wrong data read: " + i, rangeEquals(data, i * result.length, result, 0, result.length)); assertTrue(rangeEquals(data, i * result.length, result, 0, result.length), "Wrong data read: " + i);
} }
assertEquals("Wrong data read", -1, stream.read()); assertEquals(-1, stream.read(), "Wrong data read");
} }
} }
@@ -142,14 +141,14 @@ public class BufferedChannelImageInputStreamMemoryCacheTest {
InputStream input = randomDataToInputStream(data); InputStream input = randomDataToInputStream(data);
try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new MemoryCache(input))) { try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new MemoryCache(input))) {
assertEquals("Stream length should be unknown", -1, stream.length()); assertEquals(-1, stream.length(), "Stream length should be unknown");
byte[] result = new byte[7]; byte[] result = new byte[7];
for (int i = 0; i < data.length / result.length; i += 2) { for (int i = 0; i < data.length / result.length; i += 2) {
stream.readFully(result); stream.readFully(result);
stream.skipBytes(result.length); stream.skipBytes(result.length);
assertTrue("Wrong data read: " + i, rangeEquals(data, i * result.length, result, 0, result.length)); assertTrue(rangeEquals(data, i * result.length, result, 0, result.length), "Wrong data read: " + i);
} }
} }
} }
@@ -160,7 +159,7 @@ public class BufferedChannelImageInputStreamMemoryCacheTest {
InputStream input = randomDataToInputStream(data); InputStream input = randomDataToInputStream(data);
try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new MemoryCache(input))) { try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new MemoryCache(input))) {
assertEquals("Stream length should be unknown", -1, stream.length()); assertEquals(-1, stream.length(), "Stream length should be unknown");
byte[] result = new byte[9]; byte[] result = new byte[9];
@@ -168,9 +167,9 @@ public class BufferedChannelImageInputStreamMemoryCacheTest {
// Read backwards // Read backwards
long newPos = data.length - result.length - i * result.length; long newPos = data.length - result.length - i * result.length;
stream.seek(newPos); stream.seek(newPos);
assertEquals("Wrong stream position", newPos, stream.getStreamPosition()); assertEquals(newPos, stream.getStreamPosition(), "Wrong stream position");
stream.readFully(result); stream.readFully(result);
assertTrue("Wrong data read: " + i, rangeEquals(data, (int) newPos, result, 0, result.length)); assertTrue(rangeEquals(data, (int) newPos, result, 0, result.length), "Wrong data read: " + i);
} }
} }
} }
@@ -181,7 +180,7 @@ public class BufferedChannelImageInputStreamMemoryCacheTest {
InputStream input = randomDataToInputStream(data); InputStream input = randomDataToInputStream(data);
try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new MemoryCache(input))) { try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new MemoryCache(input))) {
assertEquals("Stream length should be unknown", -1, stream.length()); assertEquals(-1, stream.length(), "Stream length should be unknown");
byte[] buffer = new byte[data.length * 2]; byte[] buffer = new byte[data.length * 2];
stream.read(buffer); stream.read(buffer);
@@ -200,7 +199,7 @@ public class BufferedChannelImageInputStreamMemoryCacheTest {
// Create stream // Create stream
try (ImageInputStream stream = new BufferedChannelImageInputStream(new MemoryCache(input))) { try (ImageInputStream stream = new BufferedChannelImageInputStream(new MemoryCache(input))) {
for (int i = 1; i <= 64; i++) { for (int i = 1; i <= 64; i++) {
assertEquals(String.format("bit %d differ", i), (value << (i - 1L)) >>> 63L, stream.readBit()); assertEquals((value << (i - 1L)) >>> 63L, stream.readBit(), String.format("bit %d differ", i));
} }
} }
} }
@@ -215,7 +214,7 @@ public class BufferedChannelImageInputStreamMemoryCacheTest {
try (ImageInputStream stream = new BufferedChannelImageInputStream(new MemoryCache(input))) { try (ImageInputStream stream = new BufferedChannelImageInputStream(new MemoryCache(input))) {
for (int i = 1; i <= 64; i++) { for (int i = 1; i <= 64; i++) {
stream.seek(0); stream.seek(0);
assertEquals(String.format("bit %d differ", i), value >>> (64L - i), stream.readBits(i)); assertEquals(value >>> (64L - i), stream.readBits(i), String.format("bit %d differ", i));
assertEquals(i % 8, stream.getBitOffset()); assertEquals(i % 8, stream.getBitOffset());
} }
} }
@@ -232,7 +231,7 @@ public class BufferedChannelImageInputStreamMemoryCacheTest {
for (int i = 1; i <= 60; i++) { for (int i = 1; i <= 60; i++) {
stream.seek(0); stream.seek(0);
stream.setBitOffset(i % 8); stream.setBitOffset(i % 8);
assertEquals(String.format("bit %d differ", i), (value << (i % 8)) >>> (64L - i), stream.readBits(i)); assertEquals((value << (i % 8)) >>> (64L - i), stream.readBits(i), String.format("bit %d differ", i));
assertEquals(i * 2 % 8, stream.getBitOffset()); assertEquals(i * 2 % 8, stream.getBitOffset());
} }
} }
@@ -251,12 +250,7 @@ public class BufferedChannelImageInputStreamMemoryCacheTest {
assertEquals(buffer.getShort(), stream.readShort()); assertEquals(buffer.getShort(), stream.readShort());
} }
assertThrows(EOFException.class, new ThrowingRunnable() { assertThrows(EOFException.class, stream::readShort);
@Override
public void run() throws Throwable {
stream.readShort();
}
});
stream.seek(0); stream.seek(0);
stream.setByteOrder(ByteOrder.LITTLE_ENDIAN); stream.setByteOrder(ByteOrder.LITTLE_ENDIAN);
@@ -267,12 +261,7 @@ public class BufferedChannelImageInputStreamMemoryCacheTest {
assertEquals(buffer.getShort(), stream.readShort()); assertEquals(buffer.getShort(), stream.readShort());
} }
assertThrows(EOFException.class, new ThrowingRunnable() { assertThrows(EOFException.class, stream::readShort);
@Override
public void run() throws Throwable {
stream.readShort();
}
});
} }
} }
@@ -289,12 +278,7 @@ public class BufferedChannelImageInputStreamMemoryCacheTest {
assertEquals(buffer.getInt(), stream.readInt()); assertEquals(buffer.getInt(), stream.readInt());
} }
assertThrows(EOFException.class, new ThrowingRunnable() { assertThrows(EOFException.class, stream::readInt);
@Override
public void run() throws Throwable {
stream.readInt();
}
});
stream.seek(0); stream.seek(0);
stream.setByteOrder(ByteOrder.LITTLE_ENDIAN); stream.setByteOrder(ByteOrder.LITTLE_ENDIAN);
@@ -305,12 +289,7 @@ public class BufferedChannelImageInputStreamMemoryCacheTest {
assertEquals(buffer.getInt(), stream.readInt()); assertEquals(buffer.getInt(), stream.readInt());
} }
assertThrows(EOFException.class, new ThrowingRunnable() { assertThrows(EOFException.class, stream::readInt);
@Override
public void run() throws Throwable {
stream.readInt();
}
});
} }
} }
@@ -327,12 +306,7 @@ public class BufferedChannelImageInputStreamMemoryCacheTest {
assertEquals(buffer.getLong(), stream.readLong()); assertEquals(buffer.getLong(), stream.readLong());
} }
assertThrows(EOFException.class, new ThrowingRunnable() { assertThrows(EOFException.class, stream::readLong);
@Override
public void run() throws Throwable {
stream.readLong();
}
});
stream.seek(0); stream.seek(0);
stream.setByteOrder(ByteOrder.LITTLE_ENDIAN); stream.setByteOrder(ByteOrder.LITTLE_ENDIAN);
@@ -343,12 +317,7 @@ public class BufferedChannelImageInputStreamMemoryCacheTest {
assertEquals(buffer.getLong(), stream.readLong()); assertEquals(buffer.getLong(), stream.readLong());
} }
assertThrows(EOFException.class, new ThrowingRunnable() { assertThrows(EOFException.class, stream::readLong);
@Override
public void run() throws Throwable {
stream.readLong();
}
});
} }
} }
@@ -363,36 +332,11 @@ public class BufferedChannelImageInputStreamMemoryCacheTest {
assertEquals(-1, stream.read()); assertEquals(-1, stream.read());
assertEquals(-1, stream.read(new byte[1], 0, 1)); assertEquals(-1, stream.read(new byte[1], 0, 1));
assertThrows(EOFException.class, new ThrowingRunnable() { assertThrows(EOFException.class, () -> stream.readFully(new byte[1]));
@Override assertThrows(EOFException.class, stream::readByte);
public void run() throws Throwable { assertThrows(EOFException.class, stream::readShort);
stream.readFully(new byte[1]); assertThrows(EOFException.class, stream::readInt);
} assertThrows(EOFException.class, stream::readLong);
});
assertThrows(EOFException.class, new ThrowingRunnable() {
@Override
public void run() throws Throwable {
stream.readByte();
}
});
assertThrows(EOFException.class, new ThrowingRunnable() {
@Override
public void run() throws Throwable {
stream.readShort();
}
});
assertThrows(EOFException.class, new ThrowingRunnable() {
@Override
public void run() throws Throwable {
stream.readInt();
}
});
assertThrows(EOFException.class, new ThrowingRunnable() {
@Override
public void run() throws Throwable {
stream.readLong();
}
});
stream.seek(0); stream.seek(0);
for (byte value : bytes) { for (byte value : bytes) {
@@ -30,9 +30,6 @@
package com.twelvemonkeys.imageio.stream; package com.twelvemonkeys.imageio.stream;
import org.junit.Test;
import org.junit.function.ThrowingRunnable;
import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageInputStream;
import java.io.EOFException; import java.io.EOFException;
import java.io.File; import java.io.File;
@@ -44,8 +41,10 @@ import java.nio.channels.SeekableByteChannel;
import java.nio.file.Files; import java.nio.file.Files;
import java.util.Random; import java.util.Random;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static com.twelvemonkeys.imageio.stream.BufferedImageInputStreamTest.rangeEquals; import static com.twelvemonkeys.imageio.stream.BufferedImageInputStreamTest.rangeEquals;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
@@ -71,7 +70,7 @@ public class BufferedChannelImageInputStreamTest {
@Test @Test
public void testCreate() throws IOException { public void testCreate() throws IOException {
try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new FileInputStream(File.createTempFile("empty", ".tmp")))) { try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new FileInputStream(File.createTempFile("empty", ".tmp")))) {
assertEquals("Data length should be same as stream length", 0, stream.length()); assertEquals(0, stream.length(), "Data length should be same as stream length");
} }
} }
@@ -84,8 +83,8 @@ public class BufferedChannelImageInputStreamTest {
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
assertNotNull("Null exception message", expected.getMessage()); assertNotNull("Null exception message", expected.getMessage());
String message = expected.getMessage().toLowerCase(); String message = expected.getMessage().toLowerCase();
assertTrue("Exception message does not contain parameter name", message.contains("inputstream")); assertTrue(message.contains("inputstream"), "Exception message does not contain parameter name");
assertTrue("Exception message does not contain null", message.contains("null")); assertTrue(message.contains("null"), "Exception message does not contain null");
} }
} }
@@ -98,8 +97,8 @@ public class BufferedChannelImageInputStreamTest {
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
assertNotNull("Null exception message", expected.getMessage()); assertNotNull("Null exception message", expected.getMessage());
String message = expected.getMessage().toLowerCase(); String message = expected.getMessage().toLowerCase();
assertTrue("Exception message does not contain parameter name", message.contains("channel")); assertTrue(message.contains("channel"), "Exception message does not contain parameter name");
assertTrue("Exception message does not contain null", message.contains("null")); assertTrue(message.contains("null"), "Exception message does not contain null");
} }
} }
@@ -109,10 +108,10 @@ public class BufferedChannelImageInputStreamTest {
File file = randomDataToFile(data); File file = randomDataToFile(data);
try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new FileInputStream(file))) { try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new FileInputStream(file))) {
assertEquals("File length should be same as stream length", file.length(), stream.length()); assertEquals(file.length(), stream.length(), "File length should be same as stream length");
for (byte value : data) { for (byte value : data) {
assertEquals("Wrong data read", value & 0xff, stream.read()); assertEquals(value & 0xff, stream.read(), "Wrong data read");
} }
} }
} }
@@ -123,13 +122,13 @@ public class BufferedChannelImageInputStreamTest {
File file = randomDataToFile(data); File file = randomDataToFile(data);
try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new FileInputStream(file))) { try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new FileInputStream(file))) {
assertEquals("File length should be same as stream length", file.length(), stream.length()); assertEquals(file.length(), stream.length(), "File length should be same as stream length");
byte[] result = new byte[1024]; byte[] result = new byte[1024];
for (int i = 0; i < data.length / result.length; i++) { for (int i = 0; i < data.length / result.length; i++) {
stream.readFully(result); stream.readFully(result);
assertTrue("Wrong data read: " + i, rangeEquals(data, i * result.length, result, 0, result.length)); assertTrue(rangeEquals(data, i * result.length, result, 0, result.length), "Wrong data read: " + i);
} }
} }
} }
@@ -140,14 +139,14 @@ public class BufferedChannelImageInputStreamTest {
File file = randomDataToFile(data); File file = randomDataToFile(data);
try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new FileInputStream(file))) { try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new FileInputStream(file))) {
assertEquals("File length should be same as stream length", file.length(), stream.length()); assertEquals(file.length(), stream.length(), "File length should be same as stream length");
byte[] result = new byte[7]; byte[] result = new byte[7];
for (int i = 0; i < data.length / result.length; i += 2) { for (int i = 0; i < data.length / result.length; i += 2) {
stream.readFully(result); stream.readFully(result);
stream.skipBytes(result.length); stream.skipBytes(result.length);
assertTrue("Wrong data read: " + i, rangeEquals(data, i * result.length, result, 0, result.length)); assertTrue(rangeEquals(data, i * result.length, result, 0, result.length), "Wrong data read: " + i);
} }
} }
} }
@@ -158,7 +157,7 @@ public class BufferedChannelImageInputStreamTest {
File file = randomDataToFile(data); File file = randomDataToFile(data);
try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new FileInputStream(file))) { try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new FileInputStream(file))) {
assertEquals("File length should be same as stream length", file.length(), stream.length()); assertEquals(file.length(), stream.length(), "File length should be same as stream length");
byte[] result = new byte[9]; byte[] result = new byte[9];
@@ -166,9 +165,9 @@ public class BufferedChannelImageInputStreamTest {
// Read backwards // Read backwards
long newPos = stream.length() - result.length - i * result.length; long newPos = stream.length() - result.length - i * result.length;
stream.seek(newPos); stream.seek(newPos);
assertEquals("Wrong stream position", newPos, stream.getStreamPosition()); assertEquals(newPos, stream.getStreamPosition(), "Wrong stream position");
stream.readFully(result); stream.readFully(result);
assertTrue("Wrong data read: " + i, rangeEquals(data, (int) newPos, result, 0, result.length)); assertTrue(rangeEquals(data, (int) newPos, result, 0, result.length), "Wrong data read: " + i);
} }
} }
} }
@@ -179,7 +178,7 @@ public class BufferedChannelImageInputStreamTest {
File file = randomDataToFile(data); File file = randomDataToFile(data);
try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new FileInputStream(file))) { try (BufferedChannelImageInputStream stream = new BufferedChannelImageInputStream(new FileInputStream(file))) {
assertEquals("File length should be same as stream length", file.length(), stream.length()); assertEquals(file.length(), stream.length(), "File length should be same as stream length");
byte[] buffer = new byte[data.length * 2]; byte[] buffer = new byte[data.length * 2];
stream.read(buffer); stream.read(buffer);
@@ -198,7 +197,7 @@ public class BufferedChannelImageInputStreamTest {
// Create stream // Create stream
try (ImageInputStream stream = new BufferedChannelImageInputStream(new FileInputStream(file))) { try (ImageInputStream stream = new BufferedChannelImageInputStream(new FileInputStream(file))) {
for (int i = 1; i <= 64; i++) { for (int i = 1; i <= 64; i++) {
assertEquals(String.format("bit %d differ", i), (value << (i - 1L)) >>> 63L, stream.readBit()); assertEquals((value << (i - 1L)) >>> 63L, stream.readBit(), String.format("bit %d differ", i));
} }
} }
} }
@@ -213,7 +212,7 @@ public class BufferedChannelImageInputStreamTest {
try (ImageInputStream stream = new BufferedChannelImageInputStream(new FileInputStream(file))) { try (ImageInputStream stream = new BufferedChannelImageInputStream(new FileInputStream(file))) {
for (int i = 1; i <= 64; i++) { for (int i = 1; i <= 64; i++) {
stream.seek(0); stream.seek(0);
assertEquals(String.format("bit %d differ", i), value >>> (64L - i), stream.readBits(i)); assertEquals(value >>> (64L - i), stream.readBits(i), String.format("bit %d differ", i));
assertEquals(i % 8, stream.getBitOffset()); assertEquals(i % 8, stream.getBitOffset());
} }
} }
@@ -230,7 +229,7 @@ public class BufferedChannelImageInputStreamTest {
for (int i = 1; i <= 60; i++) { for (int i = 1; i <= 60; i++) {
stream.seek(0); stream.seek(0);
stream.setBitOffset(i % 8); stream.setBitOffset(i % 8);
assertEquals(String.format("bit %d differ", i), (value << (i % 8)) >>> (64L - i), stream.readBits(i)); assertEquals((value << (i % 8)) >>> (64L - i), stream.readBits(i), String.format("bit %d differ", i));
assertEquals(i * 2 % 8, stream.getBitOffset()); assertEquals(i * 2 % 8, stream.getBitOffset());
} }
} }
@@ -249,12 +248,7 @@ public class BufferedChannelImageInputStreamTest {
assertEquals(buffer.getShort(), stream.readShort()); assertEquals(buffer.getShort(), stream.readShort());
} }
assertThrows(EOFException.class, new ThrowingRunnable() { assertThrows(EOFException.class, stream::readShort);
@Override
public void run() throws Throwable {
stream.readShort();
}
});
stream.seek(0); stream.seek(0);
stream.setByteOrder(ByteOrder.LITTLE_ENDIAN); stream.setByteOrder(ByteOrder.LITTLE_ENDIAN);
@@ -265,12 +259,7 @@ public class BufferedChannelImageInputStreamTest {
assertEquals(buffer.getShort(), stream.readShort()); assertEquals(buffer.getShort(), stream.readShort());
} }
assertThrows(EOFException.class, new ThrowingRunnable() { assertThrows(EOFException.class, stream::readShort);
@Override
public void run() throws Throwable {
stream.readShort();
}
});
} }
} }
@@ -287,12 +276,7 @@ public class BufferedChannelImageInputStreamTest {
assertEquals(buffer.getInt(), stream.readInt()); assertEquals(buffer.getInt(), stream.readInt());
} }
assertThrows(EOFException.class, new ThrowingRunnable() { assertThrows(EOFException.class, stream::readInt);
@Override
public void run() throws Throwable {
stream.readInt();
}
});
stream.seek(0); stream.seek(0);
stream.setByteOrder(ByteOrder.LITTLE_ENDIAN); stream.setByteOrder(ByteOrder.LITTLE_ENDIAN);
@@ -302,13 +286,7 @@ public class BufferedChannelImageInputStreamTest {
for (int i = 0; i < bytes.length / 4; i++) { for (int i = 0; i < bytes.length / 4; i++) {
assertEquals(buffer.getInt(), stream.readInt()); assertEquals(buffer.getInt(), stream.readInt());
} }
assertThrows(EOFException.class, stream::readInt);
assertThrows(EOFException.class, new ThrowingRunnable() {
@Override
public void run() throws Throwable {
stream.readInt();
}
});
} }
} }
@@ -324,13 +302,7 @@ public class BufferedChannelImageInputStreamTest {
for (int i = 0; i < bytes.length / 8; i++) { for (int i = 0; i < bytes.length / 8; i++) {
assertEquals(buffer.getLong(), stream.readLong()); assertEquals(buffer.getLong(), stream.readLong());
} }
assertThrows(EOFException.class, stream::readLong);
assertThrows(EOFException.class, new ThrowingRunnable() {
@Override
public void run() throws Throwable {
stream.readLong();
}
});
stream.seek(0); stream.seek(0);
stream.setByteOrder(ByteOrder.LITTLE_ENDIAN); stream.setByteOrder(ByteOrder.LITTLE_ENDIAN);
@@ -341,12 +313,7 @@ public class BufferedChannelImageInputStreamTest {
assertEquals(buffer.getLong(), stream.readLong()); assertEquals(buffer.getLong(), stream.readLong());
} }
assertThrows(EOFException.class, new ThrowingRunnable() { assertThrows(EOFException.class, stream::readLong);
@Override
public void run() throws Throwable {
stream.readLong();
}
});
} }
} }
@@ -361,36 +328,11 @@ public class BufferedChannelImageInputStreamTest {
assertEquals(-1, stream.read()); assertEquals(-1, stream.read());
assertEquals(-1, stream.read(new byte[1], 0, 1)); assertEquals(-1, stream.read(new byte[1], 0, 1));
assertThrows(EOFException.class, new ThrowingRunnable() { assertThrows(EOFException.class, () -> stream.readFully(new byte[1]));
@Override assertThrows(EOFException.class, stream::readByte);
public void run() throws Throwable { assertThrows(EOFException.class, stream::readShort);
stream.readFully(new byte[1]); assertThrows(EOFException.class, stream::readInt);
} assertThrows(EOFException.class, stream::readLong);
});
assertThrows(EOFException.class, new ThrowingRunnable() {
@Override
public void run() throws Throwable {
stream.readByte();
}
});
assertThrows(EOFException.class, new ThrowingRunnable() {
@Override
public void run() throws Throwable {
stream.readShort();
}
});
assertThrows(EOFException.class, new ThrowingRunnable() {
@Override
public void run() throws Throwable {
stream.readInt();
}
});
assertThrows(EOFException.class, new ThrowingRunnable() {
@Override
public void run() throws Throwable {
stream.readLong();
}
});
stream.seek(0); stream.seek(0);
for (byte value : bytes) { for (byte value : bytes) {
@@ -1,13 +1,12 @@
package com.twelvemonkeys.imageio.stream; package com.twelvemonkeys.imageio.stream;
import org.junit.Test;
import javax.imageio.spi.ImageInputStreamSpi; import javax.imageio.spi.ImageInputStreamSpi;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertNull; import static org.junit.jupiter.api.Assertions.*;
import static org.junit.Assume.assumeFalse; import static org.junit.jupiter.api.Assumptions.*;
public class BufferedFileImageInputStreamSpiTest extends ImageInputStreamSpiTest<File> { public class BufferedFileImageInputStreamSpiTest extends ImageInputStreamSpiTest<File> {
@Override @Override
@@ -24,7 +23,7 @@ public class BufferedFileImageInputStreamSpiTest extends ImageInputStreamSpiTest
public void testReturnNullWhenFileDoesNotExist() throws IOException { public void testReturnNullWhenFileDoesNotExist() throws IOException {
// This is really stupid behavior, but it is consistent with the JRE bundled SPIs. // This is really stupid behavior, but it is consistent with the JRE bundled SPIs.
File input = new File("a-file-that-should-not-exist-ever.fnf"); File input = new File("a-file-that-should-not-exist-ever.fnf");
assumeFalse("File should not exist: " + input.getPath(), input.exists()); assumeFalse(input.exists(), "File should not exist: " + input.getPath());
assertNull(provider.createInputStreamInstance(input)); assertNull(provider.createInputStreamInstance(input));
} }
} }
@@ -30,9 +30,6 @@
package com.twelvemonkeys.imageio.stream; package com.twelvemonkeys.imageio.stream;
import org.junit.Test;
import org.junit.function.ThrowingRunnable;
import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageInputStream;
import java.io.EOFException; import java.io.EOFException;
import java.io.File; import java.io.File;
@@ -43,8 +40,10 @@ import java.nio.ByteOrder;
import java.nio.file.Files; import java.nio.file.Files;
import java.util.Random; import java.util.Random;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static com.twelvemonkeys.imageio.stream.BufferedImageInputStreamTest.rangeEquals; import static com.twelvemonkeys.imageio.stream.BufferedImageInputStreamTest.rangeEquals;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.only; import static org.mockito.Mockito.only;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
@@ -71,7 +70,7 @@ public class BufferedFileImageInputStreamTest {
@Test @Test
public void testCreate() throws IOException { public void testCreate() throws IOException {
try (BufferedFileImageInputStream stream = new BufferedFileImageInputStream(File.createTempFile("empty", ".tmp"))) { try (BufferedFileImageInputStream stream = new BufferedFileImageInputStream(File.createTempFile("empty", ".tmp"))) {
assertEquals("Data length should be same as stream length", 0, stream.length()); assertEquals(0, stream.length(), "Data length should be same as stream length");
} }
} }
@@ -85,8 +84,8 @@ public class BufferedFileImageInputStreamTest {
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
assertNotNull("Null exception message", expected.getMessage()); assertNotNull("Null exception message", expected.getMessage());
String message = expected.getMessage().toLowerCase(); String message = expected.getMessage().toLowerCase();
assertTrue("Exception message does not contain parameter name", message.contains("file")); assertTrue(message.contains("file"), "Exception message does not contain parameter name");
assertTrue("Exception message does not contain null", message.contains("null")); assertTrue(message.contains("null"), "Exception message does not contain null");
} }
} }
@@ -99,8 +98,8 @@ public class BufferedFileImageInputStreamTest {
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
assertNotNull("Null exception message", expected.getMessage()); assertNotNull("Null exception message", expected.getMessage());
String message = expected.getMessage().toLowerCase(); String message = expected.getMessage().toLowerCase();
assertTrue("Exception message does not contain parameter name", message.contains("raf")); assertTrue( message.contains("raf"), "Exception message does not contain parameter name");
assertTrue("Exception message does not contain null", message.contains("null")); assertTrue( message.contains("null"), "Exception message does not contain null");
} }
} }
@@ -110,10 +109,10 @@ public class BufferedFileImageInputStreamTest {
File file = randomDataToFile(data); File file = randomDataToFile(data);
try (BufferedFileImageInputStream stream = new BufferedFileImageInputStream(file)) { try (BufferedFileImageInputStream stream = new BufferedFileImageInputStream(file)) {
assertEquals("File length should be same as stream length", file.length(), stream.length()); assertEquals(file.length(), stream.length(), "File length should be same as stream length");
for (byte value : data) { for (byte value : data) {
assertEquals("Wrong data read", value & 0xff, stream.read()); assertEquals(value & 0xff, stream.read(), "Wrong data read");
} }
} }
} }
@@ -124,13 +123,13 @@ public class BufferedFileImageInputStreamTest {
File file = randomDataToFile(data); File file = randomDataToFile(data);
try (BufferedFileImageInputStream stream = new BufferedFileImageInputStream(file)) { try (BufferedFileImageInputStream stream = new BufferedFileImageInputStream(file)) {
assertEquals("File length should be same as stream length", file.length(), stream.length()); assertEquals(file.length(), stream.length(), "File length should be same as stream length");
byte[] result = new byte[1024]; byte[] result = new byte[1024];
for (int i = 0; i < data.length / result.length; i++) { for (int i = 0; i < data.length / result.length; i++) {
stream.readFully(result); stream.readFully(result);
assertTrue("Wrong data read: " + i, rangeEquals(data, i * result.length, result, 0, result.length)); assertTrue(rangeEquals(data, i * result.length, result, 0, result.length), "Wrong data read: " + i);
} }
} }
} }
@@ -141,14 +140,14 @@ public class BufferedFileImageInputStreamTest {
File file = randomDataToFile(data); File file = randomDataToFile(data);
try (BufferedFileImageInputStream stream = new BufferedFileImageInputStream(file)) { try (BufferedFileImageInputStream stream = new BufferedFileImageInputStream(file)) {
assertEquals("File length should be same as stream length", file.length(), stream.length()); assertEquals(file.length(), stream.length(), "File length should be same as stream length");
byte[] result = new byte[7]; byte[] result = new byte[7];
for (int i = 0; i < data.length / result.length; i += 2) { for (int i = 0; i < data.length / result.length; i += 2) {
stream.readFully(result); stream.readFully(result);
stream.skipBytes(result.length); stream.skipBytes(result.length);
assertTrue("Wrong data read: " + i, rangeEquals(data, i * result.length, result, 0, result.length)); assertTrue(rangeEquals(data, i * result.length, result, 0, result.length), "Wrong data read: " + i);
} }
} }
} }
@@ -159,7 +158,7 @@ public class BufferedFileImageInputStreamTest {
File file = randomDataToFile(data); File file = randomDataToFile(data);
try (BufferedFileImageInputStream stream = new BufferedFileImageInputStream(file)) { try (BufferedFileImageInputStream stream = new BufferedFileImageInputStream(file)) {
assertEquals("File length should be same as stream length", file.length(), stream.length()); assertEquals(file.length(), stream.length(), "File length should be same as stream length");
byte[] result = new byte[9]; byte[] result = new byte[9];
@@ -167,9 +166,9 @@ public class BufferedFileImageInputStreamTest {
// Read backwards // Read backwards
long newPos = stream.length() - result.length - i * result.length; long newPos = stream.length() - result.length - i * result.length;
stream.seek(newPos); stream.seek(newPos);
assertEquals("Wrong stream position", newPos, stream.getStreamPosition()); assertEquals(newPos, stream.getStreamPosition(), "Wrong stream position");
stream.readFully(result); stream.readFully(result);
assertTrue("Wrong data read: " + i, rangeEquals(data, (int) newPos, result, 0, result.length)); assertTrue(rangeEquals(data, (int) newPos, result, 0, result.length), "Wrong data read: " + i);
} }
} }
} }
@@ -180,7 +179,7 @@ public class BufferedFileImageInputStreamTest {
File file = randomDataToFile(data); File file = randomDataToFile(data);
try (BufferedFileImageInputStream stream = new BufferedFileImageInputStream(file)) { try (BufferedFileImageInputStream stream = new BufferedFileImageInputStream(file)) {
assertEquals("File length should be same as stream length", file.length(), stream.length()); assertEquals(file.length(), stream.length(), "File length should be same as stream length");
byte[] buffer = new byte[data.length * 2]; byte[] buffer = new byte[data.length * 2];
stream.read(buffer); stream.read(buffer);
@@ -199,7 +198,7 @@ public class BufferedFileImageInputStreamTest {
// Create stream // Create stream
try (ImageInputStream stream = new BufferedFileImageInputStream(file)) { try (ImageInputStream stream = new BufferedFileImageInputStream(file)) {
for (int i = 1; i <= 64; i++) { for (int i = 1; i <= 64; i++) {
assertEquals(String.format("bit %d differ", i), (value << (i - 1L)) >>> 63L, stream.readBit()); assertEquals((value << (i - 1L)) >>> 63L, stream.readBit(), String.format("bit %d differ", i));
} }
} }
} }
@@ -214,7 +213,7 @@ public class BufferedFileImageInputStreamTest {
try (ImageInputStream stream = new BufferedFileImageInputStream(file)) { try (ImageInputStream stream = new BufferedFileImageInputStream(file)) {
for (int i = 1; i <= 64; i++) { for (int i = 1; i <= 64; i++) {
stream.seek(0); stream.seek(0);
assertEquals(String.format("bit %d differ", i), value >>> (64L - i), stream.readBits(i)); assertEquals(value >>> (64L - i), stream.readBits(i), String.format("bit %d differ", i));
assertEquals(i % 8, stream.getBitOffset()); assertEquals(i % 8, stream.getBitOffset());
} }
} }
@@ -231,7 +230,7 @@ public class BufferedFileImageInputStreamTest {
for (int i = 1; i <= 60; i++) { for (int i = 1; i <= 60; i++) {
stream.seek(0); stream.seek(0);
stream.setBitOffset(i % 8); stream.setBitOffset(i % 8);
assertEquals(String.format("bit %d differ", i), (value << (i % 8)) >>> (64L - i), stream.readBits(i)); assertEquals((value << (i % 8)) >>> (64L - i), stream.readBits(i), String.format("bit %d differ", i));
assertEquals(i * 2 % 8, stream.getBitOffset()); assertEquals(i * 2 % 8, stream.getBitOffset());
} }
} }
@@ -250,12 +249,7 @@ public class BufferedFileImageInputStreamTest {
assertEquals(buffer.getShort(), stream.readShort()); assertEquals(buffer.getShort(), stream.readShort());
} }
assertThrows(EOFException.class, new ThrowingRunnable() { assertThrows(EOFException.class, stream::readShort);
@Override
public void run() throws Throwable {
stream.readShort();
}
});
stream.seek(0); stream.seek(0);
stream.setByteOrder(ByteOrder.LITTLE_ENDIAN); stream.setByteOrder(ByteOrder.LITTLE_ENDIAN);
@@ -266,12 +260,7 @@ public class BufferedFileImageInputStreamTest {
assertEquals(buffer.getShort(), stream.readShort()); assertEquals(buffer.getShort(), stream.readShort());
} }
assertThrows(EOFException.class, new ThrowingRunnable() { assertThrows(EOFException.class, stream::readShort);
@Override
public void run() throws Throwable {
stream.readShort();
}
});
} }
} }
@@ -288,12 +277,7 @@ public class BufferedFileImageInputStreamTest {
assertEquals(buffer.getInt(), stream.readInt()); assertEquals(buffer.getInt(), stream.readInt());
} }
assertThrows(EOFException.class, new ThrowingRunnable() { assertThrows(EOFException.class, stream::readInt);
@Override
public void run() throws Throwable {
stream.readInt();
}
});
stream.seek(0); stream.seek(0);
stream.setByteOrder(ByteOrder.LITTLE_ENDIAN); stream.setByteOrder(ByteOrder.LITTLE_ENDIAN);
@@ -304,12 +288,7 @@ public class BufferedFileImageInputStreamTest {
assertEquals(buffer.getInt(), stream.readInt()); assertEquals(buffer.getInt(), stream.readInt());
} }
assertThrows(EOFException.class, new ThrowingRunnable() { assertThrows(EOFException.class, stream::readInt);
@Override
public void run() throws Throwable {
stream.readInt();
}
});
} }
} }
@@ -326,12 +305,7 @@ public class BufferedFileImageInputStreamTest {
assertEquals(buffer.getLong(), stream.readLong()); assertEquals(buffer.getLong(), stream.readLong());
} }
assertThrows(EOFException.class, new ThrowingRunnable() { assertThrows(EOFException.class, stream::readLong);
@Override
public void run() throws Throwable {
stream.readLong();
}
});
stream.seek(0); stream.seek(0);
stream.setByteOrder(ByteOrder.LITTLE_ENDIAN); stream.setByteOrder(ByteOrder.LITTLE_ENDIAN);
@@ -341,13 +315,7 @@ public class BufferedFileImageInputStreamTest {
for (int i = 0; i < bytes.length / 8; i++) { for (int i = 0; i < bytes.length / 8; i++) {
assertEquals(buffer.getLong(), stream.readLong()); assertEquals(buffer.getLong(), stream.readLong());
} }
assertThrows(EOFException.class, stream::readLong);
assertThrows(EOFException.class, new ThrowingRunnable() {
@Override
public void run() throws Throwable {
stream.readLong();
}
});
} }
} }
@@ -362,36 +330,11 @@ public class BufferedFileImageInputStreamTest {
assertEquals(-1, stream.read()); assertEquals(-1, stream.read());
assertEquals(-1, stream.read(new byte[1], 0, 1)); assertEquals(-1, stream.read(new byte[1], 0, 1));
assertThrows(EOFException.class, new ThrowingRunnable() { assertThrows(EOFException.class, () -> stream.readFully(new byte[1]));
@Override assertThrows(EOFException.class, stream::readByte);
public void run() throws Throwable { assertThrows(EOFException.class, stream::readShort);
stream.readFully(new byte[1]); assertThrows(EOFException.class, stream::readInt);
} assertThrows(EOFException.class, stream::readLong);
});
assertThrows(EOFException.class, new ThrowingRunnable() {
@Override
public void run() throws Throwable {
stream.readByte();
}
});
assertThrows(EOFException.class, new ThrowingRunnable() {
@Override
public void run() throws Throwable {
stream.readShort();
}
});
assertThrows(EOFException.class, new ThrowingRunnable() {
@Override
public void run() throws Throwable {
stream.readInt();
}
});
assertThrows(EOFException.class, new ThrowingRunnable() {
@Override
public void run() throws Throwable {
stream.readLong();
}
});
stream.seek(0); stream.seek(0);
for (byte value : bytes) { for (byte value : bytes) {
@@ -33,7 +33,6 @@ package com.twelvemonkeys.imageio.stream;
import com.twelvemonkeys.io.ole2.CompoundDocument; import com.twelvemonkeys.io.ole2.CompoundDocument;
import com.twelvemonkeys.io.ole2.Entry; import com.twelvemonkeys.io.ole2.Entry;
import org.junit.Test;
import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.MemoryCacheImageInputStream; import javax.imageio.stream.MemoryCacheImageInputStream;
@@ -42,8 +41,10 @@ import java.nio.ByteBuffer;
import java.nio.ByteOrder; import java.nio.ByteOrder;
import java.util.Random; import java.util.Random;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static java.util.Arrays.fill; import static java.util.Arrays.fill;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
/** /**
@@ -71,8 +72,8 @@ public class BufferedImageInputStreamTest {
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
assertNotNull("Null exception message", expected.getMessage()); assertNotNull("Null exception message", expected.getMessage());
String message = expected.getMessage().toLowerCase(); String message = expected.getMessage().toLowerCase();
assertTrue("Exception message does not contain parameter name", message.contains("stream")); assertTrue(message.contains("stream"), "Exception message does not contain parameter name");
assertTrue("Exception message does not contain null", message.contains("null")); assertTrue(message.contains("null"), "Exception message does not contain null");
} }
} }
@@ -313,7 +314,7 @@ public class BufferedImageInputStreamTest {
for (int i = 1; i < 64; i++) { for (int i = 1; i < 64; i++) {
stream.seek(0); stream.seek(0);
assertEquals(i + " bits differ", value >>> (64L - i), stream.readBits(i)); assertEquals(value >>> (64L - i), stream.readBits(i), i + " bits differ");
} }
} }
@@ -340,8 +341,8 @@ public class BufferedImageInputStreamTest {
Entry catalog = root.getChildEntry("Catalog"); Entry catalog = root.getChildEntry("Catalog");
assertNotNull("Catalog should not be null", catalog); assertNotNull(catalog, "Catalog should not be null");
assertNotNull("Input stream can never be null", catalog.getInputStream()); assertNotNull(catalog.getInputStream(), "Input stream can never be null");
} }
@Test @Test
@@ -30,13 +30,14 @@
package com.twelvemonkeys.imageio.stream; package com.twelvemonkeys.imageio.stream;
import org.junit.Test;
import java.io.IOException; import java.io.IOException;
import java.util.Random; import java.util.Random;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static com.twelvemonkeys.imageio.stream.BufferedImageInputStreamTest.rangeEquals; import static com.twelvemonkeys.imageio.stream.BufferedImageInputStreamTest.rangeEquals;
import static org.junit.Assert.*;
/** /**
* ByteArrayImageInputStreamTest * ByteArrayImageInputStreamTest
@@ -51,7 +52,7 @@ public class ByteArrayImageInputStreamTest {
@Test @Test
public void testCreate() { public void testCreate() {
ByteArrayImageInputStream stream = new ByteArrayImageInputStream(new byte[0]); ByteArrayImageInputStream stream = new ByteArrayImageInputStream(new byte[0]);
assertEquals("Data length should be same as stream length", 0, stream.length()); assertEquals(0, stream.length(), "Data length should be same as stream length");
} }
@Test @Test
@@ -63,8 +64,8 @@ public class ByteArrayImageInputStreamTest {
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
assertNotNull("Null exception message", expected.getMessage()); assertNotNull("Null exception message", expected.getMessage());
String message = expected.getMessage().toLowerCase(); String message = expected.getMessage().toLowerCase();
assertTrue("Exception message does not contain parameter name", message.contains("data")); assertTrue(message.contains("data"), "Exception message does not contain parameter name");
assertTrue("Exception message does not contain null", message.contains("null")); assertTrue(message.contains("null"), "Exception message does not contain null");
} }
} }
@@ -77,8 +78,8 @@ public class ByteArrayImageInputStreamTest {
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
assertNotNull("Null exception message", expected.getMessage()); assertNotNull("Null exception message", expected.getMessage());
String message = expected.getMessage().toLowerCase(); String message = expected.getMessage().toLowerCase();
assertTrue("Exception message does not contain parameter name", message.contains("data")); assertTrue(message.contains("data"), "Exception message does not contain parameter name");
assertTrue("Exception message does not contain null", message.contains("null")); assertTrue(message.contains("null"), "Exception message does not contain null");
} }
} }
@@ -91,8 +92,8 @@ public class ByteArrayImageInputStreamTest {
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
assertNotNull("Null exception message", expected.getMessage()); assertNotNull("Null exception message", expected.getMessage());
String message = expected.getMessage().toLowerCase(); String message = expected.getMessage().toLowerCase();
assertTrue("Exception message does not contain parameter name", message.contains("offset")); assertTrue(message.contains("offset"), "Exception message does not contain parameter name");
assertTrue("Exception message does not contain -1", message.contains("-1")); assertTrue(message.contains("-1"), "Exception message does not contain -1");
} }
} }
@@ -105,8 +106,8 @@ public class ByteArrayImageInputStreamTest {
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
assertNotNull("Null exception message", expected.getMessage()); assertNotNull("Null exception message", expected.getMessage());
String message = expected.getMessage().toLowerCase(); String message = expected.getMessage().toLowerCase();
assertTrue("Exception message does not contain parameter name", message.contains("offset")); assertTrue(message.contains("offset"), "Exception message does not contain parameter name");
assertTrue("Exception message does not contain 2", message.contains("2")); assertTrue(message.contains("2"), "Exception message does not contain 2");
} }
} }
@@ -119,8 +120,8 @@ public class ByteArrayImageInputStreamTest {
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
assertNotNull("Null exception message", expected.getMessage()); assertNotNull("Null exception message", expected.getMessage());
String message = expected.getMessage().toLowerCase(); String message = expected.getMessage().toLowerCase();
assertTrue("Exception message does not contain parameter name", message.contains("length")); assertTrue(message.contains("length"), "Exception message does not contain parameter name");
assertTrue("Exception message does not contain -1", message.contains("-1")); assertTrue(message.contains("-1"), "Exception message does not contain -1");
} }
} }
@@ -133,8 +134,8 @@ public class ByteArrayImageInputStreamTest {
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
assertNotNull("Null exception message", expected.getMessage()); assertNotNull("Null exception message", expected.getMessage());
String message = expected.getMessage().toLowerCase(); String message = expected.getMessage().toLowerCase();
assertTrue("Exception message does not contain parameter name", message.contains("length")); assertTrue(message.contains("length"), "Exception message does not contain parameter name");
assertTrue("Exception message does not contain ™", message.contains("2")); assertTrue(message.contains("2"), "Exception message does not contain ™");
} }
} }
@@ -145,10 +146,10 @@ public class ByteArrayImageInputStreamTest {
ByteArrayImageInputStream stream = new ByteArrayImageInputStream(data); ByteArrayImageInputStream stream = new ByteArrayImageInputStream(data);
assertEquals("Data length should be same as stream length", data.length, stream.length()); assertEquals(data.length, stream.length(), "Data length should be same as stream length");
for (byte b : data) { for (byte b : data) {
assertEquals("Wrong data read", b & 0xff, stream.read()); assertEquals(b & 0xff, stream.read(), "Wrong data read");
} }
} }
@@ -161,10 +162,10 @@ public class ByteArrayImageInputStreamTest {
int length = random.nextInt(data.length - offset); int length = random.nextInt(data.length - offset);
ByteArrayImageInputStream stream = new ByteArrayImageInputStream(data, offset, length); ByteArrayImageInputStream stream = new ByteArrayImageInputStream(data, offset, length);
assertEquals("Data length should be same as stream length", length, stream.length()); assertEquals(length, stream.length(), "Data length should be same as stream length");
for (int i = offset; i < offset + length; i++) { for (int i = offset; i < offset + length; i++) {
assertEquals("Wrong data read", data[i] & 0xff, stream.read()); assertEquals(data[i] & 0xff, stream.read(), "Wrong data read");
} }
} }
@@ -175,13 +176,13 @@ public class ByteArrayImageInputStreamTest {
ByteArrayImageInputStream stream = new ByteArrayImageInputStream(data); ByteArrayImageInputStream stream = new ByteArrayImageInputStream(data);
assertEquals("Data length should be same as stream length", data.length, stream.length()); assertEquals(data.length, stream.length(), "Data length should be same as stream length");
byte[] result = new byte[1024]; byte[] result = new byte[1024];
for (int i = 0; i < data.length / result.length; i++) { for (int i = 0; i < data.length / result.length; i++) {
stream.readFully(result); stream.readFully(result);
assertTrue("Wrong data read: " + i, rangeEquals(data, i * result.length, result, 0, result.length)); assertTrue(rangeEquals(data, i * result.length, result, 0, result.length), "Wrong data read: " + i);
} }
} }
@@ -194,13 +195,13 @@ public class ByteArrayImageInputStreamTest {
int length = 10240; int length = 10240;
ByteArrayImageInputStream stream = new ByteArrayImageInputStream(data, offset, length); ByteArrayImageInputStream stream = new ByteArrayImageInputStream(data, offset, length);
assertEquals("Data length should be same as stream length", length, stream.length()); assertEquals(length, stream.length(), "Data length should be same as stream length");
byte[] result = new byte[1024]; byte[] result = new byte[1024];
for (int i = 0; i < length / result.length; i++) { for (int i = 0; i < length / result.length; i++) {
stream.readFully(result); stream.readFully(result);
assertTrue("Wrong data read: " + i, rangeEquals(data, offset + i * result.length, result, 0, result.length)); assertTrue(rangeEquals(data, offset + i * result.length, result, 0, result.length), "Wrong data read: " + i);
} }
} }
@@ -211,14 +212,14 @@ public class ByteArrayImageInputStreamTest {
ByteArrayImageInputStream stream = new ByteArrayImageInputStream(data); ByteArrayImageInputStream stream = new ByteArrayImageInputStream(data);
assertEquals("Data length should be same as stream length", data.length, stream.length()); assertEquals(data.length, stream.length(), "Data length should be same as stream length");
byte[] result = new byte[7]; byte[] result = new byte[7];
for (int i = 0; i < data.length / result.length; i += 2) { for (int i = 0; i < data.length / result.length; i += 2) {
stream.readFully(result); stream.readFully(result);
stream.skipBytes(result.length); stream.skipBytes(result.length);
assertTrue("Wrong data read: " + i, rangeEquals(data, i * result.length, result, 0, result.length)); assertTrue(rangeEquals(data, i * result.length, result, 0, result.length), "Wrong data read: " + i);
} }
} }
@@ -229,7 +230,7 @@ public class ByteArrayImageInputStreamTest {
ByteArrayImageInputStream stream = new ByteArrayImageInputStream(data); ByteArrayImageInputStream stream = new ByteArrayImageInputStream(data);
assertEquals("Data length should be same as stream length", data.length, stream.length()); assertEquals(data.length, stream.length(), "Data length should be same as stream length");
byte[] result = new byte[9]; byte[] result = new byte[9];
@@ -237,9 +238,9 @@ public class ByteArrayImageInputStreamTest {
// Read backwards // Read backwards
long newPos = stream.length() - result.length - i * result.length; long newPos = stream.length() - result.length - i * result.length;
stream.seek(newPos); stream.seek(newPos);
assertEquals("Wrong stream position", newPos, stream.getStreamPosition()); assertEquals(newPos, stream.getStreamPosition(), "Wrong stream position");
stream.readFully(result); stream.readFully(result);
assertTrue("Wrong data read: " + i, rangeEquals(data, (int) newPos, result, 0, result.length)); assertTrue(rangeEquals(data, (int) newPos, result, 0, result.length), "Wrong data read: " + i);
} }
} }
} }
@@ -30,10 +30,6 @@
package com.twelvemonkeys.imageio.stream; package com.twelvemonkeys.imageio.stream;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.function.ThrowingRunnable;
import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageInputStream;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.EOFException; import java.io.EOFException;
@@ -43,8 +39,12 @@ import java.nio.ByteBuffer;
import java.nio.ByteOrder; import java.nio.ByteOrder;
import java.util.Random; import java.util.Random;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static com.twelvemonkeys.imageio.stream.BufferedImageInputStreamTest.rangeEquals; import static com.twelvemonkeys.imageio.stream.BufferedImageInputStreamTest.rangeEquals;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
/** /**
@@ -66,7 +66,7 @@ public class DirectImageInputStreamTest {
@Test @Test
public void testCreate() throws IOException { public void testCreate() throws IOException {
try (DirectImageInputStream stream = new DirectImageInputStream(new ByteArrayInputStream(new byte[0]), 0)) { try (DirectImageInputStream stream = new DirectImageInputStream(new ByteArrayInputStream(new byte[0]), 0)) {
assertEquals("Data length should be same as stream length", 0, stream.length()); assertEquals(0, stream.length(), "Data length should be same as stream length");
} }
} }
@@ -78,8 +78,8 @@ public class DirectImageInputStreamTest {
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
assertNotNull("Null exception message", expected.getMessage()); assertNotNull("Null exception message", expected.getMessage());
String message = expected.getMessage().toLowerCase(); String message = expected.getMessage().toLowerCase();
assertTrue("Exception message does not contain parameter name", message.contains("stream")); assertTrue(message.contains("stream"), "Exception message does not contain parameter name");
assertTrue("Exception message does not contain null", message.contains("null")); assertTrue(message.contains("null"), "Exception message does not contain null");
} }
} }
@@ -90,7 +90,7 @@ public class DirectImageInputStreamTest {
try (DirectImageInputStream stream = new DirectImageInputStream(input)) { try (DirectImageInputStream stream = new DirectImageInputStream(input)) {
for (byte value : data) { for (byte value : data) {
assertEquals("Wrong data read", value & 0xff, stream.read()); assertEquals(value & 0xff, stream.read(), "Wrong data read");
} }
} }
} }
@@ -105,7 +105,7 @@ public class DirectImageInputStreamTest {
for (int i = 0; i < data.length / result.length; i++) { for (int i = 0; i < data.length / result.length; i++) {
stream.readFully(result); stream.readFully(result);
assertTrue("Wrong data read: " + i, rangeEquals(data, i * result.length, result, 0, result.length)); assertTrue(rangeEquals(data, i * result.length, result, 0, result.length), "Wrong data read: " + i);
} }
} }
} }
@@ -121,7 +121,7 @@ public class DirectImageInputStreamTest {
for (int i = 0; i < data.length / result.length; i += 2) { for (int i = 0; i < data.length / result.length; i += 2) {
stream.readFully(result); stream.readFully(result);
stream.skipBytes(result.length); stream.skipBytes(result.length);
assertTrue("Wrong data read: " + i, rangeEquals(data, i * result.length, result, 0, result.length)); assertTrue(rangeEquals(data, i * result.length, result, 0, result.length), "Wrong data read: " + i);
} }
} }
} }
@@ -137,15 +137,15 @@ public class DirectImageInputStreamTest {
for (int i = 0; i < data.length / (2 * result.length); i++) { for (int i = 0; i < data.length / (2 * result.length); i++) {
long newPos = i * 2 * result.length; long newPos = i * 2 * result.length;
stream.seek(newPos); stream.seek(newPos);
assertEquals("Wrong stream position", newPos, stream.getStreamPosition()); assertEquals(newPos, stream.getStreamPosition(), "Wrong stream position");
stream.readFully(result); stream.readFully(result);
assertTrue("Wrong data read: " + i, rangeEquals(data, (int) newPos, result, 0, result.length)); assertTrue(rangeEquals(data, (int) newPos, result, 0, result.length), "Wrong data read: " + i);
} }
} }
} }
@SuppressWarnings("ConstantConditions") @SuppressWarnings("ConstantConditions")
@Ignore("Bit reading requires backwards seek or buffer...") @Disabled("Bit reading requires backwards seek or buffer...")
@Test @Test
public void testReadBitRandom() throws IOException { public void testReadBitRandom() throws IOException {
byte[] bytes = new byte[8]; byte[] bytes = new byte[8];
@@ -155,13 +155,13 @@ public class DirectImageInputStreamTest {
// Create stream // Create stream
try (DirectImageInputStream stream = new DirectImageInputStream(input)) { try (DirectImageInputStream stream = new DirectImageInputStream(input)) {
for (int i = 1; i <= 64; i++) { for (int i = 1; i <= 64; i++) {
assertEquals(String.format("bit %d differ", i), (value << (i - 1L)) >>> 63L, stream.readBit()); assertEquals((value << (i - 1L)) >>> 63L, stream.readBit(), String.format("bit %d differ", i));
} }
} }
} }
@SuppressWarnings("ConstantConditions") @SuppressWarnings("ConstantConditions")
@Ignore("Bit reading requires backwards seek or buffer...") @Disabled("Bit reading requires backwards seek or buffer...")
@Test @Test
public void testReadBitsRandom() throws IOException { public void testReadBitsRandom() throws IOException {
byte[] bytes = new byte[8]; byte[] bytes = new byte[8];
@@ -172,14 +172,14 @@ public class DirectImageInputStreamTest {
try (DirectImageInputStream stream = new DirectImageInputStream(input)) { try (DirectImageInputStream stream = new DirectImageInputStream(input)) {
for (int i = 1; i <= 64; i++) { for (int i = 1; i <= 64; i++) {
stream.seek(0); stream.seek(0);
assertEquals(String.format("bit %d differ", i), value >>> (64L - i), stream.readBits(i)); assertEquals(value >>> (64L - i), stream.readBits(i), String.format("bit %d differ", i));
assertEquals(i % 8, stream.getBitOffset()); assertEquals(i % 8, stream.getBitOffset());
} }
} }
} }
@SuppressWarnings("ConstantConditions") @SuppressWarnings("ConstantConditions")
@Ignore("Bit reading requires backwards seek or buffer...") @Disabled("Bit reading requires backwards seek or buffer...")
@Test @Test
public void testReadBitsRandomOffset() throws IOException { public void testReadBitsRandomOffset() throws IOException {
byte[] bytes = new byte[8]; byte[] bytes = new byte[8];
@@ -191,7 +191,7 @@ public class DirectImageInputStreamTest {
for (int i = 1; i <= 60; i++) { for (int i = 1; i <= 60; i++) {
stream.seek(0); stream.seek(0);
stream.setBitOffset(i % 8); stream.setBitOffset(i % 8);
assertEquals(String.format("bit %d differ", i), (value << (i % 8)) >>> (64L - i), stream.readBits(i)); assertEquals((value << (i % 8)) >>> (64L - i), stream.readBits(i), String.format("bit %d differ", i));
assertEquals(i * 2L % 8, stream.getBitOffset()); assertEquals(i * 2L % 8, stream.getBitOffset());
} }
} }
@@ -211,12 +211,7 @@ public class DirectImageInputStreamTest {
assertEquals(buffer.getShort(), stream.readShort()); assertEquals(buffer.getShort(), stream.readShort());
} }
assertThrows(EOFException.class, new ThrowingRunnable() { assertThrows(EOFException.class, stream::readShort);
@Override
public void run() throws Throwable {
stream.readShort();
}
});
} }
try (DirectImageInputStream stream = new DirectImageInputStream(new ByteArrayInputStream(bytes))) { try (DirectImageInputStream stream = new DirectImageInputStream(new ByteArrayInputStream(bytes))) {
@@ -228,12 +223,7 @@ public class DirectImageInputStreamTest {
assertEquals(buffer.getShort(), stream.readShort()); assertEquals(buffer.getShort(), stream.readShort());
} }
assertThrows(EOFException.class, new ThrowingRunnable() { assertThrows(EOFException.class, stream::readShort);
@Override
public void run() throws Throwable {
stream.readShort();
}
});
} }
} }
@@ -250,13 +240,7 @@ public class DirectImageInputStreamTest {
for (int i = 0; i < bytes.length / 4; i++) { for (int i = 0; i < bytes.length / 4; i++) {
assertEquals(buffer.getInt(), stream.readInt()); assertEquals(buffer.getInt(), stream.readInt());
} }
assertThrows(EOFException.class, stream::readInt);
assertThrows(EOFException.class, new ThrowingRunnable() {
@Override
public void run() throws Throwable {
stream.readInt();
}
});
} }
try (DirectImageInputStream stream = new DirectImageInputStream(new ByteArrayInputStream(bytes))) { try (DirectImageInputStream stream = new DirectImageInputStream(new ByteArrayInputStream(bytes))) {
@@ -268,12 +252,7 @@ public class DirectImageInputStreamTest {
assertEquals(buffer.getInt(), stream.readInt()); assertEquals(buffer.getInt(), stream.readInt());
} }
assertThrows(EOFException.class, new ThrowingRunnable() { assertThrows(EOFException.class, stream::readInt);
@Override
public void run() throws Throwable {
stream.readInt();
}
});
} }
} }
@@ -289,13 +268,7 @@ public class DirectImageInputStreamTest {
for (int i = 0; i < bytes.length / 8; i++) { for (int i = 0; i < bytes.length / 8; i++) {
assertEquals(buffer.getLong(), stream.readLong()); assertEquals(buffer.getLong(), stream.readLong());
} }
assertThrows(EOFException.class, stream::readLong);
assertThrows(EOFException.class, new ThrowingRunnable() {
@Override
public void run() throws Throwable {
stream.readLong();
}
});
} }
try (DirectImageInputStream stream = new DirectImageInputStream(new ByteArrayInputStream(bytes))) { try (DirectImageInputStream stream = new DirectImageInputStream(new ByteArrayInputStream(bytes))) {
@@ -306,13 +279,7 @@ public class DirectImageInputStreamTest {
for (int i = 0; i < bytes.length / 8; i++) { for (int i = 0; i < bytes.length / 8; i++) {
assertEquals(buffer.getLong(), stream.readLong()); assertEquals(buffer.getLong(), stream.readLong());
} }
assertThrows(EOFException.class, stream::readLong);
assertThrows(EOFException.class, new ThrowingRunnable() {
@Override
public void run() throws Throwable {
stream.readLong();
}
});
} }
} }
@@ -327,36 +294,11 @@ public class DirectImageInputStreamTest {
assertEquals(-1, stream.read()); assertEquals(-1, stream.read());
assertEquals(-1, stream.read(new byte[1], 0, 1)); assertEquals(-1, stream.read(new byte[1], 0, 1));
assertThrows(EOFException.class, new ThrowingRunnable() { assertThrows(EOFException.class, () -> stream.readFully(new byte[1]));
@Override assertThrows(EOFException.class, stream::readByte);
public void run() throws Throwable { assertThrows(EOFException.class, stream::readShort);
stream.readFully(new byte[1]); assertThrows(EOFException.class, stream::readInt);
} assertThrows(EOFException.class, stream::readLong);
});
assertThrows(EOFException.class, new ThrowingRunnable() {
@Override
public void run() throws Throwable {
stream.readByte();
}
});
assertThrows(EOFException.class, new ThrowingRunnable() {
@Override
public void run() throws Throwable {
stream.readShort();
}
});
assertThrows(EOFException.class, new ThrowingRunnable() {
@Override
public void run() throws Throwable {
stream.readInt();
}
});
assertThrows(EOFException.class, new ThrowingRunnable() {
@Override
public void run() throws Throwable {
stream.readLong();
}
});
} }
try (DirectImageInputStream stream = new DirectImageInputStream(new ByteArrayInputStream(bytes))) { try (DirectImageInputStream stream = new DirectImageInputStream(new ByteArrayInputStream(bytes))) {
@@ -1,14 +1,14 @@
package com.twelvemonkeys.imageio.stream; package com.twelvemonkeys.imageio.stream;
import org.junit.Test;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import javax.imageio.spi.ImageInputStreamSpi; import javax.imageio.spi.ImageInputStreamSpi;
import java.io.EOFException;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.ParameterizedType; import java.lang.reflect.ParameterizedType;
import java.util.Locale; import java.util.Locale;
import static org.junit.Assert.*; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
abstract class ImageInputStreamSpiTest<T> { abstract class ImageInputStreamSpiTest<T> {
protected final ImageInputStreamSpi provider = createProvider(); protected final ImageInputStreamSpi provider = createProvider();
@@ -42,14 +42,14 @@ abstract class ImageInputStreamSpiTest<T> {
assertNotNull(provider.getDescription(Locale.ENGLISH)); assertNotNull(provider.getDescription(Locale.ENGLISH));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void createNull() throws IOException { public void createNull() throws IOException {
provider.createInputStreamInstance(null); assertThrows(IllegalArgumentException.class, () -> provider.createInputStreamInstance(null));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void createNullCached() throws IOException { public void createNullCached() throws IOException {
provider.createInputStreamInstance(null, true, ImageIO.getCacheDirectory()); assertThrows(IllegalArgumentException.class, () -> provider.createInputStreamInstance(null, true, ImageIO.getCacheDirectory()));
} }
@Test @Test
@@ -2,10 +2,9 @@ package com.twelvemonkeys.imageio.stream;
import com.twelvemonkeys.imageio.spi.ProviderInfo; import com.twelvemonkeys.imageio.spi.ProviderInfo;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class StreamProviderInfoTest { public class StreamProviderInfoTest {
private final ProviderInfo providerInfo = new StreamProviderInfo(); private final ProviderInfo providerInfo = new StreamProviderInfo();
@@ -30,8 +30,6 @@
package com.twelvemonkeys.imageio.stream; package com.twelvemonkeys.imageio.stream;
import org.junit.Test;
import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageInputStreamImpl; import javax.imageio.stream.ImageInputStreamImpl;
import javax.imageio.stream.MemoryCacheImageInputStream; import javax.imageio.stream.MemoryCacheImageInputStream;
@@ -40,7 +38,8 @@ import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
import java.util.Random; import java.util.Random;
import static org.junit.Assert.*; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* SubImageInputStreamTestCase * SubImageInputStreamTestCase
@@ -66,16 +65,18 @@ public class SubImageInputStreamTest {
}; };
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateNullStream() throws IOException { public void testCreateNullStream() throws IOException {
assertThrows(IllegalArgumentException.class, () -> {
new SubImageInputStream(null, 1); new SubImageInputStream(null, 1);
fail("Expected IllegalArgumentException with null stream"); }, "Expected IllegalArgumentException with null stream");
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateNegativeLength() throws IOException { public void testCreateNegativeLength() throws IOException {
assertThrows(IllegalArgumentException.class, () -> {
new SubImageInputStream(createStream(0), -1); new SubImageInputStream(createStream(0), -1);
fail("Expected IllegalArgumentException with negative length"); }, "Expected IllegalArgumentException with negative length");
} }
@Test @Test
@@ -31,15 +31,15 @@
package com.twelvemonkeys.imageio.util; package com.twelvemonkeys.imageio.util;
import com.twelvemonkeys.io.InputStreamAbstractTest; import com.twelvemonkeys.io.InputStreamAbstractTest;
import org.junit.Test;
import javax.imageio.ImageIO;
import javax.imageio.stream.MemoryCacheImageInputStream; import javax.imageio.stream.MemoryCacheImageInputStream;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import static org.junit.Assert.assertEquals; import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.*;
/** /**
* IIOInputStreamAdapter * IIOInputStreamAdapter
@@ -54,9 +54,9 @@ public class IIOInputStreamAdapterTest extends InputStreamAbstractTest {
return new IIOInputStreamAdapter(new MemoryCacheImageInputStream(new ByteArrayInputStream(pBytes)), pBytes.length); return new IIOInputStreamAdapter(new MemoryCacheImageInputStream(new ByteArrayInputStream(pBytes)), pBytes.length);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateNull() { public void testCreateNull() {
new IIOInputStreamAdapter(null); assertThrows(IllegalArgumentException.class, () -> new IIOInputStreamAdapter(null));
} }
@Test @Test
@@ -70,11 +70,11 @@ public class IIOInputStreamAdapterTest extends InputStreamAbstractTest {
IIOInputStreamAdapter stream = new IIOInputStreamAdapter(input); IIOInputStreamAdapter stream = new IIOInputStreamAdapter(input);
for (int i = 0; i < 10; i++) { for (int i = 0; i < 10; i++) {
assertTrue("Unexpected end of stream", -1 != stream.read()); assertTrue(-1 != stream.read(), "Unexpected end of stream");
} }
assertEquals("Read value after end of stream", -1, stream.read()); assertEquals(-1, stream.read(), "Read value after end of stream");
assertEquals("Read value after end of stream", -1, stream.read()); assertEquals(-1, stream.read(), "Read value after end of stream");
// Make sure underlying stream is positioned at end of substream after close // Make sure underlying stream is positioned at end of substream after close
stream.close(); stream.close();
@@ -90,11 +90,11 @@ public class IIOInputStreamAdapterTest extends InputStreamAbstractTest {
MemoryCacheImageInputStream input = new MemoryCacheImageInputStream(new ByteArrayInputStream(bytes)); MemoryCacheImageInputStream input = new MemoryCacheImageInputStream(new ByteArrayInputStream(bytes));
IIOInputStreamAdapter stream = new IIOInputStreamAdapter(input, 9); IIOInputStreamAdapter stream = new IIOInputStreamAdapter(input, 9);
for (int i = 0; i < 9; i++) { for (int i = 0; i < 9; i++) {
assertTrue("Unexpected end of stream", -1 != stream.read()); assertTrue(-1 != stream.read(), "Unexpected end of stream");
} }
assertEquals("Read value after end of stream", -1, stream.read()); assertEquals(-1, stream.read(), "Read value after end of stream");
assertEquals("Read value after end of stream", -1, stream.read()); assertEquals(-1, stream.read(), "Read value after end of stream");
// Make sure we don't read outside stream boundaries // Make sure we don't read outside stream boundaries
assertTrue(input.getStreamPosition() <= 9); assertTrue(input.getStreamPosition() <= 9);
@@ -109,7 +109,7 @@ public class IIOInputStreamAdapterTest extends InputStreamAbstractTest {
MemoryCacheImageInputStream input = new MemoryCacheImageInputStream(new ByteArrayInputStream(bytes)); MemoryCacheImageInputStream input = new MemoryCacheImageInputStream(new ByteArrayInputStream(bytes));
IIOInputStreamAdapter stream = new IIOInputStreamAdapter(input, 10); IIOInputStreamAdapter stream = new IIOInputStreamAdapter(input, 10);
for (int i = 0; i < 7; i++) { for (int i = 0; i < 7; i++) {
assertTrue("Unexpected end of stream", -1 != stream.read()); assertTrue(-1 != stream.read(), "Unexpected end of stream");
} }
// Make sure we don't read outside stream boundaries // Make sure we don't read outside stream boundaries
@@ -132,7 +132,7 @@ public class IIOInputStreamAdapterTest extends InputStreamAbstractTest {
assertEquals(10, input.getStreamPosition()); assertEquals(10, input.getStreamPosition());
IIOInputStreamAdapter stream = new IIOInputStreamAdapter(input); IIOInputStreamAdapter stream = new IIOInputStreamAdapter(input);
assertEquals("Should not skip backwards", 0, stream.skip(-5)); assertEquals(0, stream.skip(-5), "Should not skip backwards");
assertEquals(10, input.getStreamPosition()); assertEquals(10, input.getStreamPosition());
} }
@@ -146,7 +146,7 @@ public class IIOInputStreamAdapterTest extends InputStreamAbstractTest {
assertEquals(10, input.getStreamPosition()); assertEquals(10, input.getStreamPosition());
IIOInputStreamAdapter stream = new IIOInputStreamAdapter(input, 9); IIOInputStreamAdapter stream = new IIOInputStreamAdapter(input, 9);
assertEquals("Should not skip backwards", 0, stream.skip(-5)); assertEquals(0, stream.skip(-5), "Should not skip backwards");
assertEquals(10, input.getStreamPosition()); assertEquals(10, input.getStreamPosition());
} }
@@ -31,14 +31,14 @@
package com.twelvemonkeys.imageio.util; package com.twelvemonkeys.imageio.util;
import com.twelvemonkeys.io.OutputStreamAbstractTest; import com.twelvemonkeys.io.OutputStreamAbstractTest;
import org.junit.Test;
import javax.imageio.stream.MemoryCacheImageOutputStream; import javax.imageio.stream.MemoryCacheImageOutputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import static org.junit.Assert.assertEquals; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* IIOOutputStreamAdapterTestCase * IIOOutputStreamAdapterTestCase
@@ -53,9 +53,9 @@ public class IIOOutputStreamAdapterTest extends OutputStreamAbstractTest {
return new IIOOutputStreamAdapter(new MemoryCacheImageOutputStream(new ByteArrayOutputStream())); return new IIOOutputStreamAdapter(new MemoryCacheImageOutputStream(new ByteArrayOutputStream()));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateNull() { public void testCreateNull() {
new IIOOutputStreamAdapter(null); assertThrows(IllegalArgumentException.class, () -> new IIOOutputStreamAdapter(null));
} }
@Test @Test
@@ -1,8 +1,7 @@
package com.twelvemonkeys.imageio.util; package com.twelvemonkeys.imageio.util;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.Assert.assertArrayEquals;
/** /**
* IIOUtilTest * IIOUtilTest
@@ -33,8 +33,7 @@ package com.twelvemonkeys.imageio.util;
import com.twelvemonkeys.imageio.stream.URLImageInputStreamSpi; import com.twelvemonkeys.imageio.stream.URLImageInputStreamSpi;
import com.twelvemonkeys.lang.Validate; import com.twelvemonkeys.lang.Validate;
import org.junit.Ignore; import org.junit.jupiter.api.Disabled;
import org.junit.Test;
import org.mockito.InOrder; import org.mockito.InOrder;
import org.mockito.invocation.InvocationOnMock; import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer; import org.mockito.stubbing.Answer;
@@ -63,7 +62,8 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import static java.lang.Math.min; import static java.lang.Math.min;
import static org.junit.Assert.*; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
/** /**
@@ -129,7 +129,7 @@ public abstract class ImageReaderAbstractTest<T extends ImageReader> {
} }
} }
assertTrue(String.format("%s not provided by %s for '%s'", pReaderClass.getSimpleName(), provider.getClass().getSimpleName(), pFormat), found); assertTrue(found, String.format("%s not provided by %s for '%s'", pReaderClass.getSimpleName(), provider.getClass().getSimpleName(), pFormat));
} }
private boolean isOurProvider(final ImageReaderSpi spi) { private boolean isOurProvider(final ImageReaderSpi spi) {
@@ -164,7 +164,7 @@ public abstract class ImageReaderAbstractTest<T extends ImageReader> {
for (TestData data : testData) { for (TestData data : testData) {
ImageInputStream stream = data.getInputStream(); ImageInputStream stream = data.getInputStream();
assertNotNull(stream); assertNotNull(stream);
assertTrue("Provider is expected to be able to decode data: " + data, provider.canDecodeInput(stream)); assertTrue(provider.canDecodeInput(stream), "Provider is expected to be able to decode data: " + data);
} }
} }
@@ -184,7 +184,7 @@ public abstract class ImageReaderAbstractTest<T extends ImageReader> {
failBecause("Could not test data for read", e); failBecause("Could not test data for read", e);
} }
assertFalse("ImageReader can read null input", canRead); assertFalse(canRead, "ImageReader can read null input");
} }
@Test @Test
@@ -227,16 +227,16 @@ public abstract class ImageReaderAbstractTest<T extends ImageReader> {
failBecause(String.format("Image %s index %s could not be read: %s", data.getInput(), i, e), e); failBecause(String.format("Image %s index %s could not be read: %s", data.getInput(), i, e), e);
} }
assertNotNull(String.format("Image %s index %s was null!", data.getInput(), i), image); assertNotNull(image, String.format("Image %s index %s was null!", data.getInput(), i));
assertEquals( assertEquals(
String.format("Image %s index %s has wrong width: %s", data.getInput(), i, image.getWidth()),
data.getDimension(i).width, data.getDimension(i).width,
image.getWidth() image.getWidth(),
String.format("Image %s index %s has wrong width: %s", data.getInput(), i, image.getWidth())
); );
assertEquals( assertEquals(
String.format("Image %s index %s has wrong height: %s", data.getInput(), i, image.getHeight()), data.getDimension(i).height, image.getHeight(),
data.getDimension(i).height, image.getHeight() String.format("Image %s index %s has wrong height: %s", data.getInput(), i, image.getHeight())
); );
} }
} }
@@ -306,67 +306,55 @@ public abstract class ImageReaderAbstractTest<T extends ImageReader> {
reader.dispose(); reader.dispose();
} }
@Test(expected = IllegalStateException.class) @Test
public void testReadNoInput() throws IOException { public void testReadNoInput() throws IOException {
ImageReader reader = createReader(); ImageReader reader = createReader();
// Do not set input // Do not set input
try { assertThrows(IllegalStateException.class, () -> {
reader.read(0); reader.read(0);
fail("Read image with no input"); });
}
catch (IOException e) {
failBecause("Image could not be read", e);
}
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
public void testReadIndexNegativeWithParam() throws IOException { public void testReadIndexNegativeWithParam() throws IOException {
ImageReader reader = createReader(); ImageReader reader = createReader();
TestData data = getTestData().get(0); TestData data = getTestData().get(0);
reader.setInput(data.getInputStream()); reader.setInput(data.getInputStream());
try { try {
assertThrows(IndexOutOfBoundsException.class, () -> {
reader.read(-1, reader.getDefaultReadParam()); reader.read(-1, reader.getDefaultReadParam());
fail("Read image with illegal index"); });
}
catch (IOException e) {
failBecause("Image could not be read", e);
} }
finally { finally {
reader.dispose(); reader.dispose();
} }
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
public void testReadIndexOutOfBoundsWithParam() throws IOException { public void testReadIndexOutOfBoundsWithParam() throws IOException {
ImageReader reader = createReader(); ImageReader reader = createReader();
TestData data = getTestData().get(0); TestData data = getTestData().get(0);
reader.setInput(data.getInputStream()); reader.setInput(data.getInputStream());
try { try {
assertThrows(IndexOutOfBoundsException.class, () -> {
reader.read(Short.MAX_VALUE, reader.getDefaultReadParam()); reader.read(Short.MAX_VALUE, reader.getDefaultReadParam());
fail("Read image with index out of bounds"); });
}
catch (IOException e) {
failBecause("Image could not be read", e);
} }
finally { finally {
reader.dispose(); reader.dispose();
} }
} }
@Test(expected = IllegalStateException.class) @Test
public void testReadNoInputWithParam() throws IOException { public void testReadNoInputWithParam() throws IOException {
ImageReader reader = createReader(); ImageReader reader = createReader();
// Do not set input // Do not set input
try { try {
reader.read(0, reader.getDefaultReadParam()); assertThrows(IllegalStateException.class, () -> {
fail("Read image with no input"); reader.read(0);
} });
catch (IOException e) {
failBecause("Image could not be read", e);
} }
finally { finally {
reader.dispose(); reader.dispose();
@@ -387,9 +375,9 @@ public abstract class ImageReaderAbstractTest<T extends ImageReader> {
failBecause("Image could not be read", e); failBecause("Image could not be read", e);
} }
assertNotNull("Image was null!", image); assertNotNull(image, "Image was null!");
assertEquals("Read image has wrong width: " + image.getWidth(), data.getDimension(0).width, image.getWidth()); assertEquals(data.getDimension(0).width, image.getWidth(), "Read image has wrong width: " + image.getWidth());
assertEquals("Read image has wrong height: " + image.getHeight(), data.getDimension(0).height, image.getHeight()); assertEquals(data.getDimension(0).height, image.getHeight(), "Read image has wrong height: " + image.getHeight());
reader.dispose(); reader.dispose();
} }
@@ -408,9 +396,9 @@ public abstract class ImageReaderAbstractTest<T extends ImageReader> {
failBecause("Image could not be read", e); failBecause("Image could not be read", e);
} }
assertNotNull("Image was null!", image); assertNotNull(image, "Image was null!");
assertEquals("Read image has wrong width: " + image.getWidth(), data.getDimension(0).width, image.getWidth()); assertEquals(data.getDimension(0).width, image.getWidth(), "Read image has wrong width: " + image.getWidth());
assertEquals("Read image has wrong height: " + image.getHeight(), data.getDimension(0).height, image.getHeight()); assertEquals(data.getDimension(0).height, image.getHeight(), "Read image has wrong height: " + image.getHeight());
reader.dispose(); reader.dispose();
} }
@@ -429,9 +417,9 @@ public abstract class ImageReaderAbstractTest<T extends ImageReader> {
failBecause("Image could not be read", e); failBecause("Image could not be read", e);
} }
assertNotNull("Image was null!", image); assertNotNull(image, "Image was null!");
assertEquals("Read image has wrong width: " + image.getWidth(), data.getDimension(0).width, image.getWidth()); assertEquals(data.getDimension(0).width, image.getWidth(), "Read image has wrong width: " + image.getWidth());
assertEquals("Read image has wrong height: " + image.getHeight(), data.getDimension(0).height, image.getHeight()); assertEquals(data.getDimension(0).height, image.getHeight(), "Read image has wrong height: " + image.getHeight());
reader.dispose(); reader.dispose();
} }
@@ -454,9 +442,9 @@ public abstract class ImageReaderAbstractTest<T extends ImageReader> {
failBecause("Image could not be read", e); failBecause("Image could not be read", e);
} }
assertNotNull("Image was null!", image); assertNotNull(image, "Image was null!");
assertEquals("Read image has wrong width: " + image.getWidth(), 10, image.getWidth()); assertEquals(10, image.getWidth(), "Read image has wrong width: " + image.getWidth());
assertEquals("Read image has wrong height: " + image.getHeight(), 10, image.getHeight()); assertEquals(10, image.getHeight(), "Read image has wrong height: " + image.getHeight());
} }
reader.dispose(); reader.dispose();
@@ -479,9 +467,9 @@ public abstract class ImageReaderAbstractTest<T extends ImageReader> {
failBecause("Image could not be read", e); failBecause("Image could not be read", e);
} }
assertNotNull("Image was null!", image); assertNotNull(image, "Image was null!");
assertEquals("Read image has wrong width: ", (data.getDimension(0).width + 4) / 5, image.getWidth()); assertEquals((data.getDimension(0).width + 4) / 5, image.getWidth(), "Read image has wrong width: ");
assertEquals("Read image has wrong height: ", (data.getDimension(0).height + 4) / 5, image.getHeight()); assertEquals((data.getDimension(0).height + 4) / 5, image.getHeight(), "Read image has wrong height: ");
reader.dispose(); reader.dispose();
} }
@@ -516,8 +504,8 @@ public abstract class ImageReaderAbstractTest<T extends ImageReader> {
@SuppressWarnings("SameParameterValue") @SuppressWarnings("SameParameterValue")
protected final void assertSubsampledImageDataEquals(String message, BufferedImage expected, BufferedImage actual, ImageReadParam param) throws IOException { protected final void assertSubsampledImageDataEquals(String message, BufferedImage expected, BufferedImage actual, ImageReadParam param) throws IOException {
assertNotNull("Expected image was null", expected); assertNotNull(expected, "Expected image was null");
assertNotNull("Actual image was null!", actual); assertNotNull(actual, "Actual image was null!");
if (expected == actual) { if (expected == actual) {
return; return;
@@ -528,9 +516,9 @@ public abstract class ImageReaderAbstractTest<T extends ImageReader> {
int xSub = param.getSourceXSubsampling(); int xSub = param.getSourceXSubsampling();
int ySub = param.getSourceYSubsampling(); int ySub = param.getSourceYSubsampling();
assertEquals("Subsampled image has wrong width: ", (expected.getWidth() - xOff + xSub - 1) / xSub, actual.getWidth()); assertEquals((expected.getWidth() - xOff + xSub - 1) / xSub, actual.getWidth(), "Subsampled image has wrong width: ");
assertEquals("Subsampled image has wrong height: ", (expected.getHeight() - yOff + ySub - 1) / ySub, actual.getHeight()); assertEquals((expected.getHeight() - yOff + ySub - 1) / ySub, actual.getHeight(), "Subsampled image has wrong height: ");
assertEquals("Subsampled has different type", expected.getType(), actual.getType()); assertEquals(expected.getType(), actual.getType(), "Subsampled has different type");
for (int y = 0; y < actual.getHeight(); y++) { for (int y = 0; y < actual.getHeight(); y++) {
for (int x = 0; x < actual.getWidth(); x++) { for (int x = 0; x < actual.getWidth(); x++) {
@@ -551,15 +539,15 @@ public abstract class ImageReaderAbstractTest<T extends ImageReader> {
System.err.println("tempActual.getAbsolutePath(): " + tempActual.getAbsolutePath()); System.err.println("tempActual.getAbsolutePath(): " + tempActual.getAbsolutePath());
ImageIO.write(actual, "PNG", tempActual); ImageIO.write(actual, "PNG", tempActual);
assertEquals(String.format("%s ARGB at (%d, %d)", message, x, y), String.format("#%08x", expectedRGB), String.format("#%08x", actualRGB)); assertEquals(String.format("#%08x", expectedRGB), String.format("#%08x", actualRGB), String.format("%s ARGB at (%d, %d)", message, x, y));
} }
} }
} }
} }
public static void assertImageDataEquals(String message, BufferedImage expected, BufferedImage actual) { public static void assertImageDataEquals(String message, BufferedImage expected, BufferedImage actual) {
assertNotNull("Expected image was null", expected); assertNotNull(expected, "Expected image was null");
assertNotNull("Actual image was null!", actual); assertNotNull(actual, "Actual image was null!");
if (expected == actual) { if (expected == actual) {
return; return;
@@ -570,10 +558,10 @@ public abstract class ImageReaderAbstractTest<T extends ImageReader> {
int expectedRGB = expected.getRGB(x, y); int expectedRGB = expected.getRGB(x, y);
int actualRGB = actual.getRGB(x, y); int actualRGB = actual.getRGB(x, y);
assertEquals(String.format("%s alpha at (%d, %d)", message, x, y), (expectedRGB >> 24) & 0xff, (actualRGB >> 24) & 0xff, 5); assertEquals((expectedRGB >> 24) & 0xff, (actualRGB >> 24) & 0xff, 5, String.format("%s alpha at (%d, %d)", message, x, y));
assertEquals(String.format("%s red at (%d, %d)", message, x, y), (expectedRGB >> 16) & 0xff, (actualRGB >> 16) & 0xff, 5); assertEquals((expectedRGB >> 16) & 0xff, (actualRGB >> 16) & 0xff, 5, String.format("%s red at (%d, %d)", message, x, y));
assertEquals(String.format("%s green at (%d, %d)", message, x, y), (expectedRGB >> 8) & 0xff, (actualRGB >> 8) & 0xff, 5); assertEquals((expectedRGB >> 8) & 0xff, (actualRGB >> 8) & 0xff, 5, String.format("%s green at (%d, %d)", message, x, y));
assertEquals(String.format("%s blue at (%d, %d)", message, x, y), expectedRGB & 0xff, actualRGB & 0xff, 5); assertEquals(expectedRGB & 0xff, actualRGB & 0xff, 5, String.format("%s blue at (%d, %d)", message, x, y));
} }
} }
} }
@@ -595,9 +583,9 @@ public abstract class ImageReaderAbstractTest<T extends ImageReader> {
failBecause("Image could not be read", e); failBecause("Image could not be read", e);
} }
assertNotNull("Image was null!", image); assertNotNull(image, "Image was null!");
assertEquals("Read image has wrong width: " + image.getWidth(), 10, image.getWidth()); assertEquals(10, image.getWidth(), "Read image has wrong width: " + image.getWidth());
assertEquals("Read image has wrong height: " + image.getHeight(), 10, image.getHeight()); assertEquals(10, image.getHeight(), "Read image has wrong height: " + image.getHeight());
reader.dispose(); reader.dispose();
} }
@@ -622,9 +610,9 @@ public abstract class ImageReaderAbstractTest<T extends ImageReader> {
final BufferedImage image = reader.read(imageIndex, param); final BufferedImage image = reader.read(imageIndex, param);
assertNotNull("Image was null!", image); assertNotNull(image, "Image was null!");
assertEquals("Read image has wrong width: " + image.getWidth(), r.width, image.getWidth()); assertEquals(r.width, image.getWidth(), "Read image has wrong width: " + image.getWidth());
assertEquals("Read image has wrong height: " + image.getHeight(), r.height, image.getHeight()); assertEquals(r.height, image.getHeight(), "Read image has wrong height: " + image.getHeight());
try { try {
assertImageDataEquals("Images differ", roi, image); assertImageDataEquals("Images differ", roi, image);
@@ -678,9 +666,9 @@ public abstract class ImageReaderAbstractTest<T extends ImageReader> {
failBecause("Image could not be read", e); failBecause("Image could not be read", e);
} }
assertNotNull("Image was null!", image); assertNotNull(image, "Image was null!");
assertEquals("Read image has wrong width: " + image.getWidth(), 10, image.getWidth()); assertEquals(10, image.getWidth(), "Read image has wrong width: " + image.getWidth());
assertEquals("Read image has wrong height: " + image.getHeight(), 10, image.getHeight()); assertEquals(10, image.getHeight(), "Read image has wrong height: " + image.getHeight());
} }
reader.dispose(); reader.dispose();
@@ -705,9 +693,9 @@ public abstract class ImageReaderAbstractTest<T extends ImageReader> {
catch (IOException e) { catch (IOException e) {
failBecause("Image could not be read", e); failBecause("Image could not be read", e);
} }
assertNotNull("Image was null!", image); assertNotNull(image, "Image was null!");
assertEquals("Read image has wrong width: " + image.getWidth(), 5, image.getWidth()); assertEquals(5, image.getWidth(), "Read image has wrong width: " + image.getWidth());
assertEquals("Read image has wrong height: " + image.getHeight(), 5, image.getHeight()); assertEquals(5, image.getHeight(), "Read image has wrong height: " + image.getHeight());
reader.dispose(); reader.dispose();
} }
@@ -798,11 +786,11 @@ public abstract class ImageReaderAbstractTest<T extends ImageReader> {
failBecause("Image could not be read", e); failBecause("Image could not be read", e);
} }
assertNotNull("Image was null!", image); assertNotNull(image, "Image was null!");
assertEquals("Read image has wrong width: " + image.getWidth(), assertEquals( data.getDimension(0).width, image.getWidth(),
data.getDimension(0).width, image.getWidth()); "Read image has wrong width: " + image.getWidth());
assertEquals("Read image has wrong height: " + image.getHeight(), assertEquals( data.getDimension(0).height, image.getHeight(),
data.getDimension(0).height, image.getHeight()); "Read image has wrong height: " + image.getHeight());
reader.dispose(); reader.dispose();
} }
@@ -821,11 +809,11 @@ public abstract class ImageReaderAbstractTest<T extends ImageReader> {
failBecause("Image could not be read", e); failBecause("Image could not be read", e);
} }
assertNotNull("Image was null!", image); assertNotNull(image, "Image was null!");
assertEquals("Read image has wrong width: " + image.getWidth(), assertEquals(data.getDimension(0).width, image.getWidth(),
data.getDimension(0).width, image.getWidth()); "Read image has wrong width: " + image.getWidth());
assertEquals("Read image has wrong height: " + image.getHeight(), assertEquals(data.getDimension(0).height, image.getHeight(),
data.getDimension(0).height, image.getHeight()); "Read image has wrong height: " + image.getHeight());
reader.dispose(); reader.dispose();
} }
@@ -954,7 +942,7 @@ public abstract class ImageReaderAbstractTest<T extends ImageReader> {
catch (IOException e) { catch (IOException e) {
fail("Could not read image width: " + e); fail("Could not read image width: " + e);
} }
assertEquals("Wrong width reported", data.getDimension(0).width, width); assertEquals(data.getDimension(0).width, width, "Wrong width reported");
reader.dispose(); reader.dispose();
} }
@@ -993,7 +981,7 @@ public abstract class ImageReaderAbstractTest<T extends ImageReader> {
catch (IOException e) { catch (IOException e) {
fail("Could not read image width: " + e); fail("Could not read image width: " + e);
} }
assertEquals("Wrong width reported", 0, width); assertEquals(0, width, "Wrong width reported");
reader.dispose(); reader.dispose();
} }
@@ -1010,7 +998,7 @@ public abstract class ImageReaderAbstractTest<T extends ImageReader> {
catch (IOException e) { catch (IOException e) {
fail("Could not read image height: " + e); fail("Could not read image height: " + e);
} }
assertEquals("Wrong height reported", data.getDimension(0).height, height); assertEquals(data.getDimension(0).height, height, "Wrong height reported");
reader.dispose(); reader.dispose();
} }
@@ -1028,7 +1016,7 @@ public abstract class ImageReaderAbstractTest<T extends ImageReader> {
catch (IOException e) { catch (IOException e) {
fail("Could not read image height: " + e); fail("Could not read image height: " + e);
} }
assertEquals("Wrong height reported", 0, height); assertEquals(0, height, "Wrong height reported");
reader.dispose(); reader.dispose();
} }
@@ -1067,7 +1055,7 @@ public abstract class ImageReaderAbstractTest<T extends ImageReader> {
fail("Could not read image aspect ratio" + e); fail("Could not read image aspect ratio" + e);
} }
Dimension d = data.getDimension(0); Dimension d = data.getDimension(0);
assertEquals("Wrong aspect aspect ratio", d.getWidth() / d.getHeight(), aspectRatio, 0.001); assertEquals(d.getWidth() / d.getHeight(), aspectRatio, 0.001, "Wrong aspect aspect ratio");
reader.dispose(); reader.dispose();
} }
@@ -1085,7 +1073,7 @@ public abstract class ImageReaderAbstractTest<T extends ImageReader> {
catch (IOException e) { catch (IOException e) {
fail("Could not read image aspect ratio" + e); fail("Could not read image aspect ratio" + e);
} }
assertEquals("Wrong aspect aspect ratio", 0f, aspectRatio, 0f); assertEquals(0f, aspectRatio, 0f, "Wrong aspect aspect ratio");
reader.dispose(); reader.dispose();
} }
@@ -1381,7 +1369,7 @@ public abstract class ImageReaderAbstractTest<T extends ImageReader> {
} }
} }
assertTrue("ImageTypeSpecifier from getRawImageType should be in the iterator from getImageTypes", rawFound); assertTrue(rawFound, "ImageTypeSpecifier from getRawImageType should be in the iterator from getImageTypes");
} }
reader.dispose(); reader.dispose();
@@ -1487,7 +1475,7 @@ public abstract class ImageReaderAbstractTest<T extends ImageReader> {
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
String message = expected.getMessage().toLowerCase(); String message = expected.getMessage().toLowerCase();
assertTrue("Wrong message: " + message, message.contains("dest")); assertTrue(message.contains("dest"), "Wrong message: " + message);
} }
} }
reader.dispose(); reader.dispose();
@@ -1637,7 +1625,7 @@ public abstract class ImageReaderAbstractTest<T extends ImageReader> {
BufferedImage two = reader.read(0); BufferedImage two = reader.read(0);
// Test for same BufferedImage instance // Test for same BufferedImage instance
assertNotSame("Multiple reads return same (mutable) image", one, two); assertNotSame(one, two, "Multiple reads return same (mutable) image");
// Test for same backing storage (array) // Test for same backing storage (array)
one.setRGB(0, 0, Color.BLACK.getRGB()); one.setRGB(0, 0, Color.BLACK.getRGB());
@@ -1721,7 +1709,7 @@ public abstract class ImageReaderAbstractTest<T extends ImageReader> {
BufferedImage one = reader.readThumbnail(i, j); BufferedImage one = reader.readThumbnail(i, j);
BufferedImage two = reader.readThumbnail(i, j); BufferedImage two = reader.readThumbnail(i, j);
assertNotSame("Multiple reads return same (mutable) image", one, two); assertNotSame(one, two, "Multiple reads return same (mutable) image");
Graphics2D g = one.createGraphics(); Graphics2D g = one.createGraphics();
try { try {
@@ -1786,13 +1774,13 @@ public abstract class ImageReaderAbstractTest<T extends ImageReader> {
reader.dispose(); reader.dispose();
} }
@Ignore("TODO: Implement") @Disabled("TODO: Implement")
@Test @Test
public void testSetDestinationBands() { public void testSetDestinationBands() {
throw new UnsupportedOperationException("Method testSetDestinationBands not implemented"); // TODO: Implement throw new UnsupportedOperationException("Method testSetDestinationBands not implemented"); // TODO: Implement
} }
@Ignore("TODO: Implement") @Disabled("TODO: Implement")
@Test @Test
public void testSetSourceBands() { public void testSetSourceBands() {
throw new UnsupportedOperationException("Method testSetDestinationBands not implemented"); // TODO: Implement throw new UnsupportedOperationException("Method testSetDestinationBands not implemented"); // TODO: Implement
@@ -1893,7 +1881,7 @@ public abstract class ImageReaderAbstractTest<T extends ImageReader> {
public ImageInputStream getInputStream() { public ImageInputStream getInputStream() {
try { try {
ImageInputStream stream = ImageIO.createImageInputStream(input); ImageInputStream stream = ImageIO.createImageInputStream(input);
assertNotNull("Could not create ImageInputStream for input: " + input, stream); assertNotNull(stream, "Could not create ImageInputStream for input: " + input);
return stream; return stream;
} }
@@ -32,14 +32,13 @@ package com.twelvemonkeys.imageio.util;
import com.twelvemonkeys.lang.Validate; import com.twelvemonkeys.lang.Validate;
import org.junit.Test;
import javax.imageio.ImageTypeSpecifier; import javax.imageio.ImageTypeSpecifier;
import java.awt.color.*; import java.awt.color.*;
import java.awt.image.*; import java.awt.image.*;
import static org.junit.Assert.assertEquals; import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertSame; import static org.junit.jupiter.api.Assertions.*;
public class ImageTypeSpecifiersTest { public class ImageTypeSpecifiersTest {
@@ -32,7 +32,6 @@ package com.twelvemonkeys.imageio.util;
import com.twelvemonkeys.imageio.stream.URLImageInputStreamSpi; import com.twelvemonkeys.imageio.stream.URLImageInputStreamSpi;
import org.junit.Test;
import org.mockito.InOrder; import org.mockito.InOrder;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
@@ -50,10 +49,8 @@ import java.lang.reflect.ParameterizedType;
import java.net.URL; import java.net.URL;
import java.util.List; import java.util.List;
import static org.junit.Assert.assertEquals; import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertNotNull; import static org.junit.jupiter.api.Assertions.*;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
/** /**
@@ -145,7 +142,7 @@ public abstract class ImageWriterAbstractTest<T extends ImageWriter> {
throw new AssertionError(e.getMessage(), e); throw new AssertionError(e.getMessage(), e);
} }
assertTrue("No image data written", buffer.size() > 0); assertTrue(buffer.size() > 0, "No image data written");
} }
} }
@@ -164,26 +161,23 @@ public abstract class ImageWriterAbstractTest<T extends ImageWriter> {
throw new AssertionError(e.getMessage(), e); throw new AssertionError(e.getMessage(), e);
} }
assertEquals("Image data written", 0, buffer.size()); assertEquals(0, buffer.size(), "Image data written");
} }
@Test(expected = IllegalStateException.class) @Test
public void testWriteNoOutput() throws IOException { public void testWriteNoOutput() throws IOException {
ImageWriter writer = createWriter(); ImageWriter writer = createWriter();
try { assertThrows(IllegalStateException.class, () -> {
writer.write(getTestData(0)); writer.write(getTestData(0));
} }, "Expected IllegalStateException when no output is set on writer");
catch (IOException e) {
fail(e.getMessage());
}
} }
@Test @Test
public void testGetDefaultWriteParam() throws IOException { public void testGetDefaultWriteParam() throws IOException {
ImageWriter writer = createWriter(); ImageWriter writer = createWriter();
ImageWriteParam param = writer.getDefaultWriteParam(); ImageWriteParam param = writer.getDefaultWriteParam();
assertNotNull("Default ImageWriteParam is null", param); assertNotNull(param, "Default ImageWriteParam is null");
} }
// TODO: Test writing with params // TODO: Test writing with params
@@ -30,17 +30,14 @@
package com.twelvemonkeys.imageio.util; package com.twelvemonkeys.imageio.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer; import java.awt.image.DataBuffer;
import java.awt.image.IndexColorModel; import java.awt.image.IndexColorModel;
import javax.imageio.ImageTypeSpecifier; import javax.imageio.ImageTypeSpecifier;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* IndexedImageTypeSpecifierTestCase * IndexedImageTypeSpecifierTestCase
@@ -82,9 +79,9 @@ public class IndexedImageTypeSpecifierTest {
assertNotEquals(spec.hashCode(), different.hashCode()); assertNotEquals(spec.hashCode(), different.hashCode());
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCreateNull() { public void testCreateNull() {
new IndexedImageTypeSpecifier(null); assertThrows(IllegalArgumentException.class, () -> new IndexedImageTypeSpecifier(null));
} }
@Test @Test
@@ -1,15 +1,13 @@
package com.twelvemonkeys.imageio.util; package com.twelvemonkeys.imageio.util;
import org.junit.Test;
import javax.imageio.ImageTypeSpecifier; import javax.imageio.ImageTypeSpecifier;
import java.awt.*; import java.awt.*;
import java.awt.color.ColorSpace; import java.awt.color.ColorSpace;
import java.awt.image.*; import java.awt.image.*;
import java.util.Random; import java.util.Random;
import static org.junit.Assert.assertEquals; import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertSame; import static org.junit.jupiter.api.Assertions.*;
/** /**
* RasterUtilsTest. * RasterUtilsTest.
@@ -19,15 +17,15 @@ import static org.junit.Assert.assertSame;
* @version $Id: RasterUtilsTest.java,v 1.0 05/05/2021 haraldk Exp$ * @version $Id: RasterUtilsTest.java,v 1.0 05/05/2021 haraldk Exp$
*/ */
public class RasterUtilsTest { public class RasterUtilsTest {
@Test(expected = NullPointerException.class) @Test
public void testAsByteRasterFromNull() { public void testAsByteRasterFromNull() {
RasterUtils.asByteRaster((Raster) null); assertThrows(NullPointerException.class, () -> RasterUtils.asByteRaster((Raster) null));
} }
@SuppressWarnings("RedundantCast") @SuppressWarnings("RedundantCast")
@Test(expected = NullPointerException.class) @Test
public void testAsByteRasterWritableFromNull() { public void testAsByteRasterWritableFromNull() {
RasterUtils.asByteRaster((WritableRaster) null); assertThrows(NullPointerException.class, () -> RasterUtils.asByteRaster((WritableRaster) null));
} }
@Test @Test
@@ -32,8 +32,6 @@ package com.twelvemonkeys.imageio.util;
import com.twelvemonkeys.imageio.color.ColorSpaces; import com.twelvemonkeys.imageio.color.ColorSpaces;
import org.junit.Test;
import javax.imageio.ImageTypeSpecifier; import javax.imageio.ImageTypeSpecifier;
import java.awt.color.ColorSpace; import java.awt.color.ColorSpace;
import java.awt.image.ComponentColorModel; import java.awt.image.ComponentColorModel;
@@ -42,7 +40,9 @@ import java.awt.image.PixelInterleavedSampleModel;
import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.*;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class UInt32ImageTypeSpecifierTest { public class UInt32ImageTypeSpecifierTest {
private static final ColorSpace sRGB = ColorSpace.getInstance(ColorSpace.CS_sRGB); private static final ColorSpace sRGB = ColorSpace.getInstance(ColorSpace.CS_sRGB);
@@ -1,8 +1,7 @@
package com.twelvemonkeys.imageio.plugins.hdr.tonemap; package com.twelvemonkeys.imageio.plugins.hdr.tonemap;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.Assert.assertArrayEquals;
public class DefaultToneMapperTest { public class DefaultToneMapperTest {
@@ -1,8 +1,7 @@
package com.twelvemonkeys.imageio.plugins.hdr.tonemap; package com.twelvemonkeys.imageio.plugins.hdr.tonemap;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.Assert.assertArrayEquals;
public class GammaToneMapperTest { public class GammaToneMapperTest {
private final GammaToneMapper mapper = new GammaToneMapper(); private final GammaToneMapper mapper = new GammaToneMapper();

Some files were not shown because too many files have changed in this diff Show More