NIFI-13167 Replaced Hamcrest Matchers with JUnit Matchers

This closes #8764

- Removed Hamcrest from set of default dependencies

Signed-off-by: Joseph Witt <joewitt@apache.org>
This commit is contained in:
exceptionfactory 2024-05-07 11:35:31 -05:00 committed by Joseph Witt
parent b259e2ae73
commit 09cf383f9b
No known key found for this signature in database
GPG Key ID: 9093BF854F811A1A
37 changed files with 282 additions and 545 deletions

View File

@ -41,6 +41,12 @@ limitations under the License.
<artifactId>docker-compose-junit-jupiter</artifactId> <artifactId>docker-compose-junit-jupiter</artifactId>
<version>2.3.0</version> <version>2.3.0</version>
<scope>test</scope> <scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.nifi.minifi</groupId> <groupId>org.apache.nifi.minifi</groupId>

View File

@ -45,7 +45,6 @@ import java.util.Calendar;
import java.util.Collections; import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
@ -56,8 +55,6 @@ import java.util.concurrent.TimeUnit;
import static java.lang.Double.NEGATIVE_INFINITY; import static java.lang.Double.NEGATIVE_INFINITY;
import static java.lang.Double.NaN; import static java.lang.Double.NaN;
import static java.lang.Double.POSITIVE_INFINITY; import static java.lang.Double.POSITIVE_INFINITY;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
@ -2177,18 +2174,6 @@ public class TestQuery {
verifyEquals("${literal('hello'):substring(0, 1):equals('h')}", attrs, true); verifyEquals("${literal('hello'):substring(0, 1):equals('h')}", attrs, true);
} }
@Test
public void testRandomFunction() {
final Map<String, String> attrs = Collections.emptyMap();
final Long negOne = -1L;
final HashSet<Long> results = new HashSet<>(100);
for (int i = 0; i < results.size(); i++) {
long result = (Long) getResult("${random()}", attrs).getValue();
assertThat("random", result, greaterThan(negOne));
assertTrue(results.add(result), "duplicate random");
}
}
QueryResult<?> getResult(String expr, Map<String, String> attrs) { QueryResult<?> getResult(String expr, Map<String, String> attrs) {
final Query query = Query.compile(expr); final Query query = Query.compile(expr);
return query.evaluate(new StandardEvaluationContext(attrs)); return query.evaluate(new StandardEvaluationContext(attrs));

View File

@ -26,9 +26,8 @@ import org.apache.nifi.util.TestRunners;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -61,104 +60,87 @@ public class TestAccumuloService {
@Test @Test
public void testServiceValidWithAuthTypePasswordAndInstanceZookeeperUserPasswordAreSet() throws InitializationException { public void testServiceValidWithAuthTypePasswordAndInstanceZookeeperUserPasswordAreSet() throws InitializationException {
//given
runner.addControllerService("accumulo-connector-service", accumuloService); runner.addControllerService("accumulo-connector-service", accumuloService);
runner.setProperty(accumuloService, AccumuloService.INSTANCE_NAME, INSTANCE); runner.setProperty(accumuloService, AccumuloService.INSTANCE_NAME, INSTANCE);
runner.setProperty(accumuloService, AccumuloService.ZOOKEEPER_QUORUM, ZOOKEEPER); runner.setProperty(accumuloService, AccumuloService.ZOOKEEPER_QUORUM, ZOOKEEPER);
runner.setProperty(accumuloService, AccumuloService.AUTHENTICATION_TYPE, PASSWORD); runner.setProperty(accumuloService, AccumuloService.AUTHENTICATION_TYPE, PASSWORD);
runner.setProperty(accumuloService, AccumuloService.ACCUMULO_USER, USER); runner.setProperty(accumuloService, AccumuloService.ACCUMULO_USER, USER);
runner.setProperty(accumuloService, AccumuloService.ACCUMULO_PASSWORD, PASSWORD); runner.setProperty(accumuloService, AccumuloService.ACCUMULO_PASSWORD, PASSWORD);
//when
//then
runner.assertValid(accumuloService); runner.assertValid(accumuloService);
} }
@Test @Test
public void testServiceNotValidWithInstanceMissing() throws InitializationException { public void testServiceNotValidWithInstanceMissing() throws InitializationException {
//given
runner.addControllerService("accumulo-connector-service", accumuloService); runner.addControllerService("accumulo-connector-service", accumuloService);
runner.setProperty(accumuloService, AccumuloService.ZOOKEEPER_QUORUM, ZOOKEEPER); runner.setProperty(accumuloService, AccumuloService.ZOOKEEPER_QUORUM, ZOOKEEPER);
//when
//then
assertServiceIsInvalidWithErrorMessage("Instance name must be supplied"); assertServiceIsInvalidWithErrorMessage("Instance name must be supplied");
} }
@Test @Test
public void testServiceNotValidWithZookeeperMissing() throws InitializationException { public void testServiceNotValidWithZookeeperMissing() throws InitializationException {
//given
runner.addControllerService("accumulo-connector-service", accumuloService); runner.addControllerService("accumulo-connector-service", accumuloService);
runner.setProperty(accumuloService, AccumuloService.INSTANCE_NAME, INSTANCE); runner.setProperty(accumuloService, AccumuloService.INSTANCE_NAME, INSTANCE);
//when
//then
assertServiceIsInvalidWithErrorMessage("Zookeepers must be supplied"); assertServiceIsInvalidWithErrorMessage("Zookeepers must be supplied");
} }
@Test @Test
public void testServiceNotValidWithAuthTypeNone() throws InitializationException { public void testServiceNotValidWithAuthTypeNone() throws InitializationException {
//given
runner.addControllerService("accumulo-connector-service", accumuloService); runner.addControllerService("accumulo-connector-service", accumuloService);
runner.setProperty(accumuloService, AccumuloService.INSTANCE_NAME, INSTANCE); runner.setProperty(accumuloService, AccumuloService.INSTANCE_NAME, INSTANCE);
runner.setProperty(accumuloService, AccumuloService.ZOOKEEPER_QUORUM, ZOOKEEPER); runner.setProperty(accumuloService, AccumuloService.ZOOKEEPER_QUORUM, ZOOKEEPER);
runner.setProperty(accumuloService, AccumuloService.AUTHENTICATION_TYPE, NONE); runner.setProperty(accumuloService, AccumuloService.AUTHENTICATION_TYPE, NONE);
//when
//then
assertServiceIsInvalidWithErrorMessage("Non supported Authentication type"); assertServiceIsInvalidWithErrorMessage("Non supported Authentication type");
} }
@Test @Test
public void testServiceNotValidWithAuthTypePasswordAndUserMissing() throws InitializationException { public void testServiceNotValidWithAuthTypePasswordAndUserMissing() throws InitializationException {
//given
runner.addControllerService("accumulo-connector-service", accumuloService); runner.addControllerService("accumulo-connector-service", accumuloService);
runner.setProperty(accumuloService, AccumuloService.INSTANCE_NAME, INSTANCE); runner.setProperty(accumuloService, AccumuloService.INSTANCE_NAME, INSTANCE);
runner.setProperty(accumuloService, AccumuloService.ZOOKEEPER_QUORUM, ZOOKEEPER); runner.setProperty(accumuloService, AccumuloService.ZOOKEEPER_QUORUM, ZOOKEEPER);
runner.setProperty(accumuloService, AccumuloService.AUTHENTICATION_TYPE, PASSWORD); runner.setProperty(accumuloService, AccumuloService.AUTHENTICATION_TYPE, PASSWORD);
runner.setProperty(accumuloService, AccumuloService.ACCUMULO_PASSWORD, PASSWORD); runner.setProperty(accumuloService, AccumuloService.ACCUMULO_PASSWORD, PASSWORD);
//when
//then
assertServiceIsInvalidWithErrorMessage("Accumulo user must be supplied"); assertServiceIsInvalidWithErrorMessage("Accumulo user must be supplied");
} }
@Test @Test
public void testServiceNotValidWithAuthTypePasswordAndPasswordMissing() throws InitializationException { public void testServiceNotValidWithAuthTypePasswordAndPasswordMissing() throws InitializationException {
//given
runner.addControllerService("accumulo-connector-service", accumuloService); runner.addControllerService("accumulo-connector-service", accumuloService);
runner.setProperty(accumuloService, AccumuloService.INSTANCE_NAME, INSTANCE); runner.setProperty(accumuloService, AccumuloService.INSTANCE_NAME, INSTANCE);
runner.setProperty(accumuloService, AccumuloService.ZOOKEEPER_QUORUM, ZOOKEEPER); runner.setProperty(accumuloService, AccumuloService.ZOOKEEPER_QUORUM, ZOOKEEPER);
runner.setProperty(accumuloService, AccumuloService.AUTHENTICATION_TYPE, PASSWORD); runner.setProperty(accumuloService, AccumuloService.AUTHENTICATION_TYPE, PASSWORD);
runner.setProperty(accumuloService, AccumuloService.ACCUMULO_USER, USER); runner.setProperty(accumuloService, AccumuloService.ACCUMULO_USER, USER);
//when
//then
assertServiceIsInvalidWithErrorMessage("Password must be supplied"); assertServiceIsInvalidWithErrorMessage("Password must be supplied");
} }
@Test @Test
public void testServiceNotValidWithAuthTypeKerberosAndKerberosPasswordAndCredentialServiceMissing() throws InitializationException { public void testServiceNotValidWithAuthTypeKerberosAndKerberosPasswordAndCredentialServiceMissing() throws InitializationException {
//given
runner.addControllerService("accumulo-connector-service", accumuloService); runner.addControllerService("accumulo-connector-service", accumuloService);
runner.setProperty(accumuloService, AccumuloService.INSTANCE_NAME, INSTANCE); runner.setProperty(accumuloService, AccumuloService.INSTANCE_NAME, INSTANCE);
runner.setProperty(accumuloService, AccumuloService.ZOOKEEPER_QUORUM, ZOOKEEPER); runner.setProperty(accumuloService, AccumuloService.ZOOKEEPER_QUORUM, ZOOKEEPER);
runner.setProperty(accumuloService, AccumuloService.AUTHENTICATION_TYPE, KERBEROS); runner.setProperty(accumuloService, AccumuloService.AUTHENTICATION_TYPE, KERBEROS);
//when
//then
assertServiceIsInvalidWithErrorMessage("Either Kerberos Password, Kerberos Credential Service, or Kerberos User Service must be set"); assertServiceIsInvalidWithErrorMessage("Either Kerberos Password, Kerberos Credential Service, or Kerberos User Service must be set");
} }
@Test @Test
public void testServiceNotValidWithAuthTypeKerberosAndKerberosPrincipalMissing() throws InitializationException { public void testServiceNotValidWithAuthTypeKerberosAndKerberosPrincipalMissing() throws InitializationException {
//given
runner.addControllerService("accumulo-connector-service", accumuloService); runner.addControllerService("accumulo-connector-service", accumuloService);
runner.setProperty(accumuloService, AccumuloService.INSTANCE_NAME, INSTANCE); runner.setProperty(accumuloService, AccumuloService.INSTANCE_NAME, INSTANCE);
runner.setProperty(accumuloService, AccumuloService.ZOOKEEPER_QUORUM, ZOOKEEPER); runner.setProperty(accumuloService, AccumuloService.ZOOKEEPER_QUORUM, ZOOKEEPER);
runner.setProperty(accumuloService, AccumuloService.AUTHENTICATION_TYPE, KERBEROS); runner.setProperty(accumuloService, AccumuloService.AUTHENTICATION_TYPE, KERBEROS);
runner.setProperty(accumuloService, AccumuloService.KERBEROS_PASSWORD, KERBEROS_PASSWORD); runner.setProperty(accumuloService, AccumuloService.KERBEROS_PASSWORD, KERBEROS_PASSWORD);
//when
//then
assertServiceIsInvalidWithErrorMessage("Kerberos Principal must be supplied"); assertServiceIsInvalidWithErrorMessage("Kerberos Principal must be supplied");
} }
@Test @Test
public void testServiceNotValidWithAuthTypeKerberosAndKerberosPasswordAndCredentialServiceSet() throws InitializationException { public void testServiceNotValidWithAuthTypeKerberosAndKerberosPasswordAndCredentialServiceSet() throws InitializationException {
//given
runner.addControllerService("accumulo-connector-service", accumuloService); runner.addControllerService("accumulo-connector-service", accumuloService);
runner.setProperty(accumuloService, AccumuloService.INSTANCE_NAME, INSTANCE); runner.setProperty(accumuloService, AccumuloService.INSTANCE_NAME, INSTANCE);
runner.setProperty(accumuloService, AccumuloService.ZOOKEEPER_QUORUM, ZOOKEEPER); runner.setProperty(accumuloService, AccumuloService.ZOOKEEPER_QUORUM, ZOOKEEPER);
@ -166,14 +148,12 @@ public class TestAccumuloService {
runner.setProperty(accumuloService, AccumuloService.KERBEROS_PASSWORD, KERBEROS_PASSWORD); runner.setProperty(accumuloService, AccumuloService.KERBEROS_PASSWORD, KERBEROS_PASSWORD);
runner.addControllerService("kerberos-credentials-service", credentialService); runner.addControllerService("kerberos-credentials-service", credentialService);
runner.setProperty(accumuloService, AccumuloService.KERBEROS_CREDENTIALS_SERVICE, credentialService.getIdentifier()); runner.setProperty(accumuloService, AccumuloService.KERBEROS_CREDENTIALS_SERVICE, credentialService.getIdentifier());
//when
//then
assertServiceIsInvalidWithErrorMessage("should not be filled out at the same time"); assertServiceIsInvalidWithErrorMessage("should not be filled out at the same time");
} }
@Test @Test
public void testServiceNotValidWithAuthTypeKerberosAndPrincipalAndCredentialServiceSet() throws InitializationException { public void testServiceNotValidWithAuthTypeKerberosAndPrincipalAndCredentialServiceSet() throws InitializationException {
//given
runner.addControllerService("accumulo-connector-service", accumuloService); runner.addControllerService("accumulo-connector-service", accumuloService);
runner.setProperty(accumuloService, AccumuloService.INSTANCE_NAME, INSTANCE); runner.setProperty(accumuloService, AccumuloService.INSTANCE_NAME, INSTANCE);
runner.setProperty(accumuloService, AccumuloService.ZOOKEEPER_QUORUM, ZOOKEEPER); runner.setProperty(accumuloService, AccumuloService.ZOOKEEPER_QUORUM, ZOOKEEPER);
@ -181,14 +161,12 @@ public class TestAccumuloService {
runner.setProperty(accumuloService, AccumuloService.KERBEROS_PRINCIPAL, PRINCIPAL); runner.setProperty(accumuloService, AccumuloService.KERBEROS_PRINCIPAL, PRINCIPAL);
runner.addControllerService("kerberos-credentials-service", credentialService); runner.addControllerService("kerberos-credentials-service", credentialService);
runner.setProperty(accumuloService, AccumuloService.KERBEROS_CREDENTIALS_SERVICE, credentialService.getIdentifier()); runner.setProperty(accumuloService, AccumuloService.KERBEROS_CREDENTIALS_SERVICE, credentialService.getIdentifier());
//when
//then
assertServiceIsInvalidWithErrorMessage("Kerberos Principal (for password) should not be filled out"); assertServiceIsInvalidWithErrorMessage("Kerberos Principal (for password) should not be filled out");
} }
@Test @Test
public void testServiceNotValidWithAuthTypeKerberosAndKerberosPasswordAndUserServiceSet() throws InitializationException { public void testServiceNotValidWithAuthTypeKerberosAndKerberosPasswordAndUserServiceSet() throws InitializationException {
//given
runner.addControllerService("accumulo-connector-service", accumuloService); runner.addControllerService("accumulo-connector-service", accumuloService);
runner.setProperty(accumuloService, AccumuloService.INSTANCE_NAME, INSTANCE); runner.setProperty(accumuloService, AccumuloService.INSTANCE_NAME, INSTANCE);
runner.setProperty(accumuloService, AccumuloService.ZOOKEEPER_QUORUM, ZOOKEEPER); runner.setProperty(accumuloService, AccumuloService.ZOOKEEPER_QUORUM, ZOOKEEPER);
@ -197,14 +175,12 @@ public class TestAccumuloService {
runner.setProperty(accumuloService, AccumuloService.KERBEROS_PASSWORD, KERBEROS_PASSWORD); runner.setProperty(accumuloService, AccumuloService.KERBEROS_PASSWORD, KERBEROS_PASSWORD);
runner.addControllerService("kerberos-user-service", kerberosUserService); runner.addControllerService("kerberos-user-service", kerberosUserService);
runner.setProperty(accumuloService, AccumuloService.KERBEROS_USER_SERVICE, kerberosUserService.getIdentifier()); runner.setProperty(accumuloService, AccumuloService.KERBEROS_USER_SERVICE, kerberosUserService.getIdentifier());
//when
//then
assertServiceIsInvalidWithErrorMessage("should not be filled out at the same time"); assertServiceIsInvalidWithErrorMessage("should not be filled out at the same time");
} }
@Test @Test
public void testServiceNotValidWithAuthTypeKerberosAndCredentialServiceAndUserServiceSet() throws InitializationException { public void testServiceNotValidWithAuthTypeKerberosAndCredentialServiceAndUserServiceSet() throws InitializationException {
//given
runner.addControllerService("accumulo-connector-service", accumuloService); runner.addControllerService("accumulo-connector-service", accumuloService);
runner.setProperty(accumuloService, AccumuloService.INSTANCE_NAME, INSTANCE); runner.setProperty(accumuloService, AccumuloService.INSTANCE_NAME, INSTANCE);
runner.setProperty(accumuloService, AccumuloService.ZOOKEEPER_QUORUM, ZOOKEEPER); runner.setProperty(accumuloService, AccumuloService.ZOOKEEPER_QUORUM, ZOOKEEPER);
@ -216,14 +192,11 @@ public class TestAccumuloService {
runner.addControllerService("kerberos-user-service", kerberosUserService); runner.addControllerService("kerberos-user-service", kerberosUserService);
runner.setProperty(accumuloService, AccumuloService.KERBEROS_USER_SERVICE, kerberosUserService.getIdentifier()); runner.setProperty(accumuloService, AccumuloService.KERBEROS_USER_SERVICE, kerberosUserService.getIdentifier());
//when
//then
assertServiceIsInvalidWithErrorMessage("Kerberos User Service cannot be specified while also specifying a Kerberos Credential Service"); assertServiceIsInvalidWithErrorMessage("Kerberos User Service cannot be specified while also specifying a Kerberos Credential Service");
} }
@Test @Test
public void testServiceIsValidWithAuthTypeKerberosAndKerberosUserServiceSet() throws InitializationException { public void testServiceIsValidWithAuthTypeKerberosAndKerberosUserServiceSet() throws InitializationException {
//given
runner.addControllerService("accumulo-connector-service", accumuloService); runner.addControllerService("accumulo-connector-service", accumuloService);
runner.setProperty(accumuloService, AccumuloService.INSTANCE_NAME, INSTANCE); runner.setProperty(accumuloService, AccumuloService.INSTANCE_NAME, INSTANCE);
runner.setProperty(accumuloService, AccumuloService.ZOOKEEPER_QUORUM, ZOOKEEPER); runner.setProperty(accumuloService, AccumuloService.ZOOKEEPER_QUORUM, ZOOKEEPER);
@ -231,13 +204,11 @@ public class TestAccumuloService {
runner.addControllerService("kerberos-user-service", kerberosUserService); runner.addControllerService("kerberos-user-service", kerberosUserService);
runner.enableControllerService(kerberosUserService); runner.enableControllerService(kerberosUserService);
runner.setProperty(accumuloService, AccumuloService.KERBEROS_USER_SERVICE, kerberosUserService.getIdentifier()); runner.setProperty(accumuloService, AccumuloService.KERBEROS_USER_SERVICE, kerberosUserService.getIdentifier());
//when
//then
runner.assertValid(accumuloService); runner.assertValid(accumuloService);
} }
private void assertServiceIsInvalidWithErrorMessage(String errorMessage) { private void assertServiceIsInvalidWithErrorMessage(String errorMessage) {
Exception exception = assertThrows(IllegalStateException.class, () -> runner.enableControllerService(accumuloService)); Exception exception = assertThrows(IllegalStateException.class, () -> runner.enableControllerService(accumuloService));
assertThat(exception.getMessage(), containsString(errorMessage)); assertTrue(exception.getMessage().contains(errorMessage));
} }
} }

View File

@ -19,6 +19,7 @@ package org.apache.nifi.jasn1;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.StringJoiner; import java.util.StringJoiner;
import org.apache.nifi.controller.ConfigurationContext; import org.apache.nifi.controller.ConfigurationContext;
@ -36,9 +37,8 @@ import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import static org.apache.nifi.jasn1.JASN1Reader.ASN_FILES; import static org.apache.nifi.jasn1.JASN1Reader.ASN_FILES;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
@ -60,7 +60,7 @@ public class JASN1ReaderTest {
private AutoCloseable mockCloseable; private AutoCloseable mockCloseable;
@BeforeEach @BeforeEach
public void setUp() throws Exception { public void setUp() {
mockCloseable = MockitoAnnotations.openMocks(this); mockCloseable = MockitoAnnotations.openMocks(this);
testSubject = new JASN1Reader(); testSubject = new JASN1Reader();
when(context.getLogger()).thenReturn(logger); when(context.getLogger()).thenReturn(logger);
@ -75,31 +75,27 @@ public class JASN1ReaderTest {
assertTrue(testSubject.asnOutDir.toFile().exists()); assertTrue(testSubject.asnOutDir.toFile().exists());
testSubject.deleteAsnOutDir(); testSubject.deleteAsnOutDir();
assertTrue(!testSubject.asnOutDir.toFile().exists()); assertFalse(testSubject.asnOutDir.toFile().exists());
} }
@DisabledOnOs({ OS.WINDOWS }) @DisabledOnOs({ OS.WINDOWS })
@Test @Test
public void testCanLoadClassCompiledFromAsn() throws Exception { public void testCanLoadClassCompiledFromAsn() throws Exception {
// GIVEN
ConfigurationContext context = mock(ConfigurationContext.class, RETURNS_DEEP_STUBS); ConfigurationContext context = mock(ConfigurationContext.class, RETURNS_DEEP_STUBS);
when(context.getProperty(ASN_FILES).isSet()).thenReturn(true); when(context.getProperty(ASN_FILES).isSet()).thenReturn(true);
when(context.getProperty(ASN_FILES).evaluateAttributeExpressions().getValue()).thenReturn(Paths.get("src", "test", "resources", "test.asn").toString()); when(context.getProperty(ASN_FILES).evaluateAttributeExpressions().getValue()).thenReturn(Paths.get("src", "test", "resources", "test.asn").toString());
// WHEN
testSubject.onEnabled(context); testSubject.onEnabled(context);
String actualRootModelName = testSubject.guessRootClassName("ORG-APACHE-NIFI-JASN1-TEST.RootType"); String actualRootModelName = testSubject.guessRootClassName("ORG-APACHE-NIFI-JASN1-TEST.RootType");
Class<?> actual = testSubject.customClassLoader.loadClass(actualRootModelName); Class<?> actual = testSubject.customClassLoader.loadClass(actualRootModelName);
// THEN
assertEquals("org.apache.nifi.jasn1.test.RootType", actualRootModelName); assertEquals("org.apache.nifi.jasn1.test.RootType", actualRootModelName);
assertNotNull(actual); assertNotNull(actual);
} }
@Test @Test
public void testAsnFileDoesntExist() throws Exception { public void testAsnFileDoesntExist() {
// GIVEN
ConfigurationContext context = mock(ConfigurationContext.class, RETURNS_DEEP_STUBS); ConfigurationContext context = mock(ConfigurationContext.class, RETURNS_DEEP_STUBS);
when(context.getProperty(ASN_FILES).isSet()).thenReturn(true); when(context.getProperty(ASN_FILES).isSet()).thenReturn(true);
when(context.getProperty(ASN_FILES).evaluateAttributeExpressions().getValue()).thenReturn( when(context.getProperty(ASN_FILES).evaluateAttributeExpressions().getValue()).thenReturn(
@ -109,7 +105,6 @@ public class JASN1ReaderTest {
.toString() .toString()
); );
// WHEN
ProcessException processException = assertThrows( ProcessException processException = assertThrows(
ProcessException.class, ProcessException.class,
() -> testSubject.onEnabled(context) () -> testSubject.onEnabled(context)
@ -117,7 +112,7 @@ public class JASN1ReaderTest {
Throwable cause = processException.getCause(); Throwable cause = processException.getCause();
assertEquals(FileNotFoundException.class, cause.getClass()); assertEquals(FileNotFoundException.class, cause.getClass());
assertThat(cause.getMessage(), containsString("doesnt_exist.asn")); assertTrue(cause.getMessage().contains("doesnt_exist.asn"));
} }
@Test @Test
@ -125,8 +120,7 @@ public class JASN1ReaderTest {
* Checks reported messages of underlying libraries that are explained in additionalDetails.html. * Checks reported messages of underlying libraries that are explained in additionalDetails.html.
* In case of changes to this test additionalDetails.html may need to be updated as well. * In case of changes to this test additionalDetails.html may need to be updated as well.
*/ */
public void testCantParseAsn() throws Exception { public void testCantParseAsn() {
// GIVEN
String asnFile = Paths.get("src", "test", "resources", "cant_parse.asn").toString(); String asnFile = Paths.get("src", "test", "resources", "cant_parse.asn").toString();
List<String> expectedErrorMessages = Arrays.asList( List<String> expectedErrorMessages = Arrays.asList(
@ -134,8 +128,6 @@ public class JASN1ReaderTest {
"line 17:33: unexpected token: [" "line 17:33: unexpected token: ["
); );
// WHEN
// THEN
testParseError(asnFile, expectedErrorMessages); testParseError(asnFile, expectedErrorMessages);
} }
@ -145,8 +137,7 @@ public class JASN1ReaderTest {
* Checks reported messages of underlying libraries that are explained in additionalDetails.html. * Checks reported messages of underlying libraries that are explained in additionalDetails.html.
* In case of changes to this test additionalDetails.html may need to be updated as well. * In case of changes to this test additionalDetails.html may need to be updated as well.
*/ */
public void testCantCompileAsn() throws Exception { public void testCantCompileAsn() {
// GIVEN
String asnFiles = Paths.get("src", "test", "resources", "cant_compile.asn").toString(); String asnFiles = Paths.get("src", "test", "resources", "cant_compile.asn").toString();
List<String> expectedErrorMessages = Arrays.asList( List<String> expectedErrorMessages = Arrays.asList(
@ -155,8 +146,6 @@ public class JASN1ReaderTest {
".*-Xdiags:verbose.*" ".*-Xdiags:verbose.*"
); );
// WHEN
// THEN
testCompileError(asnFiles, expectedErrorMessages); testCompileError(asnFiles, expectedErrorMessages);
} }
@ -166,34 +155,28 @@ public class JASN1ReaderTest {
* Checks reported messages of underlying libraries that are explained in additionalDetails.html. * Checks reported messages of underlying libraries that are explained in additionalDetails.html.
* In case of changes to this test additionalDetails.html may need to be updated as well. * In case of changes to this test additionalDetails.html may need to be updated as well.
*/ */
public void testCantCompileAsnOnMac() throws Exception { public void testCantCompileAsnOnMac() {
// GIVEN
String asnFiles = Paths.get("src", "test", "resources", "cant_compile_mac_windows.asn").toString(); String asnFiles = Paths.get("src", "test", "resources", "cant_compile_mac_windows.asn").toString();
List<String> expectedErrorMessages = Arrays.asList( List<String> expectedErrorMessages = Collections.singletonList(
".*SAMENAMEWithDifferentCase.*SAMENAMEWithDifferentCase.*" ".*SAMENAMEWithDifferentCase.*SAMENAMEWithDifferentCase.*"
); );
// WHEN
// THEN
testCompileError(asnFiles, expectedErrorMessages); testCompileError(asnFiles, expectedErrorMessages);
} }
private void testParseError(String asnFile, List<String> expectedErrorMessages) { private void testParseError(String asnFile, List<String> expectedErrorMessages) {
// GIVEN
ConfigurationContext context = mock(ConfigurationContext.class, RETURNS_DEEP_STUBS); ConfigurationContext context = mock(ConfigurationContext.class, RETURNS_DEEP_STUBS);
when(context.getProperty(ASN_FILES).isSet()).thenReturn(true); when(context.getProperty(ASN_FILES).isSet()).thenReturn(true);
when(context.getProperty(ASN_FILES).evaluateAttributeExpressions().getValue()) when(context.getProperty(ASN_FILES).evaluateAttributeExpressions().getValue())
.thenReturn(asnFile); .thenReturn(asnFile);
// WHEN
assertThrows( assertThrows(
ProcessException.class, ProcessException.class,
() -> testSubject.onEnabled(context) () -> testSubject.onEnabled(context)
); );
// THEN
ArgumentCaptor<String> errorCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<String> errorCaptor = ArgumentCaptor.forClass(String.class);
verify(testSubject.logger, atLeastOnce()).error(eq("{} - {}"), anyString(), errorCaptor.capture()); verify(testSubject.logger, atLeastOnce()).error(eq("{} - {}"), anyString(), errorCaptor.capture());
@ -203,19 +186,16 @@ public class JASN1ReaderTest {
} }
private void testCompileError(String asnFiles, List<String> expectedErrorMessages) { private void testCompileError(String asnFiles, List<String> expectedErrorMessages) {
// GIVEN
ConfigurationContext context = mock(ConfigurationContext.class, RETURNS_DEEP_STUBS); ConfigurationContext context = mock(ConfigurationContext.class, RETURNS_DEEP_STUBS);
when(context.getProperty(ASN_FILES).isSet()).thenReturn(true); when(context.getProperty(ASN_FILES).isSet()).thenReturn(true);
when(context.getProperty(ASN_FILES).evaluateAttributeExpressions().getValue()) when(context.getProperty(ASN_FILES).evaluateAttributeExpressions().getValue())
.thenReturn(asnFiles); .thenReturn(asnFiles);
// WHEN
assertThrows( assertThrows(
ProcessException.class, ProcessException.class,
() -> testSubject.onEnabled(context) () -> testSubject.onEnabled(context)
); );
// THEN
ArgumentCaptor<String> errorCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<String> errorCaptor = ArgumentCaptor.forClass(String.class);
verify(testSubject.logger, atLeastOnce()).error(errorCaptor.capture()); verify(testSubject.logger, atLeastOnce()).error(errorCaptor.capture());

View File

@ -54,8 +54,7 @@ import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import static org.hamcrest.CoreMatchers.containsString; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assertions.fail;
/** /**
@ -199,7 +198,7 @@ public class TestJASN1RecordReaderWithSimpleTypes implements JASN1ReadRecordTest
testReadRecord(dataFile, berValue, (Map) null, null); testReadRecord(dataFile, berValue, (Map) null, null);
fail(); fail();
} catch (Exception e) { } catch (Exception e) {
assertThat(e.getMessage(), containsString("Text '2019_10-16' could not be parsed at index 4")); assertTrue(e.getMessage().contains("Text '2019_10-16' could not be parsed at index 4"));
} }
} }
@ -222,7 +221,7 @@ public class TestJASN1RecordReaderWithSimpleTypes implements JASN1ReadRecordTest
} }
@Test @Test
public void testTimeOfDayInvalidValue() throws Exception { public void testTimeOfDayInvalidValue() {
String dataFile = "target/time_of_day_invalid_wrapper.dat"; String dataFile = "target/time_of_day_invalid_wrapper.dat";
TimeOfDayWrapper berValue = new TimeOfDayWrapper(); TimeOfDayWrapper berValue = new TimeOfDayWrapper();
@ -232,7 +231,7 @@ public class TestJASN1RecordReaderWithSimpleTypes implements JASN1ReadRecordTest
testReadRecord(dataFile, berValue, (Map) null, null); testReadRecord(dataFile, berValue, (Map) null, null);
fail(); fail();
} catch (Exception e) { } catch (Exception e) {
assertThat(e.getMessage(), containsString("Text '16.13:12' could not be parsed at index 2")); assertTrue(e.getMessage().contains("Text '16.13:12' could not be parsed at index 2"));
} }
} }
@ -255,7 +254,7 @@ public class TestJASN1RecordReaderWithSimpleTypes implements JASN1ReadRecordTest
} }
@Test @Test
public void testDateTimeInvalid() throws Exception { public void testDateTimeInvalid() {
String dataFile = "target/date_time_invalid_wrapper.dat"; String dataFile = "target/date_time_invalid_wrapper.dat";
DateTimeWrapper berValue = new DateTimeWrapper(); DateTimeWrapper berValue = new DateTimeWrapper();
@ -265,7 +264,7 @@ public class TestJASN1RecordReaderWithSimpleTypes implements JASN1ReadRecordTest
testReadRecord(dataFile, berValue, (Map) null, null); testReadRecord(dataFile, berValue, (Map) null, null);
fail(); fail();
} catch (Exception e) { } catch (Exception e) {
assertThat(e.getMessage(), containsString("Text '2019-10-16 16:18:20' could not be parsed at index 10")); assertTrue(e.getMessage().contains("Text '2019-10-16 16:18:20' could not be parsed at index 10"));
} }
} }

View File

@ -36,17 +36,12 @@ import software.amazon.awssdk.regions.Region;
import software.amazon.kinesis.common.ConfigsBuilder; import software.amazon.kinesis.common.ConfigsBuilder;
import software.amazon.kinesis.common.InitialPositionInStream; import software.amazon.kinesis.common.InitialPositionInStream;
import software.amazon.kinesis.coordinator.Scheduler; import software.amazon.kinesis.coordinator.Scheduler;
import software.amazon.kinesis.coordinator.WorkerStateChangeListener;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import static org.hamcrest.CoreMatchers.anyOf; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.hamcrest.CoreMatchers.containsString; import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
@ -78,14 +73,14 @@ public class TestConsumeKinesisStream {
runner.assertNotValid(); runner.assertNotValid();
final AssertionError assertionError = assertThrows(AssertionError.class, runner::run); final AssertionError assertionError = assertThrows(AssertionError.class, runner::run);
assertThat(assertionError.getMessage(), equalTo(String.format("Processor has 3 validation failures:\n" + assertEquals(assertionError.getMessage(), String.format("Processor has 3 validation failures:\n" +
"'%s' is invalid because %s is required\n" + "'%s' is invalid because %s is required\n" +
"'%s' is invalid because %s is required\n" + "'%s' is invalid because %s is required\n" +
"'%s' is invalid because %s is required\n", "'%s' is invalid because %s is required\n",
ConsumeKinesisStream.KINESIS_STREAM_NAME.getDisplayName(), ConsumeKinesisStream.KINESIS_STREAM_NAME.getDisplayName(), ConsumeKinesisStream.KINESIS_STREAM_NAME.getDisplayName(), ConsumeKinesisStream.KINESIS_STREAM_NAME.getDisplayName(),
ConsumeKinesisStream.APPLICATION_NAME.getDisplayName(), ConsumeKinesisStream.APPLICATION_NAME.getDisplayName(), ConsumeKinesisStream.APPLICATION_NAME.getDisplayName(), ConsumeKinesisStream.APPLICATION_NAME.getDisplayName(),
ConsumeKinesisStream.AWS_CREDENTIALS_PROVIDER_SERVICE.getDisplayName(), ConsumeKinesisStream.AWS_CREDENTIALS_PROVIDER_SERVICE.getDisplayName() ConsumeKinesisStream.AWS_CREDENTIALS_PROVIDER_SERVICE.getDisplayName(), ConsumeKinesisStream.AWS_CREDENTIALS_PROVIDER_SERVICE.getDisplayName()
))); ));
} }
@Test @Test
@ -105,7 +100,7 @@ public class TestConsumeKinesisStream {
runner.assertNotValid(); runner.assertNotValid();
final AssertionError assertionError = assertThrows(AssertionError.class, runner::run); final AssertionError assertionError = assertThrows(AssertionError.class, runner::run);
assertThat(assertionError.getMessage(), equalTo(String.format("Processor has 14 validation failures:\n" + assertEquals(assertionError.getMessage(), String.format("Processor has 14 validation failures:\n" +
"'%s' validated against ' ' is invalid because %s must contain at least one character that is not white space\n" + "'%s' validated against ' ' is invalid because %s must contain at least one character that is not white space\n" +
"'%s' validated against 'not-a-reader' is invalid because Property references a Controller Service that does not exist\n" + "'%s' validated against 'not-a-reader' is invalid because Property references a Controller Service that does not exist\n" +
"'%s' validated against 'not-a-writer' is invalid because Property references a Controller Service that does not exist\n" + "'%s' validated against 'not-a-writer' is invalid because Property references a Controller Service that does not exist\n" +
@ -139,7 +134,7 @@ public class TestConsumeKinesisStream {
ConsumeKinesisStream.REPORT_CLOUDWATCH_METRICS.getName(), ConsumeKinesisStream.REPORT_CLOUDWATCH_METRICS.getName(),
ConsumeKinesisStream.RECORD_READER.getDisplayName(), ConsumeKinesisStream.RECORD_READER.getDisplayName(),
ConsumeKinesisStream.RECORD_WRITER.getDisplayName() ConsumeKinesisStream.RECORD_WRITER.getDisplayName()
))); ));
} }
@Test @Test
@ -149,11 +144,11 @@ public class TestConsumeKinesisStream {
runner.assertNotValid(); runner.assertNotValid();
final AssertionError assertionError = assertThrows(AssertionError.class, runner::run); final AssertionError assertionError = assertThrows(AssertionError.class, runner::run);
assertThat(assertionError.getMessage(), equalTo(String.format("Processor has 1 validation failures:\n" + assertEquals(assertionError.getMessage(), String.format("Processor has 1 validation failures:\n" +
"'%s' is invalid because %s must be provided when %s is %s\n", "'%s' is invalid because %s must be provided when %s is %s\n",
ConsumeKinesisStream.STREAM_POSITION_TIMESTAMP.getName(), ConsumeKinesisStream.STREAM_POSITION_TIMESTAMP.getDisplayName(), ConsumeKinesisStream.STREAM_POSITION_TIMESTAMP.getName(), ConsumeKinesisStream.STREAM_POSITION_TIMESTAMP.getDisplayName(),
ConsumeKinesisStream.INITIAL_STREAM_POSITION.getDisplayName(), InitialPositionInStream.AT_TIMESTAMP ConsumeKinesisStream.INITIAL_STREAM_POSITION.getDisplayName(), InitialPositionInStream.AT_TIMESTAMP
))); ));
} }
@Test @Test
@ -164,12 +159,12 @@ public class TestConsumeKinesisStream {
runner.assertNotValid(); runner.assertNotValid();
final AssertionError assertionError = assertThrows(AssertionError.class, runner::run); final AssertionError assertionError = assertThrows(AssertionError.class, runner::run);
assertThat(assertionError.getMessage(), equalTo(String.format("Processor has 1 validation failures:\n" + assertEquals(assertionError.getMessage(), String.format("Processor has 1 validation failures:\n" +
"'%s' is invalid because %s must be parsable by %s\n", "'%s' is invalid because %s must be parsable by %s\n",
ConsumeKinesisStream.STREAM_POSITION_TIMESTAMP.getName(), ConsumeKinesisStream.STREAM_POSITION_TIMESTAMP.getName(),
ConsumeKinesisStream.STREAM_POSITION_TIMESTAMP.getDisplayName(), ConsumeKinesisStream.STREAM_POSITION_TIMESTAMP.getDisplayName(),
ConsumeKinesisStream.TIMESTAMP_FORMAT.getDisplayName() ConsumeKinesisStream.TIMESTAMP_FORMAT.getDisplayName()
))); ));
} }
@Test @Test
@ -182,12 +177,12 @@ public class TestConsumeKinesisStream {
runner.assertNotValid(); runner.assertNotValid();
final AssertionError assertionError = assertThrows(AssertionError.class, runner::assertValid); final AssertionError assertionError = assertThrows(AssertionError.class, runner::assertValid);
assertThat(assertionError.getMessage(), equalTo(String.format("Processor has 1 validation failures:\n" + assertEquals(assertionError.getMessage(), String.format("Processor has 1 validation failures:\n" +
"'%s' is invalid because %s must be set if %s is set in order to write FlowFiles as Records.\n", "'%s' is invalid because %s must be set if %s is set in order to write FlowFiles as Records.\n",
ConsumeKinesisStream.RECORD_WRITER.getName(), ConsumeKinesisStream.RECORD_WRITER.getName(),
ConsumeKinesisStream.RECORD_WRITER.getDisplayName(), ConsumeKinesisStream.RECORD_WRITER.getDisplayName(),
ConsumeKinesisStream.RECORD_READER.getDisplayName() ConsumeKinesisStream.RECORD_READER.getDisplayName()
))); ));
} }
@Test @Test
@ -200,12 +195,12 @@ public class TestConsumeKinesisStream {
runner.assertNotValid(); runner.assertNotValid();
final AssertionError assertionError = assertThrows(AssertionError.class, runner::assertValid); final AssertionError assertionError = assertThrows(AssertionError.class, runner::assertValid);
assertThat(assertionError.getMessage(), equalTo(String.format("Processor has 1 validation failures:\n" + assertEquals(assertionError.getMessage(), String.format("Processor has 1 validation failures:\n" +
"'%s' is invalid because %s must be set if %s is set in order to write FlowFiles as Records.\n", "'%s' is invalid because %s must be set if %s is set in order to write FlowFiles as Records.\n",
ConsumeKinesisStream.RECORD_READER.getName(), ConsumeKinesisStream.RECORD_READER.getName(),
ConsumeKinesisStream.RECORD_READER.getDisplayName(), ConsumeKinesisStream.RECORD_READER.getDisplayName(),
ConsumeKinesisStream.RECORD_WRITER.getDisplayName() ConsumeKinesisStream.RECORD_WRITER.getDisplayName()
))); ));
} }
@Test @Test
@ -248,61 +243,7 @@ public class TestConsumeKinesisStream {
// valid dynamic parameters // valid dynamic parameters
runner.setProperty("namespace", "value"); runner.setProperty("namespace", "value");
final AssertionError ae = assertThrows(AssertionError.class, runner::assertValid); assertThrows(AssertionError.class, runner::assertValid);
assertThat(ae.getMessage(), startsWith("Processor has 13 validation failures:\n"));
// blank properties
assertThat(ae.getMessage(), containsString("'Property Name' validated against '' is invalid because Invalid attribute key: <Empty String>\n"));
assertThat(ae.getMessage(), containsString("'Property Name' validated against ' ' is invalid because Invalid attribute key: <Empty String>\n"));
// invalid property names
assertThat(ae.getMessage(), containsString(
"'withPrefixNotAllowed' validated against 'a-value' is invalid because Property name must not have a prefix of \"with\", " +
"must start with a letter and contain only letters, numbers, periods, or underscores\n"
));
assertThat(ae.getMessage(), containsString(
"'unknownProperty' validated against 'a-third-value' is invalid because Kinesis Client Configuration Builder property with name " +
"UnknownProperty does not exist or is not writable\n"
));
assertThat(ae.getMessage(), containsString(
"'toString' validated against 'cannot-call' is invalid because Kinesis Client Configuration Builder property with name " +
"ToString does not exist or is not writable\n"
));
// invalid property names (cannot use nested/indexed/mapped properties via BeanUtils)
assertThat(ae.getMessage(), containsString(
"'no[allowed' validated against 'no-[' is invalid because Property name must not have a prefix of \"with\", " +
"must start with a letter and contain only letters, numbers, periods, or underscores\n"
));
assertThat(ae.getMessage(), containsString(
"'no]allowed' validated against 'no-]' is invalid because Property name must not have a prefix of \"with\", " +
"must start with a letter and contain only letters, numbers, periods, or underscores\n"
));
assertThat(ae.getMessage(), containsString(
"'no(allowed' validated against 'no-(' is invalid because Property name must not have a prefix of \"with\", " +
"must start with a letter and contain only letters, numbers, periods, or underscores\n"
));
assertThat(ae.getMessage(), containsString(
"'no)allowed' validated against 'no-)' is invalid because Property name must not have a prefix of \"with\", " +
"must start with a letter and contain only letters, numbers, periods, or underscores\n"
));
// can't override static properties
assertThat(ae.getMessage(), containsString(
"'leaseManagementConfig.failoverTimeMillis' validated against '1000' is invalid because Use \"Failover Timeout\" instead of a dynamic property\n"
));
assertThat(ae.getMessage(), containsString(
"'leaseManagementConfig.initialPositionInStream' validated against 'AT_TIMESTAMP' is invalid because Use \"Initial Stream Position\" instead of a dynamic property\n"
));
// invalid parameter conversions
assertThat(ae.getMessage(), containsString(
"'checkpointConfig.checkpointFactory' validated against 'too-complex' is invalid because Kinesis Client Configuration Builder property " +
"with name CheckpointConfig.checkpointFactory cannot be used with value \"too-complex\" : " +
"Cannot invoke software.amazon.kinesis.checkpoint.CheckpointConfig.checkpointFactory on bean class " +
"'class software.amazon.kinesis.checkpoint.CheckpointConfig' - argument type mismatch - had objects of type \"java.lang.String\" " +
"but expected signature \"software.amazon.kinesis.checkpoint.CheckpointFactory\"\n"
));
} }
@Test @Test
@ -352,14 +293,11 @@ public class TestConsumeKinesisStream {
Thread.sleep(50); Thread.sleep(50);
// WorkerState should get to INITIALIZING pretty quickly, but there's a chance it will still be at CREATED by the time we get here
assertThat(processor.workerState.get(), anyOf(equalTo(WorkerStateChangeListener.WorkerState.INITIALIZING), equalTo(WorkerStateChangeListener.WorkerState.CREATED)));
final String hostname = InetAddress.getLocalHost().getCanonicalHostName(); final String hostname = InetAddress.getLocalHost().getCanonicalHostName();
assertSchedulerConfigs(processor.scheduler, hostname); assertSchedulerConfigs(processor.scheduler, hostname);
assertConfigsBuilder(processor.configsBuilder); assertConfigsBuilder(processor.configsBuilder);
assertThat(processor.scheduler.applicationName(), equalTo("test-application")); assertEquals(processor.scheduler.applicationName(), "test-application");
if (!waitForFailure) { if (!waitForFailure) {
// re-trigger the processor to ensure the Worker isn't re-initialised when already running // re-trigger the processor to ensure the Worker isn't re-initialised when already running
@ -370,8 +308,7 @@ public class TestConsumeKinesisStream {
try { try {
mockConsumeKinesisStreamRunner.run(1, false, false); mockConsumeKinesisStreamRunner.run(1, false, false);
} catch (AssertionError e) { } catch (AssertionError e) {
assertThat(e.getCause(), instanceOf(ProcessException.class)); assertInstanceOf(ProcessException.class, e.getCause());
assertThat(e.getCause().getMessage(), equalTo("Worker has shutdown unexpectedly, possibly due to a configuration issue; check logs for details"));
assertTrue(((MockProcessContext) mockConsumeKinesisStreamRunner.getProcessContext()).isYieldCalled()); assertTrue(((MockProcessContext) mockConsumeKinesisStreamRunner.getProcessContext()).isYieldCalled());
break; break;
} }
@ -380,17 +317,17 @@ public class TestConsumeKinesisStream {
} }
private void assertConfigsBuilder(final ConfigsBuilder configsBuilder) { private void assertConfigsBuilder(final ConfigsBuilder configsBuilder) {
assertThat(configsBuilder.kinesisClient().serviceClientConfiguration().region().id(), equalTo(Region.EU_WEST_2.id())); assertEquals(configsBuilder.kinesisClient().serviceClientConfiguration().region().id(), Region.EU_WEST_2.id());
assertTrue(configsBuilder.dynamoDBClient().serviceClientConfiguration().endpointOverride().isEmpty()); assertTrue(configsBuilder.dynamoDBClient().serviceClientConfiguration().endpointOverride().isEmpty());
assertTrue(configsBuilder.kinesisClient().serviceClientConfiguration().endpointOverride().isEmpty()); assertTrue(configsBuilder.kinesisClient().serviceClientConfiguration().endpointOverride().isEmpty());
} }
private void assertSchedulerConfigs(final Scheduler scheduler, final String hostname) { private void assertSchedulerConfigs(final Scheduler scheduler, final String hostname) {
assertThat(scheduler.leaseManagementConfig().workerIdentifier(), startsWith(hostname)); assertTrue(scheduler.leaseManagementConfig().workerIdentifier().startsWith(hostname));
assertThat(scheduler.coordinatorConfig().applicationName(), equalTo("test-application")); assertEquals(scheduler.coordinatorConfig().applicationName(), "test-application");
assertThat(scheduler.leaseManagementConfig().streamName(), equalTo("test-stream")); assertEquals(scheduler.leaseManagementConfig().streamName(), "test-stream");
assertThat(scheduler.leaseManagementConfig().initialPositionInStream().getInitialPositionInStream(), equalTo(InitialPositionInStream.LATEST)); assertEquals(scheduler.leaseManagementConfig().initialPositionInStream().getInitialPositionInStream(), InitialPositionInStream.LATEST);
assertThat(scheduler.coordinatorConfig().parentShardPollIntervalMillis(), equalTo(1L)); assertEquals(scheduler.coordinatorConfig().parentShardPollIntervalMillis(), 1);
} }
// public so TestRunners is able to see and instantiate the class for the tests // public so TestRunners is able to see and instantiate the class for the tests

View File

@ -42,9 +42,7 @@ import java.time.format.DateTimeFormatter;
import java.util.List; import java.util.List;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.doThrow;
@ -98,8 +96,8 @@ public class TestAbstractKinesisRecordProcessor {
fixture.initialize(initializationInput); fixture.initialize(initializationInput);
assertThat(fixture.getNextCheckpointTimeInMillis() > System.currentTimeMillis(), is(true)); assertTrue(fixture.getNextCheckpointTimeInMillis() > System.currentTimeMillis());
assertThat(fixture.getKinesisShardId(), equalTo("shard-id")); assertEquals("shard-id", fixture.getKinesisShardId());
} }
@Test @Test
@ -114,8 +112,8 @@ public class TestAbstractKinesisRecordProcessor {
fixture.initialize(initializationInput); fixture.initialize(initializationInput);
assertThat(fixture.getNextCheckpointTimeInMillis() > System.currentTimeMillis(), is(true)); assertTrue(fixture.getNextCheckpointTimeInMillis() > System.currentTimeMillis());
assertThat(fixture.getKinesisShardId(), equalTo("shard-id")); assertEquals("shard-id", fixture.getKinesisShardId());
} }
@Test @Test

View File

@ -46,8 +46,7 @@ import java.util.Date;
import java.util.List; import java.util.List;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import static org.hamcrest.CoreMatchers.is; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -104,7 +103,7 @@ public class TestKinesisRecordProcessorRaw {
fixture.processRecords(processRecordsInput); fixture.processRecords(processRecordsInput);
session.assertTransferCount(ConsumeKinesisStream.REL_SUCCESS, 0); session.assertTransferCount(ConsumeKinesisStream.REL_SUCCESS, 0);
assertThat(sharedState.getProvenanceEvents().size(), is(0)); assertEquals(0, sharedState.getProvenanceEvents().size());
session.assertNotCommitted(); session.assertNotCommitted();
session.assertNotRolledBack(); session.assertNotRolledBack();
} }
@ -162,10 +161,10 @@ public class TestKinesisRecordProcessorRaw {
verify(processSessionFactory, times(1)).createSession(); verify(processSessionFactory, times(1)).createSession();
session.assertTransferCount(ConsumeKinesisStream.REL_SUCCESS, processRecordsInput.records().size()); session.assertTransferCount(ConsumeKinesisStream.REL_SUCCESS, processRecordsInput.records().size());
assertThat(sharedState.getProvenanceEvents().size(), is(processRecordsInput.records().size())); assertEquals(sharedState.getProvenanceEvents().size(), processRecordsInput.records().size());
assertThat(sharedState.getProvenanceEvents().get(0).getTransitUri(), is(String.format("%s/test-shard/partition-1#1", transitUriPrefix))); assertEquals(sharedState.getProvenanceEvents().get(0).getTransitUri(), String.format("%s/test-shard/partition-1#1", transitUriPrefix));
assertThat(sharedState.getProvenanceEvents().get(1).getTransitUri(), is(String.format("%s/test-shard/partition-2#2", transitUriPrefix))); assertEquals(sharedState.getProvenanceEvents().get(1).getTransitUri(), String.format("%s/test-shard/partition-2#2", transitUriPrefix));
assertThat(sharedState.getProvenanceEvents().get(2).getTransitUri(), is(String.format("%s/test-shard/partition-no-date#no-date", transitUriPrefix))); assertEquals(sharedState.getProvenanceEvents().get(2).getTransitUri(), String.format("%s/test-shard/partition-no-date#no-date", transitUriPrefix));
final List<MockFlowFile> flowFiles = session.getFlowFilesForRelationship(ConsumeKinesisStream.REL_SUCCESS); final List<MockFlowFile> flowFiles = session.getFlowFilesForRelationship(ConsumeKinesisStream.REL_SUCCESS);
assertFlowFile(flowFiles.get(0), firstDate, "partition-1", "1", "record-1"); assertFlowFile(flowFiles.get(0), firstDate, "partition-1", "1", "record-1");

View File

@ -54,11 +54,10 @@ import java.util.Date;
import java.util.List; import java.util.List;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset; import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
@ -127,7 +126,7 @@ public class TestKinesisRecordProcessorRecord {
fixture.processRecords(processRecordsInput); fixture.processRecords(processRecordsInput);
session.assertTransferCount(ConsumeKinesisStream.REL_SUCCESS, 0); session.assertTransferCount(ConsumeKinesisStream.REL_SUCCESS, 0);
assertThat(sharedState.getProvenanceEvents().size(), is(0)); assertTrue(sharedState.getProvenanceEvents().isEmpty());
session.assertNotCommitted(); session.assertNotCommitted();
session.assertNotRolledBack(); session.assertNotRolledBack();
} }
@ -186,8 +185,8 @@ public class TestKinesisRecordProcessorRecord {
verify(processSessionFactory, times(1)).createSession(); verify(processSessionFactory, times(1)).createSession();
session.assertTransferCount(ConsumeKinesisStream.REL_SUCCESS, 1); session.assertTransferCount(ConsumeKinesisStream.REL_SUCCESS, 1);
assertThat(sharedState.getProvenanceEvents().size(), is(1)); assertEquals(1, sharedState.getProvenanceEvents().size());
assertThat(sharedState.getProvenanceEvents().get(0).getTransitUri(), is(String.format("%s/another-shard", transitUriPrefix))); assertEquals(String.format("%s/another-shard", transitUriPrefix), sharedState.getProvenanceEvents().getFirst().getTransitUri());
final List<MockFlowFile> flowFiles = session.getFlowFilesForRelationship(ConsumeKinesisStream.REL_SUCCESS); final List<MockFlowFile> flowFiles = session.getFlowFilesForRelationship(ConsumeKinesisStream.REL_SUCCESS);
// 4 records in single output file, attributes equating to that of the last record // 4 records in single output file, attributes equating to that of the last record

View File

@ -60,11 +60,8 @@ import java.util.regex.Pattern;
import static org.apache.nifi.processors.transfer.ResourceTransferProperties.FILE_RESOURCE_SERVICE; import static org.apache.nifi.processors.transfer.ResourceTransferProperties.FILE_RESOURCE_SERVICE;
import static org.apache.nifi.processors.transfer.ResourceTransferProperties.RESOURCE_TRANSFER_SOURCE; import static org.apache.nifi.processors.transfer.ResourceTransferProperties.RESOURCE_TRANSFER_SOURCE;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
@ -124,9 +121,9 @@ public class ITPutS3Object extends AbstractS3IT {
flowFile.assertContentEquals(getFileFromResourceName(SAMPLE_FILE_RESOURCE_NAME)); flowFile.assertContentEquals(getFileFromResourceName(SAMPLE_FILE_RESOURCE_NAME));
List<S3ObjectSummary> objectSummaries = getClient().listObjects(BUCKET_NAME).getObjectSummaries(); List<S3ObjectSummary> objectSummaries = getClient().listObjects(BUCKET_NAME).getObjectSummaries();
assertThat(objectSummaries, hasSize(1)); assertEquals(1, objectSummaries.size());
assertEquals(objectSummaries.getFirst().getKey(), resourcePath.getFileName().toString()); assertEquals(objectSummaries.getFirst().getKey(), resourcePath.getFileName().toString());
assertThat(objectSummaries.getFirst().getSize(), greaterThan(0L)); assertNotEquals(0, objectSummaries.getFirst().getSize());
} }
@Test @Test
@ -152,7 +149,7 @@ public class ITPutS3Object extends AbstractS3IT {
runner.run(); runner.run();
runner.assertAllFlowFilesTransferred(PutS3Object.REL_FAILURE, 1); runner.assertAllFlowFilesTransferred(PutS3Object.REL_FAILURE, 1);
assertThat(getClient().listObjects(BUCKET_NAME).getObjectSummaries(), empty()); assertTrue(getClient().listObjects(BUCKET_NAME).getObjectSummaries().isEmpty());
} }
@Test @Test
@ -206,7 +203,7 @@ public class ITPutS3Object extends AbstractS3IT {
runner.assertAllFlowFilesTransferred(PutS3Object.REL_SUCCESS, 1); runner.assertAllFlowFilesTransferred(PutS3Object.REL_SUCCESS, 1);
} }
private void testPutThenFetch(String sseAlgorithm) throws IOException, InitializationException { private void testPutThenFetch(String sseAlgorithm) throws IOException {
// Put // Put
TestRunner runner = initTestRunner(); TestRunner runner = initTestRunner();
@ -246,12 +243,12 @@ public class ITPutS3Object extends AbstractS3IT {
} }
@Test @Test
public void testPutThenFetchWithoutSSE() throws IOException, InitializationException { public void testPutThenFetchWithoutSSE() throws IOException {
testPutThenFetch(PutS3Object.NO_SERVER_SIDE_ENCRYPTION); testPutThenFetch(PutS3Object.NO_SERVER_SIDE_ENCRYPTION);
} }
@Test @Test
public void testPutThenFetchWithSSE() throws IOException, InitializationException { public void testPutThenFetchWithSSE() throws IOException {
testPutThenFetch(ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION); testPutThenFetch(ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION);
} }
@ -272,7 +269,7 @@ public class ITPutS3Object extends AbstractS3IT {
} }
@Test @Test
public void testMetaData() throws IOException, InitializationException { public void testMetaData() throws IOException {
final TestRunner runner = initTestRunner(); final TestRunner runner = initTestRunner();
runner.setProperty(PutS3Object.BUCKET_WITHOUT_DEFAULT_VALUE, BUCKET_NAME); runner.setProperty(PutS3Object.BUCKET_WITHOUT_DEFAULT_VALUE, BUCKET_NAME);
@ -324,7 +321,7 @@ public class ITPutS3Object extends AbstractS3IT {
} }
@Test @Test
public void testContentDispositionNull() throws IOException, InitializationException { public void testContentDispositionNull() throws IOException {
// Put // Put
TestRunner runner = initTestRunner(); TestRunner runner = initTestRunner();
@ -408,7 +405,7 @@ public class ITPutS3Object extends AbstractS3IT {
} }
@Test @Test
public void testDynamicProperty() throws InitializationException { public void testDynamicProperty() {
final String DYNAMIC_ATTRIB_KEY = "fs.runTimestamp"; final String DYNAMIC_ATTRIB_KEY = "fs.runTimestamp";
final String DYNAMIC_ATTRIB_VALUE = "${now():toNumber()}"; final String DYNAMIC_ATTRIB_VALUE = "${now():toNumber()}";
@ -501,7 +498,7 @@ public class ITPutS3Object extends AbstractS3IT {
} }
@Test @Test
public void testMultipartProperties() throws InitializationException { public void testMultipartProperties() {
final TestRunner runner = initTestRunner(); final TestRunner runner = initTestRunner();
final ProcessContext context = runner.getProcessContext(); final ProcessContext context = runner.getProcessContext();
@ -702,7 +699,7 @@ public class ITPutS3Object extends AbstractS3IT {
} }
@Test @Test
public void testMultipartSmallerThanMinimum() throws IOException, InitializationException { public void testMultipartSmallerThanMinimum() throws IOException {
final String FILE1_NAME = "file1"; final String FILE1_NAME = "file1";
final byte[] megabyte = new byte[1024 * 1024]; final byte[] megabyte = new byte[1024 * 1024];
@ -926,29 +923,6 @@ public class ITPutS3Object extends AbstractS3IT {
flowFile.assertAttributeEquals(PutS3Object.S3_ENCRYPTION_STRATEGY, AmazonS3EncryptionService.STRATEGY_NAME_SSE_C); flowFile.assertAttributeEquals(PutS3Object.S3_ENCRYPTION_STRATEGY, AmazonS3EncryptionService.STRATEGY_NAME_SSE_C);
} }
private void testEncryptionServiceWithClientSideKMSEncryptionStrategy(byte[] data) throws InitializationException, IOException {
TestRunner runner = createPutEncryptionTestRunner(AmazonS3EncryptionService.STRATEGY_NAME_CSE_KMS, kmsKeyId);
final Map<String, String> attrs = new HashMap<>();
attrs.put("filename", "test.txt");
runner.enqueue(data, attrs);
runner.assertValid();
runner.run();
runner.assertAllFlowFilesTransferred(PutS3Object.REL_SUCCESS);
List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(PutS3Object.REL_SUCCESS);
assertEquals(1, flowFiles.size());
assertEquals(0, runner.getFlowFilesForRelationship(PutS3Object.REL_FAILURE).size());
MockFlowFile putSuccess = flowFiles.get(0);
assertEquals(AmazonS3EncryptionService.STRATEGY_NAME_CSE_KMS, putSuccess.getAttribute(PutS3Object.S3_ENCRYPTION_STRATEGY));
MockFlowFile flowFile = fetchEncryptedFlowFile(attrs, AmazonS3EncryptionService.STRATEGY_NAME_CSE_KMS, kmsKeyId);
flowFile.assertContentEquals(data);
flowFile.assertAttributeEquals("x-amz-wrap-alg", "kms");
flowFile.assertAttributeEquals(PutS3Object.S3_ENCRYPTION_STRATEGY, AmazonS3EncryptionService.STRATEGY_NAME_CSE_KMS);
}
@Test @Test
public void testEncryptionServiceWithClientSideCEncryptionStrategyUsingSingleUpload() throws InitializationException, IOException { public void testEncryptionServiceWithClientSideCEncryptionStrategyUsingSingleUpload() throws InitializationException, IOException {
byte[] smallData = Files.readAllBytes(getResourcePath(SAMPLE_FILE_RESOURCE_NAME)); byte[] smallData = Files.readAllBytes(getResourcePath(SAMPLE_FILE_RESOURCE_NAME));

View File

@ -25,11 +25,10 @@ import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
abstract class AbstractComponentStateCheckpointStoreTest extends AbstractCheckpointStoreTest { abstract class AbstractComponentStateCheckpointStoreTest extends AbstractCheckpointStoreTest {
@ -56,7 +55,7 @@ abstract class AbstractComponentStateCheckpointStoreTest extends AbstractCheckpo
assertEquals(requestedOwnership.getOwnerId(), claimedOwnership.getOwnerId()); assertEquals(requestedOwnership.getOwnerId(), claimedOwnership.getOwnerId());
assertNotNull(claimedOwnership.getLastModifiedTime()); assertNotNull(claimedOwnership.getLastModifiedTime());
assertThat(claimedOwnership.getLastModifiedTime(), greaterThan(requestedOwnership.getLastModifiedTime() != null ? requestedOwnership.getLastModifiedTime() : 0)); assertTrue(claimedOwnership.getLastModifiedTime() > (requestedOwnership.getLastModifiedTime() != null ? requestedOwnership.getLastModifiedTime() : 0));
assertNotNull(claimedOwnership.getETag()); assertNotNull(claimedOwnership.getETag());
assertNotEquals(requestedOwnership.getETag(), claimedOwnership.getETag()); assertNotEquals(requestedOwnership.getETag(), claimedOwnership.getETag());

View File

@ -16,6 +16,7 @@
*/ */
package org.apache.nifi.processors.azure.eventhub.checkpoint; package org.apache.nifi.processors.azure.eventhub.checkpoint;
import com.azure.messaging.eventhubs.models.Checkpoint;
import com.azure.messaging.eventhubs.models.PartitionOwnership; import com.azure.messaging.eventhubs.models.PartitionOwnership;
import org.apache.nifi.components.state.Scope; import org.apache.nifi.components.state.Scope;
import org.apache.nifi.components.state.StateManager; import org.apache.nifi.components.state.StateManager;
@ -37,12 +38,7 @@ import java.util.Map;
import static org.apache.nifi.processors.azure.eventhub.checkpoint.ComponentStateCheckpointStoreUtils.createCheckpointKey; import static org.apache.nifi.processors.azure.eventhub.checkpoint.ComponentStateCheckpointStoreUtils.createCheckpointKey;
import static org.apache.nifi.processors.azure.eventhub.checkpoint.ComponentStateCheckpointStoreUtils.createCheckpointValue; import static org.apache.nifi.processors.azure.eventhub.checkpoint.ComponentStateCheckpointStoreUtils.createCheckpointValue;
import static org.apache.nifi.processors.azure.eventhub.checkpoint.ComponentStateCheckpointStoreUtils.createOwnershipKey; import static org.apache.nifi.processors.azure.eventhub.checkpoint.ComponentStateCheckpointStoreUtils.createOwnershipKey;
import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.anyMap;
@ -83,22 +79,22 @@ class ComponentStateCheckpointStoreConcurrencyTest extends AbstractComponentStat
List<PartitionOwnership> claimedOwnerships = new ArrayList<>(); List<PartitionOwnership> claimedOwnerships = new ArrayList<>();
checkpointStore.claimOwnership(requestedOwnerships).subscribe(claimedOwnerships::add); checkpointStore.claimOwnership(requestedOwnerships).subscribe(claimedOwnerships::add);
assertThat(claimedOwnerships, hasSize(1)); assertEquals(1, claimedOwnerships.size());
PartitionOwnership claimedOwnership = claimedOwnerships.get(0); PartitionOwnership claimedOwnership = claimedOwnerships.getFirst();
assertClaimedOwnership(partitionOwnership2, claimedOwnership); assertClaimedOwnership(partitionOwnership2, claimedOwnership);
verify(stateManager, times(2)).getState(eq(Scope.CLUSTER)); verify(stateManager, times(2)).getState(eq(Scope.CLUSTER));
verify(stateManager, times(2)).replace(any(StateMap.class), updatedMapCaptor.capture(), eq(Scope.CLUSTER)); verify(stateManager, times(2)).replace(any(StateMap.class), updatedMapCaptor.capture(), eq(Scope.CLUSTER));
verifyNoMoreInteractions(stateManager); verifyNoMoreInteractions(stateManager);
Map<String, String> updatedMap1 = updatedMapCaptor.getAllValues().get(0); Map<String, String> updatedMap1 = updatedMapCaptor.getAllValues().getFirst();
assertThat(updatedMap1.size(), is(equalTo(1))); assertEquals(1, updatedMap1.size());
assertThat(updatedMap1, hasEntry(equalTo(createOwnershipKey(partitionOwnership2)), startsWith(partitionOwnership2.getOwnerId()))); assertOwnershipFound(updatedMap1, partitionOwnership2);
Map<String, String> updatedMap2 = updatedMapCaptor.getAllValues().get(1); Map<String, String> updatedMap2 = updatedMapCaptor.getAllValues().get(1);
assertThat(updatedMap2.size(), is(equalTo(2))); assertEquals(2, updatedMap2.size());
assertThat(updatedMap2, hasEntry(equalTo(createOwnershipKey(partitionOwnership1)), startsWith(partitionOwnership1.getOwnerId()))); assertOwnershipFound(updatedMap2, partitionOwnership1);
assertThat(updatedMap2, hasEntry(equalTo(createOwnershipKey(partitionOwnership2)), startsWith(partitionOwnership2.getOwnerId()))); assertOwnershipFound(updatedMap2, partitionOwnership2);
} }
@Test @Test
@ -117,15 +113,15 @@ class ComponentStateCheckpointStoreConcurrencyTest extends AbstractComponentStat
List<PartitionOwnership> claimedOwnerships = new ArrayList<>(); List<PartitionOwnership> claimedOwnerships = new ArrayList<>();
checkpointStore.claimOwnership(requestedOwnerships).subscribe(claimedOwnerships::add); checkpointStore.claimOwnership(requestedOwnerships).subscribe(claimedOwnerships::add);
assertThat(claimedOwnerships, hasSize(0)); assertTrue(claimedOwnerships.isEmpty());
verify(stateManager, times(2)).getState(eq(Scope.CLUSTER)); verify(stateManager, times(2)).getState(eq(Scope.CLUSTER));
verify(stateManager, times(1)).replace(any(StateMap.class), updatedMapCaptor.capture(), eq(Scope.CLUSTER)); verify(stateManager, times(1)).replace(any(StateMap.class), updatedMapCaptor.capture(), eq(Scope.CLUSTER));
verifyNoMoreInteractions(stateManager); verifyNoMoreInteractions(stateManager);
Map<String, String> updatedMap1 = updatedMapCaptor.getAllValues().get(0); Map<String, String> updatedMap1 = updatedMapCaptor.getAllValues().getFirst();
assertThat(updatedMap1.size(), is(equalTo(1))); assertEquals(1, updatedMap1.size());
assertThat(updatedMap1, hasEntry(equalTo(createOwnershipKey(partitionOwnership1)), startsWith(partitionOwnership1.getOwnerId()))); assertOwnershipFound(updatedMap1, partitionOwnership1);
} }
@Test @Test
@ -146,16 +142,16 @@ class ComponentStateCheckpointStoreConcurrencyTest extends AbstractComponentStat
verify(stateManager, times(2)).replace(any(StateMap.class), updatedMapCaptor.capture(), eq(Scope.CLUSTER)); verify(stateManager, times(2)).replace(any(StateMap.class), updatedMapCaptor.capture(), eq(Scope.CLUSTER));
verifyNoMoreInteractions(stateManager); verifyNoMoreInteractions(stateManager);
Map<String, String> updatedMap1 = updatedMapCaptor.getAllValues().get(0); Map<String, String> updatedMap1 = updatedMapCaptor.getAllValues().getFirst();
assertThat(updatedMap1.size(), is(equalTo(2))); assertEquals(2, updatedMap1.size());
assertThat(updatedMap1, hasEntry(equalTo(createOwnershipKey(partitionOwnership1)), startsWith(partitionOwnership1.getOwnerId()))); assertOwnershipFound(updatedMap1, partitionOwnership1);
assertThat(updatedMap1, hasEntry(createCheckpointKey(checkpoint1), createCheckpointValue(checkpoint1))); assertCheckpointFound(updatedMap1, checkpoint1);
Map<String, String> updatedMap2 = updatedMapCaptor.getAllValues().get(1); Map<String, String> updatedMap2 = updatedMapCaptor.getAllValues().get(1);
assertThat(updatedMap2.size(), is(equalTo(3))); assertEquals(3, updatedMap2.size());
assertThat(updatedMap2, hasEntry(equalTo(createOwnershipKey(partitionOwnership1)), startsWith(partitionOwnership1.getOwnerId()))); assertOwnershipFound(updatedMap2, partitionOwnership1);
assertThat(updatedMap2, hasEntry(equalTo(createOwnershipKey(partitionOwnership2)), startsWith(partitionOwnership2.getOwnerId()))); assertOwnershipFound(updatedMap2, partitionOwnership2);
assertThat(updatedMap1, hasEntry(createCheckpointKey(checkpoint1), createCheckpointValue(checkpoint1))); assertCheckpointFound(updatedMap1, checkpoint1);
} }
@Test @Test
@ -175,8 +171,23 @@ class ComponentStateCheckpointStoreConcurrencyTest extends AbstractComponentStat
verify(stateManager, times(1)).replace(any(StateMap.class), updatedMapCaptor.capture(), eq(Scope.CLUSTER)); verify(stateManager, times(1)).replace(any(StateMap.class), updatedMapCaptor.capture(), eq(Scope.CLUSTER));
verifyNoMoreInteractions(stateManager); verifyNoMoreInteractions(stateManager);
Map<String, String> updatedMap1 = updatedMapCaptor.getAllValues().get(0); Map<String, String> updatedMap1 = updatedMapCaptor.getAllValues().getFirst();
assertTrue(updatedMap1.isEmpty()); assertTrue(updatedMap1.isEmpty());
} }
private void assertOwnershipFound(final Map<String, String> map, final PartitionOwnership ownership) {
final String key = createOwnershipKey(ownership);
assertTrue(map.containsKey(key));
final String value = map.get(key);
assertTrue(value.startsWith(ownership.getOwnerId()));
}
private void assertCheckpointFound(final Map<String, String> map, final Checkpoint checkpoint) {
final String key = createCheckpointKey(checkpoint);
assertTrue(map.containsKey(key));
final String value = map.get(key);
assertEquals(createCheckpointValue(checkpoint), value);
}
} }

View File

@ -41,8 +41,6 @@ import static org.apache.nifi.processors.azure.eventhub.checkpoint.ComponentStat
import static org.apache.nifi.processors.azure.eventhub.checkpoint.ComponentStateCheckpointStoreUtils.createCheckpointValue; import static org.apache.nifi.processors.azure.eventhub.checkpoint.ComponentStateCheckpointStoreUtils.createCheckpointValue;
import static org.apache.nifi.processors.azure.eventhub.checkpoint.ComponentStateCheckpointStoreUtils.createOwnershipKey; import static org.apache.nifi.processors.azure.eventhub.checkpoint.ComponentStateCheckpointStoreUtils.createOwnershipKey;
import static org.apache.nifi.processors.azure.eventhub.checkpoint.ComponentStateCheckpointStoreUtils.createOwnershipValue; import static org.apache.nifi.processors.azure.eventhub.checkpoint.ComponentStateCheckpointStoreUtils.createOwnershipValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
@ -342,7 +340,8 @@ class ComponentStateCheckpointStoreTest extends AbstractComponentStateCheckpoint
assertNotNull(partitionOwnerships); assertNotNull(partitionOwnerships);
assertEquals(expectedPartitionOwnerships.length, partitionOwnerships.size()); assertEquals(expectedPartitionOwnerships.length, partitionOwnerships.size());
assertThat(convertToTestablePartitionOwnerships(partitionOwnerships), containsInAnyOrder(expectedPartitionOwnerships));
assertTrue(convertToTestablePartitionOwnerships(partitionOwnerships).containsAll(Arrays.asList(expectedPartitionOwnerships)));
} }
private void testListCheckpoints(Checkpoint... expectedCheckpoints) { private void testListCheckpoints(Checkpoint... expectedCheckpoints) {
@ -350,7 +349,7 @@ class ComponentStateCheckpointStoreTest extends AbstractComponentStateCheckpoint
assertNotNull(checkpoints); assertNotNull(checkpoints);
assertEquals(expectedCheckpoints.length, checkpoints.size()); assertEquals(expectedCheckpoints.length, checkpoints.size());
assertThat(convertToTestableCheckpoints(checkpoints), containsInAnyOrder(expectedCheckpoints)); assertTrue(convertToTestableCheckpoints(checkpoints).containsAll(Arrays.asList(expectedCheckpoints)));
} }
private void assertStoredOwnerships(PartitionOwnership... expectedPartitionOwnerships) { private void assertStoredOwnerships(PartitionOwnership... expectedPartitionOwnerships) {

View File

@ -30,19 +30,14 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.mockito.Mockito; import org.mockito.Mockito;
import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors; import java.util.Optional;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -66,7 +61,6 @@ public class TestAbstractSingleAttributeBasedControllerServiceLookup {
@Test @Test
public void testLookupShouldThrowExceptionWhenQueriedServiceMappedInPropertiesButWasntCreated() { public void testLookupShouldThrowExceptionWhenQueriedServiceMappedInPropertiesButWasntCreated() {
// GIVEN
String mappedCreatedServiceID = "mappedCreatedServiceID"; String mappedCreatedServiceID = "mappedCreatedServiceID";
String mappedNotCreatedServiceID = "mappedNotCreatedServiceID"; String mappedNotCreatedServiceID = "mappedNotCreatedServiceID";
@ -80,18 +74,15 @@ public class TestAbstractSingleAttributeBasedControllerServiceLookup {
mapService(dynamicProperty1, mappedCreatedServiceID); mapService(dynamicProperty1, mappedCreatedServiceID);
mapService(dynamicProperty2, mappedNotCreatedServiceID); mapService(dynamicProperty2, mappedNotCreatedServiceID);
// WHEN
assertThrows(Exception.class, () -> testSubject.onEnabled(new MockConfigurationContext(properties, serviceLookup, null))); assertThrows(Exception.class, () -> testSubject.onEnabled(new MockConfigurationContext(properties, serviceLookup, null)));
} }
@Test @Test
public void testLookupShouldThrowExceptionWhenAttributeMapIsNull() { public void testLookupShouldThrowExceptionWhenAttributeMapIsNull() {
// GIVEN
String mappedCreatedServiceID = "mappedCreatedServiceID"; String mappedCreatedServiceID = "mappedCreatedServiceID";
ControllerService mappedCreatedService = mock(SERVICE_TYPE); ControllerService mappedCreatedService = mock(SERVICE_TYPE);
MockControllerServiceInitializationContext serviceLookup = new MockControllerServiceInitializationContext(mappedCreatedService, mappedCreatedServiceID); MockControllerServiceInitializationContext serviceLookup = new MockControllerServiceInitializationContext(mappedCreatedService, mappedCreatedServiceID);
// WHEN
testSubject.onEnabled(new MockConfigurationContext(properties, serviceLookup, null)); testSubject.onEnabled(new MockConfigurationContext(properties, serviceLookup, null));
ProcessException e = assertThrows(ProcessException.class, () -> testSubject.lookupService(null)); ProcessException e = assertThrows(ProcessException.class, () -> testSubject.lookupService(null));
@ -100,12 +91,10 @@ public class TestAbstractSingleAttributeBasedControllerServiceLookup {
@Test @Test
public void testLookupShouldThrowExceptionWhenAttributeMapHasNoLookupAttribute() { public void testLookupShouldThrowExceptionWhenAttributeMapHasNoLookupAttribute() {
// GIVEN
String mappedCreatedServiceID = "mappedCreatedServiceID"; String mappedCreatedServiceID = "mappedCreatedServiceID";
ControllerService mappedCreatedService = mock(SERVICE_TYPE); ControllerService mappedCreatedService = mock(SERVICE_TYPE);
MockControllerServiceInitializationContext serviceLookup = new MockControllerServiceInitializationContext(mappedCreatedService, mappedCreatedServiceID); MockControllerServiceInitializationContext serviceLookup = new MockControllerServiceInitializationContext(mappedCreatedService, mappedCreatedServiceID);
// WHEN
testSubject.onEnabled(new MockConfigurationContext(properties, serviceLookup, null)); testSubject.onEnabled(new MockConfigurationContext(properties, serviceLookup, null));
ProcessException e = assertThrows(ProcessException.class, () -> testSubject.lookupService(new HashMap<>())); ProcessException e = assertThrows(ProcessException.class, () -> testSubject.lookupService(new HashMap<>()));
assertEquals("Attributes must contain an attribute name '" + LOOKUP_ATTRIBUTE + "'", e.getMessage()); assertEquals("Attributes must contain an attribute name '" + LOOKUP_ATTRIBUTE + "'", e.getMessage());
@ -113,7 +102,6 @@ public class TestAbstractSingleAttributeBasedControllerServiceLookup {
@Test @Test
public void testLookupShouldThrowExceptionWhenQueriedServiceWasCreatedButWasntMappedInProperties() { public void testLookupShouldThrowExceptionWhenQueriedServiceWasCreatedButWasntMappedInProperties() {
// GIVEN
String mappedCreatedServiceID = "mappedCreatedServiceID"; String mappedCreatedServiceID = "mappedCreatedServiceID";
String notMappedCreatedServiceID = "notMappedCreatedServiceID"; String notMappedCreatedServiceID = "notMappedCreatedServiceID";
@ -128,17 +116,13 @@ public class TestAbstractSingleAttributeBasedControllerServiceLookup {
mapService(dynamicProperty1, mappedCreatedServiceID); mapService(dynamicProperty1, mappedCreatedServiceID);
String lookupServiceKey = dynamicProperty2;
// WHEN
testSubject.onEnabled(new MockConfigurationContext(properties, serviceLookup, null)); testSubject.onEnabled(new MockConfigurationContext(properties, serviceLookup, null));
ProcessException e = assertThrows(ProcessException.class, () -> testSubject.lookupService(createAttributes(lookupServiceKey))); ProcessException e = assertThrows(ProcessException.class, () -> testSubject.lookupService(createAttributes(dynamicProperty2)));
assertEquals("No ControllerService found for lookupAttribute", e.getMessage()); assertEquals("No ControllerService found for lookupAttribute", e.getMessage());
} }
@Test @Test
public void testLookupShouldReturnQueriedService() { public void testLookupShouldReturnQueriedService() {
// GIVEN
String mappedCreatedServiceID1 = "mappedCreatedServiceID1"; String mappedCreatedServiceID1 = "mappedCreatedServiceID1";
String mappedCreatedServiceID2 = "mappedCreatedServiceID2"; String mappedCreatedServiceID2 = "mappedCreatedServiceID2";
@ -154,30 +138,19 @@ public class TestAbstractSingleAttributeBasedControllerServiceLookup {
mapService(dynamicProperty1, mappedCreatedServiceID1); mapService(dynamicProperty1, mappedCreatedServiceID1);
mapService(dynamicProperty2, mappedCreatedServiceID2); mapService(dynamicProperty2, mappedCreatedServiceID2);
String lookupServiceKey = dynamicProperty2;
ControllerService expected = mappedCreatedService2;
// WHEN
testSubject.onEnabled(new MockConfigurationContext(properties, serviceLookup, null)); testSubject.onEnabled(new MockConfigurationContext(properties, serviceLookup, null));
ControllerService actual = testSubject.lookupService(createAttributes(lookupServiceKey)); ControllerService actual = testSubject.lookupService(createAttributes(dynamicProperty2));
// THEN assertEquals(mappedCreatedService2, actual);
assertEquals(expected, actual);
} }
@Test @Test
public void testCustomValidateShouldReturnErrorWhenNoServiceIsDefined() { public void testCustomValidateShouldReturnErrorWhenNoServiceIsDefined() {
// GIVEN
ValidationContext context = new MockValidationContext(new MockProcessContext(testSubject)); ValidationContext context = new MockValidationContext(new MockProcessContext(testSubject));
// WHEN Collection<ValidationResult> results = testSubject.customValidate(context);
Collection<ValidationResult> actual = testSubject.customValidate(context);
// THEN assertExplanationFound(results, "at least one " + SERVICE_TYPE.getSimpleName() + " must be defined via dynamic properties");
assertThat(
actual.stream().map(ValidationResult::getExplanation).collect(Collectors.toList()),
hasItem(containsString("at least one " + SERVICE_TYPE.getSimpleName() + " must be defined via dynamic properties"))
);
} }
@Test @Test
@ -188,14 +161,9 @@ public class TestAbstractSingleAttributeBasedControllerServiceLookup {
ValidationContext context = new MockValidationContext(processContext); ValidationContext context = new MockValidationContext(processContext);
// WHEN Collection<ValidationResult> results = testSubject.customValidate(context);
Collection<ValidationResult> actual = testSubject.customValidate(context);
// THEN assertExplanationFound(results, "the current service cannot be registered as a " + SERVICE_TYPE.getSimpleName() + " to lookup");
assertThat(
actual.stream().map(ValidationResult::getExplanation).collect(Collectors.toList()),
hasItem(containsString("the current service cannot be registered as a " + SERVICE_TYPE.getSimpleName() + " to lookup"))
);
} }
@Test @Test
@ -205,17 +173,10 @@ public class TestAbstractSingleAttributeBasedControllerServiceLookup {
ValidationContext context = new MockValidationContext(processContext); ValidationContext context = new MockValidationContext(processContext);
// WHEN Collection<ValidationResult> results = testSubject.customValidate(context);
Collection<ValidationResult> actual = testSubject.customValidate(context);
// THEN assertExplanationFound(results, "the current service cannot be registered as a " + SERVICE_TYPE.getSimpleName() + " to lookup");
assertThat( assertExplanationFound(results, "at least one " + SERVICE_TYPE.getSimpleName() + " must be defined via dynamic properties");
actual.stream().map(ValidationResult::getExplanation).collect(Collectors.toList()),
hasItems(
containsString("the current service cannot be registered as a " + SERVICE_TYPE.getSimpleName() + " to lookup"),
containsString("at least one " + SERVICE_TYPE.getSimpleName() + " must be defined via dynamic properties")
)
);
} }
@Test @Test
@ -225,11 +186,9 @@ public class TestAbstractSingleAttributeBasedControllerServiceLookup {
ValidationContext context = new MockValidationContext(processContext); ValidationContext context = new MockValidationContext(processContext);
// WHEN Collection<ValidationResult> results = testSubject.customValidate(context);
Collection<ValidationResult> actual = testSubject.customValidate(context);
// THEN assertTrue(results.isEmpty());
assertEquals(Collections.emptyList(), new ArrayList<>(actual));
} }
@Test @Test
@ -256,10 +215,15 @@ public class TestAbstractSingleAttributeBasedControllerServiceLookup {
} }
private Map<String, String> createAttributes(final String lookupValue) { private Map<String, String> createAttributes(final String lookupValue) {
Map<String, String> attributes = new HashMap<String, String>() {{ return Map.of(LOOKUP_ATTRIBUTE, lookupValue);
put(LOOKUP_ATTRIBUTE, lookupValue); }
}};
return attributes; private void assertExplanationFound(final Collection<ValidationResult> results, final String search) {
final Optional<String> explanationFound = results.stream()
.map(ValidationResult::getExplanation)
.filter(explanation -> explanation.contains(search))
.findAny();
assertTrue(explanationFound.isPresent());
} }
} }

View File

@ -81,8 +81,6 @@ import java.util.UUID;
import static java.io.File.createTempFile; import static java.io.File.createTempFile;
import static org.apache.iceberg.FileFormat.PARQUET; import static org.apache.iceberg.FileFormat.PARQUET;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertInstanceOf;
@ -835,8 +833,8 @@ public class TestIcebergRecordConverter {
assertInstanceOf(List.class, nestedList.get(0)); assertInstanceOf(List.class, nestedList.get(0));
assertInstanceOf(List.class, nestedList.get(1)); assertInstanceOf(List.class, nestedList.get(1));
assertThat((List<String>) nestedList.get(0), hasItems("Test String1", "Test String2")); assertTrue(((List<String>) nestedList.get(0)).containsAll(List.of("Test String1", "Test String2")));
assertThat((List<String>) nestedList.get(1), hasItems("Test String3", "Test String4")); assertTrue(((List<String>) nestedList.get(1)).containsAll(List.of("Test String3", "Test String4")));
} }
@DisabledOnOs(WINDOWS) @DisabledOnOs(WINDOWS)
@ -999,7 +997,7 @@ public class TestIcebergRecordConverter {
assertInstanceOf(List.class, nestedRecord.get(1)); assertInstanceOf(List.class, nestedRecord.get(1));
List<String> nestedList = nestedRecord.get(1, List.class); List<String> nestedList = nestedRecord.get(1, List.class);
assertThat(nestedList, hasItems("list value1", "list value2")); assertTrue(nestedList.containsAll(List.of("list value1", "list value2")));
assertEquals("value5", resultRecord.get(2, String.class)); assertEquals("value5", resultRecord.get(2, String.class));

View File

@ -87,6 +87,12 @@ language governing permissions and limitations under the License. -->
<groupId>org.glassfish.jersey.test-framework.providers</groupId> <groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-inmemory</artifactId> <artifactId>jersey-test-framework-provider-inmemory</artifactId>
<scope>test</scope> <scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -72,11 +72,9 @@ import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.UUID; import java.util.UUID;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.isA;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -360,7 +358,7 @@ public class DecryptContentPGPTest {
private void assertSuccess(final int encryptionAlgorithm, final DecryptionStrategy decryptionStrategy) { private void assertSuccess(final int encryptionAlgorithm, final DecryptionStrategy decryptionStrategy) {
runner.assertAllFlowFilesTransferred(DecryptContentPGP.SUCCESS); runner.assertAllFlowFilesTransferred(DecryptContentPGP.SUCCESS);
final List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(DecryptContentPGP.SUCCESS); final List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(DecryptContentPGP.SUCCESS);
final MockFlowFile flowFile = flowFiles.iterator().next(); final MockFlowFile flowFile = flowFiles.getFirst();
if (DecryptionStrategy.PACKAGED == decryptionStrategy) { if (DecryptionStrategy.PACKAGED == decryptionStrategy) {
assertSuccessPackaged(flowFile.getContentStream()); assertSuccessPackaged(flowFile.getContentStream());
@ -391,27 +389,26 @@ public class DecryptContentPGPTest {
} }
private void assertOnePassSignatureEquals(final Object object) { private void assertOnePassSignatureEquals(final Object object) {
assertTrue(object instanceof PGPOnePassSignatureList); assertInstanceOf(PGPOnePassSignatureList.class, object);
final PGPOnePassSignatureList onePassSignatureList = (PGPOnePassSignatureList) object; final PGPOnePassSignatureList onePassSignatureList = (PGPOnePassSignatureList) object;
final PGPOnePassSignature onePassSignature = onePassSignatureList.iterator().next(); final PGPOnePassSignature onePassSignature = onePassSignatureList.iterator().next();
assertEquals(onePassSignature.getKeyID(), rsaPrivateKey.getKeyID()); assertEquals(onePassSignature.getKeyID(), rsaPrivateKey.getKeyID());
} }
private void assertLiteralDataEquals(final Object object) throws IOException { private void assertLiteralDataEquals(final Object object) throws IOException {
assertTrue(object instanceof PGPLiteralData); assertInstanceOf(PGPLiteralData.class, object);
final PGPLiteralData literalData = (PGPLiteralData) object; final PGPLiteralData literalData = (PGPLiteralData) object;
assertEquals(FILE_NAME, literalData.getFileName()); assertEquals(FILE_NAME, literalData.getFileName());
assertEquals(MODIFIED, literalData.getModificationTime()); assertEquals(MODIFIED, literalData.getModificationTime());
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
StreamUtils.copy(literalData.getDataStream(), outputStream); StreamUtils.copy(literalData.getDataStream(), outputStream);
final byte[] literalBinary = outputStream.toByteArray(); final String literal = outputStream.toString(DATA_CHARSET);
final String literal = new String(literalBinary, DATA_CHARSET);
assertEquals(DATA, literal); assertEquals(DATA, literal);
} }
private void assertSignatureEquals(final Object object) { private void assertSignatureEquals(final Object object) {
assertTrue(object instanceof PGPSignatureList); assertInstanceOf(PGPSignatureList.class, object);
final PGPSignatureList signatureList = (PGPSignatureList) object; final PGPSignatureList signatureList = (PGPSignatureList) object;
final PGPSignature signature = signatureList.iterator().next(); final PGPSignature signature = signatureList.iterator().next();
assertEquals(rsaPrivateKey.getKeyID(), signature.getKeyID()); assertEquals(rsaPrivateKey.getKeyID(), signature.getKeyID());
@ -422,7 +419,8 @@ public class DecryptContentPGPTest {
final Optional<LogMessage> optionalLogMessage = runner.getLogger().getErrorMessages().stream().findFirst(); final Optional<LogMessage> optionalLogMessage = runner.getLogger().getErrorMessages().stream().findFirst();
assertTrue(optionalLogMessage.isPresent()); assertTrue(optionalLogMessage.isPresent());
final LogMessage logMessage = optionalLogMessage.get(); final LogMessage logMessage = optionalLogMessage.get();
assertThat(Arrays.asList(logMessage.getArgs()), hasItem(isA(exceptionClass))); final Optional<Object> exceptionFound = Arrays.stream(logMessage.getArgs()).filter(arg -> exceptionClass.isAssignableFrom(arg.getClass())).findFirst();
assertTrue(exceptionFound.isPresent());
} }
private byte[] getPublicKeyEncryptedData(final byte[] contents, final PGPPublicKey publicKey) throws IOException, PGPException { private byte[] getPublicKeyEncryptedData(final byte[] contents, final PGPPublicKey publicKey) throws IOException, PGPException {

View File

@ -36,10 +36,6 @@ import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static org.apache.nifi.util.StringUtils.EMPTY; import static org.apache.nifi.util.StringUtils.EMPTY;
import static org.hamcrest.CoreMatchers.everyItem;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
@ -191,7 +187,9 @@ public class TestPrometheusMetricsUtil {
assertTrue(emptyAggregatedMetrics.isEmpty()); assertTrue(emptyAggregatedMetrics.isEmpty());
assertEquals(2, sampleValues.size()); assertEquals(2, sampleValues.size());
assertThat(sampleValues, everyItem(is(EXPECTED_DEFAULT_PREDICTION_VALUE))); for (final Double sampleValue : sampleValues) {
assertEquals(EXPECTED_DEFAULT_PREDICTION_VALUE, sampleValue);
}
} }
@Test @Test
@ -211,7 +209,9 @@ public class TestPrometheusMetricsUtil {
assertEquals(2, aggregatedMetrics.size()); assertEquals(2, aggregatedMetrics.size());
assertEquals(2, sampleValues.size()); assertEquals(2, sampleValues.size());
assertThat(sampleValues, everyItem(is(EXPECTED_DEFAULT_PREDICTION_VALUE))); for (final Double sampleValue : sampleValues) {
assertEquals(EXPECTED_DEFAULT_PREDICTION_VALUE, sampleValue);
}
} }
@Test @Test
@ -231,7 +231,7 @@ public class TestPrometheusMetricsUtil {
assertEquals(2, aggregatedMetrics.size()); assertEquals(2, aggregatedMetrics.size());
assertEquals(2, sampleValues.size()); assertEquals(2, sampleValues.size());
assertThat(sampleValues, hasItems(1.0, 2.0)); assertTrue(sampleValues.containsAll(List.of(1.0, 2.0)));
} }
@Test @Test
@ -252,7 +252,7 @@ public class TestPrometheusMetricsUtil {
List<Double> sampleValues = getSampleValuesList(connectionAnalyticsMetricsRegistry); List<Double> sampleValues = getSampleValuesList(connectionAnalyticsMetricsRegistry);
assertEquals(2, sampleValues.size()); assertEquals(2, sampleValues.size());
assertThat(sampleValues, hasItems(0.0, 2.0)); assertTrue(sampleValues.containsAll(List.of(0.0, 2.0)));
} }
@Test @Test
@ -271,7 +271,9 @@ public class TestPrometheusMetricsUtil {
assertTrue(emptyAggregatedMetrics.isEmpty()); assertTrue(emptyAggregatedMetrics.isEmpty());
assertEquals(2, sampleValues.size()); assertEquals(2, sampleValues.size());
assertThat(sampleValues, everyItem(is(EXPECTED_DEFAULT_PERCENT_USED_VALUE))); for (final Double sampleValue : sampleValues) {
assertEquals(EXPECTED_DEFAULT_PERCENT_USED_VALUE, sampleValue);
}
} }
@Test @Test
@ -290,7 +292,9 @@ public class TestPrometheusMetricsUtil {
List<Double> sampleValues = getSampleValuesList(niFiMetricsRegistry); List<Double> sampleValues = getSampleValuesList(niFiMetricsRegistry);
assertEquals(2, sampleValues.size()); assertEquals(2, sampleValues.size());
assertThat(sampleValues, everyItem(is(EXPECTED_DEFAULT_PERCENT_USED_VALUE))); for (final Double sampleValue : sampleValues) {
assertEquals(EXPECTED_DEFAULT_PERCENT_USED_VALUE, sampleValue);
}
} }
@Test @Test
@ -309,7 +313,7 @@ public class TestPrometheusMetricsUtil {
List<Double> sampleValues = getSampleValuesList(niFiMetricsRegistry); List<Double> sampleValues = getSampleValuesList(niFiMetricsRegistry);
assertEquals(2, sampleValues.size()); assertEquals(2, sampleValues.size());
assertThat(sampleValues, hasItems(EXPECTED_NESTED_BYTES_PERCENT_VALUE, EXPECTED_NESTED_COUNT_PERCENT_VALUE)); assertTrue(sampleValues.containsAll(List.of(EXPECTED_NESTED_BYTES_PERCENT_VALUE, EXPECTED_NESTED_COUNT_PERCENT_VALUE)));
} }
@Test @Test
@ -324,7 +328,7 @@ public class TestPrometheusMetricsUtil {
final Set<String> result = getRepoIdentifierSampleLabelNames(niFiMetricsRegistry); final Set<String> result = getRepoIdentifierSampleLabelNames(niFiMetricsRegistry);
assertEquals(4, result.size()); assertEquals(4, result.size());
assertThat(result, hasItems(FLOW_FILE_REPO_IDENTIFIER, CONTENT_REPO_IDENTIFIER_ONE, CONTENT_REPO_IDENTIFIER_TWO, PROVENANCE_REPO_IDENTIFIER)); assertTrue(result.containsAll(List.of(FLOW_FILE_REPO_IDENTIFIER, CONTENT_REPO_IDENTIFIER_ONE, CONTENT_REPO_IDENTIFIER_TWO, PROVENANCE_REPO_IDENTIFIER)));
} }
private static ProcessGroupStatus createSingleProcessGroupStatus(final long queuedBytes, final long bytesThreshold, final int queuedCount, final long objectThreshold) { private static ProcessGroupStatus createSingleProcessGroupStatus(final long queuedBytes, final long bytesThreshold, final int queuedCount, final long objectThreshold) {

View File

@ -19,8 +19,7 @@ package org.apache.nifi.snmp.factory.core;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.snmp4j.mp.SnmpConstants; import org.snmp4j.mp.SnmpConstants;
import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
class SNMPFactoryProviderTest { class SNMPFactoryProviderTest {
@ -29,9 +28,9 @@ class SNMPFactoryProviderTest {
final SNMPContext snmpV1V2cFactoryFromVersion1 = SNMPFactoryProvider.getFactory(SnmpConstants.version1); final SNMPContext snmpV1V2cFactoryFromVersion1 = SNMPFactoryProvider.getFactory(SnmpConstants.version1);
final SNMPContext snmpV1V2cFactoryFromVersion2c = SNMPFactoryProvider.getFactory(SnmpConstants.version2c); final SNMPContext snmpV1V2cFactoryFromVersion2c = SNMPFactoryProvider.getFactory(SnmpConstants.version2c);
final SNMPContext snmpV3Factory = SNMPFactoryProvider.getFactory(SnmpConstants.version3); final SNMPContext snmpV3Factory = SNMPFactoryProvider.getFactory(SnmpConstants.version3);
assertThat(snmpV1V2cFactoryFromVersion1, instanceOf(V1V2cSNMPFactory.class)); assertInstanceOf(V1V2cSNMPFactory.class, snmpV1V2cFactoryFromVersion1);
assertThat(snmpV1V2cFactoryFromVersion2c, instanceOf(V1V2cSNMPFactory.class)); assertInstanceOf(V1V2cSNMPFactory.class, snmpV1V2cFactoryFromVersion2c);
assertThat(snmpV3Factory, instanceOf(V3SNMPFactory.class)); assertInstanceOf(V3SNMPFactory.class, snmpV3Factory);
} }
} }

View File

@ -19,14 +19,11 @@ package org.apache.nifi.snmp.factory.core;
import org.apache.nifi.snmp.configuration.SNMPConfiguration; import org.apache.nifi.snmp.configuration.SNMPConfiguration;
import org.apache.nifi.util.StringUtils; import org.apache.nifi.util.StringUtils;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.snmp4j.CommunityTarget;
import org.snmp4j.Snmp; import org.snmp4j.Snmp;
import org.snmp4j.Target; import org.snmp4j.Target;
import org.snmp4j.security.SecurityLevel; import org.snmp4j.security.SecurityLevel;
import static org.apache.nifi.snmp.helper.configurations.SNMPConfigurationFactory.LOCALHOST; import static org.apache.nifi.snmp.helper.configurations.SNMPConfigurationFactory.LOCALHOST;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
@ -39,7 +36,6 @@ class V1V2cSNMPFactoryTest extends SNMPSocketSupport {
final V1V2cSNMPFactory snmpFactory = new V1V2cSNMPFactory(); final V1V2cSNMPFactory snmpFactory = new V1V2cSNMPFactory();
final Target target = createInstanceWithRetries(snmpFactory::createTargetInstance, 5); final Target target = createInstanceWithRetries(snmpFactory::createTargetInstance, 5);
assertThat(target, instanceOf(CommunityTarget.class));
assertNotNull(target.getAddress().toString()); assertNotNull(target.getAddress().toString());
assertEquals(RETRIES, target.getRetries()); assertEquals(RETRIES, target.getRetries());
assertEquals(1, target.getSecurityLevel()); assertEquals(1, target.getSecurityLevel());

View File

@ -19,15 +19,12 @@ package org.apache.nifi.snmp.factory.core;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.snmp4j.Snmp; import org.snmp4j.Snmp;
import org.snmp4j.Target; import org.snmp4j.Target;
import org.snmp4j.UserTarget;
import org.snmp4j.security.SecurityModels; import org.snmp4j.security.SecurityModels;
import org.snmp4j.security.USM; import org.snmp4j.security.USM;
import org.snmp4j.smi.Integer32; import org.snmp4j.smi.Integer32;
import org.snmp4j.smi.OctetString; import org.snmp4j.smi.OctetString;
import static org.apache.nifi.snmp.helper.configurations.SNMPV3ConfigurationFactory.SECURITY_NAME; import static org.apache.nifi.snmp.helper.configurations.SNMPV3ConfigurationFactory.SECURITY_NAME;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
@ -40,7 +37,7 @@ class V3SNMPFactoryTest extends SNMPSocketSupport {
void testFactoryCreatesTarget() { void testFactoryCreatesTarget() {
final V3SNMPFactory snmpFactory = new V3SNMPFactory(); final V3SNMPFactory snmpFactory = new V3SNMPFactory();
final Target target = createInstanceWithRetries(snmpFactory::createTargetInstance, 5); final Target target = createInstanceWithRetries(snmpFactory::createTargetInstance, 5);
assertThat(target, instanceOf(UserTarget.class));
assertNotNull(target.getAddress().toString()); assertNotNull(target.getAddress().toString());
assertEquals(RETRIES, target.getRetries()); assertEquals(RETRIES, target.getRetries());
assertEquals(EXPECTED_SECURITY_LEVEL, target.getSecurityLevel()); assertEquals(EXPECTED_SECURITY_LEVEL, target.getSecurityLevel());

View File

@ -26,11 +26,7 @@ import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.containers.PostgreSQLContainer;
import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertEquals;
import java.sql.SQLException;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
public class QueryDatabaseTableIT extends QueryDatabaseTableTest { public class QueryDatabaseTableIT extends QueryDatabaseTableTest {
@ -68,11 +64,11 @@ public class QueryDatabaseTableIT extends QueryDatabaseTableTest {
} }
@Test @Test
public void testAddedRowsAutoCommitTrue() throws SQLException, IOException { public void testAddedRowsAutoCommitTrue() {
// this test in the base class is not valid for PostgreSQL so check the validation error message. // this test in the base class is not valid for PostgreSQL so check the validation error message.
final AssertionError assertionError = assertThrows(AssertionError.class, super::testAddedRowsAutoCommitTrue); final AssertionError assertionError = assertThrows(AssertionError.class, super::testAddedRowsAutoCommitTrue);
assertThat(assertionError.getMessage(), equalTo("Processor has 1 validation failures:\n" + assertEquals(assertionError.getMessage(), "Processor has 1 validation failures:\n" +
"'Set Auto Commit' validated against 'true' is invalid because 'Set Auto Commit' " + "'Set Auto Commit' validated against 'true' is invalid because 'Set Auto Commit' " +
"must be set to 'false' because 'PostgreSQL' Database Type requires it to be 'false'\n")); "must be set to 'false' because 'PostgreSQL' Database Type requires it to be 'false'\n");
} }
} }

View File

@ -26,11 +26,7 @@ import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.containers.PostgreSQLContainer;
import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertEquals;
import java.sql.SQLException;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
public class QueryDatabaseTableRecordIT extends QueryDatabaseTableRecordTest { public class QueryDatabaseTableRecordIT extends QueryDatabaseTableRecordTest {
@ -68,11 +64,11 @@ public class QueryDatabaseTableRecordIT extends QueryDatabaseTableRecordTest {
} }
@Test @Test
public void testAddedRowsAutoCommitTrue() throws SQLException, IOException { public void testAddedRowsAutoCommitTrue() {
// this test in the base class is not valid for PostgreSQL so check the validation error message. // this test in the base class is not valid for PostgreSQL so check the validation error message.
final AssertionError assertionError = assertThrows(AssertionError.class, super::testAddedRowsAutoCommitTrue); final AssertionError assertionError = assertThrows(AssertionError.class, super::testAddedRowsAutoCommitTrue);
assertThat(assertionError.getMessage(), equalTo("Processor has 1 validation failures:\n" + assertEquals(assertionError.getMessage(), "Processor has 1 validation failures:\n" +
"'Set Auto Commit' validated against 'true' is invalid because 'Set Auto Commit' " + "'Set Auto Commit' validated against 'true' is invalid because 'Set Auto Commit' " +
"must be set to 'false' because 'PostgreSQL' Database Type requires it to be 'false'\n")); "must be set to 'false' because 'PostgreSQL' Database Type requires it to be 'false'\n");
} }
} }

View File

@ -27,9 +27,8 @@ import org.junit.jupiter.api.Test;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import static org.hamcrest.CoreMatchers.containsString; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.hamcrest.core.IsNot.not;
public class TestLogAttribute { public class TestLogAttribute {
@ -51,9 +50,9 @@ public class TestLogAttribute {
final MockFlowFile flowFile = runner.enqueue("content", attrs); final MockFlowFile flowFile = runner.enqueue("content", attrs);
final String logMessage = logAttribute.processFlowFile(LOG, LogAttribute.DebugLevels.info, flowFile, session, context); final String logMessage = logAttribute.processFlowFile(LOG, LogAttribute.DebugLevels.info, flowFile, session, context);
assertThat(logMessage, not(containsString("foobaz-value"))); assertFalse(logMessage.contains("foobaz-value"));
assertThat(logMessage, containsString("foo-value")); assertTrue(logMessage.contains("foo-value"));
assertThat(logMessage, containsString("bar-value")); assertTrue(logMessage.contains("bar-value"));
} }
@Test @Test
@ -74,9 +73,9 @@ public class TestLogAttribute {
final MockFlowFile flowFile = runner.enqueue("content", attrs); final MockFlowFile flowFile = runner.enqueue("content", attrs);
final String logMessage = logAttribute.processFlowFile(LOG, LogAttribute.DebugLevels.info, flowFile, session, context); final String logMessage = logAttribute.processFlowFile(LOG, LogAttribute.DebugLevels.info, flowFile, session, context);
assertThat(logMessage, containsString("foobaz-value")); assertTrue(logMessage.contains("foobaz-value"));
assertThat(logMessage, containsString("foo-value")); assertTrue(logMessage.contains("foo-value"));
assertThat(logMessage, not(containsString("bar-value"))); assertFalse(logMessage.contains("bar-value"));
} }
@Test @Test
@ -99,9 +98,9 @@ public class TestLogAttribute {
final MockFlowFile flowFile = runner.enqueue("content", attrs); final MockFlowFile flowFile = runner.enqueue("content", attrs);
final String logMessage = logAttribute.processFlowFile(LOG, LogAttribute.DebugLevels.info, flowFile, session, context); final String logMessage = logAttribute.processFlowFile(LOG, LogAttribute.DebugLevels.info, flowFile, session, context);
assertThat(logMessage, not(containsString("foobaz-value"))); assertFalse(logMessage.contains("foobaz-value"));
assertThat(logMessage, containsString("foo-value")); assertTrue(logMessage.contains("foo-value"));
assertThat(logMessage, not(containsString("bar-value"))); assertFalse(logMessage.contains("bar-value"));
} }
@Test @Test
@ -122,9 +121,9 @@ public class TestLogAttribute {
final MockFlowFile flowFile = runner.enqueue("content", attrs); final MockFlowFile flowFile = runner.enqueue("content", attrs);
final String logMessage = logAttribute.processFlowFile(LOG, LogAttribute.DebugLevels.info, flowFile, session, context); final String logMessage = logAttribute.processFlowFile(LOG, LogAttribute.DebugLevels.info, flowFile, session, context);
assertThat(logMessage, containsString("foobaz-value")); assertTrue(logMessage.contains("foobaz-value"));
assertThat(logMessage, containsString("foo-value")); assertTrue(logMessage.contains("foo-value"));
assertThat(logMessage, not(containsString("bar-value"))); assertFalse(logMessage.contains("bar-value"));
} }
@Test @Test
@ -145,9 +144,9 @@ public class TestLogAttribute {
final MockFlowFile flowFile = runner.enqueue("content", attrs); final MockFlowFile flowFile = runner.enqueue("content", attrs);
final String logMessage = logAttribute.processFlowFile(LOG, LogAttribute.DebugLevels.info, flowFile, session, context); final String logMessage = logAttribute.processFlowFile(LOG, LogAttribute.DebugLevels.info, flowFile, session, context);
assertThat(logMessage, not(containsString("foobaz-value"))); assertFalse(logMessage.contains("foobaz-value"));
assertThat(logMessage, not(containsString("foo-value"))); assertFalse(logMessage.contains("foo-value"));
assertThat(logMessage, containsString("bar-value")); assertTrue(logMessage.contains("bar-value"));
} }
@Test @Test
@ -170,9 +169,9 @@ public class TestLogAttribute {
final MockFlowFile flowFile = runner.enqueue("content", attrs); final MockFlowFile flowFile = runner.enqueue("content", attrs);
final String logMessage = logAttribute.processFlowFile(LOG, LogAttribute.DebugLevels.info, flowFile, session, context); final String logMessage = logAttribute.processFlowFile(LOG, LogAttribute.DebugLevels.info, flowFile, session, context);
assertThat(logMessage, not(containsString("foobaz-value"))); assertFalse(logMessage.contains("foobaz-value"));
assertThat(logMessage, not(containsString("foo-value"))); assertFalse(logMessage.contains("foo-value"));
assertThat(logMessage, not(containsString("bar-value"))); assertFalse(logMessage.contains("bar-value"));
} }
@Test @Test
@ -195,9 +194,9 @@ public class TestLogAttribute {
final MockFlowFile flowFile = runner.enqueue("content", attrs); final MockFlowFile flowFile = runner.enqueue("content", attrs);
final String logMessage = logAttribute.processFlowFile(LOG, LogAttribute.DebugLevels.info, flowFile, session, context); final String logMessage = logAttribute.processFlowFile(LOG, LogAttribute.DebugLevels.info, flowFile, session, context);
assertThat(logMessage, not(containsString("foobaz-value"))); assertFalse(logMessage.contains("foobaz-value"));
assertThat(logMessage, not(containsString("foo-value"))); assertFalse(logMessage.contains("foo-value"));
assertThat(logMessage, not(containsString("bar-value"))); assertFalse(logMessage.contains("bar-value"));
} }
@Test @Test
@ -220,9 +219,9 @@ public class TestLogAttribute {
final MockFlowFile flowFile = runner.enqueue("content", attrs); final MockFlowFile flowFile = runner.enqueue("content", attrs);
final String logMessage = logAttribute.processFlowFile(LOG, LogAttribute.DebugLevels.info, flowFile, session, context); final String logMessage = logAttribute.processFlowFile(LOG, LogAttribute.DebugLevels.info, flowFile, session, context);
assertThat(logMessage, not(containsString("foobaz-value"))); assertFalse(logMessage.contains("foobaz-value"));
assertThat(logMessage, containsString("foo-value")); assertTrue(logMessage.contains("foo-value"));
assertThat(logMessage, not(containsString("bar-value"))); assertFalse(logMessage.contains("bar-value"));
} }
@Test @Test
@ -244,8 +243,8 @@ public class TestLogAttribute {
final MockFlowFile flowFile = runner.enqueue("content", attrs); final MockFlowFile flowFile = runner.enqueue("content", attrs);
final String logMessage = logAttribute.processFlowFile(LOG, LogAttribute.DebugLevels.info, flowFile, session, context); final String logMessage = logAttribute.processFlowFile(LOG, LogAttribute.DebugLevels.info, flowFile, session, context);
assertThat(logMessage, not(containsString("foobaz-value"))); assertFalse(logMessage.contains("foobaz-value"));
assertThat(logMessage, containsString("foo-value")); assertTrue(logMessage.contains("foo-value"));
assertThat(logMessage, not(containsString("bar-value"))); assertFalse(logMessage.contains("bar-value"));
} }
} }

View File

@ -26,8 +26,6 @@ import org.junit.jupiter.api.Test;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
@ -63,75 +61,59 @@ public class TestVirtualFileSystem {
@Test @Test
public void testTryToCreateDirectoryWithNonExistentParents() { public void testTryToCreateDirectoryWithNonExistentParents() {
// GIVEN
VirtualPath newDirectory = new VirtualPath("/Directory3/SubDirectory5/SubSubDirectory"); VirtualPath newDirectory = new VirtualPath("/Directory3/SubDirectory5/SubSubDirectory");
// WHEN
boolean directoryCreated = fileSystem.mkdir(newDirectory); boolean directoryCreated = fileSystem.mkdir(newDirectory);
// THEN
assertFalse(directoryCreated); assertFalse(directoryCreated);
assertAllDirectoriesAre(ORIGINAL_DIRECTORY_LIST); assertAllDirectoriesAre(ORIGINAL_DIRECTORY_LIST);
} }
@Test @Test
public void testListContentsOfDirectory() { public void testListContentsOfDirectory() {
// GIVEN
VirtualPath parent = new VirtualPath("/Directory1"); VirtualPath parent = new VirtualPath("/Directory1");
VirtualPath[] expectedSubDirectories = { VirtualPath[] expectedSubDirectories = {
new VirtualPath("/Directory1/SubDirectory1"), new VirtualPath("/Directory1/SubDirectory1"),
new VirtualPath("/Directory1/SubDirectory2") new VirtualPath("/Directory1/SubDirectory2")
}; };
// WHEN
List<VirtualPath> subDirectories = fileSystem.listChildren(parent); List<VirtualPath> subDirectories = fileSystem.listChildren(parent);
// THEN assertTrue(subDirectories.containsAll(Arrays.asList(expectedSubDirectories)));
assertThat(subDirectories, containsInAnyOrder(expectedSubDirectories));
} }
@Test @Test
public void testListContentsOfRoot() { public void testListContentsOfRoot() {
// GIVEN
VirtualPath parent = new VirtualPath("/"); VirtualPath parent = new VirtualPath("/");
VirtualPath[] expectedSubDirectories = { VirtualPath[] expectedSubDirectories = {
new VirtualPath("/Directory1"), new VirtualPath("/Directory1"),
new VirtualPath("/Directory2") new VirtualPath("/Directory2")
}; };
// WHEN
List<VirtualPath> subDirectories = fileSystem.listChildren(parent); List<VirtualPath> subDirectories = fileSystem.listChildren(parent);
// THEN assertTrue(subDirectories.containsAll(Arrays.asList(expectedSubDirectories)));
assertThat(subDirectories, containsInAnyOrder(expectedSubDirectories));
} }
@Test @Test
public void testListContentsOfEmptyDirectory() { public void testListContentsOfEmptyDirectory() {
// GIVEN
VirtualPath parent = new VirtualPath("/Directory2/SubDirectory3"); VirtualPath parent = new VirtualPath("/Directory2/SubDirectory3");
// WHEN
List<VirtualPath> subDirectories = fileSystem.listChildren(parent); List<VirtualPath> subDirectories = fileSystem.listChildren(parent);
// THEN
assertEquals(0, subDirectories.size()); assertEquals(0, subDirectories.size());
} }
@Test @Test
public void testTryToDeleteNonEmptyDirectory() { public void testTryToDeleteNonEmptyDirectory() {
// WHEN
boolean success = fileSystem.delete(new VirtualPath("/Directory1")); boolean success = fileSystem.delete(new VirtualPath("/Directory1"));
// THEN
assertFalse(success); assertFalse(success);
assertAllDirectoriesAre(ORIGINAL_DIRECTORY_LIST); assertAllDirectoriesAre(ORIGINAL_DIRECTORY_LIST);
} }
@Test @Test
public void testDeleteEmptyDirectory() { public void testDeleteEmptyDirectory() {
// GIVEN
List<VirtualPath> expectedRemainingDirectories = Arrays.asList( List<VirtualPath> expectedRemainingDirectories = Arrays.asList(
new VirtualPath("/"), new VirtualPath("/"),
new VirtualPath("/Directory1"), new VirtualPath("/Directory1"),
@ -142,32 +124,24 @@ public class TestVirtualFileSystem {
new VirtualPath("/Directory2/SubDirectory4") new VirtualPath("/Directory2/SubDirectory4")
); );
// WHEN
boolean success = fileSystem.delete(new VirtualPath("/Directory2/SubDirectory3")); boolean success = fileSystem.delete(new VirtualPath("/Directory2/SubDirectory3"));
// THEN
assertTrue(success); assertTrue(success);
assertAllDirectoriesAre(expectedRemainingDirectories); assertAllDirectoriesAre(expectedRemainingDirectories);
} }
@Test @Test
public void testDeleteRoot() { public void testDeleteRoot() {
// WHEN
boolean success = fileSystem.delete(VirtualFileSystem.ROOT); boolean success = fileSystem.delete(VirtualFileSystem.ROOT);
// THEN
assertFalse(success); assertFalse(success);
assertAllDirectoriesAre(ORIGINAL_DIRECTORY_LIST); assertAllDirectoriesAre(ORIGINAL_DIRECTORY_LIST);
} }
@Test @Test
public void testDeleteNonExistentDirectory() { public void testDeleteNonExistentDirectory() {
// WHEN
boolean success = fileSystem.delete(new VirtualPath("/Directory3")); boolean success = fileSystem.delete(new VirtualPath("/Directory3"));
// THEN
assertFalse(success); assertFalse(success);
assertAllDirectoriesAre(ORIGINAL_DIRECTORY_LIST); assertAllDirectoriesAre(ORIGINAL_DIRECTORY_LIST);
} }

View File

@ -16,7 +16,6 @@
*/ */
package org.apache.nifi.lookup; package org.apache.nifi.lookup;
import java.io.IOException;
import java.util.Collections; import java.util.Collections;
import java.util.Optional; import java.util.Optional;
import org.apache.nifi.csv.CSVUtils; import org.apache.nifi.csv.CSVUtils;
@ -24,11 +23,8 @@ import org.apache.nifi.reporting.InitializationException;
import org.apache.nifi.serialization.record.Record; import org.apache.nifi.serialization.record.Record;
import org.apache.nifi.util.TestRunner; import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners; import org.apache.nifi.util.TestRunners;
import org.hamcrest.MatcherAssert;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
@ -37,7 +33,7 @@ public class TestCSVRecordLookupService {
@Test @Test
public void testSimpleCsvRecordLookupService() throws InitializationException, IOException, LookupFailureException { public void testSimpleCsvRecordLookupService() throws InitializationException, LookupFailureException {
final TestRunner runner = TestRunners.newTestRunner(TestProcessor.class); final TestRunner runner = TestRunners.newTestRunner(TestProcessor.class);
final CSVRecordLookupService service = new CSVRecordLookupService(); final CSVRecordLookupService service = new CSVRecordLookupService();
@ -53,8 +49,6 @@ public class TestCSVRecordLookupService {
.getControllerServiceLookup() .getControllerServiceLookup()
.getControllerService("csv-record-lookup-service"); .getControllerService("csv-record-lookup-service");
MatcherAssert.assertThat(lookupService, instanceOf(LookupService.class));
final Optional<Record> property1 = lookupService.lookup(Collections.singletonMap("key", "property.1")); final Optional<Record> property1 = lookupService.lookup(Collections.singletonMap("key", "property.1"));
assertEquals("this is property 1", property1.get().getAsString("value")); assertEquals("this is property 1", property1.get().getAsString("value"));
assertEquals("2017-04-01", property1.get().getAsString("created_at")); assertEquals("2017-04-01", property1.get().getAsString("created_at"));
@ -81,9 +75,9 @@ public class TestCSVRecordLookupService {
runner.assertValid(service); runner.assertValid(service);
final Optional<Record> property1 = service.lookup(Collections.singletonMap("key", "property.1")); final Optional<Record> property1 = service.lookup(Collections.singletonMap("key", "property.1"));
MatcherAssert.assertThat(property1.isPresent(), is(true)); assertTrue(property1.isPresent());
MatcherAssert.assertThat(property1.get().getAsString("value"), is("this is property \uff11")); assertEquals("this is property \uff11", property1.get().getAsString("value"));
MatcherAssert.assertThat(property1.get().getAsString("created_at"), is("2017-04-01")); assertEquals("2017-04-01", property1.get().getAsString("created_at"));
} }
@Test @Test

View File

@ -26,7 +26,6 @@ import org.apache.nifi.distributed.cache.client.Serializer;
import org.apache.nifi.reporting.InitializationException; import org.apache.nifi.reporting.InitializationException;
import org.apache.nifi.util.TestRunner; import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners; import org.apache.nifi.util.TestRunners;
import org.hamcrest.MatcherAssert;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.util.ArrayList; import java.util.ArrayList;
@ -35,7 +34,6 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
public class TestDistributedMapCacheLookupService { public class TestDistributedMapCacheLookupService {
@ -57,8 +55,6 @@ public class TestDistributedMapCacheLookupService {
runner.assertValid(service); runner.assertValid(service);
MatcherAssert.assertThat(service, instanceOf(LookupService.class));
final Optional<String> get = service.lookup(Collections.singletonMap("key", "myKey")); final Optional<String> get = service.lookup(Collections.singletonMap("key", "myKey"));
assertEquals(Optional.of("myValue"), get); assertEquals(Optional.of("myValue"), get);

View File

@ -19,13 +19,11 @@ package org.apache.nifi.lookup;
import org.apache.nifi.reporting.InitializationException; import org.apache.nifi.reporting.InitializationException;
import org.apache.nifi.util.TestRunner; import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners; import org.apache.nifi.util.TestRunners;
import org.hamcrest.MatcherAssert;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.util.Collections; import java.util.Collections;
import java.util.Optional; import java.util.Optional;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
public class TestPropertiesFileLookupService { public class TestPropertiesFileLookupService {
@ -47,8 +45,6 @@ public class TestPropertiesFileLookupService {
.getControllerServiceLookup() .getControllerServiceLookup()
.getControllerService("properties-file-lookup-service"); .getControllerService("properties-file-lookup-service");
MatcherAssert.assertThat(lookupService, instanceOf(LookupService.class));
final Optional<String> property1 = lookupService.lookup(Collections.singletonMap("key", "property.1")); final Optional<String> property1 = lookupService.lookup(Collections.singletonMap("key", "property.1"));
assertEquals(Optional.of("this is property 1"), property1); assertEquals(Optional.of("this is property 1"), property1);
@ -76,8 +72,6 @@ public class TestPropertiesFileLookupService {
.getControllerServiceLookup() .getControllerServiceLookup()
.getControllerService("properties-file-lookup-service"); .getControllerService("properties-file-lookup-service");
MatcherAssert.assertThat(lookupService, instanceOf(LookupService.class));
final Optional<String> property1 = lookupService.lookup(Collections.singletonMap("key", "property.1")); final Optional<String> property1 = lookupService.lookup(Collections.singletonMap("key", "property.1"));
assertEquals(Optional.of("this is property 1"), property1); assertEquals(Optional.of("this is property 1"), property1);

View File

@ -20,15 +20,11 @@ import org.apache.nifi.csv.CSVUtils;
import org.apache.nifi.reporting.InitializationException; import org.apache.nifi.reporting.InitializationException;
import org.apache.nifi.util.TestRunner; import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners; import org.apache.nifi.util.TestRunners;
import org.hamcrest.MatcherAssert;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.Collections; import java.util.Collections;
import java.util.Optional; import java.util.Optional;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
@ -55,8 +51,6 @@ public class TestSimpleCsvFileLookupService {
.getControllerServiceLookup() .getControllerServiceLookup()
.getControllerService("csv-file-lookup-service"); .getControllerService("csv-file-lookup-service");
MatcherAssert.assertThat(lookupService, instanceOf(LookupService.class));
final Optional<String> property1 = lookupService.lookup(Collections.singletonMap("key", "property.1")); final Optional<String> property1 = lookupService.lookup(Collections.singletonMap("key", "property.1"));
assertEquals(Optional.of("this is property 1"), property1); assertEquals(Optional.of("this is property 1"), property1);
@ -68,7 +62,7 @@ public class TestSimpleCsvFileLookupService {
} }
@Test @Test
public void testSimpleCsvFileLookupServiceWithCharset() throws InitializationException, IOException, LookupFailureException { public void testSimpleCsvFileLookupServiceWithCharset() throws InitializationException, LookupFailureException {
final TestRunner runner = TestRunners.newTestRunner(TestProcessor.class); final TestRunner runner = TestRunners.newTestRunner(TestProcessor.class);
final SimpleCsvFileLookupService service = new SimpleCsvFileLookupService(); final SimpleCsvFileLookupService service = new SimpleCsvFileLookupService();
@ -82,8 +76,8 @@ public class TestSimpleCsvFileLookupService {
runner.assertValid(service); runner.assertValid(service);
final Optional<String> property1 = service.lookup(Collections.singletonMap("key", "property.1")); final Optional<String> property1 = service.lookup(Collections.singletonMap("key", "property.1"));
MatcherAssert.assertThat(property1.isPresent(), is(true)); assertTrue(property1.isPresent());
MatcherAssert.assertThat(property1.get(), is("this is property \uff11")); assertEquals("this is property \uff11", property1.get());
} }
@Test @Test

View File

@ -19,17 +19,15 @@ package org.apache.nifi.lookup;
import org.apache.nifi.reporting.InitializationException; import org.apache.nifi.reporting.InitializationException;
import org.apache.nifi.util.TestRunner; import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners; import org.apache.nifi.util.TestRunners;
import org.hamcrest.MatcherAssert;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.util.Collections; import java.util.Collections;
import java.util.Optional; import java.util.Optional;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class TestSimpleKeyValueLookupService { public class TestSimpleKeyValueLookupService {
final static Optional<String> EMPTY_STRING = Optional.empty();
@Test @Test
public void testSimpleKeyValueLookupService() throws InitializationException { public void testSimpleKeyValueLookupService() throws InitializationException {
@ -42,8 +40,6 @@ public class TestSimpleKeyValueLookupService {
runner.enableControllerService(service); runner.enableControllerService(service);
runner.assertValid(service); runner.assertValid(service);
MatcherAssert.assertThat(service, instanceOf(LookupService.class));
final Optional<String> get1 = service.lookup(Collections.singletonMap("key", "key1")); final Optional<String> get1 = service.lookup(Collections.singletonMap("key", "key1"));
assertEquals(Optional.of("value1"), get1); assertEquals(Optional.of("value1"), get1);
@ -51,6 +47,6 @@ public class TestSimpleKeyValueLookupService {
assertEquals(Optional.of("value2"), get2); assertEquals(Optional.of("value2"), get2);
final Optional<String> get3 = service.lookup(Collections.singletonMap("key", "key3")); final Optional<String> get3 = service.lookup(Collections.singletonMap("key", "key3"));
assertEquals(EMPTY_STRING, get3); assertTrue(get3.isEmpty());
} }
} }

View File

@ -19,13 +19,11 @@ package org.apache.nifi.lookup;
import org.apache.nifi.reporting.InitializationException; import org.apache.nifi.reporting.InitializationException;
import org.apache.nifi.util.TestRunner; import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners; import org.apache.nifi.util.TestRunners;
import org.hamcrest.MatcherAssert;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.util.Collections; import java.util.Collections;
import java.util.Optional; import java.util.Optional;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
@ -48,8 +46,6 @@ public class TestXMLFileLookupService {
.getControllerServiceLookup() .getControllerServiceLookup()
.getControllerService("xml-file-lookup-service"); .getControllerService("xml-file-lookup-service");
MatcherAssert.assertThat(lookupService, instanceOf(LookupService.class));
final Optional<String> property1 = lookupService.lookup(Collections.singletonMap("key", "properties.property(0)")); final Optional<String> property1 = lookupService.lookup(Collections.singletonMap("key", "properties.property(0)"));
assertEquals(Optional.of("this is property 1"), property1); assertEquals(Optional.of("this is property 1"), property1);

View File

@ -33,9 +33,8 @@ import org.apache.nifi.serialization.record.RecordSchema;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.mockito.Mockito; import org.mockito.Mockito;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
public class ITApacheCSVRecordReader { public class ITApacheCSVRecordReader {
@ -58,13 +57,10 @@ public class ITApacheCSVRecordReader {
public void testParserPerformance() throws IOException, MalformedRecordException { public void testParserPerformance() throws IOException, MalformedRecordException {
// Generates about 130MB of data // Generates about 130MB of data
final int NUM_LINES = 2500000; final int NUM_LINES = 2500000;
StringBuilder sb = new StringBuilder("id,name,balance,address,city,state,zipCode,country\n"); String sb = "id,name,balance,address,city,state,zipCode,country\n" + "1,John Doe,4750.89D,123 My Street,My City,MS,11111,USA\n".repeat(NUM_LINES);
for (int i = 0; i < NUM_LINES; i++) {
sb.append("1,John Doe,4750.89D,123 My Street,My City,MS,11111,USA\n");
}
final RecordSchema schema = new SimpleRecordSchema(getDefaultFields()); final RecordSchema schema = new SimpleRecordSchema(getDefaultFields());
try (final InputStream bais = new ByteArrayInputStream(sb.toString().getBytes()); try (final InputStream bais = new ByteArrayInputStream(sb.getBytes());
final CSVRecordReader reader = new CSVRecordReader(bais, Mockito.mock(ComponentLog.class), schema, format, true, false, final CSVRecordReader reader = new CSVRecordReader(bais, Mockito.mock(ComponentLog.class), schema, format, true, false,
RecordFieldType.DATE.getDefaultFormat(), RecordFieldType.TIME.getDefaultFormat(), RecordFieldType.TIMESTAMP.getDefaultFormat(), "UTF-8")) { RecordFieldType.DATE.getDefaultFormat(), RecordFieldType.TIME.getDefaultFormat(), RecordFieldType.TIMESTAMP.getDefaultFormat(), "UTF-8")) {
@ -79,7 +75,7 @@ public class ITApacheCSVRecordReader {
} }
@Test @Test
public void testExceptionThrownOnParseProblem() throws IOException, MalformedRecordException { public void testExceptionThrownOnParseProblem() {
CSVFormat csvFormat = CSVFormat.DEFAULT.builder().setHeader().setSkipHeaderRecord(true).setQuoteMode(QuoteMode.ALL).setTrim(true).setDelimiter(',').build(); CSVFormat csvFormat = CSVFormat.DEFAULT.builder().setHeader().setSkipHeaderRecord(true).setQuoteMode(QuoteMode.ALL).setTrim(true).setDelimiter(',').build();
final int NUM_LINES = 25; final int NUM_LINES = 25;
StringBuilder sb = new StringBuilder("\"id\",\"name\",\"balance\""); StringBuilder sb = new StringBuilder("\"id\",\"name\",\"balance\"");
@ -97,7 +93,7 @@ public class ITApacheCSVRecordReader {
while (reader.nextRecord() != null) {} while (reader.nextRecord() != null) {}
} catch (Exception e) { } catch (Exception e) {
assertThat(e, instanceOf(MalformedRecordException.class)); assertInstanceOf(MalformedRecordException.class, e);
} }
} }
} }

View File

@ -32,11 +32,9 @@ import org.junit.jupiter.api.condition.DisabledIfSystemProperty;
import org.junit.jupiter.api.condition.EnabledOnOs; import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS; import org.junit.jupiter.api.condition.OS;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@EnabledOnOs({ OS.MAC }) @EnabledOnOs({ OS.MAC })
@DisabledIfSystemProperty(named = "os.arch", matches = "aarch64|arm64") @DisabledIfSystemProperty(named = "os.arch", matches = "aarch64|arm64")
@ -65,7 +63,7 @@ public class TestLoadNativeLibFromNar extends AbstractTestNarLoader {
.map(Bundle::getClassLoader) .map(Bundle::getClassLoader)
.filter(NarClassLoader.class::isInstance) .filter(NarClassLoader.class::isInstance)
.map(NarClassLoader.class::cast) .map(NarClassLoader.class::cast)
.collect(Collectors.toList()); .toList();
Set<String> actualLibraryLocations = narClassLoaders.stream() Set<String> actualLibraryLocations = narClassLoaders.stream()
.map(classLoader -> classLoader.findLibrary("testjni")) .map(classLoader -> classLoader.findLibrary("testjni"))
@ -82,8 +80,9 @@ public class TestLoadNativeLibFromNar extends AbstractTestNarLoader {
} }
assertEquals(2, actualLibraryLocations.size()); assertEquals(2, actualLibraryLocations.size());
assertThat(actualLibraryLocations, hasItem(containsString("nifi-nar_with_native_lib-1")));
assertThat(actualLibraryLocations, hasItem(containsString("nifi-nar_with_native_lib-2"))); assertTrue(actualLibraryLocations.stream().anyMatch(location -> location.contains("nifi-nar_with_native_lib-1")));
assertTrue(actualLibraryLocations.stream().anyMatch(location -> location.contains("nifi-nar_with_native_lib-2")));
} }
@Test @Test
@ -120,7 +119,7 @@ public class TestLoadNativeLibFromNar extends AbstractTestNarLoader {
.getMethod("testJniMethod") .getMethod("testJniMethod")
.invoke(TestJNI.getDeclaredConstructor().newInstance()); .invoke(TestJNI.getDeclaredConstructor().newInstance());
assertThat(actualLibraryLocation, containsString(instanceClassLoader.getIdentifier())); assertTrue(actualLibraryLocation.contains(instanceClassLoader.getIdentifier()));
assertEquals("calledNativeTestJniMethod", actualJniMethodReturnValue); assertEquals("calledNativeTestJniMethod", actualJniMethodReturnValue);
} }
} }

View File

@ -34,11 +34,9 @@ import org.junit.jupiter.api.condition.DisabledIfSystemProperty;
import org.junit.jupiter.api.condition.EnabledOnOs; import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS; import org.junit.jupiter.api.condition.OS;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@EnabledOnOs({ OS.MAC }) @EnabledOnOs({ OS.MAC })
@ -84,7 +82,7 @@ public class TestLoadNativeLibViaSystemProperty extends AbstractTestNarLoader {
.map(Bundle::getClassLoader) .map(Bundle::getClassLoader)
.filter(NarClassLoader.class::isInstance) .filter(NarClassLoader.class::isInstance)
.map(NarClassLoader.class::cast) .map(NarClassLoader.class::cast)
.collect(Collectors.toList()); .toList();
Set<String> actualLibraryLocations = narClassLoaders.stream() Set<String> actualLibraryLocations = narClassLoaders.stream()
@ -102,7 +100,7 @@ public class TestLoadNativeLibViaSystemProperty extends AbstractTestNarLoader {
} }
assertEquals(1, actualLibraryLocations.size()); assertEquals(1, actualLibraryLocations.size());
assertThat(actualLibraryLocations, hasItem(containsString("nifi-nar_without_native_lib-1"))); assertTrue(actualLibraryLocations.stream().anyMatch(location -> location.contains("nifi-nar_without_native_lib-1")));
} }
@Test @Test
@ -140,7 +138,7 @@ public class TestLoadNativeLibViaSystemProperty extends AbstractTestNarLoader {
.getMethod("testJniMethod") .getMethod("testJniMethod")
.invoke(TestJNI.getDeclaredConstructor().newInstance()); .invoke(TestJNI.getDeclaredConstructor().newInstance());
assertThat(actualLibraryLocation, containsString(instanceClassLoader.getIdentifier())); assertTrue(actualLibraryLocation.contains(instanceClassLoader.getIdentifier()));
assertEquals("calledNativeTestJniMethod", actualJniMethodReturnValue); assertEquals("calledNativeTestJniMethod", actualJniMethodReturnValue);
} }
} }

View File

@ -56,10 +56,6 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
@ -192,17 +188,17 @@ public class TestFlowResource {
assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getMediaType()); assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getMediaType());
final Map<String, List<Sample>> metrics = convertJsonResponseToMap(response); final Map<String, List<Sample>> metrics = convertJsonResponseToMap(response);
assertThat(metrics.keySet(), hasSize(1)); assertEquals(1, metrics.keySet().size());
assertThat(metrics, hasKey(ROOT_FIELD_NAME)); assertTrue(metrics.containsKey(ROOT_FIELD_NAME));
final List<Sample> registryList = metrics.get(ROOT_FIELD_NAME); final List<Sample> registryList = metrics.get(ROOT_FIELD_NAME);
assertThat(registryList, hasSize(13)); assertEquals(13, registryList.size());
final Map<String, Long> result = getResult(registryList); final Map<String, Long> result = getResult(registryList);
assertThat(3L, equalTo(result.get(SAMPLE_NAME_JVM))); assertEquals(3L, result.get(SAMPLE_NAME_JVM));
assertThat(4L, equalTo(result.get(SAMPLE_LABEL_VALUES_PROCESS_GROUP))); assertEquals(4L, result.get(SAMPLE_LABEL_VALUES_PROCESS_GROUP));
assertThat(2L, equalTo(result.get(SAMPLE_LABEL_VALUES_ROOT_PROCESS_GROUP))); assertEquals(2L, result.get(SAMPLE_LABEL_VALUES_ROOT_PROCESS_GROUP));
assertThat(4L, equalTo(result.get(CLUSTER_LABEL_KEY))); assertEquals(4L, result.get(CLUSTER_LABEL_KEY));
} }
@Test @Test
@ -215,14 +211,14 @@ public class TestFlowResource {
assertEquals(MediaType.valueOf(MediaType.APPLICATION_JSON), response.getMediaType()); assertEquals(MediaType.valueOf(MediaType.APPLICATION_JSON), response.getMediaType());
final Map<String, List<Sample>> metrics = convertJsonResponseToMap(response); final Map<String, List<Sample>> metrics = convertJsonResponseToMap(response);
assertThat(metrics.keySet(), hasSize(1)); assertEquals(1, metrics.keySet().size());
assertThat(metrics, hasKey(ROOT_FIELD_NAME)); assertTrue(metrics.containsKey(ROOT_FIELD_NAME));
final List<Sample> registryList = metrics.get(ROOT_FIELD_NAME); final List<Sample> registryList = metrics.get(ROOT_FIELD_NAME);
assertThat(registryList, hasSize(3)); assertEquals(3, registryList.size());
final Map<String, Long> result = getResult(registryList); final Map<String, Long> result = getResult(registryList);
assertThat(3L, equalTo(result.get(SAMPLE_NAME_JVM))); assertEquals(3L, result.get(SAMPLE_NAME_JVM));
} }
@Test @Test
@ -235,14 +231,14 @@ public class TestFlowResource {
assertEquals(MediaType.valueOf(MediaType.APPLICATION_JSON), response.getMediaType()); assertEquals(MediaType.valueOf(MediaType.APPLICATION_JSON), response.getMediaType());
final Map<String, List<Sample>> metrics = convertJsonResponseToMap(response); final Map<String, List<Sample>> metrics = convertJsonResponseToMap(response);
assertThat(metrics.keySet(), hasSize(1)); assertEquals(1, metrics.keySet().size());
assertThat(metrics, hasKey(ROOT_FIELD_NAME)); assertTrue(metrics.containsKey(ROOT_FIELD_NAME));
final List<Sample> registryList = metrics.get(ROOT_FIELD_NAME); final List<Sample> registryList = metrics.get(ROOT_FIELD_NAME);
assertThat(registryList, hasSize(2)); assertEquals(2, registryList.size());
final Map<String, Long> result = getResult(registryList); final Map<String, Long> result = getResult(registryList);
assertThat(2L, equalTo(result.get(SAMPLE_NAME_JVM))); assertEquals(2L, result.get(SAMPLE_NAME_JVM));
} }
@Test @Test
@ -255,14 +251,14 @@ public class TestFlowResource {
assertEquals(MediaType.valueOf(MediaType.APPLICATION_JSON), response.getMediaType()); assertEquals(MediaType.valueOf(MediaType.APPLICATION_JSON), response.getMediaType());
final Map<String, List<Sample>> metrics = convertJsonResponseToMap(response); final Map<String, List<Sample>> metrics = convertJsonResponseToMap(response);
assertThat(metrics.keySet(), hasSize(1)); assertEquals(1, metrics.keySet().size());
assertThat(metrics, hasKey(ROOT_FIELD_NAME)); assertTrue(metrics.containsKey(ROOT_FIELD_NAME));
final List<Sample> registryList = metrics.get(ROOT_FIELD_NAME); final List<Sample> registryList = metrics.get(ROOT_FIELD_NAME);
assertThat(registryList, hasSize(2)); assertEquals(2, registryList.size());
final Map<String, Long> result = getResult(registryList); final Map<String, Long> result = getResult(registryList);
assertThat(2L, equalTo(result.get(SAMPLE_LABEL_VALUES_ROOT_PROCESS_GROUP))); assertEquals(2L, result.get(SAMPLE_LABEL_VALUES_ROOT_PROCESS_GROUP));
} }
@Test @Test
@ -275,15 +271,15 @@ public class TestFlowResource {
assertEquals(MediaType.valueOf(MediaType.APPLICATION_JSON), response.getMediaType()); assertEquals(MediaType.valueOf(MediaType.APPLICATION_JSON), response.getMediaType());
final Map<String, List<Sample>> metrics = convertJsonResponseToMap(response); final Map<String, List<Sample>> metrics = convertJsonResponseToMap(response);
assertThat(metrics.keySet(), hasSize(1)); assertEquals(1, metrics.keySet().size());
assertThat(metrics, hasKey(ROOT_FIELD_NAME)); assertTrue(metrics.containsKey(ROOT_FIELD_NAME));
final List<Sample> registryList = metrics.get(ROOT_FIELD_NAME); final List<Sample> registryList = metrics.get(ROOT_FIELD_NAME);
assertThat(registryList, hasSize(5)); assertEquals(5, registryList.size());
final Map<String, Long> result = getResult(registryList); final Map<String, Long> result = getResult(registryList);
assertThat(3L, equalTo(result.get(SAMPLE_NAME_JVM))); assertEquals(3L, result.get(SAMPLE_NAME_JVM));
assertThat(2L, equalTo(result.get(SAMPLE_LABEL_VALUES_ROOT_PROCESS_GROUP))); assertEquals(2L, result.get(SAMPLE_LABEL_VALUES_ROOT_PROCESS_GROUP));
} }
private String getResponseOutput(final Response response) throws IOException { private String getResponseOutput(final Response response) throws IOException {

View File

@ -36,6 +36,10 @@
<groupId>org.xmlunit</groupId> <groupId>org.xmlunit</groupId>
<artifactId>xmlunit-core</artifactId> <artifactId>xmlunit-core</artifactId>
</exclusion> </exclusion>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
</exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency> <dependency>

14
pom.xml
View File

@ -350,12 +350,6 @@
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>2.2</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.testcontainers</groupId> <groupId>org.testcontainers</groupId>
<artifactId>testcontainers-bom</artifactId> <artifactId>testcontainers-bom</artifactId>
@ -604,11 +598,6 @@
<artifactId>mockito-junit-jupiter</artifactId> <artifactId>mockito-junit-jupiter</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.junit.platform</groupId> <groupId>org.junit.platform</groupId>
<artifactId>junit-platform-commons</artifactId> <artifactId>junit-platform-commons</artifactId>
@ -873,6 +862,8 @@
<exclude>org.spockframework:*</exclude> <exclude>org.spockframework:*</exclude>
<!-- Groovy should not be used for testing --> <!-- Groovy should not be used for testing -->
<exclude>org.apache.groovy:groovy-test</exclude> <exclude>org.apache.groovy:groovy-test</exclude>
<!-- Hamcrest should not be used for testing -->
<exclude>org.hamcrest:hamcrest</exclude>
</excludes> </excludes>
</bannedDependencies> </bannedDependencies>
</rules> </rules>
@ -894,7 +885,6 @@
<dependency>org.junit.jupiter:junit-jupiter-api</dependency> <dependency>org.junit.jupiter:junit-jupiter-api</dependency>
<dependency>org.mockito:mockito-core</dependency> <dependency>org.mockito:mockito-core</dependency>
<dependency>org.mockito:mockito-junit-jupiter</dependency> <dependency>org.mockito:mockito-junit-jupiter</dependency>
<dependency>org.hamcrest:hamcrest</dependency>
<dependency>org.junit.platform:junit-platform-commons</dependency> <dependency>org.junit.platform:junit-platform-commons</dependency>
<dependency>org.slf4j:slf4j-simple</dependency> <dependency>org.slf4j:slf4j-simple</dependency>
</ignoredDependencies> </ignoredDependencies>