diff --git a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/ByteBufferUtilTest.java b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/ByteBufferUtilTest.java index 9b474d6bed5..073fdd86762 100644 --- a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/ByteBufferUtilTest.java +++ b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/ByteBufferUtilTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2023 Crown Copyright + * Copyright 2017-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,17 +30,16 @@ import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; /** * This test class is copied from org.apache.accumulo.core.util.ByteByfferUtilTest. */ -public class ByteBufferUtilTest { +class ByteBufferUtilTest { private static final byte[] TEST_DATA_STRING = "0123456789".getBytes(UTF_8); @Test - public void testNonZeroArrayOffset() { + void testNonZeroArrayOffset() { final ByteBuffer bb1 = ByteBuffer.wrap(TEST_DATA_STRING, 3, 4); // create a ByteBuffer with a non-zero array offset @@ -49,9 +48,9 @@ public void testNonZeroArrayOffset() { // The purpose of this test is to ensure ByteBufferUtil code works when arrayOffset is non-zero. The following asserts are not to test ByteBuffer, but // ensure the behaviour of slice() is as expected. - assertEquals(3, bb2.arrayOffset()); - assertEquals(0, bb2.position()); - assertEquals(4, bb2.limit()); + assertThat(bb2.arrayOffset()).isEqualTo(3); + assertThat(bb2.position()).isZero(); + assertThat(bb2.limit()).isEqualTo(4); // start test with non zero arrayOffset assertByteBufferEquals("3456", bb2); @@ -62,21 +61,21 @@ public void testNonZeroArrayOffset() { } @Test - public void testZeroArrayOffsetAndNonZeroPosition() { + void testZeroArrayOffsetAndNonZeroPosition() { final ByteBuffer bb = ByteBuffer.wrap(TEST_DATA_STRING, 3, 4); assertByteBufferEquals("3456", bb); } @Test - public void testZeroArrayOffsetAndPosition() { + void testZeroArrayOffsetAndPosition() { final ByteBuffer bb = ByteBuffer.wrap(TEST_DATA_STRING, 0, 4); assertByteBufferEquals("0123", bb); } @Test - public void testDirectByteBuffer() { + void testDirectByteBuffer() { // allocate direct so it does not have a backing array final ByteBuffer bb = ByteBuffer.allocateDirect(10); bb.put(TEST_DATA_STRING); @@ -90,15 +89,14 @@ public void testDirectByteBuffer() { } private static void assertByteBufferEquals(final String expected, final ByteBuffer bb) { - assertEquals(expected, ByteBufferUtil.toString(bb)); - assertEquals(expected, new String(ByteBufferUtil.toBytes(bb), UTF_8)); - assertEquals(expected, ByteBufferUtil.toString(bb)); + assertThat(ByteBufferUtil.toString(bb)).isEqualTo(expected); + assertThat(new String(ByteBufferUtil.toBytes(bb), UTF_8)).isEqualTo(expected); List bal = ByteBufferUtil.toBytesList(Collections.singletonList(bb)); assertThat(bal).hasSize(1); - assertEquals(expected, new String(bal.get(0), UTF_8)); + assertThat(new String(bal.get(0), UTF_8)).isEqualTo(expected); - assertEquals(new ArrayByteSequence(expected), new ArrayByteSequence(bb)); + assertThat(new ArrayByteSequence(bb)).isEqualTo(new ArrayByteSequence(expected)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); @@ -109,13 +107,13 @@ private static void assertByteBufferEquals(final String expected, final ByteBuff throw new RuntimeException(e); } - assertEquals(expected, new String(baos.toByteArray(), UTF_8)); + assertThat(new String(baos.toByteArray(), UTF_8)).isEqualTo(expected); ByteArrayInputStream bais = ByteBufferUtil.toByteArrayInputStream(bb); byte[] buffer = new byte[expected.length()]; try { bais.read(buffer); - assertEquals(expected, new String(buffer, UTF_8)); + assertThat(new String(buffer, UTF_8)).isEqualTo(expected); } catch (IOException e) { throw new RuntimeException(e); } diff --git a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/CloseableUtilTest.java b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/CloseableUtilTest.java index f444c1aae48..e021379e443 100644 --- a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/CloseableUtilTest.java +++ b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/CloseableUtilTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 Crown Copyright + * Copyright 2017-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,10 +28,10 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; -public class CloseableUtilTest { +class CloseableUtilTest { @Test - public void shouldCloseACloseable() throws IOException { + void shouldCloseACloseable() throws IOException { final Closeable closeable = mock(Closeable.class); CloseableUtil.close(closeable); @@ -40,7 +40,7 @@ public void shouldCloseACloseable() throws IOException { } @Test - public void shouldCloseAllCloseables() throws IOException { + void shouldCloseAllCloseables() throws IOException { final Closeable closeable1 = mock(Closeable.class); final Closeable closeable2 = mock(Closeable.class); final Object nonCloseable = mock(Object.class); @@ -51,10 +51,19 @@ public void shouldCloseAllCloseables() throws IOException { verify(closeable2).close(); } + @Test + void shouldCloseAutoCloseables() throws Exception { + final AutoCloseable autoCloseable = mock(AutoCloseable.class); + + CloseableUtil.close(autoCloseable); + + verify(autoCloseable).close(); + } + @ParameterizedTest @NullSource @ValueSource(strings = {"Some string"}) - public void shouldNotThrowExceptionForNullOrStringObject(Object obj) { + void shouldNotThrowExceptionForNullOrStringObject(Object obj) { assertThatNoException().isThrownBy(() -> CloseableUtil.close(obj)); } } diff --git a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/CollectionUtilTest.java b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/CollectionUtilTest.java index 962da073307..9df6e041066 100644 --- a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/CollectionUtilTest.java +++ b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/CollectionUtilTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 Crown Copyright + * Copyright 2017-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,14 +27,11 @@ import java.util.TreeSet; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; -public class CollectionUtilTest { +class CollectionUtilTest { @Test - public void shouldReturnTreeSetWithProvidedItem() { + void shouldReturnTreeSetWithProvidedItem() { final String item = "test item"; final TreeSet treeSet = CollectionUtil.treeSet(item); @@ -44,14 +41,14 @@ public void shouldReturnTreeSetWithProvidedItem() { } @Test - public void shouldReturnTreeSetWithWithOutNullItem() { - final TreeSet treeSet = CollectionUtil.treeSet(null); + void shouldReturnTreeSetWithWithOutNullItem() { + final TreeSet treeSet = CollectionUtil.treeSet((String) null); assertThat(treeSet).isEmpty(); } @Test - public void shouldReturnTreeSetWithProvidedItems() { + void shouldReturnTreeSetWithProvidedItems() { final String[] items = {"test item 1", "test item 2", null}; final TreeSet treeSet = CollectionUtil.treeSet(items); @@ -65,14 +62,7 @@ public void shouldReturnTreeSetWithProvidedItems() { } @Test - public void shouldReturnTreeSetWithNoItemsForNullArray() { - final TreeSet treeSet = CollectionUtil.treeSet(null); - - assertThat(treeSet).isEmpty(); - } - - @Test - public void shouldConvertMapToStringKeys() { + void shouldConvertMapToStringKeys() { // Given final Map, String> map = new HashMap<>(); populateClassKeyMap(map); @@ -83,11 +73,11 @@ public void shouldConvertMapToStringKeys() { // Then final Map expectedResult = new HashMap<>(); populateStringKeyMap(expectedResult); - assertEquals(expectedResult, result); + assertThat(result).isEqualTo(expectedResult); } @Test - public void shouldConvertMapToStringKeysWithProvidedMap() { + void shouldConvertMapToStringKeysWithProvidedMap() { // Given final Map, String> map = new HashMap<>(); populateClassKeyMap(map); @@ -100,11 +90,11 @@ public void shouldConvertMapToStringKeysWithProvidedMap() { // Then final Map expectedResult = new LinkedHashMap<>(); populateStringKeyMap(expectedResult); - assertEquals(expectedResult, result); + assertThat(result).isEqualTo(expectedResult); } @Test - public void shouldConvertMapToClassKeys() throws ClassNotFoundException { + void shouldConvertMapToClassKeys() throws ClassNotFoundException { // Given final Map map = new HashMap<>(); populateStringKeyMap(map); @@ -115,11 +105,11 @@ public void shouldConvertMapToClassKeys() throws ClassNotFoundException { // Then final Map, String> expectedResult = new HashMap<>(); populateClassKeyMap(expectedResult); - assertEquals(expectedResult, result); + assertThat(result).isEqualTo(expectedResult); } @Test - public void shouldConvertMapToClassKeysWithProvidedMap() throws ClassNotFoundException { + void shouldConvertMapToClassKeysWithProvidedMap() throws ClassNotFoundException { // Given final Map map = new HashMap<>(); populateStringKeyMap(map); @@ -132,11 +122,11 @@ public void shouldConvertMapToClassKeysWithProvidedMap() throws ClassNotFoundExc // Then final Map, String> expectedResult = new LinkedHashMap<>(); populateClassKeyMap(expectedResult); - assertEquals(expectedResult, result); + assertThat(result).isEqualTo(expectedResult); } @Test - public void shouldReturnTrueWhenCollectionContainsAProvidedValue() { + void shouldReturnTrueWhenCollectionContainsAProvidedValue() { // Given final Collection collection = Sets.newHashSet(10, 20, 2, 30); final Object[] values = new Object[] {1, 2, 3}; @@ -145,11 +135,11 @@ public void shouldReturnTrueWhenCollectionContainsAProvidedValue() { final boolean result = CollectionUtil.containsAny(collection, values); // Then - assertTrue(result); + assertThat(result).isTrue(); } @Test - public void shouldReturnFalseWhenCollectionDoesNotContainsAProvidedValue() { + void shouldReturnFalseWhenCollectionDoesNotContainsAProvidedValue() { // Given final Collection collection = Sets.newHashSet(10, 20, 30); final Object[] values = new Object[] {1, 2, 3}; @@ -158,11 +148,11 @@ public void shouldReturnFalseWhenCollectionDoesNotContainsAProvidedValue() { final boolean result = CollectionUtil.containsAny(collection, values); // Then - assertFalse(result); + assertThat(result).isFalse(); } @Test - public void shouldReturnFalseWhenContainsAnyCalledWithNullValue() { + void shouldReturnFalseWhenContainsAnyCalledWithNullValue() { // Given final Collection collection = Sets.newHashSet(10, 20, 30); @@ -170,20 +160,20 @@ public void shouldReturnFalseWhenContainsAnyCalledWithNullValue() { final boolean result = CollectionUtil.containsAny(collection, null); // Then - assertFalse(result); + assertThat(result).isFalse(); } @Test - public void shouldReturnFalseWhenContainsAnyCalledWithNullCollection() { + void shouldReturnFalseWhenContainsAnyCalledWithNullCollection() { final Object[] values = new Object[] {1, 2, 3}; final boolean result = CollectionUtil.containsAny(null, values); - assertFalse(result); + assertThat(result).isFalse(); } @Test - public void shouldReturnFalseWhenAnyMissingCalledWhenTheCollectionContainsAllValues() { + void shouldReturnFalseWhenAnyMissingCalledWhenTheCollectionContainsAllValues() { // Given final Collection collection = Sets.newHashSet(10, 20, 30); final Object[] values = new Object[] {10, 20, 30}; @@ -192,11 +182,11 @@ public void shouldReturnFalseWhenAnyMissingCalledWhenTheCollectionContainsAllVal final boolean result = CollectionUtil.anyMissing(collection, values); // Then - assertFalse(result); + assertThat(result).isFalse(); } @Test - public void shouldReturnFalseWhenAnyMissingCalledWhenNullValues() { + void shouldReturnFalseWhenAnyMissingCalledWhenNullValues() { // Given final Collection collection = Sets.newHashSet(10, 20, 30); @@ -204,11 +194,11 @@ public void shouldReturnFalseWhenAnyMissingCalledWhenNullValues() { final boolean result = CollectionUtil.anyMissing(collection, null); // Then - assertFalse(result); + assertThat(result).isFalse(); } @Test - public void shouldReturnTrueWhenAnyMissingCalledWhenTheCollectionDoesNotContainAProvidedValue() { + void shouldReturnTrueWhenAnyMissingCalledWhenTheCollectionDoesNotContainAProvidedValue() { // Given final Collection collection = Sets.newHashSet(10, 20, 30); final Object[] values = new Object[] {1, 2, 3}; @@ -217,23 +207,11 @@ public void shouldReturnTrueWhenAnyMissingCalledWhenTheCollectionDoesNotContainA final boolean result = CollectionUtil.anyMissing(collection, values); // Then - assertTrue(result); - } - - @Test - public void shouldReturnFalseWhenAnyMissingCalledWithNullValue() { - // Given - final Collection collection = Sets.newHashSet(10, 20, 30); - - // When - final boolean result = CollectionUtil.anyMissing(collection, null); - - // Then - assertFalse(result); + assertThat(result).isTrue(); } @Test - public void shouldReturnTrueWhenAnyMissingCalledWithNullCollectionAndSomeValues() { + void shouldReturnTrueWhenAnyMissingCalledWithNullCollectionAndSomeValues() { // Given final Object[] values = new Object[] {1, 2, 3}; @@ -241,20 +219,20 @@ public void shouldReturnTrueWhenAnyMissingCalledWithNullCollectionAndSomeValues( final boolean result = CollectionUtil.anyMissing(null, values); // Then - assertTrue(result); + assertThat(result).isTrue(); } @Test - public void shouldReturnFalseWhenAnyMissingCalledWithNullCollectionAndValues() { + void shouldReturnFalseWhenAnyMissingCalledWithNullCollectionAndValues() { // When final boolean result = CollectionUtil.anyMissing(null, null); // Then - assertFalse(result); + assertThat(result).isFalse(); } @Test - public void shouldReturnTrueWhenDistinctCalledWithCollectionOfUniqueValues() { + void shouldReturnTrueWhenDistinctCalledWithCollectionOfUniqueValues() { // Given final Collection collection = Lists.newArrayList(1, 2, 3, 4, 5); @@ -262,11 +240,11 @@ public void shouldReturnTrueWhenDistinctCalledWithCollectionOfUniqueValues() { final boolean result = CollectionUtil.distinct(collection); // Then - assertTrue(result); + assertThat(result).isTrue(); } @Test - public void shouldReturnFalseWhenDistinctCalledWithCollectionOfNonUniqueValues() { + void shouldReturnFalseWhenDistinctCalledWithCollectionOfNonUniqueValues() { // Given final Collection collection = Lists.newArrayList(1, 2, 3, 1, 2); @@ -274,7 +252,7 @@ public void shouldReturnFalseWhenDistinctCalledWithCollectionOfNonUniqueValues() final boolean result = CollectionUtil.distinct(collection); // Then - assertFalse(result); + assertThat(result).isFalse(); } private void populateClassKeyMap(Map, String> map) { diff --git a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/FieldUtilTest.java b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/FieldUtilTest.java index 0d6bfd63fb6..fe7597b0751 100644 --- a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/FieldUtilTest.java +++ b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/FieldUtilTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2019-2020 Crown Copyright + * Copyright 2019-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,28 +24,28 @@ import java.util.LinkedHashSet; import java.util.Set; -import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; -public class FieldUtilTest { +class FieldUtilTest { @Test - public void testNullField() { - final Pair nullPair = new Pair("Test", null); + void testNullField() { + final Pair nullPair = new Pair("Test", null); final ValidationResult validationResult = FieldUtil.validateRequiredFields(nullPair); final Set expected = new LinkedHashSet<>(); expected.add("Test is required."); - assertEquals(expected, validationResult.getErrors()); + assertThat(validationResult.getErrors()).isEqualTo(expected); } @Test - public void testNotNullField() { - final Pair nonNullPair = new Pair("Test", "Test"); + void testNotNullField() { + final Pair nonNullPair = new Pair("Test", "Test"); final ValidationResult validationResult = FieldUtil.validateRequiredFields(nonNullPair); final Set expected = new LinkedHashSet<>(); - assertEquals(expected, validationResult.getErrors()); + assertThat(validationResult.getErrors()).isEqualTo(expected); } } diff --git a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/GroupUtilTest.java b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/GroupUtilTest.java index 5599ec7aefa..3eeb7084091 100644 --- a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/GroupUtilTest.java +++ b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/GroupUtilTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 Crown Copyright + * Copyright 2017-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,19 +21,19 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatNoException; -public class GroupUtilTest { +class GroupUtilTest { private static final String INVALID_STRING = "inv@l1dStr|ng&^"; private static final String VALID_STRING = "vAl1d-Str|ng"; @Test - public void shouldThrowExceptionWithInvalidStringName() { + void shouldThrowExceptionWithInvalidStringName() { assertThatIllegalArgumentException() .isThrownBy(() -> GroupUtil.validateName(INVALID_STRING)) .withMessage("Group is invalid: inv@l1dStr|ng&^, it must match regex: [a-zA-Z0-9|-]*"); } @Test - public void shouldPassValidationWithValidStringName() { + void shouldPassValidationWithValidStringName() { assertThatNoException().isThrownBy(() -> GroupUtil.validateName(VALID_STRING)); } } diff --git a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/JsonAssert.java b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/JsonAssert.java index d29353347b7..df55289db70 100644 --- a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/JsonAssert.java +++ b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/JsonAssert.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2020 Crown Copyright + * Copyright 2016-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,8 @@ package uk.gov.gchq.gaffer.commonutil; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.jupiter.api.Assertions; + +import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.util.Collections; @@ -33,18 +34,18 @@ private JsonAssert() { public static void assertEquals(final String expectedJson, final String actualJson) { try { - final Map expectedSchemaMap = null != expectedJson ? OBJECT_MAPPER.readValue(expectedJson, Map.class) : Collections.emptyMap(); - final Map actualSchemaMap = null != actualJson ? OBJECT_MAPPER.readValue(actualJson, Map.class) : Collections.emptyMap(); - Assertions.assertEquals(expectedSchemaMap, actualSchemaMap); + final Map expectedSchemaMap = expectedJson != null ? OBJECT_MAPPER.readValue(expectedJson, Map.class) : Collections.emptyMap(); + final Map actualSchemaMap = actualJson != null ? OBJECT_MAPPER.readValue(actualJson, Map.class) : Collections.emptyMap(); + assertThat(actualSchemaMap).isEqualTo(expectedSchemaMap); return; } catch (final IOException e) { // ignore the error and try using lists instead } try { - final List expectedSchemaMap = null != expectedJson ? OBJECT_MAPPER.readValue(expectedJson, List.class) : Collections.emptyList(); - final List actualSchemaMap = null != actualJson ? OBJECT_MAPPER.readValue(actualJson, List.class) : Collections.emptyList(); - Assertions.assertEquals(expectedSchemaMap, actualSchemaMap); + final List expectedSchemaMap = expectedJson != null ? OBJECT_MAPPER.readValue(expectedJson, List.class) : Collections.emptyList(); + final List actualSchemaMap = actualJson != null ? OBJECT_MAPPER.readValue(actualJson, List.class) : Collections.emptyList(); + assertThat(actualSchemaMap).isEqualTo(expectedSchemaMap); } catch (final IOException e) { throw new AssertionError(expectedJson + " is not equal to " + actualJson, e); } @@ -56,9 +57,9 @@ public static void assertEquals(final byte[] expectedJson, final byte[] actualJs public static void assertNotEqual(final String firstJson, final String secondJson) { try { - final Map firstSchemaMap = null != firstJson ? OBJECT_MAPPER.readValue(firstJson, Map.class) : Collections.emptyMap(); - final Map secondSchemaMap = null != secondJson ? OBJECT_MAPPER.readValue(secondJson, Map.class) : Collections.emptyMap(); - Assertions.assertNotEquals(firstSchemaMap, secondSchemaMap); + final Map firstSchemaMap = firstJson != null ? OBJECT_MAPPER.readValue(firstJson, Map.class) : Collections.emptyMap(); + final Map secondSchemaMap = secondJson != null ? OBJECT_MAPPER.readValue(secondJson, Map.class) : Collections.emptyMap(); + assertThat(firstSchemaMap).isNotEqualTo(secondSchemaMap); } catch (final IOException e) { // ignore } diff --git a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/JsonUtilTest.java b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/JsonUtilTest.java index 8ce62ecc67a..1d1c2eacb64 100644 --- a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/JsonUtilTest.java +++ b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/JsonUtilTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2020 Crown Copyright + * Copyright 2017-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,94 +13,69 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package uk.gov.gchq.gaffer.commonutil; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; +import java.util.stream.Stream; -public class JsonUtilTest { +class JsonUtilTest { @Test - public void shouldReturnTrueWhenJsonObjectsAreEqualButInADifferentOrder() { + void shouldReturnTrueWhenJsonObjectsAreEqualButInADifferentOrder() { final String json1 = "{\"a\": 1, \"b\": 2}"; final String json2 = "{\"b\": 2, \"a\": 1}"; - assertTrue(JsonUtil.equals(json1, json2)); - assertTrue(JsonUtil.equals(json1.getBytes(), json2.getBytes())); + assertThat(JsonUtil.equals(json1, json2)).isTrue(); + assertThat(JsonUtil.equals(json1.getBytes(), json2.getBytes())).isTrue(); JsonAssert.assertEquals(json1, json2); JsonAssert.assertEquals(json1.getBytes(), json2.getBytes()); } @Test - public void shouldReturnFalseWhenJsonObjectsAreDifferentSizes() { - final String json1 = "{\"a\": 1, \"b\": 2}"; - final String json2 = "{\"a\": 1, \"b\": 2, \"c\": 3}"; - - assertFalse(JsonUtil.equals(json1, json2)); - assertFalse(JsonUtil.equals(json1.getBytes(), json2.getBytes())); - - JsonAssert.assertNotEqual(json1, json2); - JsonAssert.assertNotEqual(json1.getBytes(), json2.getBytes()); - } - - @Test - public void shouldReturnFalseWhenJsonObjectsAreNotEqual() { - final String json1 = "{\"a\": 1, \"b\": 2}"; - final String json2 = "{\"a\": 1, \"b\": 3}"; - - assertFalse(JsonUtil.equals(json1, json2)); - assertFalse(JsonUtil.equals(json1.getBytes(), json2.getBytes())); - - JsonAssert.assertNotEqual(json1, json2); - JsonAssert.assertNotEqual(json1.getBytes(), json2.getBytes()); - } - - @Test - public void shouldReturnTrueWhenJsonArraysAreEqual() { + void shouldReturnTrueWhenJsonArraysAreEqual() { final String json1 = "[1,2,3]"; final String json2 = "[1,2,3]"; - assertTrue(JsonUtil.equals(json1, json2)); - assertTrue(JsonUtil.equals(json1.getBytes(), json2.getBytes())); + assertThat(JsonUtil.equals(json1, json2)).isTrue(); + assertThat(JsonUtil.equals(json1.getBytes(), json2.getBytes())).isTrue(); JsonAssert.assertEquals(json1, json2); JsonAssert.assertEquals(json1.getBytes(), json2.getBytes()); } - @Test - public void shouldReturnFalseWhenJsonArraysAreNotEqual() { - // Given - final String json1 = "[1,2,3]"; - final String json2 = "[1,2,4]"; - - assertFalse(JsonUtil.equals(json1, json2)); - assertFalse(JsonUtil.equals(json1.getBytes(), json2.getBytes())); + @ParameterizedTest + @MethodSource("provideJSONStrings") + void shouldReturnFalse(String json1, String json2) { + assertThat(JsonUtil.equals(json1, json2)).isFalse(); + assertThat(JsonUtil.equals(json1.getBytes(), json2.getBytes())).isFalse(); JsonAssert.assertNotEqual(json1, json2); JsonAssert.assertNotEqual(json1.getBytes(), json2.getBytes()); } - @Test - public void shouldReturnFalseWhenJsonArraysAreDifferentSizes() { - final String json1 = "[1,2,3]"; - final String json2 = "[1,2,3,4]"; - - assertFalse(JsonUtil.equals(json1, json2)); - assertFalse(JsonUtil.equals(json1.getBytes(), json2.getBytes())); - - JsonAssert.assertNotEqual(json1, json2); - JsonAssert.assertNotEqual(json1.getBytes(), json2.getBytes()); + private static Stream provideJSONStrings() { + return Stream.of( + Arguments.of("{\"a\": 1, \"b\": 2}", "{\"a\": 1, \"b\": 2, \"c\": 3}"), + Arguments.of("{\"a\": 1, \"b\": 2}", "{\"a\": 1, \"b\": 3}"), + Arguments.of("[1,2,3]", "[1,2,4]"), + Arguments.of("[1,2,3]", "[1,2,3,4]") + ); } @Test - public void shouldReturnFalseWhenActualObjectIsNull() { + void shouldReturnFalseWhenActualObjectIsNull() { final String json1 = "{\"a\": 1, \"b\": 2}"; - assertFalse(JsonUtil.equals(json1, null)); - assertFalse(JsonUtil.equals(json1.getBytes(), null)); + assertThat(JsonUtil.equals(json1, null)).isFalse(); + assertThat(JsonUtil.equals(json1.getBytes(), null)).isFalse(); JsonAssert.assertNotEqual(json1, null); JsonAssert.assertNotEqual(json1.getBytes(), null); diff --git a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/LongUtilTest.java b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/LongUtilTest.java index e8d803bd5e6..6115ca5c69f 100644 --- a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/LongUtilTest.java +++ b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/LongUtilTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 Crown Copyright + * Copyright 2017-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,10 +23,10 @@ import static org.assertj.core.api.Assertions.assertThat; -public class LongUtilTest { +class LongUtilTest { @Test - public void shouldGetDifferentPositiveTimeBasedRandoms() { + void shouldGetDifferentPositiveTimeBasedRandoms() { final int n = 1000; final Set timestamps = new HashSet<>(n); diff --git a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/PropertiesUtilTest.java b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/PropertiesUtilTest.java index aef6acbf8ef..a4ffa83ee68 100644 --- a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/PropertiesUtilTest.java +++ b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/PropertiesUtilTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 Crown Copyright + * Copyright 2017-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,22 +18,39 @@ import org.junit.jupiter.api.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatNoException; -public class PropertiesUtilTest { +class PropertiesUtilTest { private static final String INVALID_STRING = "inv@l1dStr|ng&^"; private static final String VALID_STRING = "vAl1d-Str|ng"; @Test - public void shouldThrowExceptionWithInvalidStringName() { + void shouldThrowExceptionWithInvalidStringName() { assertThatIllegalArgumentException() .isThrownBy(() -> PropertiesUtil.validateName(INVALID_STRING)) .withMessage("Property is invalid: inv@l1dStr|ng&^, it must match regex: [a-zA-Z0-9|-]*"); } @Test - public void shouldPassValidationWithValidStringName() { + void shouldPassValidationWithValidStringName() { assertThatNoException().isThrownBy(() -> PropertiesUtil.validateName(VALID_STRING)); } + + @Test + void shouldBeFalseWithInvalidStringName() { + assertThat(PropertiesUtil.isValidName(INVALID_STRING)).isFalse(); + } + + @Test + void shouldBeTrueWithValidStringName() { + assertThat(PropertiesUtil.isValidName(VALID_STRING)).isTrue(); + } + + @Test + void shouldStripInvalidCharacters() { + final String expectedString = "invl1dStr|ng"; + assertThat(PropertiesUtil.stripInvalidCharacters(INVALID_STRING)).isEqualTo(expectedString); + } } diff --git a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/StreamUtilTest.java b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/StreamUtilTest.java index 420bf7e1275..18ca1e25db6 100644 --- a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/StreamUtilTest.java +++ b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/StreamUtilTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 Crown Copyright + * Copyright 2017-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package uk.gov.gchq.gaffer.commonutil; import org.junit.jupiter.api.Test; @@ -23,12 +24,12 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.fail; -public class StreamUtilTest { +class StreamUtilTest { public static final String FILE_NAME = "URLSchema.json"; @Test - public void testOpenStreamsURLNotEmpty() throws Exception { + void testOpenStreamsURLNotEmpty() throws Exception { final URI resource = getClass().getClassLoader().getResource(FILE_NAME).toURI(); if (null == resource) { fail("Test json file not found:" + FILE_NAME); @@ -37,8 +38,8 @@ public void testOpenStreamsURLNotEmpty() throws Exception { final InputStream[] inputStreams = StreamUtil.openStreams(resource); assertThat(inputStreams) - .isNotEmpty() - .overridingErrorMessage("InputStreams length is %s", 0); + .overridingErrorMessage("InputStreams length is %s", 0) + .isNotEmpty(); StreamUtil.closeStreams(inputStreams); } diff --git a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/StringUtilTest.java b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/StringUtilTest.java index 06cec46c3e8..f02d96edcc9 100644 --- a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/StringUtilTest.java +++ b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/StringUtilTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2018-2020 Crown Copyright + * Copyright 2018-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,64 +25,64 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; -public class StringUtilTest { +class StringUtilTest { @Test - public void unescapeCommaShouldReplaceBackslashesWithComma() { + void unescapeCommaShouldReplaceBackslashesWithComma() { assertEquals("replaceBackslashesWith,Comma", StringUtil.unescapeComma("replaceBackslashesWith\\\\Comma")); } @Test - public void unescapeCommaShouldNotRemoveSemicolon() { + void unescapeCommaShouldNotRemoveSemicolon() { assertEquals("don'tRemove;SemiColon", StringUtil.unescapeComma("don'tRemove;SemiColon")); } @Test - public void unescapeCommaShouldNotRemoveComma() { + void unescapeCommaShouldNotRemoveComma() { assertEquals("don'tRemove,Comma", StringUtil.unescapeComma("don'tRemove,Comma")); } @Test - public void unescapeCommaShouldRemoveBackslash() { + void unescapeCommaShouldRemoveBackslash() { assertEquals("removeBackslash", StringUtil.unescapeComma("remove\\Backslash")); } @Test - public void escapeCommaShouldReplaceBackslashWithSemiColon() { + void escapeCommaShouldReplaceBackslashWithSemiColon() { assertEquals("replaceWith\\;semicolon", StringUtil.escapeComma("replaceWith\\semicolon")); } @Test - public void escapeCommaShouldReplaceCommaWith2Backslashes() { + void escapeCommaShouldReplaceCommaWith2Backslashes() { assertEquals("replaceWith\\\\comma", StringUtil.escapeComma("replaceWith,comma")); } @Test - public void toBytesWhenStringIsValid() { + void toBytesWhenStringIsValid() { assertArrayEquals("isValid".getBytes(), StringUtil.toBytes("isValid")); } @Test - public void toBytesWhenStringIsNull() { + void toBytesWhenStringIsNull() { assertArrayEquals(new byte[0], StringUtil.toBytes(null)); } @Test - public void toStringWhenBytesAreValid() { + void toStringWhenBytesAreValid() { final byte[] validBytes = "isValid".getBytes(); assertEquals("isValid", StringUtil.toString(validBytes)); } @Test - public void ifEmptyStringTestReturnNull() { + void ifEmptyStringTestReturnNull() { assertNull(StringUtil.nullIfEmpty("")); } @ParameterizedTest @NullSource @ValueSource(strings = {" ", "String", " string "}) - public void shouldReturnValueWhenNotEmptyString(String input) { + void shouldReturnValueWhenNotEmptyString(String input) { assertEquals(input, StringUtil.nullIfEmpty(input)); } } diff --git a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/ToStringBuilderTest.java b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/ToStringBuilderTest.java index fcfc17c80c0..faf300ce53e 100644 --- a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/ToStringBuilderTest.java +++ b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/ToStringBuilderTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2020 Crown Copyright + * Copyright 2017-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,12 +20,12 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; -public class ToStringBuilderTest { +class ToStringBuilderTest { @BeforeEach - public void setUp() throws Exception { + public void setUp() { clearDebugModeProperty(); } @@ -35,19 +35,19 @@ public void after() { } @Test - public void testDebugOffToStringBuilder() { + void testDebugOffToStringBuilder() { setDebugMode("false"); ToStringBuilder toStringBuilder = new ToStringBuilder("Test String"); - assertEquals(ToStringBuilder.SHORT_STYLE, toStringBuilder.getStyle()); + assertThat(toStringBuilder.getStyle()).isEqualTo(ToStringBuilder.SHORT_STYLE); } @Test - public void testDebugOnToStringBuilder() { + void testDebugOnToStringBuilder() { setDebugMode("true"); ToStringBuilder toStringBuilder = new ToStringBuilder("Test String"); - assertEquals(ToStringBuilder.FULL_STYLE, toStringBuilder.getStyle()); + assertThat(toStringBuilder.getStyle()).isEqualTo(ToStringBuilder.FULL_STYLE); } private void setDebugMode(final String value) { diff --git a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/elementvisibilityutil/ArrayByteSequenceTest.java b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/elementvisibilityutil/ArrayByteSequenceTest.java index f3f4aa0bdef..996385f7759 100644 --- a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/elementvisibilityutil/ArrayByteSequenceTest.java +++ b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/elementvisibilityutil/ArrayByteSequenceTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 Crown Copyright + * Copyright 2017-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,13 +21,13 @@ import java.nio.ByteBuffer; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.jupiter.api.Assertions.assertEquals; /** * This test class is copied from org.apache.accumulo.core.data.ArrayByteSequenceTest. */ -public class ArrayByteSequenceTest { +class ArrayByteSequenceTest { ArrayByteSequence abs; byte[] data; @@ -39,74 +39,76 @@ public void setUp() { } @Test - public void testInvalidByteBufferBounds0ShouldThrowIAX() { + void testInvalidByteBufferBounds0ShouldThrowIAX() { assertThatIllegalArgumentException().isThrownBy(() -> abs = new ArrayByteSequence(data, -1, 0)); } @Test - public void testInvalidByteBufferBounds1ShouldThrowIAX() { + void testInvalidByteBufferBounds1ShouldThrowIAX() { assertThatIllegalArgumentException().isThrownBy(() -> abs = new ArrayByteSequence(data, data.length + 1, 0)); } @Test - public void testInvalidByteBufferBounds2ShouldThrowIAX() { + void testInvalidByteBufferBounds2ShouldThrowIAX() { assertThatIllegalArgumentException().isThrownBy(() -> abs = new ArrayByteSequence(data, 0, -1)); } @Test - public void testInvalidByteBufferBounds3ShouldThrowIAX() { + void testInvalidByteBufferBounds3ShouldThrowIAX() { assertThatIllegalArgumentException().isThrownBy(() -> abs = new ArrayByteSequence(data, 6, 2)); } @Test - public void testInvalidByteAt0ShouldThrowIAX() { + void testInvalidByteAt0ShouldThrowIAX() { assertThatIllegalArgumentException().isThrownBy(() -> abs.byteAt(-1)); } @Test - public void testInvalidByteAt1ShouldThrowIAX() { + void testInvalidByteAt1ShouldThrowIAX() { assertThatIllegalArgumentException().isThrownBy(() -> abs.byteAt(data.length)); } @Test - public void testSubSequence() { - assertEquals(0, abs.subSequence(0, 0).length()); - assertEquals("mile", abs.subSequence(1, 5).toString()); + void testSubSequence() { + assertThat(abs.subSequence(0, 0).length()).isZero(); + assertThat(abs.subSequence(1, 5)).hasToString("mile"); } @Test - public void testInvalidSubsequence0ShouldThrowIAX() { + void testInvalidSubsequence0ShouldThrowIAX() { assertThatIllegalArgumentException().isThrownBy(() -> abs.subSequence(5, 1)); } @Test - public void testInvalidSubsequence1ShouldThrowIAX() { + void testInvalidSubsequence1ShouldThrowIAX() { assertThatIllegalArgumentException().isThrownBy(() -> abs.subSequence(-1, 1)); } @Test - public void testInvalidSubsequence3ShouldThrowIAX() { + void testInvalidSubsequence3ShouldThrowIAX() { assertThatIllegalArgumentException().isThrownBy(() -> abs.subSequence(0, 10)); } @Test - public void testFromByteBuffer() { + void testFromByteBuffer() { final ByteBuffer bb = ByteBuffer.wrap(data, 1, 4); abs = new ArrayByteSequence(bb); - assertEquals("mile", abs.toString()); + assertThat(abs).hasToString("mile"); } @Test - public void testFromReadOnlyByteBuffer() { + void testFromReadOnlyByteBuffer() { final ByteBuffer bb = ByteBuffer.wrap(data, 1, 4).asReadOnlyBuffer(); abs = new ArrayByteSequence(bb); - assertEquals("mile", abs.toString()); + assertThat(abs).hasToString("mile"); } @Test - public void testToString() { - assertEquals("", new ArrayByteSequence("").toString(), "String conversion should round trip correctly"); + void testToString() { + assertThat(new ArrayByteSequence("")) + .as("String conversion should round trip correctly") + .hasToString(""); } } diff --git a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/elementvisibilityutil/AuthorisationsTest.java b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/elementvisibilityutil/AuthorisationsTest.java index 2b2981311fd..7fc9fefd53e 100644 --- a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/elementvisibilityutil/AuthorisationsTest.java +++ b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/elementvisibilityutil/AuthorisationsTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 Crown Copyright + * Copyright 2017-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,54 +19,54 @@ import org.junit.jupiter.api.Test; import java.nio.ByteBuffer; +import java.util.List; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; /** * This test class is copied from org.apache.accumulo.core.security.AuthorizationsTest. */ -public class AuthorisationsTest { +class AuthorisationsTest { @Test - public void testEncodeDecode() { + void testEncodeDecode() { final Authorisations a = new Authorisations("a", "abcdefg", "hijklmno", ","); final byte[] array = a.getAuthorisationsArray(); final Authorisations b = new Authorisations(array); - assertEquals(a, b); + assertThat(b).isEqualTo(a); } @Test - public void testEncodeEmptyAuthorisations() { + void testEncodeEmptyAuthorisations() { final Authorisations a = new Authorisations(); final byte[] array = a.getAuthorisationsArray(); final Authorisations b = new Authorisations(array); - assertEquals(a, b); + assertThat(b).isEqualTo(a); } @Test - public void testEncodeMultiByteAuthorisations() { + void testEncodeMultiByteAuthorisations() { final Authorisations a = new Authorisations("五", "b", "c", "九"); final byte[] array = a.getAuthorisationsArray(); final Authorisations b = new Authorisations(array); - assertEquals(a, b); + assertThat(b).isEqualTo(a); } @Test - public void testSerialization() { + void testSerialization() { final Authorisations a1 = new Authorisations("a", "b"); final Authorisations a2 = new Authorisations("b", "a"); - assertEquals(a1, a2); - assertEquals(a1.serialise(), a2.serialise()); + assertThat(a2).isEqualTo(a1); + assertThat(a2.serialise()).isEqualTo(a1.serialise()); } @Test - public void testDefensiveAccess() { + void testDefensiveAccess() { final Authorisations expected = new Authorisations("foo", "a"); final Authorisations actual = new Authorisations("foo", "a"); @@ -74,37 +74,46 @@ public void testDefensiveAccess() { for (byte[] bytes : actual) { bytes[0]++; } - assertArrayEquals(expected.getAuthorisationsArray(), actual.getAuthorisationsArray()); + assertThat(actual.getAuthorisationsArray()).isEqualTo(expected.getAuthorisationsArray()); // test defensive getter and serializer actual.getAuthorisations().get(0)[0]++; - assertArrayEquals(expected.getAuthorisationsArray(), actual.getAuthorisationsArray()); - assertEquals(expected.serialise(), actual.serialise()); + assertThat(actual.getAuthorisationsArray()).isEqualTo(expected.getAuthorisationsArray()); + assertThat(actual.serialise()).isEqualTo(expected.serialise()); } // This should throw ReadOnlyBufferException, but THRIFT-883 requires that the ByteBuffers themselves not be read-only // @Test(expected = ReadOnlyBufferException.class) @Test - public void testReadOnlyByteBuffer() { + void testReadOnlyByteBuffer() { final Authorisations expected = new Authorisations("foo"); final Authorisations actual = new Authorisations("foo"); - assertArrayEquals(expected.getAuthorisationsArray(), actual.getAuthorisationsArray()); + assertThat(actual.getAuthorisationsArray()).isEqualTo(expected.getAuthorisationsArray()); actual.getAuthorisationsBB().get(0).array()[0]++; - assertArrayEquals(expected.getAuthorisationsArray(), actual.getAuthorisationsArray()); + assertThat(actual.getAuthorisationsArray()).isEqualTo(expected.getAuthorisationsArray()); } @Test - public void testUnmodifiableList() { + void testUnmodifiableList() { final Authorisations expected = new Authorisations("foo"); final Authorisations actual = new Authorisations("foo"); - assertArrayEquals(expected.getAuthorisationsArray(), actual.getAuthorisationsArray()); + assertThat(actual.getAuthorisationsArray()).isEqualTo(expected.getAuthorisationsArray()); - assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> { - actual.getAuthorisationsBB().add(ByteBuffer.wrap(new byte[] {'a'})); - }); + final ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[] {'a'}); + final List getAuthBB = actual.getAuthorisationsBB(); + + assertThatExceptionOfType(UnsupportedOperationException.class) + .isThrownBy(() -> getAuthBB.add(byteBuffer)); + } + + @Test + void testToString() { + final Authorisations a = new Authorisations("a", "abcdefg", "hijklmno"); + + assertThat(a).hasToString("a,hijklmno,abcdefg"); } } diff --git a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/elementvisibilityutil/ElementVisibilityTest.java b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/elementvisibilityutil/ElementVisibilityTest.java index ff2eaf1e856..40422e88ea0 100644 --- a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/elementvisibilityutil/ElementVisibilityTest.java +++ b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/elementvisibilityutil/ElementVisibilityTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 Crown Copyright + * Copyright 2017-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,68 +23,67 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatNoException; -import static org.junit.jupiter.api.Assertions.assertEquals; import static uk.gov.gchq.gaffer.commonutil.elementvisibilityutil.ElementVisibility.quote; /** * This test class is copied from org.apache.accumulo.core.security.ColumnVisibilityTest. */ -public class ElementVisibilityTest { +class ElementVisibilityTest { @Test - public void testEmptyStringIsValid() { + void testEmptyStringIsValid() { final ElementVisibility a = new ElementVisibility(new byte[0]); final ElementVisibility b = new ElementVisibility(""); - assertEquals(a, b); + assertThat(b).isEqualTo(a); } @Test - public void testCharactersOnly() { + void testCharactersOnly() { getBytesShouldNotThrowIAX("test", "words"); } @Test - public void testCompound() { + void testCompound() { getBytesShouldNotThrowIAX("a|b", "a&b", "ab&bc", "_&-&:", "A&B&C&D&E", "A|B|C|D|E", "(A|B|C)", "(A)|B|(C)", "A&(B)&(C)", "A&B&(L)"); } @Test - public void testBadCharacters() { + void testBadCharacters() { getBytesShouldThrowIAX("=", "*", "^", "%", "@", "a*b"); } @Test - public void testComplexCompound() { + void testComplexCompound() { getBytesShouldNotThrowIAX("(a|b)&(x|y)", "a&(x|y)", "(a|b)&(x|y)", "A&(L|M)", "B&(L|M)", "A&B&(L|M)"); getBytesShouldNotThrowIAX("A&FOO&(L|M)", "(A|B)&FOO&(L|M)", "A&B&(L|M|FOO)", "((A|B|C)|foo)&bar"); getBytesShouldNotThrowIAX("(one&two)|(foo&bar)", "(one|foo)&three", "one|foo|bar", "(one|foo)|bar", "((one|foo)|bar)&two"); } @Test - public void testDanglingOperators() { + void testDanglingOperators() { getBytesShouldThrowIAX("a|b&", "(|a)", "|", "a|", "|a", "|", "&"); getBytesShouldThrowIAX("&(five)", "|(five)", "(five)&", "five|", "a|(b)&", "(&five)", "(five|)"); } @Test - public void testMissingSeparators() { + void testMissingSeparators() { getBytesShouldThrowIAX("one(five)", "(five)one", "(one)(two)", "a|(b(c))"); } @Test - public void testMismatchedParentheses() { + void testMismatchedParentheses() { getBytesShouldThrowIAX("(", ")", "(a&b", "b|a)", "A|B)"); } @Test - public void testMixedOperators() { + void testMixedOperators() { getBytesShouldThrowIAX("(A&B)|(C&D)&(E)", "a|b&c", "A&B&C|D", "(A&B)|(C&D)&(E)"); } @Test - public void testQuotes() { + void testQuotes() { getBytesShouldThrowIAX("\"\"", "\"A\"A", "\"A\"\"B\"", "(A)\"B\"", "\"A\"(B)"); getBytesShouldThrowIAX("\"A", "\"", "\"B", "A&\"B", "A&\"B\\'"); @@ -92,21 +91,21 @@ public void testQuotes() { } @Test - public void testToStringSimpleCharacter() { + void testToStringSimpleCharacter() { final ElementVisibility cv = new ElementVisibility(quote("a")); - assertEquals("[a]", cv.toString()); + assertThat(cv).hasToString("[a]"); } @Test - public void testToStringMultiByte() { + void testToStringMultiByte() { final ElementVisibility cv = new ElementVisibility(quote("五")); - assertEquals("[\"五\"]", cv.toString()); + assertThat(cv).hasToString("[\"五\"]"); } @Test - public void testParseTree() { + void testParseTree() { final ElementVisibility.Node node = parse("(W)|(U&V)"); assertNode(node, ElementVisibility.NodeType.OR, 0, 9); @@ -115,14 +114,14 @@ public void testParseTree() { } @Test - public void testParseTreeWithNoChildren() { + void testParseTreeWithNoChildren() { final ElementVisibility.Node node = parse("ABC"); assertNode(node, ElementVisibility.NodeType.TERM, 0, 3); } @Test - public void testParseTreeWithTwoChildren() { + void testParseTreeWithTwoChildren() { final ElementVisibility.Node node = parse("ABC|DEF"); assertNode(node, ElementVisibility.NodeType.OR, 0, 7); @@ -131,7 +130,7 @@ public void testParseTreeWithTwoChildren() { } @Test - public void testParseTreeWithParenthesesAndTwoChildren() { + void testParseTreeWithParenthesesAndTwoChildren() { final ElementVisibility.Node node = parse("(ABC|DEF)"); assertNode(node, ElementVisibility.NodeType.OR, 1, 8); @@ -140,7 +139,7 @@ public void testParseTreeWithParenthesesAndTwoChildren() { } @Test - public void testParseTreeWithParenthesizedChildren() { + void testParseTreeWithParenthesizedChildren() { final ElementVisibility.Node node = parse("ABC|(DEF&GHI)"); assertNode(node, ElementVisibility.NodeType.OR, 0, 13); @@ -151,7 +150,7 @@ public void testParseTreeWithParenthesizedChildren() { } @Test - public void testParseTreeWithMoreParentheses() { + void testParseTreeWithMoreParentheses() { final ElementVisibility.Node node = parse("(W)|(U&V)"); assertNode(node, ElementVisibility.NodeType.OR, 0, 9); diff --git a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/elementvisibilityutil/VisibilityEvaluatorTest.java b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/elementvisibilityutil/VisibilityEvaluatorTest.java index 4eec071231d..8c496ac1d16 100644 --- a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/elementvisibilityutil/VisibilityEvaluatorTest.java +++ b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/elementvisibilityutil/VisibilityEvaluatorTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 Crown Copyright + * Copyright 2017-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,98 +24,106 @@ import java.util.regex.PatternSyntaxException; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; import static uk.gov.gchq.gaffer.commonutil.elementvisibilityutil.ElementVisibility.quote; /** * This test class is copied from org.apache.accumulo.core.security.VisibilityEvaluatorTest. */ -public class VisibilityEvaluatorTest { +class VisibilityEvaluatorTest { final VisibilityEvaluator ve = new VisibilityEvaluator(new Authorisations("one", "two", "three", "four")); @Test - public void testVisibilityEvaluator() throws VisibilityParseException { + void testVisibilityEvaluator() throws VisibilityParseException { // test for empty vis - assertTrue(ve.evaluate(new ElementVisibility(new byte[0]))); + assertThat(ve.evaluate(new ElementVisibility(new byte[0]))).isTrue(); // test for and - assertTrue(ve.evaluate(new ElementVisibility("one&two")), "'and' test"); + assertThat(ve.evaluate(new ElementVisibility("one&two"))) + .as("'and' test") + .isTrue(); // test for or - assertTrue(ve.evaluate(new ElementVisibility("foor|four")), "'or' test"); + assertThat(ve.evaluate(new ElementVisibility("foor|four"))) + .as("'or' test") + .isTrue(); // test for and and or - assertTrue(ve.evaluate(new ElementVisibility("(one&two)|(foo&bar)")), "'and' and 'or' test"); + assertThat(ve.evaluate(new ElementVisibility("(one&two)|(foo&bar)"))) + .as("'and' and 'or' test") + .isTrue(); } @ParameterizedTest @ValueSource(strings = {"one", "one|five", "five|one", "(one)", "(one&two)|(foo&bar)", "(one|foo)&three", "one|foo|bar", "(one|foo)|bar", "((one|foo)|bar)&two"}) - public void testFalseNegatives(String marking) throws VisibilityParseException { - assertTrue(ve.evaluate(new ElementVisibility(marking)), marking); + void testFalseNegatives(String marking) throws VisibilityParseException { + assertThat(ve.evaluate(new ElementVisibility(marking))) + .as(marking) + .isTrue(); } @ParameterizedTest @ValueSource(strings = {"five", "one&five", "five&one", "((one|foo)|bar)&goober"}) - public void testFalsePositives(String marking) throws VisibilityParseException { - assertFalse(ve.evaluate(new ElementVisibility(marking)), marking); + void testFalsePositives(String marking) throws VisibilityParseException { + assertThat(ve.evaluate(new ElementVisibility(marking))) + .as(marking) + .isFalse(); } @ParameterizedTest @ValueSource(strings = {"one(five)", "(five)one", "(one)(two)", "a|(b(c))"}) - public void testMissingSeparatorsShouldThrowPSX(String marking) { + void testMissingSeparatorsShouldThrowPSX(String marking) { assertThatExceptionOfType(PatternSyntaxException.class).isThrownBy(() -> new ElementVisibility(marking)); } @ParameterizedTest @ValueSource(strings = {"&(five)", "|(five)", "(five)&", "five|", "a|(b)&", "(&five)", "(five|)"}) - public void testUnexpectedSeparatorShouldThrowPSX(String marking) { + void testUnexpectedSeparatorShouldThrowPSX(String marking) { assertThatExceptionOfType(PatternSyntaxException.class).isThrownBy(() -> new ElementVisibility(marking)); } @ParameterizedTest @ValueSource(strings = {"(", ")", "(a&b", "b|a)"}) - public void testMismatchedParenthesisShouldThrowPSX(String marking) { + void testMismatchedParenthesisShouldThrowPSX(String marking) { assertThatExceptionOfType(PatternSyntaxException.class).isThrownBy(() -> new ElementVisibility(marking)); } @Test - public void testQuotedExpressions() throws VisibilityParseException { + void testQuotedExpressions() throws VisibilityParseException { final Authorisations auths = new Authorisations("A#C", "A\"C", "A\\C", "AC"); - final VisibilityEvaluator ve = new VisibilityEvaluator(auths); + final VisibilityEvaluator visEv = new VisibilityEvaluator(auths); - assertTrue(ve.evaluate(new ElementVisibility(quote("A#C") + "|" + quote("A?C")))); + assertThat(visEv.evaluate(new ElementVisibility(quote("A#C") + "|" + quote("A?C")))).isTrue(); - assertFalse(ve.evaluate(new ElementVisibility(quote("A#C") + "&B"))); + assertThat(visEv.evaluate(new ElementVisibility(quote("A#C") + "&B"))).isFalse(); - assertTrue(ve.evaluate(new ElementVisibility(quote("A#C")))); - assertTrue(ve.evaluate(new ElementVisibility("(" + quote("A#C") + ")"))); + assertThat(visEv.evaluate(new ElementVisibility(quote("A#C")))).isTrue(); + assertThat(visEv.evaluate(new ElementVisibility("(" + quote("A#C") + ")"))).isTrue(); } @Test - public void testQuote() { - assertEquals("\"A#C\"", quote("A#C")); - assertEquals("\"A\\\"C\"", quote("A\"C")); - assertEquals("\"A\\\"\\\\C\"", quote("A\"\\C")); - assertEquals("ACS", quote("ACS")); - assertEquals("\"九\"", quote("九")); - assertEquals("\"五十\"", quote("五十")); + void testQuote() { + assertThat(quote("A#C")).isEqualTo("\"A#C\""); + assertThat(quote("A\"C")).isEqualTo("\"A\\\"C\""); + assertThat(quote("A\"\\C")).isEqualTo("\"A\\\"\\\\C\""); + assertThat(quote("ACS")).isEqualTo("ACS"); + assertThat(quote("九")).isEqualTo("\"九\""); + assertThat(quote("五十")).isEqualTo("\"五十\""); } @Test - public void testNonAscii() throws VisibilityParseException { - final VisibilityEvaluator ve = new VisibilityEvaluator(new Authorisations("五", "六", "八", "九", "五十")); - - assertTrue(ve.evaluate(new ElementVisibility(quote("五") + "|" + quote("四")))); - assertFalse(ve.evaluate(new ElementVisibility(quote("五") + "&" + quote("四")))); - assertTrue(ve.evaluate(new ElementVisibility(quote("五") + "&(" + quote("四") + "|" + quote("九") + ")"))); - assertTrue(ve.evaluate(new ElementVisibility("\"五\"&(\"四\"|\"五十\")"))); - assertFalse(ve.evaluate(new ElementVisibility(quote("五") + "&(" + quote("四") + "|" + quote("三") + ")"))); - assertFalse(ve.evaluate(new ElementVisibility("\"五\"&(\"四\"|\"三\")"))); + void testNonAscii() throws VisibilityParseException { + final VisibilityEvaluator visEv = new VisibilityEvaluator(new Authorisations("五", "六", "八", "九", "五十")); + + assertThat(visEv.evaluate(new ElementVisibility(quote("五") + "|" + quote("四")))).isTrue(); + assertThat(visEv.evaluate(new ElementVisibility(quote("五") + "&" + quote("四")))).isFalse(); + assertThat(visEv.evaluate(new ElementVisibility(quote("五") + "&(" + quote("四") + "|" + quote("九") + ")"))).isTrue(); + assertThat(visEv.evaluate(new ElementVisibility("\"五\"&(\"四\"|\"五十\")"))).isTrue(); + assertThat(visEv.evaluate(new ElementVisibility(quote("五") + "&(" + quote("四") + "|" + quote("三") + ")"))).isFalse(); + assertThat(visEv.evaluate(new ElementVisibility("\"五\"&(\"四\"|\"三\")"))).isFalse(); } } diff --git a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/AlwaysValidTrue.java b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/AlwaysValidTrueTest.java similarity index 78% rename from core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/AlwaysValidTrue.java rename to core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/AlwaysValidTrueTest.java index 128a54c9bdb..97d96e4e348 100644 --- a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/AlwaysValidTrue.java +++ b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/AlwaysValidTrueTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2020 Crown Copyright + * Copyright 2016-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,29 +22,29 @@ import uk.gov.gchq.koryphe.ValidationResult; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; -public class AlwaysValidTrue { +class AlwaysValidTrueTest { @ParameterizedTest @NullSource @ValueSource(strings = {"test"}) - public void shouldReturnTrueForNullAndString(final String input) { + void shouldReturnTrueForNullAndString(final String input) { final AlwaysValid validator = new AlwaysValid<>(); final boolean result = validator.validate(input); - assertTrue(result); + assertThat(result).isTrue(); } @ParameterizedTest @NullSource @ValueSource(strings = {"test"}) - public void shouldReturnValidationResultForNullAndString(final String input) { + void shouldReturnValidationResultForNullAndString(final String input) { final AlwaysValid validator = new AlwaysValid<>(); final ValidationResult result = validator.validateWithValidationResult(input); - assertTrue(result.isValid()); + assertThat(result.isValid()).isTrue(); } } diff --git a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/CachingIterableTest.java b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/CachingIterableTest.java index 8f8bbe4386b..76c742463cf 100644 --- a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/CachingIterableTest.java +++ b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/CachingIterableTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2018-2023 Crown Copyright + * Copyright 2018-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,13 +37,13 @@ import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) -public class CachingIterableTest { +class CachingIterableTest { private static final List SMALL_LIST = Arrays.asList(0, 1, 2, 3, 4); private static final List LARGE_LIST = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); @Test - public void shouldCacheSmallIterable(@Mock final Iterable mockIterable) { + void shouldCacheSmallIterable(@Mock final Iterable mockIterable) { when(mockIterable.iterator()) .thenReturn(SMALL_LIST.iterator()) .thenReturn(SMALL_LIST.iterator()); @@ -57,7 +57,7 @@ public void shouldCacheSmallIterable(@Mock final Iterable mockIterable) } @Test - public void shouldNotCacheALargeIterable(@Mock final Iterable mockIterable) { + void shouldNotCacheALargeIterable(@Mock final Iterable mockIterable) { when(mockIterable.iterator()) .thenReturn(LARGE_LIST.iterator()) .thenReturn(LARGE_LIST.iterator()); @@ -71,14 +71,14 @@ public void shouldNotCacheALargeIterable(@Mock final Iterable mockItera } @Test - public void shouldHandleNullIterable() { + void shouldHandleNullIterable() { Iterable cachingIterable = new CachingIterable<>(null); assertThat(cachingIterable).isEmpty(); } @Test - public void shouldCloseTheIterable() throws IOException { + void shouldCloseTheIterable() throws IOException { @SuppressWarnings("unchecked") final Iterable iterable = Mockito.mock(Iterable.class, Mockito.withSettings().extraInterfaces(Closeable.class)); @@ -90,7 +90,7 @@ public void shouldCloseTheIterable() throws IOException { } @Test - public void shouldCloseTheIterableWhenFullyCached() throws IOException { + void shouldCloseTheIterableWhenFullyCached() throws IOException { @SuppressWarnings("unchecked") final Iterable iterable = Mockito.mock(Iterable.class, Mockito.withSettings().extraInterfaces(Closeable.class)); @@ -104,7 +104,7 @@ public void shouldCloseTheIterableWhenFullyCached() throws IOException { @SuppressWarnings("unchecked") @Test - public void shouldHandleMultipleIterators() throws IOException { + void shouldHandleMultipleIterators() throws IOException { // Given final Iterable iterable = Mockito.mock(Iterable.class, Mockito.withSettings().extraInterfaces(Closeable.class)); diff --git a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/ConsumableBlockingQueueTest.java b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/ConsumableBlockingQueueTest.java index d7c81a606d1..7a8f6bee7c0 100644 --- a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/ConsumableBlockingQueueTest.java +++ b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/ConsumableBlockingQueueTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 Crown Copyright + * Copyright 2017-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,28 +21,22 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import java.util.NoSuchElementException; import java.util.stream.Collectors; -import java.util.stream.IntStream; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -public class ConsumableBlockingQueueTest { +class ConsumableBlockingQueueTest { @Test - public void shouldConsumeResultsWhenIterating() { + void shouldConsumeResultsWhenIterating() throws InterruptedException { // Given final ConsumableBlockingQueue queue = new ConsumableBlockingQueue<>(5); - IntStream.range(0, 4) - .forEach(i -> { - try { - queue.put(i); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - }); + for (int i = 0; i < 4; i++) { + queue.put(i); + } // When final List items = queue.stream().collect(Collectors.toList()); @@ -57,26 +51,25 @@ public void shouldConsumeResultsWhenIterating() { } @Test - public void shouldBlockOnAdditionWhenQueueIsFull() throws InterruptedException { + void shouldBlockOnAdditionWhenQueueIsFull() throws InterruptedException { // Given final ConsumableBlockingQueue queue = new ConsumableBlockingQueue<>(5); final boolean[] finishedAdding = new boolean[] {false}; new Thread(() -> { - IntStream.range(0, 10) - .forEach(i -> { - try { - queue.put(i); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - }); + for (int i = 0; i < 10; i++) { + try { + queue.put(i); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } finishedAdding[0] = true; }).start(); // Wait for some items to be added, but there isn't room for all of them Thread.sleep(1000L); - assertFalse(finishedAdding[0]); + assertThat(finishedAdding[0]).isFalse(); // Consume some results final Iterator consumer = queue.iterator(); @@ -88,7 +81,7 @@ public void shouldBlockOnAdditionWhenQueueIsFull() throws InterruptedException { // Now the queue has space some items should be added, but there still isn't room for all of them Thread.sleep(1000L); - assertFalse(finishedAdding[0]); + assertThat(finishedAdding[0]).isFalse(); // Consume some more results for (int i = 0; i < 4; i++) { @@ -98,7 +91,7 @@ public void shouldBlockOnAdditionWhenQueueIsFull() throws InterruptedException { // Now the queue has space some items should be added and this time there is room for the rest of them Thread.sleep(1000L); - assertTrue(finishedAdding[0]); + assertThat(finishedAdding[0]).isTrue(); // Consume some rest of the results while (consumer.hasNext()) { @@ -110,11 +103,33 @@ public void shouldBlockOnAdditionWhenQueueIsFull() throws InterruptedException { } @Test - public void shouldNotBlockWhenConsumingWhenQueueIsEmpty() { + void shouldNotBlockWhenConsumingWhenQueueIsEmpty() { final ConsumableBlockingQueue queue = new ConsumableBlockingQueue<>(5); final Iterator iterator = queue.iterator(); assertThat(iterator).isExhausted(); } + + @Test + void shouldThrowExceptionWhenQueueIsEmpty() { + final ConsumableBlockingQueue queue = new ConsumableBlockingQueue<>(5); + + final Iterator iterator = queue.iterator(); + + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> iterator.next()) + .withMessage("No more items"); + } + + @Test + void shouldReturnToString() throws InterruptedException { + final ConsumableBlockingQueue queue = new ConsumableBlockingQueue<>(5); + + for (int i = 0; i < 4; i++) { + queue.put(i); + } + + assertThat(queue).hasToString("ConsumableBlockingQueue[items={0,1,2,3}]"); + } } diff --git a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/EmptyIterableTest.java b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/EmptyIterableTest.java index 80f03271365..f38352ff2b7 100644 --- a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/EmptyIterableTest.java +++ b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/EmptyIterableTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2021 Crown Copyright + * Copyright 2015-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,10 +20,10 @@ import static org.assertj.core.api.Assertions.assertThat; -public class EmptyIterableTest { +class EmptyIterableTest { @Test - public void shouldBeEmpty() { + void shouldBeEmpty() { final EmptyIterable iterable = new EmptyIterable<>(); assertThat(iterable).isEmpty(); diff --git a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/LimitedInMemorySortedIterableTest.java b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/LimitedInMemorySortedIterableTest.java index 00cc2fd759c..a5cd7b2c670 100644 --- a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/LimitedInMemorySortedIterableTest.java +++ b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/LimitedInMemorySortedIterableTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 Crown Copyright + * Copyright 2017-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package uk.gov.gchq.gaffer.commonutil.iterable; import com.google.common.collect.Lists; @@ -26,11 +27,12 @@ import java.util.stream.IntStream; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -public class LimitedInMemorySortedIterableTest { +class LimitedInMemorySortedIterableTest { @Test - public void shouldLimitEntries() { + void shouldLimitEntries() { final LimitedInMemorySortedIterable list = new LimitedInMemorySortedIterable(Comparator.naturalOrder(), 100); final List expectedItems = new ArrayList<>(); IntStream.rangeClosed(1, 100).forEach(expectedItems::add); @@ -43,7 +45,7 @@ public void shouldLimitEntries() { } @Test - public void shouldLimitAndDeduplicateEntries() { + void shouldLimitAndDeduplicateEntries() { final LimitedInMemorySortedIterable list = new LimitedInMemorySortedIterable(Comparator.naturalOrder(), 2, true); list.add(1); @@ -57,7 +59,7 @@ public void shouldLimitAndDeduplicateEntries() { } @Test - public void shouldDeduplicateEntries() { + void shouldDeduplicateEntries() { final LimitedInMemorySortedIterable list = new LimitedInMemorySortedIterable(Comparator.naturalOrder(), 100, true); list.add(1); @@ -67,7 +69,7 @@ public void shouldDeduplicateEntries() { } @Test - public void shouldNotDeduplicateEntries() { + void shouldNotDeduplicateEntries() { final LimitedInMemorySortedIterable list = new LimitedInMemorySortedIterable(Comparator.naturalOrder(), 100, false); list.add(1); @@ -77,7 +79,7 @@ public void shouldNotDeduplicateEntries() { } @Test - public void shouldLimitAndNotDeduplicateEntries() { + void shouldLimitAndNotDeduplicateEntries() { final LimitedInMemorySortedIterable list = new LimitedInMemorySortedIterable(Comparator.naturalOrder(), 4, false); list.add(1); @@ -89,7 +91,7 @@ public void shouldLimitAndNotDeduplicateEntries() { } @Test - public void shouldAddAll() { + void shouldAddAll() { final LimitedInMemorySortedIterable itr = new LimitedInMemorySortedIterable(Comparator.naturalOrder(), 100); // When/Then @@ -122,7 +124,7 @@ public void shouldAddAll() { } @Test - public void shouldLimitEntriesOnAddAll() { + void shouldLimitEntriesOnAddAll() { // Given final LimitedInMemorySortedIterable itr = new LimitedInMemorySortedIterable(Comparator.naturalOrder(), 10); @@ -156,7 +158,7 @@ public void shouldLimitEntriesOnAddAll() { } @Test - public void shouldSortLargeNumberOfItems() { + void shouldSortLargeNumberOfItems() { // Given final int streamSize = 1000000; final int resultLimit = 10000; @@ -177,4 +179,27 @@ public void shouldSortLargeNumberOfItems() { final List expected = Lists.newArrayList(list); assertThat(sortedElements).isEqualTo(expected); } + + @Test + void shouldThrowExceptionWithNoComparator() { + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> new LimitedInMemorySortedIterable(null, 100)) + .withMessage("Comparator is required"); + } + + @Test + void shouldThrowExceptionWithInvalidLimit() { + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> new LimitedInMemorySortedIterable(Comparator.naturalOrder(), 0)) + .withMessage("Limit cannot be less than or equal to 0"); + } + + @Test + void shouldReturnToString() { + final LimitedInMemorySortedIterable list = new LimitedInMemorySortedIterable(Comparator.naturalOrder(), 1); + list.add(1); + + assertThat(list) + .hasToString("LimitedInMemorySortedIterable[size=1,limit=1,deduplicate=false,backingMap={1=OneOrMore[deduplicate=false,singleItem=1]}]"); + } } diff --git a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/RepeatItemIterableTest.java b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/RepeatItemIterableTest.java index b1d782f1436..1d283314947 100644 --- a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/RepeatItemIterableTest.java +++ b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/RepeatItemIterableTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 Crown Copyright + * Copyright 2017-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,10 +22,10 @@ import static org.assertj.core.api.Assertions.assertThat; -public class RepeatItemIterableTest { +class RepeatItemIterableTest { @Test - public void shouldRepeatItem5Times() { + void shouldRepeatItem5Times() { final String item = "item"; final long repeats = 5; @@ -38,7 +38,7 @@ public void shouldRepeatItem5Times() { @ParameterizedTest @ValueSource(longs = {0, -1, -5}) - public void shouldRepeatItem0TimesWhenRepeatsIsEqualOrLessThanZero(long repeats) { + void shouldRepeatItem0TimesWhenRepeatsIsEqualOrLessThanZero(long repeats) { final String item = "item"; final Iterable itr = new RepeatItemIterable<>(item, repeats); diff --git a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/StreamIterableTest.java b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/StreamIterableTest.java index 7873fa784ed..aa688034042 100644 --- a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/StreamIterableTest.java +++ b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/StreamIterableTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2020 Crown Copyright + * Copyright 2017-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,10 +32,10 @@ import static org.mockito.Mockito.verify; @ExtendWith(MockitoExtension.class) -public class StreamIterableTest { +class StreamIterableTest { @Test - public void shouldDelegateIteratorToIterable(@Mock final StreamSupplier streamSupplier, + void shouldDelegateIteratorToIterable(@Mock final StreamSupplier streamSupplier, @Mock final Stream stream, @Mock final Iterator iterator) { // Given @@ -58,7 +58,7 @@ public void shouldDelegateIteratorToIterable(@Mock final StreamSupplier } @Test - public void shouldDelegateCloseToStreamIterable(@Mock final StreamSupplier streamSupplier) + void shouldDelegateCloseToStreamIterable(@Mock final StreamSupplier streamSupplier) throws IOException { // Given final StreamIterable streamIterable = new StreamIterable<>(streamSupplier); diff --git a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/StreamIteratorTest.java b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/StreamIteratorTest.java index 757ad787bc5..2461e03d566 100644 --- a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/StreamIteratorTest.java +++ b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/StreamIteratorTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2020 Crown Copyright + * Copyright 2017-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,10 +26,10 @@ import static org.mockito.Mockito.verify; @ExtendWith(MockitoExtension.class) -public class StreamIteratorTest { +class StreamIteratorTest { @Test - public void shouldDelegateCloseToWrappedIterator(@Mock final Stream stream) { + void shouldDelegateCloseToWrappedIterator(@Mock final Stream stream) { final StreamIterator streamIterator = new StreamIterator<>(stream); streamIterator.close(); diff --git a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/SuppliedIterableTest.java b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/SuppliedIterableTest.java index 1abd6b59df8..2a8d729b4de 100644 --- a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/SuppliedIterableTest.java +++ b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/SuppliedIterableTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2020 Crown Copyright + * Copyright 2017-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,10 +37,10 @@ import static org.mockito.Mockito.withSettings; @ExtendWith(MockitoExtension.class) -public class SuppliedIterableTest { +class SuppliedIterableTest { @Test - public void shouldRequestNewIterableFromSupplierWhenIteratorInvoked(@Mock final Supplier> supplier) { + void shouldRequestNewIterableFromSupplierWhenIteratorInvoked(@Mock final Supplier> supplier) { // Given final Iterable iterable1 = Arrays.asList(1, 2, 3); final Iterable iterable2 = Arrays.asList(4, 5, 6); @@ -69,7 +69,7 @@ public void shouldRequestNewIterableFromSupplierWhenIteratorInvoked(@Mock final @SuppressWarnings("unchecked") @Test - public void shouldCloseIterables(@Mock final Supplier> supplier) throws IOException { + void shouldCloseIterables(@Mock final Supplier> supplier) throws IOException { // Given final Iterable iterable1 = mock(Iterable.class, withSettings().extraInterfaces(Closeable.class)); final Iterable iterable2 = mock(Iterable.class, withSettings().extraInterfaces(Closeable.class)); diff --git a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/TransformIterableTest.java b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/TransformIterableTest.java index 608c07323b1..9e3f69c7cc3 100644 --- a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/TransformIterableTest.java +++ b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/TransformIterableTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 Crown Copyright + * Copyright 2016-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,10 +41,10 @@ import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) -public class TransformIterableTest { +class TransformIterableTest { @Test - public void shouldCreateIteratorThatReturnsOnlyValidStrings(@Mock final Validator validator) { + void shouldCreateIteratorThatReturnsOnlyValidStrings(@Mock final Validator validator) { // Given final String item1 = "valid item 1"; final String item2 = "invalid item 2"; @@ -74,7 +74,7 @@ public void shouldCreateIteratorThatReturnsOnlyValidStrings(@Mock final Validato } @Test - public void shouldThrowIAXExceptionWhenNextItemIsInvalidString(@Mock final Validator validator) { + void shouldThrowIAXExceptionWhenNextItemIsInvalidString(@Mock final Validator validator) { // Given final String item1 = "valid item 1"; final String item2 = "invalid item 2 invalid"; @@ -100,7 +100,7 @@ public void shouldThrowIAXExceptionWhenNextItemIsInvalidString(@Mock final Valid } @Test - public void shouldThrowNoElementExceptionWhenNextCalledWhenNoNextString(@Mock final Validator validator) { + void shouldThrowNoElementExceptionWhenNextCalledWhenNoNextString(@Mock final Validator validator) { // Given final String item1 = "item 1"; final Iterable items = Arrays.asList(item1); @@ -122,7 +122,7 @@ public void shouldThrowNoElementExceptionWhenNextCalledWhenNoNextString(@Mock fi } @Test - public void shouldThrowExceptionIfRemoveCalled(@Mock final Validator validator) { + void shouldThrowExceptionIfRemoveCalled(@Mock final Validator validator) { final String item1 = "item 1"; final String item2 = "item 2"; final Iterable items = Arrays.asList(item1, item2); @@ -139,7 +139,7 @@ public void shouldThrowExceptionIfRemoveCalled(@Mock final Validator val @SuppressWarnings("unchecked") @Test - public void shouldAutoCloseIterator() throws IOException { + void shouldAutoCloseIterator() throws IOException { // Given final boolean autoClose = true; final Iterable items = mock(Iterable.class, Mockito.withSettings().extraInterfaces(Closeable.class)); @@ -164,7 +164,7 @@ public void shouldAutoCloseIterator() throws IOException { @SuppressWarnings("unchecked") @Test - public void shouldNotAutoCloseIterator() throws IOException { + void shouldNotAutoCloseIterator() throws IOException { // Given final boolean autoClose = false; final Iterable items = mock(Iterable.class, Mockito.withSettings().extraInterfaces(Closeable.class)); @@ -188,6 +188,31 @@ public void shouldNotAutoCloseIterator() throws IOException { } } + @Test + void shouldThrowExceptionWithNullInput() { + // Given + final boolean autoClose = true; + final AlwaysValid valid = new AlwaysValid<>(); + + // When/then + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> new TransformIterableImpl(null, valid, false, autoClose)) + .withMessage("Input iterable is required"); + } + + @SuppressWarnings("unchecked") + @Test + void shouldGetValidator() { + // Given + final boolean autoClose = true; + final Iterable items = mock(Iterable.class, Mockito.withSettings().extraInterfaces(Closeable.class)); + + try (TransformIterable iterable = new TransformIterableImpl(items, new AlwaysValid<>(), false, autoClose)) { + // Then + assertThat(iterable.getValidator()).isInstanceOf(AlwaysValid.class); + } + } + private class TransformIterableImpl extends TransformIterable { TransformIterableImpl(final Iterable input, final Validator validator) { diff --git a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/TransformOneToManyIterableTest.java b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/TransformOneToManyIterableTest.java index e6bfc2db597..ce8673ce149 100644 --- a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/TransformOneToManyIterableTest.java +++ b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/iterable/TransformOneToManyIterableTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 Crown Copyright + * Copyright 2016-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,10 +43,10 @@ import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) -public class TransformOneToManyIterableTest { +class TransformOneToManyIterableTest { @Test - public void shouldCreateIteratorThatReturnsOnlyValidStrings(@Mock final Validator validator) { + void shouldCreateIteratorThatReturnsOnlyValidStrings(@Mock final Validator validator) { // Given final String nullItem0 = null; final String validItem1 = "item 1"; @@ -79,7 +79,7 @@ public void shouldCreateIteratorThatReturnsOnlyValidStrings(@Mock final Validato } @Test - public void shouldCreateIteratorThatThrowsExceptionOnInvalidString(@Mock final Validator validator) { + void shouldCreateIteratorThatThrowsExceptionOnInvalidString(@Mock final Validator validator) { // Given final String item1 = "item 1"; final String item2 = "item 2a invalid,item 2b"; @@ -106,7 +106,7 @@ public void shouldCreateIteratorThatThrowsExceptionOnInvalidString(@Mock final V } @Test - public void shouldThrowExceptionIfNextCalledWhenNoNextString(@Mock final Validator validator) { + void shouldThrowExceptionIfNextCalledWhenNoNextString(@Mock final Validator validator) { // Given final String item1 = "item 1"; final String items2A_B = "item 2a,item 2b"; @@ -132,7 +132,7 @@ public void shouldThrowExceptionIfNextCalledWhenNoNextString(@Mock final Validat } @Test - public void shouldThrowExceptionIfRemoveCalled(@Mock final Validator validator) { + void shouldThrowExceptionIfRemoveCalled(@Mock final Validator validator) { final String item1 = "item 1"; final String item2 = "item 2"; final Iterable items = Arrays.asList(item1, item2); @@ -151,7 +151,7 @@ public void shouldThrowExceptionIfRemoveCalled(@Mock final Validator val @SuppressWarnings("unchecked") @Test - public void shouldAutoCloseIterator() throws IOException { + void shouldAutoCloseIterator() throws IOException { // Given final boolean autoClose = true; final Iterable items = mock(Iterable.class, Mockito.withSettings().extraInterfaces(Closeable.class)); @@ -176,7 +176,7 @@ public void shouldAutoCloseIterator() throws IOException { @SuppressWarnings("unchecked") @Test - public void shouldNotAutoCloseIterator() throws IOException { + void shouldNotAutoCloseIterator() throws IOException { // Given final boolean autoClose = false; final Iterable items = mock(Iterable.class, Mockito.withSettings().extraInterfaces(Closeable.class)); diff --git a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/pair/PairTest.java b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/pair/PairTest.java index 04e87d70ee8..04637ef1d48 100644 --- a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/pair/PairTest.java +++ b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/pair/PairTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2020 Crown Copyright + * Copyright 2017-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,48 +13,55 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package uk.gov.gchq.gaffer.commonutil.pair; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; +import static org.assertj.core.api.Assertions.assertThat; -public class PairTest { +class PairTest { @Test - public void shouldCreateMutablePair() { + void shouldCreateMutablePair() { final Pair pair = new Pair<>(0, "foo"); - assertEquals(0, pair.getFirst().intValue()); - assertEquals("foo", pair.getSecond()); + assertThat(pair.getFirst().intValue()).isZero(); + assertThat(pair.getSecond()).isEqualTo("foo"); } @Test - public void shouldCreateMutablePair2() { + void shouldCreateMutablePair2() { final Pair pair = new Pair<>(null, "bar"); - assertNull(pair.getFirst()); - assertEquals("bar", pair.getSecond()); + assertThat(pair.getFirst()).isNull(); + assertThat(pair.getSecond()).isEqualTo("bar"); } @Test - public void shouldBeAbleToMutateFirstInPair() { + void shouldBeAbleToMutateFirstInPair() { final Pair pair = new Pair<>(0); pair.setFirst(1); - assertEquals(1, pair.getFirst().intValue()); - assertNull(pair.getSecond()); + assertThat(pair.getFirst().intValue()).isEqualTo(1); + assertThat(pair.getSecond()).isNull(); } @Test - public void shouldBeAbleToMutateSecondInPair() { + void shouldBeAbleToMutateSecondInPair() { final Pair pair = new Pair<>(); pair.setSecond("2nd"); - assertNull(pair.getFirst()); - assertEquals("2nd", pair.getSecond()); + assertThat(pair.getFirst()).isNull(); + assertThat(pair.getSecond()).isEqualTo("2nd"); + } + + @Test + void shouldReturnToString() { + final Pair pair = new Pair<>("foo", "bar"); + + assertThat(pair).hasToString("Pair[first=foo,second=bar]"); } } diff --git a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/stream/GafferCollectorTest.java b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/stream/GafferCollectorTest.java index 1cf3335da98..a0056e75e70 100644 --- a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/stream/GafferCollectorTest.java +++ b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/stream/GafferCollectorTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 Crown Copyright + * Copyright 2017-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package uk.gov.gchq.gaffer.commonutil.stream; import org.junit.jupiter.api.Test; @@ -26,10 +27,10 @@ import static uk.gov.gchq.gaffer.commonutil.stream.GafferCollectors.toLimitedInMemorySortedIterable; import static uk.gov.gchq.gaffer.commonutil.stream.GafferCollectors.toLinkedHashSet; -public class GafferCollectorTest { +class GafferCollectorTest { @Test - public void shouldCollectToLinkedHashSet() { + void shouldCollectToLinkedHashSet() { final IntStream stream = IntStream.range(0, 100); final Iterable iterable = stream.boxed() @@ -41,7 +42,7 @@ public void shouldCollectToLinkedHashSet() { } @Test - public void shouldCollectToLimitedSortedSet() { + void shouldCollectToLimitedSortedSet() { final IntStream stream = IntStream.range(0, 100); final int limit = 50; final boolean deduplicate = true; diff --git a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/stream/StreamsTest.java b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/stream/StreamsTest.java index 1b993cf1199..ac87d0f3424 100644 --- a/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/stream/StreamsTest.java +++ b/core/common-util/src/test/java/uk/gov/gchq/gaffer/commonutil/stream/StreamsTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2020 Crown Copyright + * Copyright 2016-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,11 +29,11 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; -public class StreamsTest { +class StreamsTest { @SuppressWarnings("unchecked") @Test - public void shouldCloseIteratorWhenStreamIsClosed() throws Throwable { + void shouldCloseIteratorWhenStreamIsClosed() throws Throwable { // Given final Iterator iterator = mock(Iterator.class, Mockito.withSettings().extraInterfaces(Closeable.class)); given(iterator.hasNext()).willReturn(true, false); @@ -53,7 +53,7 @@ public void shouldCloseIteratorWhenStreamIsClosed() throws Throwable { @SuppressWarnings("unchecked") @Test - public void shouldCloseIterableWhenStreamIsClosed() throws Throwable { + void shouldCloseIterableWhenStreamIsClosed() throws Throwable { // Given final Iterable iterable = mock(Iterable.class, Mockito.withSettings().extraInterfaces(Closeable.class)); final Iterator iterator = mock(Iterator.class, Mockito.withSettings().extraInterfaces(Closeable.class)); @@ -76,7 +76,7 @@ public void shouldCloseIterableWhenStreamIsClosed() throws Throwable { @SuppressWarnings("unchecked") @Test - public void shouldCloseIteratorWhenParallelStreamIsClosed() throws Throwable { + void shouldCloseIteratorWhenParallelStreamIsClosed() throws Throwable { // Given final Iterator iterator = mock(Iterator.class, Mockito.withSettings().extraInterfaces(Closeable.class)); given(iterator.hasNext()).willReturn(true, false); @@ -96,7 +96,7 @@ public void shouldCloseIteratorWhenParallelStreamIsClosed() throws Throwable { @SuppressWarnings("unchecked") @Test - public void shouldCloseIterableWhenParallelStreamIsClosed() throws Throwable { + void shouldCloseIterableWhenParallelStreamIsClosed() throws Throwable { // Given final Iterable iterable = mock(Iterable.class, Mockito.withSettings().extraInterfaces(Closeable.class)); final Iterator iterator = mock(Iterator.class, Mockito.withSettings().extraInterfaces(Closeable.class)); diff --git a/core/graph/src/test/java/uk/gov/gchq/gaffer/graph/hook/NamedOperationResolverTest.java b/core/graph/src/test/java/uk/gov/gchq/gaffer/graph/hook/NamedOperationResolverTest.java index 866e8c945b4..52ab591687a 100644 --- a/core/graph/src/test/java/uk/gov/gchq/gaffer/graph/hook/NamedOperationResolverTest.java +++ b/core/graph/src/test/java/uk/gov/gchq/gaffer/graph/hook/NamedOperationResolverTest.java @@ -16,6 +16,8 @@ package uk.gov.gchq.gaffer.graph.hook; +import org.json.JSONArray; +import org.json.JSONObject; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; @@ -29,7 +31,6 @@ import uk.gov.gchq.gaffer.named.operation.ParameterDetail; import uk.gov.gchq.gaffer.operation.Operation; import uk.gov.gchq.gaffer.operation.OperationChain; -import uk.gov.gchq.gaffer.operation.OperationException; import uk.gov.gchq.gaffer.operation.impl.Limit; import uk.gov.gchq.gaffer.operation.impl.get.GetAdjacentIds; import uk.gov.gchq.gaffer.operation.impl.get.GetAllElements; @@ -54,6 +55,7 @@ class NamedOperationResolverTest extends GraphHookTest { static final String SUFFIX_CACHE_NAME = "suffix"; + static final String OP_NAME = "opName"; NamedOperationResolverTest() { super(NamedOperationResolver.class); @@ -62,6 +64,7 @@ class NamedOperationResolverTest extends GraphHookTest { @SuppressWarnings({"unchecked", "rawtypes"}) @Test void shouldResolveNamedOperation(@Mock final User user, + @Mock final Context context, @Mock final NamedOperationCache cache, @Mock final NamedOperationDetail namedOpDetail, @Mock final GetAdjacentIds op1, @@ -69,24 +72,24 @@ void shouldResolveNamedOperation(@Mock final User user, @Mock final Iterable input) throws CacheOperationException { // Given - final String opName = "opName"; final NamedOperationResolver resolver = new NamedOperationResolver(cache); final OperationChain testChain = new OperationChain(Arrays.asList(op1, op2)); final List expectedResolvedChain = Arrays.asList(testChain); given(op1.getInput()).willReturn(null); - given(cache.getNamedOperation(opName, user)).willReturn(namedOpDetail); + given(cache.getNamedOperation(OP_NAME, user)).willReturn(namedOpDetail); given(namedOpDetail.getOperationChain(null)).willReturn(testChain); + given(context.getUser()).willReturn(user); final OperationChain opChain = new OperationChain.Builder() .first(new NamedOperation.Builder<>() - .name(opName) + .name(OP_NAME) .input(input) .build()) .build(); // When - resolver.preExecute(opChain, new Context(user)); + resolver.preExecute(opChain, context); // Then assertThat(opChain.getOperations()).isEqualTo(expectedResolvedChain); @@ -98,14 +101,14 @@ void shouldResolveNamedOperation(@Mock final User user, @SuppressWarnings({"unchecked", "rawtypes"}) @Test void shouldResolveNestedNamedOperation(@Mock final User user, + @Mock final Context context, @Mock final NamedOperationCache cache, @Mock final NamedOperationDetail namedOpDetail, @Mock final GetAdjacentIds op1, @Mock final GetElements op2, @Mock final Iterable input) - throws OperationException, CacheOperationException { + throws CacheOperationException { // Given - final String opName = "opName"; final NamedOperationResolver resolver = new NamedOperationResolver(cache); final OperationChain namedOperationOpChain = new OperationChain(Arrays.asList(op1, op2)); @@ -113,20 +116,21 @@ void shouldResolveNestedNamedOperation(@Mock final User user, final Map params = null; given(op1.getInput()).willReturn(null); - given(cache.getNamedOperation(opName, user)).willReturn(namedOpDetail); + given(cache.getNamedOperation(OP_NAME, user)).willReturn(namedOpDetail); given(namedOpDetail.getOperationChain(params)).willReturn(namedOperationOpChain); + given(context.getUser()).willReturn(user); final OperationChain opChain = new OperationChain.Builder() .first(new OperationChain.Builder() .first(new NamedOperation.Builder<>() - .name(opName) + .name(OP_NAME) .input(input) .build()) .build()) .build(); // When - resolver.preExecute(opChain, new Context(user)); + resolver.preExecute(opChain, context); // Then assertThat(opChain.getOperations()).hasSize(1); @@ -141,6 +145,7 @@ void shouldResolveNestedNamedOperation(@Mock final User user, @Test void shouldFailToResolveNestedNamedOperationsOverDefaultLimit( @Mock final User user, + @Mock final Context context, @Mock final NamedOperationCache cache, @Mock final NamedOperationDetail namedOp1Detail, @Mock final NamedOperationDetail namedOp2Detail, @@ -156,6 +161,7 @@ void shouldFailToResolveNestedNamedOperationsOverDefaultLimit( final String namedOp4Name = "namedOp4"; final NamedOperationResolver resolver = new NamedOperationResolver(cache); + given(context.getUser()).willReturn(user); // Setup cache returns (we can ignore named op 4 as it wont be used due to the depth limit) given(cache.getNamedOperation(namedOp1Name, user)).willReturn(namedOp1Detail); given(cache.getNamedOperation(namedOp2Name, user)).willReturn(namedOp2Detail); @@ -201,7 +207,7 @@ void shouldFailToResolveNestedNamedOperationsOverDefaultLimit( .build(); // When assertThatExceptionOfType(GafferRuntimeException.class) - .isThrownBy(() -> resolver.preExecute(opChain, new Context(user))) + .isThrownBy(() -> resolver.preExecute(opChain, context)) .withMessageContaining("NamedOperation Resolver hit nested depth limit"); } @@ -209,6 +215,7 @@ void shouldFailToResolveNestedNamedOperationsOverDefaultLimit( @Test void shouldAllowConfigurableResolverDepthLimit( @Mock final User user, + @Mock final Context context, @Mock final NamedOperationCache cache, @Mock final NamedOperationDetail namedOp1Detail, @Mock final NamedOperationDetail namedOp2Detail, @@ -223,6 +230,7 @@ void shouldAllowConfigurableResolverDepthLimit( final String namedOp3Name = "namedOp3"; // Make a resolver with a stricter depth limit final NamedOperationResolver resolverStrict = new NamedOperationResolver(cache, 2); + given(context.getUser()).willReturn(user); // Setup cache returns given(cache.getNamedOperation(namedOp1Name, user)).willReturn(namedOp1Detail); @@ -261,40 +269,40 @@ void shouldAllowConfigurableResolverDepthLimit( // When resolved using the stricter limit it should fail to resolve the chain assertThatExceptionOfType(GafferRuntimeException.class) - .isThrownBy(() -> resolverStrict.preExecute(opChainStrict, new Context(user))) + .isThrownBy(() -> resolverStrict.preExecute(opChainStrict, context)) .withMessageContaining("NamedOperation Resolver hit nested depth limit"); } - @SuppressWarnings({"unchecked", "rawtypes"}) @Test void shouldExecuteNamedOperationWithoutOverridingInput(@Mock final User user, + @Mock final Context context, @Mock final NamedOperationCache cache, @Mock final NamedOperationDetail namedOpDetail, @Mock final GetAdjacentIds op1, @Mock final GetElements op2, @Mock final Iterable input, @Mock final Iterable mockIterable) - throws OperationException, CacheOperationException { + throws CacheOperationException { // Given - final String opName = "opName"; final NamedOperationResolver resolver = new NamedOperationResolver(cache); final OperationChain namedOpChain = new OperationChain(Arrays.asList(op1, op2)); final Map params = null; given(op1.getInput()).willReturn(mockIterable); - given(cache.getNamedOperation(opName, user)).willReturn(namedOpDetail); + given(cache.getNamedOperation(OP_NAME, user)).willReturn(namedOpDetail); given(namedOpDetail.getOperationChain(params)).willReturn(namedOpChain); + given(context.getUser()).willReturn(user); // When final OperationChain opChain = new OperationChain.Builder() .first(new NamedOperation.Builder<>() - .name(opName) + .name(OP_NAME) .input(input) .build()) .build(); - resolver.preExecute(opChain, new Context(user)); + resolver.preExecute(opChain, context); // Then assertThat(opChain.getOperations().get(0)).isSameAs(namedOpChain); @@ -305,173 +313,128 @@ void shouldExecuteNamedOperationWithoutOverridingInput(@Mock final User user, @SuppressWarnings({ "rawtypes" }) @Test void shouldResolveNamedOperationWithParameter(@Mock final User user, - @Mock final NamedOperationCache cache) - throws OperationException, CacheOperationException { + @Mock final Context context, + @Mock final NamedOperationCache cache) + throws CacheOperationException { // Given - final String opName = "opName"; final NamedOperationResolver resolver = new NamedOperationResolver(cache); final Map paramMap = new HashMap<>(); paramMap.put("param1", 1L); - final ParameterDetail param = new ParameterDetail.Builder() - .defaultValue(1L) - .description("Limit param") - .valueClass(Long.class) - .build(); - final Map paramDetailMap = new HashMap<>(); - paramDetailMap.put("param1", param); - // Make a real NamedOperationDetail with a parameter - final NamedOperationDetail namedOpDetail = new NamedOperationDetail.Builder() - .operationName(opName) - .description("standard operation") - .operationChain("{ \"operations\": [ { \"class\":\"uk.gov.gchq.gaffer.operation.impl.get.GetAllElements\" }, " - + "{ \"class\":\"uk.gov.gchq.gaffer.operation.impl.Limit\", \"resultLimit\": \"${param1}\" } ] }") - .parameters(paramDetailMap) - .build(); + final NamedOperationDetail namedOpDetail = getValidNamedOperation(); - given(cache.getNamedOperation(opName, user)).willReturn(namedOpDetail); + given(cache.getNamedOperation(OP_NAME, user)).willReturn(namedOpDetail); + given(context.getUser()).willReturn(user); final OperationChain opChain = new OperationChain.Builder() .first(new NamedOperation.Builder<>() - .name(opName) + .name(OP_NAME) .parameters(paramMap) .build()) .build(); // When - resolver.preExecute(opChain, new Context(user)); + resolver.preExecute(opChain, context); // Then - assertThat(opChain.getOperations().get(0)) - .isInstanceOf(OperationChain.class); + assertThat(opChain.getOperations().get(0)).isInstanceOf(OperationChain.class); assertThat(((OperationChain) opChain.getOperations().get(0)).getOperations().get(0)).isInstanceOf(GetAllElements.class); assertThat(((OperationChain) opChain.getOperations().get(0)).getOperations().get(1)).isInstanceOf(Limit.class); // Check the parameter has been inserted - assertThat(((Limit) ((OperationChain) opChain.getOperations().get(0)).getOperations().get(1)).getResultLimit()).isEqualTo(1L); + assertThat(((Limit) ((OperationChain) opChain.getOperations().get(0)).getOperations().get(1)).getResultLimit()).isEqualTo(1); } @Test void shouldNotExecuteNamedOperationWithParameterOfWrongType(@Mock final User user, + @Mock final Context context, @Mock final NamedOperationCache cache) - throws OperationException, CacheOperationException { + throws CacheOperationException { // Given - final String opName = "opName"; final NamedOperationResolver resolver = new NamedOperationResolver(cache); + + // Create Named Op with param of wrong type final Map paramMap = new HashMap<>(); - // A parameter of the wrong type paramMap.put("param1", new ArrayList<>()); - final ParameterDetail param = new ParameterDetail.Builder() - .defaultValue(1L) - .description("Limit param") - .valueClass(Long.class) - .build(); - final Map paramDetailMap = new HashMap<>(); - paramDetailMap.put("param1", param); + final OperationChain wrongParamTypeNamedOp = new OperationChain.Builder() + .first(new NamedOperation.Builder<>() + .name(OP_NAME) + .parameters(paramMap) + .build()) + .build(); // Make a real NamedOperationDetail with a parameter - final NamedOperationDetail namedOpDetail = new NamedOperationDetail.Builder() - .operationName(opName) - .description("standard operation") - .operationChain("{ \"operations\": [ { \"class\":\"uk.gov.gchq.gaffer.operation.impl.get.GetAllElements\" }, " - + "{ \"class\":\"uk.gov.gchq.gaffer.operation.impl.Limit\", \"resultLimit\": \"${param1}\" } ] }") - .parameters(paramDetailMap) - .build(); + final NamedOperationDetail namedOpDetail = getValidNamedOperation(); - given(cache.getNamedOperation(opName, user)).willReturn(namedOpDetail); + given(cache.getNamedOperation(OP_NAME, user)).willReturn(namedOpDetail); + given(context.getUser()).willReturn(user); // When assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> resolver.preExecute(new OperationChain.Builder() - .first(new NamedOperation.Builder<>() - .name(opName) - .parameters(paramMap) - .build()) - .build(), new Context(user))) + .isThrownBy(() -> resolver.preExecute(wrongParamTypeNamedOp, context)) .withMessageContaining("Cannot deserialize value of type"); } @Test void shouldNotExecuteNamedOperationWithWrongParameterName(@Mock final User user, + @Mock final Context context, @Mock final NamedOperationCache cache) - throws OperationException, CacheOperationException { + throws CacheOperationException { // Given - final String opName = "opName"; final NamedOperationResolver resolver = new NamedOperationResolver(cache); - final Map paramMap = new HashMap<>(); + // A parameter with the wrong name + final Map paramMap = new HashMap<>(); paramMap.put("param2", 1L); - final ParameterDetail param = new ParameterDetail.Builder() - .defaultValue(1L) - .description("Limit param") - .valueClass(Long.class) - .build(); - final Map paramDetailMap = new HashMap<>(); - paramDetailMap.put("param1", param); + final OperationChain wrongParamNameNamedOp = new OperationChain.Builder() + .first(new NamedOperation.Builder<>() + .name(OP_NAME) + .parameters(paramMap) + .build()) + .build(); // Make a real NamedOperationDetail with a parameter - final NamedOperationDetail namedOpDetail = new NamedOperationDetail.Builder() - .operationName(opName) - .description("standard operation") - .operationChain("{ \"operations\": [ { \"class\":\"uk.gov.gchq.gaffer.operation.impl.get.GetAllElements\" }, " - + "{ \"class\":\"uk.gov.gchq.gaffer.operation.impl.Limit\", \"resultLimit\": \"${param1}\" } ] }") - .parameters(paramDetailMap) - .build(); + final NamedOperationDetail namedOpDetail = getValidNamedOperation(); - given(cache.getNamedOperation(opName, user)).willReturn(namedOpDetail); + given(cache.getNamedOperation(OP_NAME, user)).willReturn(namedOpDetail); + given(context.getUser()).willReturn(user); // When assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> resolver.preExecute(new OperationChain.Builder() - .first(new NamedOperation.Builder<>() - .name(opName) - .parameters(paramMap) - .build()) - .build(), new Context(user))) + .isThrownBy(() -> resolver.preExecute(wrongParamNameNamedOp, context)) .withMessageContaining("Unexpected parameter name in NamedOperation"); } @Test void shouldNotExecuteNamedOperationWithMissingRequiredArg(@Mock final User user, + @Mock final Context context, @Mock final NamedOperationCache cache) - throws OperationException, CacheOperationException { + throws CacheOperationException { // Given - final String opName = "opName"; final NamedOperationResolver resolver = new NamedOperationResolver(cache); // Don't set any parameters final Map paramMap = new HashMap<>(); - final ParameterDetail param = new ParameterDetail.Builder() - .description("Limit param") - .valueClass(Long.class) - .required(true) - .build(); - final Map paramDetailMap = new HashMap<>(); - paramDetailMap.put("param1", param); + final OperationChain badParamNamedOp = new OperationChain.Builder() + .first(new NamedOperation.Builder<>() + .name(OP_NAME) + .parameters(paramMap) + .build()) + .build(); // Make a real NamedOperationDetail with a parameter - final NamedOperationDetail namedOpDetail = new NamedOperationDetail.Builder() - .operationName(opName) - .description("standard operation") - .operationChain("{ \"operations\": [ { \"class\":\"uk.gov.gchq.gaffer.operation.impl.get.GetAllElements\" }, " - + "{ \"class\":\"uk.gov.gchq.gaffer.operation.impl.Limit\", \"resultLimit\": \"${param1}\" } ] }") - .parameters(paramDetailMap) - .build(); + final NamedOperationDetail namedOpDetail = getValidNamedOperation(); - given(cache.getNamedOperation(opName, user)).willReturn(namedOpDetail); + given(cache.getNamedOperation(OP_NAME, user)).willReturn(namedOpDetail); + given(context.getUser()).willReturn(user); // When assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> resolver.preExecute(new OperationChain.Builder() - .first(new NamedOperation.Builder<>() - .name(opName) - .parameters(paramMap) - .build()) - .build(), new Context(user))) + .isThrownBy(() -> resolver.preExecute(badParamNamedOp, context)) .withMessageContaining("Missing parameter param1 with no default"); } @@ -499,4 +462,31 @@ void shouldReturnOperationsInParameters() { public NamedOperationResolver getTestObject() { return new NamedOperationResolver(SUFFIX_CACHE_NAME); } + + private NamedOperationDetail getValidNamedOperation() { + final ParameterDetail param = new ParameterDetail.Builder() + .description("Limit param") + .valueClass(Long.class) + .required(true) + .build(); + final Map paramDetailMap = new HashMap<>(); + paramDetailMap.put("param1", param); + + final String opChainString = new JSONObject() + .put("operations", new JSONArray() + .put(new JSONObject() + .put("class", "uk.gov.gchq.gaffer.operation.impl.get.GetAllElements")) + .put(new JSONObject() + .put("class", "uk.gov.gchq.gaffer.operation.impl.Limit") + .put("resultLimit", "${param1}"))) + .toString(); + + // Make a real NamedOperationDetail with a parameter + return new NamedOperationDetail.Builder() + .operationName(OP_NAME) + .description("standard operation") + .operationChain(opChainString) + .parameters(paramDetailMap) + .build(); + } } diff --git a/core/store/src/test/java/uk/gov/gchq/gaffer/store/operation/DeleteAllDataTest.java b/core/store/src/test/java/uk/gov/gchq/gaffer/store/operation/DeleteAllDataTest.java index 5be04c7ed42..743378afae7 100644 --- a/core/store/src/test/java/uk/gov/gchq/gaffer/store/operation/DeleteAllDataTest.java +++ b/core/store/src/test/java/uk/gov/gchq/gaffer/store/operation/DeleteAllDataTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2022 Crown Copyright + * Copyright 2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,24 +16,28 @@ package uk.gov.gchq.gaffer.store.operation; +import org.junit.jupiter.api.Test; + import uk.gov.gchq.gaffer.operation.OperationTest; import static org.assertj.core.api.Assertions.assertThat; public class DeleteAllDataTest extends OperationTest { - + @Test @Override public void builderShouldCreatePopulatedOperation() { final DeleteAllData operation = new DeleteAllData.Builder().option("a", "1").build(); - assertThat(operation.getOption("a")).isEqualTo(1); + assertThat(operation.getOption("a")).isEqualTo("1"); } + @Test @Override public void shouldShallowCloneOperation() { final DeleteAllData a = new DeleteAllData(); final DeleteAllData b = a.shallowClone(); - assertThat(a).isNotSameAs(b).isEqualTo(b); + assertThat(a).isNotEqualTo(b); + assertThat(b).isInstanceOf(DeleteAllData.class); } @Override diff --git a/core/type/src/test/java/uk/gov/gchq/gaffer/serialisation/CustomMapSerialiserTest.java b/core/type/src/test/java/uk/gov/gchq/gaffer/serialisation/CustomMapSerialiserTest.java index 5cb1eeefab2..483e904e319 100644 --- a/core/type/src/test/java/uk/gov/gchq/gaffer/serialisation/CustomMapSerialiserTest.java +++ b/core/type/src/test/java/uk/gov/gchq/gaffer/serialisation/CustomMapSerialiserTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2020 Crown Copyright + * Copyright 2017-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,12 +25,12 @@ import uk.gov.gchq.gaffer.serialisation.implementation.ordered.OrderedIntegerSerialiser; import uk.gov.gchq.gaffer.types.CustomMap; -import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; -public class CustomMapSerialiserTest extends ToBytesSerialisationTest { +class CustomMapSerialiserTest extends ToBytesSerialisationTest { @Test - public void shouldSerialiseStringInt() throws SerialisationException { + void shouldSerialiseStringInt() throws SerialisationException { // Given final CustomMap expected = new CustomMap<>(new StringSerialiser(), new OrderedIntegerSerialiser()); expected.put("one", 111); @@ -40,38 +40,47 @@ public void shouldSerialiseStringInt() throws SerialisationException { final CustomMap deserialise = serialiser.deserialise(serialiser.serialise(expected)); // Then + if (deserialise.equals(expected)) { + return; + } detailedEquals(expected, deserialise, String.class, Integer.class, new StringSerialiser(), new OrderedIntegerSerialiser()); } - private void detailedEquals(final CustomMap expected, final CustomMap actual, final Class expectedKClass, final Class expectedVClass, final ToBytesSerialiser kS, final ToBytesSerialiser vS) { - try { - assertEquals(expected, actual); - } catch (AssertionError e) { - //Serialiser - assertEquals(kS, expected.getKeySerialiser()); - assertEquals(kS, actual.getKeySerialiser()); - assertEquals(vS, expected.getValueSerialiser()); - assertEquals(vS, actual.getValueSerialiser()); - assertEquals(expected.getKeySerialiser(), actual.getKeySerialiser()); - //Key element - assertEquals(expectedKClass, expected.keySet().iterator().next().getClass()); - assertEquals(expectedKClass, actual.keySet().iterator().next().getClass()); - //Value element - assertEquals(expectedVClass, expected.values().iterator().next().getClass()); - assertEquals(expectedVClass, actual.values().iterator().next().getClass()); - //ketSets - assertEquals(expected.keySet(), actual.keySet()); - //values - for (Object k : expected.keySet()) { - final Object expectedV = expected.get(k); - final Object actualV = actual.get(k); - assertEquals(expectedV.getClass(), actualV.getClass()); - assertEquals(expectedVClass, actualV.getClass()); - assertEquals(expectedVClass, expectedV.getClass()); - assertEquals(expectedV, actualV); - } - assertEquals(expected, actual); + private void detailedEquals(final CustomMap expected, + final CustomMap actual, + final Class expectedKClass, + final Class expectedVClass, + final ToBytesSerialiser kS, + final ToBytesSerialiser vS) { + + // Serialiser + assertThat(expected.getKeySerialiser()).isEqualTo(kS); + assertThat(actual.getKeySerialiser()).isEqualTo(kS); + assertThat(expected.getValueSerialiser()).isEqualTo(vS); + assertThat(actual.getValueSerialiser()).isEqualTo(vS); + assertThat(actual.getKeySerialiser()).isEqualTo(expected.getKeySerialiser()); + + // Key element + assertThat(expected.keySet().iterator().next().getClass()).isEqualTo(expectedKClass); + assertThat(actual.keySet().iterator().next().getClass()).isEqualTo(expectedKClass); + + // Value element + assertThat(expected.values().iterator().next().getClass()).isEqualTo(expectedVClass); + assertThat(actual.values().iterator().next().getClass()).isEqualTo(expectedVClass); + + // keySets + assertThat(actual.keySet()).isEqualTo(expected.keySet()); + + //values + for (Object k : expected.keySet()) { + final Object expectedV = expected.get(k); + final Object actualV = actual.get(k); + assertThat(actualV.getClass()).isEqualTo(expectedV.getClass()); + assertThat(actualV.getClass()).isEqualTo(expectedVClass); + assertThat(expectedV.getClass()).isEqualTo(expectedVClass); + assertThat(actualV).isEqualTo(expectedV); } + assertThat(actual).isEqualTo(expected); } @Override @@ -81,7 +90,7 @@ public Serialiser getSerialisation() { @Override public Pair[] getHistoricSerialisationPairs() { - final CustomMap cm1 = new CustomMap(new StringSerialiser(), new OrderedIntegerSerialiser()); + final CustomMap cm1 = new CustomMap<>(new StringSerialiser(), new OrderedIntegerSerialiser()); cm1.put("One", 1); final CustomMap cm2 = new CustomMap<>(new OrderedFloatSerialiser(), new StringSerialiser()); diff --git a/library/cache-library/jcs-cache-service/src/test/java/uk/gov/gchq/gaffer/cache/impl/JcsCacheTest.java b/library/cache-library/jcs-cache-service/src/test/java/uk/gov/gchq/gaffer/cache/impl/JcsCacheTest.java index 11a802991ec..a48b99990c0 100644 --- a/library/cache-library/jcs-cache-service/src/test/java/uk/gov/gchq/gaffer/cache/impl/JcsCacheTest.java +++ b/library/cache-library/jcs-cache-service/src/test/java/uk/gov/gchq/gaffer/cache/impl/JcsCacheTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 Crown Copyright + * Copyright 2017-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,38 +27,36 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.fail; -public class JcsCacheTest { +class JcsCacheTest { private static JcsCache cache; @BeforeAll - public static void setUp() throws CacheException { + static void setUp() throws CacheException { CompositeCacheManager manager = CompositeCacheManager.getInstance(); cache = new JcsCache<>(manager.getCache("test")); } @BeforeEach - public void before() throws CacheOperationException { + void before() throws CacheOperationException { cache.clear(); } @Test - public void shouldThrowAnExceptionIfEntryAlreadyExistsWhenUsingPutSafe() { - try { - cache.put("test", 1); - cache.putSafe("test", 1); - fail(); - } catch (final OverwritingException | CacheOperationException e) { - assertEquals("Cache entry already exists for key: test", e.getMessage()); - } + void shouldThrowAnExceptionIfEntryAlreadyExistsWhenUsingPutSafe() throws CacheOperationException { + // given + cache.put("test", 1); + + // then + assertThatExceptionOfType(OverwritingException.class) + .isThrownBy(() -> cache.putSafe("test", 1)) + .withMessage("Cache entry already exists for key: test"); } @Test - public void shouldThrowExceptionWhenAddingNullKeyToCache() { + void shouldThrowExceptionWhenAddingNullKeyToCache() { assertThatExceptionOfType(CacheOperationException.class) .isThrownBy(() -> cache.put(null, 2)) .extracting("message") @@ -66,7 +64,7 @@ public void shouldThrowExceptionWhenAddingNullKeyToCache() { } @Test - public void shouldThrowExceptionIfAddingNullValue() { + void shouldThrowExceptionIfAddingNullValue() { assertThatExceptionOfType(CacheOperationException.class) .isThrownBy(() -> cache.put("test", null)) .extracting("message") @@ -74,7 +72,7 @@ public void shouldThrowExceptionIfAddingNullValue() { } @Test - public void shouldAddToCache() throws CacheOperationException { + void shouldAddToCache() throws CacheOperationException { // when cache.put("key", 1); @@ -84,17 +82,17 @@ public void shouldAddToCache() throws CacheOperationException { } @Test - public void shouldReadFromCache() throws CacheOperationException { + void shouldReadFromCache() throws CacheOperationException { // when cache.put("key", 2); // then - assertEquals(new Integer(2), cache.get("key")); + assertThat(cache.get("key")).isEqualTo(2); } @Test - public void shouldDeleteCachedEntries() throws CacheOperationException { + void shouldDeleteCachedEntries() throws CacheOperationException { // given cache.put("key", 3); @@ -107,7 +105,7 @@ public void shouldDeleteCachedEntries() throws CacheOperationException { } @Test - public void shouldUpdateCachedEntries() throws CacheOperationException { + void shouldUpdateCachedEntries() throws CacheOperationException { // given cache.put("key", 4); @@ -117,11 +115,11 @@ public void shouldUpdateCachedEntries() throws CacheOperationException { // then assertThat(cache.size()).isOne(); - assertEquals(new Integer(5), cache.get("key")); + assertThat(cache.get("key")).isEqualTo(5); } @Test - public void shouldRemoveAllEntries() throws CacheOperationException { + void shouldRemoveAllEntries() throws CacheOperationException { // given cache.put("key1", 1); @@ -136,7 +134,7 @@ public void shouldRemoveAllEntries() throws CacheOperationException { } @Test - public void shouldGetAllKeys() throws CacheOperationException { + void shouldGetAllKeys() throws CacheOperationException { cache.put("test1", 1); cache.put("test2", 2); cache.put("test3", 3); @@ -146,14 +144,14 @@ public void shouldGetAllKeys() throws CacheOperationException { } @Test - public void shouldGetAllValues() throws CacheOperationException { + void shouldGetAllValues() throws CacheOperationException { cache.put("test1", 1); cache.put("test2", 2); cache.put("test3", 3); cache.put("duplicate", 3); assertThat(cache.size()).isEqualTo(4); - assertEquals(4, cache.getAllValues().size()); + assertThat(cache.getAllValues()).hasSize(4); assertThat(cache.getAllValues()).contains(1, 2, 3); } diff --git a/library/hdfs-library/src/test/java/uk/gov/gchq/gaffer/hdfs/integration/loader/AddElementsFromHdfsLoaderIT.java b/library/hdfs-library/src/test/java/uk/gov/gchq/gaffer/hdfs/integration/loader/AddElementsFromHdfsLoaderIT.java index 7b287789051..db339935b0d 100644 --- a/library/hdfs-library/src/test/java/uk/gov/gchq/gaffer/hdfs/integration/loader/AddElementsFromHdfsLoaderIT.java +++ b/library/hdfs-library/src/test/java/uk/gov/gchq/gaffer/hdfs/integration/loader/AddElementsFromHdfsLoaderIT.java @@ -1,5 +1,5 @@ /* - * Copyright 2018-2022 Crown Copyright + * Copyright 2018-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -89,7 +89,7 @@ public BasicSchemaAddElementsLoaderIT() { } } - private static class AddElementsFromHdfsLoader extends UserLoaderIT { + static class AddElementsFromHdfsLoader extends UserLoaderIT { @TempDir public File testFolder; @@ -133,7 +133,7 @@ public void _setup() throws Exception { } @Test - public void shouldThrowExceptionWhenAddElementsFromHdfsWhenFailureDirectoryContainsFiles(final TestInfo testInfo) throws Exception { + void shouldThrowExceptionWhenAddElementsFromHdfsWhenFailureDirectoryContainsFiles(final TestInfo testInfo) throws Exception { tearDown(); fs.mkdirs(new Path(failureDir)); try (final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fs.create(new Path(failureDir + "/someFile.txt"), true)))) { @@ -146,7 +146,7 @@ public void shouldThrowExceptionWhenAddElementsFromHdfsWhenFailureDirectoryConta } @Test - public void shouldAddElementsFromHdfsWhenDirectoriesAlreadyExist(TestInfo testInfo) throws Exception { + void shouldAddElementsFromHdfsWhenDirectoriesAlreadyExist(TestInfo testInfo) throws Exception { // Given tearDown(); fs.mkdirs(new Path(outputDir)); @@ -160,7 +160,7 @@ public void shouldAddElementsFromHdfsWhenDirectoriesAlreadyExist(TestInfo testIn } @Test - public void shouldThrowExceptionWhenAddElementsFromHdfsWhenOutputDirectoryContainsFiles(final TestInfo testInfo) throws Exception { + void shouldThrowExceptionWhenAddElementsFromHdfsWhenOutputDirectoryContainsFiles(final TestInfo testInfo) throws Exception { // Given tearDown(); fs.mkdirs(new Path(outputDir)); diff --git a/library/time-library/src/test/java/uk/gov/gchq/gaffer/time/serialisation/RBMBackedTimestampSetSerialiserTest.java b/library/time-library/src/test/java/uk/gov/gchq/gaffer/time/serialisation/RBMBackedTimestampSetSerialiserTest.java index b5a403c2ab5..c92a7506a83 100644 --- a/library/time-library/src/test/java/uk/gov/gchq/gaffer/time/serialisation/RBMBackedTimestampSetSerialiserTest.java +++ b/library/time-library/src/test/java/uk/gov/gchq/gaffer/time/serialisation/RBMBackedTimestampSetSerialiserTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2023 Crown Copyright + * Copyright 2017-2024 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,14 +43,13 @@ import java.util.Random; import java.util.stream.IntStream; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; -public class RBMBackedTimestampSetSerialiserTest extends ToBytesSerialisationTest { +class RBMBackedTimestampSetSerialiserTest extends ToBytesSerialisationTest { @Test - public void testSerialiser() throws SerialisationException { + void testSerialiser() throws SerialisationException { // Given final RBMBackedTimestampSet rbmBackedTimestampSet = getExampleValue(); @@ -59,7 +58,7 @@ public void testSerialiser() throws SerialisationException { final RBMBackedTimestampSet deserialised = serialiser.deserialise(serialised); // Then - assertEquals(rbmBackedTimestampSet, deserialised); + assertThat(deserialised).isEqualTo(rbmBackedTimestampSet); } private RBMBackedTimestampSet getExampleValue() { @@ -70,13 +69,13 @@ private RBMBackedTimestampSet getExampleValue() { } @Test - public void testCanHandle() throws SerialisationException { - assertTrue(serialiser.canHandle(RBMBackedTimestampSet.class)); - assertFalse(serialiser.canHandle(String.class)); + void testCanHandle() { + assertThat(serialiser.canHandle(RBMBackedTimestampSet.class)).isTrue(); + assertThat(serialiser.canHandle(String.class)).isFalse(); } @Test - public void testSerialisationSizesQuotedInJavadoc() throws SerialisationException { + void testSerialisationSizesQuotedInJavadoc() throws SerialisationException { // Given final Random random = new Random(123456789L); final Instant instant = ZonedDateTime.of(2017, 1, 1, 1, 1, 1, 0, ZoneId.of("UTC")).toInstant(); @@ -99,13 +98,13 @@ public void testSerialisationSizesQuotedInJavadoc() throws SerialisationExceptio final int lengthSet3 = serialiser.serialise(rbmBackedTimestampSet3).length; // Then - assertTrue(200 < lengthSet1 && lengthSet1 < 220); - assertTrue(72000 < lengthSet2 && lengthSet2 < 74000); - assertTrue(3900000 < lengthSet3 && lengthSet3 < 4100000); + assertThat(lengthSet1).isBetween(200, 220); + assertThat(lengthSet2).isBetween(72000, 74000); + assertThat(lengthSet3).isBetween(3900000, 4100000); } @Test - public void shouldSerialiserStringRBMBackedTimestampSet() throws SerialisationException { + void shouldSerialiserStringRBMBackedTimestampSet() throws SerialisationException { // Given final Serialiser customMapSerialiser = new CustomMapSerialiser(); final RBMBackedTimestampSet timestampSet1 = new RBMBackedTimestampSet.Builder() @@ -126,43 +125,48 @@ public void shouldSerialiserStringRBMBackedTimestampSet() throws SerialisationEx // When final CustomMap deserialise = customMapSerialiser.deserialise(customMapSerialiser.serialise(expected)); + // Then detailedEquals(expected, deserialise, String.class, RBMBackedTimestampSet.class, new StringSerialiser(), new RBMBackedTimestampSetSerialiser()); } private void detailedEquals(final CustomMap expected, final CustomMap actual, final Class expectedKClass, final Class expectedVClass, final ToBytesSerialiser kS, final ToBytesSerialiser vS) { - try { - assertEquals(expected, actual); - } catch (AssertionError e) { - //Serialiser - assertEquals(kS, expected.getKeySerialiser()); - assertEquals(kS, actual.getKeySerialiser()); - assertEquals(vS, expected.getValueSerialiser()); - assertEquals(vS, actual.getValueSerialiser()); - assertEquals(expected.getKeySerialiser(), actual.getKeySerialiser()); - //Key element - assertEquals(expectedKClass, expected.keySet().iterator().next().getClass()); - assertEquals(expectedKClass, actual.keySet().iterator().next().getClass()); - //Value element - assertEquals(expectedVClass, expected.values().iterator().next().getClass()); - assertEquals(expectedVClass, actual.values().iterator().next().getClass()); - //ketSets - assertEquals(expected.keySet(), actual.keySet()); + Throwable thrown = catchThrowable(() -> assertThat(actual).isEqualTo(expected)); + + if (thrown != null) { + // Serialiser + assertThat(expected.getKeySerialiser()).isEqualTo(kS); + assertThat(actual.getKeySerialiser()).isEqualTo(kS); + assertThat(expected.getValueSerialiser()).isEqualTo(vS); + assertThat(actual.getValueSerialiser()).isEqualTo(vS); + assertThat(actual.getKeySerialiser()).isEqualTo(expected.getKeySerialiser()); + + // Key element + assertThat(expected.keySet().iterator().next().getClass()).isEqualTo(expectedKClass); + assertThat(actual.keySet().iterator().next().getClass()).isEqualTo(expectedKClass); + + // Value element + assertThat(expected.values().iterator().next().getClass()).isEqualTo(expectedVClass); + assertThat(actual.values().iterator().next().getClass()).isEqualTo(expectedVClass); + + // keySets + assertThat(actual.keySet()).isEqualTo(expected.keySet()); + //values for (Object k : expected.keySet()) { final Object expectedV = expected.get(k); final Object actualV = actual.get(k); - assertEquals(expectedV.getClass(), actualV.getClass()); - assertEquals(expectedVClass, actualV.getClass()); - assertEquals(expectedVClass, expectedV.getClass()); - assertEquals(expectedV, actualV); + assertThat(actualV.getClass()).isEqualTo(expectedV.getClass()); + assertThat(actualV.getClass()).isEqualTo(expectedVClass); + assertThat(expectedV.getClass()).isEqualTo(expectedVClass); + assertThat(actualV).isEqualTo(expectedV); } - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } } @Test - public void shouldJSONSerialiseFloatRDM() throws IOException { + void shouldJSONSerialiseFloatRDM() throws IOException { //given System.setProperty(JSONSerialiser.JSON_SERIALISER_MODULES, BitmapJsonModules.class.getCanonicalName()); @@ -188,8 +192,8 @@ public void shouldJSONSerialiseFloatRDM() throws IOException { final CustomMap deserialiseMap = JSONSerialiser.deserialise(serialise, CustomMap.class); //then - assertEquals(jsonMap, deserialiseMap, "The expected map from Json doesn't match"); - assertEquals(expectedMap, deserialiseMap, "The expected map doesn't match"); + assertThat(jsonMap).isEqualTo(expectedMap); + assertThat(deserialiseMap).isEqualTo(expectedMap); } protected String jsonFromFile(final String path) throws IOException {