NIFI-9149 Refactored multiple NAR modules to use JUnit 5

- NIFI-9163 Refactored nifi-websocket-bundle to use JUnit 5
- NIFI-9162 Refactored nifi-update-attribute-bundle to use JUnit 5
- NIFI-9161 Refactored nifi-tcp-bundle to use JUnit 5
- NIFI-9160 Refactored nifi-stateful-analysis-bundle to use JUnit 5
- NIFI-9159 Refactored nifi-sql-reporting-bundle to use JUnit 5
- NIFI-9158 Refactored nifi-spring-bundle to use JUnit 5
- NIFI-9157 Refactored nifi-splunk-bundle to use JUnit 5
- NIFI-9156 Refactored nifi-spark-bundle to use JUnit 5
- NIFI-9155 Refactored nifi-solr-bundle to use JUnit 5
- NIFI-9154 Refactored nifi-social-media-bundle to use JUnit 5
- NIFI-9153 Refactored nifi-snmp-bundle to use JUnit 5
- NIFI-9152 Refactored nifi-smb-bundle to use JUnit 5
- NIFI-9151 Refactored nifi-slack-bundle to use JUnit 5
- NIFI-9150 Refactored nifi-site-to-site-reporting-bundle to use JUnit 5
- NIFI-9149 Refactored nifi-single-user-iaa-providers-bundle to use JUnit 5

This closes #5362

Signed-off-by: David Handermann <exceptionfactory@apache.org>
This commit is contained in:
Mike Thomsen 2021-08-31 11:24:55 -04:00 committed by exceptionfactory
parent 6259269f73
commit 1ca5a1dbbf
No known key found for this signature in database
GPG Key ID: 29B6A52D2AAE8DBA
49 changed files with 628 additions and 641 deletions

View File

@ -22,11 +22,11 @@ import org.apache.nifi.authentication.LoginIdentityProviderConfigurationContext;
import org.apache.nifi.authentication.exception.InvalidLoginCredentialsException;
import org.apache.nifi.authentication.single.user.encoder.PasswordEncoder;
import org.apache.nifi.util.NiFiProperties;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import java.net.URISyntaxException;
@ -38,13 +38,13 @@ import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class SingleUserLoginIdentityProviderTest {
private static final String BLANK_PROVIDERS = "/conf/login-identity-providers.xml";
@ -65,7 +65,7 @@ public class SingleUserLoginIdentityProviderTest {
private SingleUserLoginIdentityProvider provider;
@Before
@BeforeEach
public void setProvider() {
provider = new SingleUserLoginIdentityProvider();
encoder = new StringPasswordEncoder();
@ -90,11 +90,11 @@ public class SingleUserLoginIdentityProviderTest {
final String providersConfiguration = new String(Files.readAllBytes(configuredProvidersPath));
final Matcher usernameMatcher = USERNAME_PATTERN.matcher(providersConfiguration);
assertTrue("Username not found", usernameMatcher.find());
assertTrue(usernameMatcher.find(), "Username not found");
final String username = usernameMatcher.group(FIRST_GROUP);
final Matcher passwordMatcher = PASSWORD_PATTERN.matcher(providersConfiguration);
assertTrue("Password not found", passwordMatcher.find());
assertTrue(passwordMatcher.find(), "Password not found");
final LoginCredentials loginCredentials = new LoginCredentials(username, encoder.encoded);
final AuthenticationResponse response = provider.authenticate(loginCredentials);

View File

@ -19,21 +19,21 @@ package org.apache.nifi.authorization.single.user;
import org.apache.nifi.authorization.AuthorizerInitializationContext;
import org.apache.nifi.authorization.exception.AuthorizerCreationException;
import org.apache.nifi.util.NiFiProperties;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.jupiter.MockitoExtension;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;
import static org.junit.Assert.assertThrows;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class SingleUserAuthorizerTest {
private static final String BLANK_PROVIDERS = "/conf/login-identity-providers.xml";
@ -54,7 +54,7 @@ public class SingleUserAuthorizerTest {
@Mock
private AuthorizerInitializationContext initializationContext;
@Before
@BeforeEach
public void setAuthorizer() {
authorizer = new SingleUserAuthorizer();
when(initializationContext.getIdentifier()).thenReturn(AUTHORIZER_IDENTIFIER);

View File

@ -29,8 +29,7 @@ import org.apache.nifi.remote.client.SiteToSiteClient;
import org.apache.nifi.reporting.s2s.SiteToSiteUtils;
import org.apache.nifi.reporting.s2s.SiteToSiteUtils.NiFiUrlValidator;
import org.apache.nifi.util.MockPropertyValue;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.mockito.stubbing.Answer;
@ -47,9 +46,10 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
public class TestSiteToSiteBulletinReportingTask {
@ -115,6 +115,7 @@ public class TestSiteToSiteBulletinReportingTask {
final String msg = new String(task.dataSent.get(0), StandardCharsets.UTF_8);
JsonReader jsonReader = Json.createReader(new ByteArrayInputStream(msg.getBytes()));
JsonObject bulletinJson = jsonReader.readArray().getJsonObject(0);
assertEquals("message", bulletinJson.getString("bulletinMessage"));
assertEquals("group-name", bulletinJson.getString("bulletinGroupName"));
assertEquals("group-path", bulletinJson.getString("bulletinGroupPath"));
@ -179,18 +180,15 @@ public class TestSiteToSiteBulletinReportingTask {
final SiteToSiteClient client = Mockito.mock(SiteToSiteClient.class);
final Transaction transaction = Mockito.mock(Transaction.class);
try {
Mockito.doAnswer((Answer<Object>) invocation -> {
final byte[] data = invocation.getArgument(0, byte[].class);
dataSent.add(data);
return null;
}).when(transaction).send(Mockito.any(byte[].class), Mockito.any(Map.class));
assertDoesNotThrow(() -> {
Mockito.doAnswer((Answer<Object>) invocation -> {
final byte[] data = invocation.getArgument(0, byte[].class);
dataSent.add(data);
return null;
}).when(transaction).send(Mockito.any(byte[].class), Mockito.any(Map.class));
when(client.createTransaction(Mockito.any(TransferDirection.class))).thenReturn(transaction);
} catch (final Exception e) {
e.printStackTrace();
Assert.fail(e.toString());
}
when(client.createTransaction(Mockito.any(TransferDirection.class))).thenReturn(transaction);
});
siteToSiteClient = client;
}
}

View File

@ -17,7 +17,6 @@
package org.apache.nifi.reporting;
import org.apache.commons.lang3.SystemUtils;
import org.apache.nifi.attribute.expression.language.StandardPropertyValue;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.components.PropertyValue;
@ -35,13 +34,11 @@ import org.apache.nifi.serialization.RecordSetWriterFactory;
import org.apache.nifi.serialization.record.MockRecordWriter;
import org.apache.nifi.state.MockStateManager;
import org.apache.nifi.util.MockPropertyValue;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import javax.json.Json;
@ -60,21 +57,18 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.when;
@DisabledOnOs(OS.WINDOWS)
public class TestSiteToSiteMetricsReportingTask {
private ReportingContext context;
private ProcessGroupStatus status;
@BeforeClass
public static void setUpSuite() {
Assume.assumeTrue("Test only runs on *nix", !SystemUtils.IS_OS_WINDOWS);
}
@Before
@BeforeEach
public void setup() {
status = new ProcessGroupStatus();
status.setId("1234");
@ -116,12 +110,9 @@ public class TestSiteToSiteMetricsReportingTask {
context = Mockito.mock(ReportingContext.class);
Mockito.when(context.getStateManager()).thenReturn(new MockStateManager(task));
Mockito.doAnswer(new Answer<PropertyValue>() {
@Override
public PropertyValue answer(final InvocationOnMock invocation) throws Throwable {
final PropertyDescriptor descriptor = invocation.getArgument(0, PropertyDescriptor.class);
return new MockPropertyValue(properties.get(descriptor));
}
Mockito.doAnswer((Answer<PropertyValue>) invocation -> {
final PropertyDescriptor descriptor = invocation.getArgument(0, PropertyDescriptor.class);
return new MockPropertyValue(properties.get(descriptor));
}).when(context).getProperty(Mockito.any(PropertyDescriptor.class));
final EventAccess eventAccess = Mockito.mock(EventAccess.class);
@ -165,12 +156,9 @@ public class TestSiteToSiteMetricsReportingTask {
Mockito.when(pValueUrl.evaluateAttributeExpressions()).thenReturn(pValueUrl);
Mockito.when(pValueUrl.getValue()).thenReturn(url);
Mockito.doAnswer(new Answer<PropertyValue>() {
@Override
public PropertyValue answer(final InvocationOnMock invocation) throws Throwable {
final PropertyDescriptor descriptor = invocation.getArgument(0, PropertyDescriptor.class);
return new MockPropertyValue(properties.get(descriptor));
}
Mockito.doAnswer((Answer<PropertyValue>) invocation -> {
final PropertyDescriptor descriptor = invocation.getArgument(0, PropertyDescriptor.class);
return new MockPropertyValue(properties.get(descriptor));
}).when(validationContext).getProperty(Mockito.any(PropertyDescriptor.class));
final PropertyValue pValue = Mockito.mock(StandardPropertyValue.class);
@ -179,8 +167,8 @@ public class TestSiteToSiteMetricsReportingTask {
// should be invalid because both ambari format and record writer are set
Collection<ValidationResult> list = task.validate(validationContext);
Assert.assertEquals(1, list.size());
Assert.assertEquals(SiteToSiteMetricsReportingTask.RECORD_WRITER.getDisplayName(), list.iterator().next().getInput());
assertEquals(1, list.size());
assertEquals(SiteToSiteMetricsReportingTask.RECORD_WRITER.getDisplayName(), list.iterator().next().getInput());
}
@Test
@ -206,12 +194,9 @@ public class TestSiteToSiteMetricsReportingTask {
Mockito.when(pValueUrl.evaluateAttributeExpressions()).thenReturn(pValueUrl);
Mockito.when(pValueUrl.getValue()).thenReturn(url);
Mockito.doAnswer(new Answer<PropertyValue>() {
@Override
public PropertyValue answer(final InvocationOnMock invocation) throws Throwable {
final PropertyDescriptor descriptor = invocation.getArgument(0, PropertyDescriptor.class);
return new MockPropertyValue(properties.get(descriptor));
}
Mockito.doAnswer((Answer<PropertyValue>) invocation -> {
final PropertyDescriptor descriptor = invocation.getArgument(0, PropertyDescriptor.class);
return new MockPropertyValue(properties.get(descriptor));
}).when(validationContext).getProperty(Mockito.any(PropertyDescriptor.class));
final PropertyValue pValue = Mockito.mock(StandardPropertyValue.class);
@ -220,8 +205,8 @@ public class TestSiteToSiteMetricsReportingTask {
// should be invalid because both ambari format and record writer are set
Collection<ValidationResult> list = task.validate(validationContext);
Assert.assertEquals(1, list.size());
Assert.assertEquals(SiteToSiteMetricsReportingTask.RECORD_WRITER.getDisplayName(), list.iterator().next().getInput());
assertEquals(1, list.size());
assertEquals(SiteToSiteMetricsReportingTask.RECORD_WRITER.getDisplayName(), list.iterator().next().getInput());
}
@Test
@ -309,18 +294,15 @@ public class TestSiteToSiteMetricsReportingTask {
final SiteToSiteClient client = Mockito.mock(SiteToSiteClient.class);
final Transaction transaction = Mockito.mock(Transaction.class);
try {
Mockito.doAnswer((Answer<Object>) invocation -> {
final byte[] data = invocation.getArgument(0, byte[].class);
dataSent.add(data);
return null;
}).when(transaction).send(Mockito.any(byte[].class), Mockito.any(Map.class));
assertDoesNotThrow(() -> {
Mockito.doAnswer((Answer<Object>) invocation -> {
final byte[] data = invocation.getArgument(0, byte[].class);
dataSent.add(data);
return null;
}).when(transaction).send(Mockito.any(byte[].class), Mockito.any(Map.class));
when(client.createTransaction(Mockito.any(TransferDirection.class))).thenReturn(transaction);
} catch (final Exception e) {
e.printStackTrace();
Assert.fail(e.toString());
}
when(client.createTransaction(Mockito.any(TransferDirection.class))).thenReturn(transaction);
});
siteToSiteClient = client;
}
}

View File

@ -41,10 +41,8 @@ import org.apache.nifi.reporting.s2s.SiteToSiteUtils;
import org.apache.nifi.state.MockStateManager;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.MockPropertyValue;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import javax.json.Json;
@ -62,8 +60,9 @@ import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.when;
public class TestSiteToSiteProvenanceReportingTask {
@ -81,41 +80,32 @@ public class TestSiteToSiteProvenanceReportingTask {
when(context.getStateManager())
.thenReturn(new MockStateManager(task));
Mockito.doAnswer(new Answer<PropertyValue>() {
@Override
public PropertyValue answer(final InvocationOnMock invocation) throws Throwable {
final PropertyDescriptor descriptor = invocation.getArgument(0, PropertyDescriptor.class);
return new MockPropertyValue(properties.get(descriptor));
}
Mockito.doAnswer((Answer<PropertyValue>) invocation -> {
final PropertyDescriptor descriptor = invocation.getArgument(0, PropertyDescriptor.class);
return new MockPropertyValue(properties.get(descriptor));
}).when(context).getProperty(Mockito.any(PropertyDescriptor.class));
Mockito.doAnswer(new Answer<PropertyValue>() {
@Override
public PropertyValue answer(final InvocationOnMock invocation) throws Throwable {
final PropertyDescriptor descriptor = invocation.getArgument(0, PropertyDescriptor.class);
return new MockPropertyValue(properties.get(descriptor));
}
Mockito.doAnswer((Answer<PropertyValue>) invocation -> {
final PropertyDescriptor descriptor = invocation.getArgument(0, PropertyDescriptor.class);
return new MockPropertyValue(properties.get(descriptor));
}).when(confContext).getProperty(Mockito.any(PropertyDescriptor.class));
final AtomicInteger totalEvents = new AtomicInteger(0);
final EventAccess eventAccess = Mockito.mock(EventAccess.class);
Mockito.doAnswer(new Answer<List<ProvenanceEventRecord>>() {
@Override
public List<ProvenanceEventRecord> answer(final InvocationOnMock invocation) throws Throwable {
final long startId = invocation.getArgument(0, Long.class);
final int maxRecords = invocation.getArgument(1, Integer.class);
Mockito.doAnswer((Answer<List<ProvenanceEventRecord>>) invocation -> {
final long startId = invocation.getArgument(0, Long.class);
final int maxRecords = invocation.getArgument(1, Integer.class);
final List<ProvenanceEventRecord> eventsToReturn = new ArrayList<>();
for (int i = (int) Math.max(0, startId); i < (int) (startId + maxRecords) && totalEvents.get() < maxEventId; i++) {
if (event != null) {
eventsToReturn.add(event);
}
totalEvents.getAndIncrement();
final List<ProvenanceEventRecord> eventsToReturn = new ArrayList<>();
for (int i = (int) Math.max(0, startId); i < (int) (startId + maxRecords) && totalEvents.get() < maxEventId; i++) {
if (event != null) {
eventsToReturn.add(event);
}
return eventsToReturn;
totalEvents.getAndIncrement();
}
return eventsToReturn;
}).when(eventAccess).getProvenanceEvents(Mockito.anyLong(), Mockito.anyInt());
ProcessGroupStatus pgRoot = new ProcessGroupStatus();
pgRoot.setId("root");
@ -178,12 +168,7 @@ public class TestSiteToSiteProvenanceReportingTask {
pgB3.getConnectionStatus().add(b3RemoteOutputPort);
final ProvenanceEventRepository provenanceRepository = Mockito.mock(ProvenanceEventRepository.class);
Mockito.doAnswer(new Answer<Long>() {
@Override
public Long answer(final InvocationOnMock invocation) throws Throwable {
return maxEventId;
}
}).when(provenanceRepository).getMaxEventId();
Mockito.doAnswer((Answer<Long>) invocation -> maxEventId).when(provenanceRepository).getMaxEventId();
when(context.getEventAccess()).thenReturn(eventAccess);
when(eventAccess.getProvenanceRepository()).thenReturn(provenanceRepository);
@ -615,12 +600,7 @@ public class TestSiteToSiteProvenanceReportingTask {
// setup the mock provenance repository to return maxEventId
final ProvenanceEventRepository provenanceRepository = Mockito.mock(ProvenanceEventRepository.class);
Mockito.doAnswer(new Answer<Long>() {
@Override
public Long answer(final InvocationOnMock invocation) throws Throwable {
return maxEventId;
}
}).when(provenanceRepository).getMaxEventId();
Mockito.doAnswer((Answer<Long>) invocation -> maxEventId).when(provenanceRepository).getMaxEventId();
// setup the mock EventAccess to return the mock provenance repository
final EventAccess eventAccess = Mockito.mock(EventAccess.class);
@ -680,18 +660,16 @@ public class TestSiteToSiteProvenanceReportingTask {
final SiteToSiteClient client = Mockito.mock(SiteToSiteClient.class);
final Transaction transaction = Mockito.mock(Transaction.class);
try {
Mockito.doAnswer((Answer<Object>) invocation -> {
final byte[] data = invocation.getArgument(0, byte[].class);
dataSent.add(data);
return null;
}).when(transaction).send(Mockito.any(byte[].class), Mockito.any(Map.class));
assertDoesNotThrow(() -> {
Mockito.doAnswer((Answer<Object>) invocation -> {
final byte[] data = invocation.getArgument(0, byte[].class);
dataSent.add(data);
return null;
}).when(transaction).send(Mockito.any(byte[].class), Mockito.any(Map.class));
when(client.createTransaction(Mockito.any(TransferDirection.class))).thenReturn(transaction);
} catch (final Exception e) {
e.printStackTrace();
Assert.fail(e.toString());
}
when(client.createTransaction(Mockito.any(TransferDirection.class))).thenReturn(transaction);
});
siteToSiteClient = client;
}
}

View File

@ -37,10 +37,8 @@ import org.apache.nifi.reporting.s2s.SiteToSiteUtils;
import org.apache.nifi.state.MockStateManager;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.MockPropertyValue;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import javax.json.Json;
@ -59,11 +57,12 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
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.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
public class TestSiteToSiteStatusReportingTask {
@ -81,12 +80,9 @@ public class TestSiteToSiteStatusReportingTask {
context = Mockito.mock(ReportingContext.class);
Mockito.when(context.getStateManager())
.thenReturn(new MockStateManager(task));
Mockito.doAnswer(new Answer<PropertyValue>() {
@Override
public PropertyValue answer(final InvocationOnMock invocation) throws Throwable {
final PropertyDescriptor descriptor = invocation.getArgument(0, PropertyDescriptor.class);
return new MockPropertyValue(properties.get(descriptor));
}
Mockito.doAnswer((Answer<PropertyValue>) invocation -> {
final PropertyDescriptor descriptor = invocation.getArgument(0, PropertyDescriptor.class);
return new MockPropertyValue(properties.get(descriptor));
}).when(context).getProperty(Mockito.any(PropertyDescriptor.class));
final EventAccess eventAccess = Mockito.mock(EventAccess.class);
@ -542,18 +538,15 @@ public class TestSiteToSiteStatusReportingTask {
final SiteToSiteClient client = Mockito.mock(SiteToSiteClient.class);
final Transaction transaction = Mockito.mock(Transaction.class);
try {
Mockito.doAnswer((Answer<Object>) invocation -> {
final byte[] data = invocation.getArgument(0, byte[].class);
dataSent.add(data);
return null;
}).when(transaction).send(Mockito.any(byte[].class), Mockito.any(Map.class));
assertDoesNotThrow(() -> {
Mockito.doAnswer((Answer<Object>) invocation -> {
final byte[] data = invocation.getArgument(0, byte[].class);
dataSent.add(data);
return null;
}).when(transaction).send(Mockito.any(byte[].class), Mockito.any(Map.class));
when(client.createTransaction(Mockito.any(TransferDirection.class))).thenReturn(transaction);
} catch (final Exception e) {
e.printStackTrace();
Assert.fail(e.toString());
}
when(client.createTransaction(Mockito.any(TransferDirection.class))).thenReturn(transaction);
});
siteToSiteClient = client;
}
}

View File

@ -40,8 +40,7 @@ import org.apache.nifi.serialization.record.RecordSchema;
import org.apache.nifi.serialization.record.RecordSet;
import org.apache.nifi.state.MockStateManager;
import org.apache.nifi.util.MockControllerServiceInitializationContext;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.mockito.stubbing.Answer;
@ -53,8 +52,9 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
public class TestSiteToSiteReportingRecordSink {
@ -154,7 +154,7 @@ public class TestSiteToSiteReportingRecordSink {
final SiteToSiteClient client = Mockito.mock(SiteToSiteClient.class);
final Transaction transaction = Mockito.mock(Transaction.class);
try {
assertDoesNotThrow(() -> {
Mockito.doAnswer((Answer<Object>) invocation -> {
final byte[] data = invocation.getArgument(0, byte[].class);
dataSent.add(data);
@ -162,10 +162,7 @@ public class TestSiteToSiteReportingRecordSink {
}).when(transaction).send(Mockito.any(byte[].class), Mockito.any(Map.class));
Mockito.when(client.createTransaction(Mockito.any(TransferDirection.class))).thenReturn(transaction);
} catch (final Exception e) {
e.printStackTrace();
Assert.fail(e.toString());
}
});
return client;
}

View File

@ -18,14 +18,14 @@ package org.apache.nifi.processors.slack;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class PostSlackConfigValidationTest {
private TestRunner testRunner;
@Before
@BeforeEach
public void setup() {
testRunner = TestRunners.newTestRunner(PostSlack.class);
}

View File

@ -23,8 +23,8 @@ import org.apache.nifi.util.TestRunners;
import org.apache.nifi.web.util.TestServer;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.charset.Charset;
import java.util.HashMap;
@ -33,10 +33,10 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.apache.nifi.processors.slack.PostSlackCaptureServlet.REQUEST_PATH_SUCCESS_FILE_MSG;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class PostSlackFileMessageTest {
@ -45,7 +45,7 @@ public class PostSlackFileMessageTest {
private TestServer server;
private PostSlackCaptureServlet servlet;
@Before
@BeforeEach
public void setup() throws Exception {
testRunner = TestRunners.newTestRunner(PostSlack.class);
@ -212,32 +212,32 @@ public class PostSlackFileMessageTest {
assertTrue(contentType.startsWith("multipart/form-data"));
String boundary = parseMultipartBoundary(contentType);
assertNotNull("Multipart boundary not found in Content-Type header: " + contentType, boundary);
assertNotNull(boundary, "Multipart boundary not found in Content-Type header: " + contentType);
Map<String, String> parts = parsePostBodyParts(boundary);
assertNotNull("'channels' parameter not found in the POST request body", parts.get("channels"));
assertEquals("'channels' parameter has wrong value", "my-channel", parts.get("channels"));
assertNotNull(parts.get("channels"), "'channels' parameter not found in the POST request body");
assertEquals("my-channel", parts.get("channels"), "'channels' parameter has wrong value");
if (text != null) {
assertNotNull("'initial_comment' parameter not found in the POST request body", parts.get("initial_comment"));
assertEquals("'initial_comment' parameter has wrong value", text, parts.get("initial_comment"));
assertNotNull(parts.get("initial_comment"), "'initial_comment' parameter not found in the POST request body");
assertEquals(text, parts.get("initial_comment"), "'initial_comment' parameter has wrong value");
}
assertNotNull("'filename' parameter not found in the POST request body", parts.get("filename"));
assertEquals("'fileName' parameter has wrong value", fileName, parts.get("filename"));
assertNotNull(parts.get("filename"), "'filename' parameter not found in the POST request body");
assertEquals(fileName, parts.get("filename"), "'fileName' parameter has wrong value");
if (title != null) {
assertNotNull("'title' parameter not found in the POST request body", parts.get("title"));
assertEquals("'title' parameter has wrong value", title, parts.get("title"));
assertNotNull(parts.get("title"), "'title' parameter not found in the POST request body");
assertEquals(title, parts.get("title"), "'title' parameter has wrong value");
}
assertNotNull("The file part not found in the POST request body", parts.get("file"));
assertNotNull(parts.get("file"), "The file part not found in the POST request body");
Map<String, String> fileParameters = parseFilePart(boundary);
assertEquals("File data is wrong in the POST request body", "my-data", fileParameters.get("data"));
assertEquals("'filename' attribute of the file part has wrong value", fileName, fileParameters.get("filename"));
assertEquals("Content-Type of the file part is wrong", mimeType, fileParameters.get("contentType"));
assertEquals("my-data", fileParameters.get("data"), "File data is wrong in the POST request body");
assertEquals(fileName, fileParameters.get("filename"), "'filename' attribute of the file part has wrong value");
assertEquals(mimeType, fileParameters.get("contentType"), "Content-Type of the file part is wrong");
}
private String parseMultipartBoundary(String contentType) {

View File

@ -21,8 +21,8 @@ import org.apache.nifi.util.TestRunners;
import org.apache.nifi.web.util.TestServer;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import javax.json.Json;
import javax.json.JsonObject;
@ -36,8 +36,8 @@ import static org.apache.nifi.processors.slack.PostSlackCaptureServlet.REQUEST_P
import static org.apache.nifi.processors.slack.PostSlackCaptureServlet.REQUEST_PATH_INVALID_JSON;
import static org.apache.nifi.processors.slack.PostSlackCaptureServlet.REQUEST_PATH_SUCCESS_TEXT_MSG;
import static org.apache.nifi.processors.slack.PostSlackCaptureServlet.REQUEST_PATH_WARNING;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
public class PostSlackTextMessageTest {
@ -46,7 +46,7 @@ public class PostSlackTextMessageTest {
private TestServer server;
private PostSlackCaptureServlet servlet;
@Before
@BeforeEach
public void setup() throws Exception {
testRunner = TestRunners.newTestRunner(PostSlack.class);

View File

@ -23,16 +23,17 @@ import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.apache.nifi.web.util.TestServer;
import org.eclipse.jetty.servlet.ServletHandler;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class PutSlackTest {
@ -41,7 +42,7 @@ public class PutSlackTest {
private CaptureServlet servlet;
public static final String WEBHOOK_TEST_TEXT = "Hello From Apache NiFi";
@Before
@BeforeEach
public void init() throws Exception {
testRunner = TestRunners.newTestRunner(PutSlack.class);
@ -57,13 +58,13 @@ public class PutSlackTest {
servlet = (CaptureServlet) handler.getServlets()[0].getServlet();
}
@Test(expected = AssertionError.class)
@Test
public void testBlankText() {
testRunner.setProperty(PutSlack.WEBHOOK_URL, server.getUrl());
testRunner.setProperty(PutSlack.WEBHOOK_TEXT, "");
testRunner.enqueue(new byte[0]);
testRunner.run(1);
assertThrows(AssertionError.class, () -> testRunner.run(1));
}
@Test
@ -87,24 +88,24 @@ public class PutSlackTest {
testRunner.assertAllFlowFilesTransferred(PutSlack.REL_FAILURE);
}
@Test(expected = AssertionError.class)
@Test
public void testInvalidIconUrl() {
testRunner.setProperty(PutSlack.WEBHOOK_URL, server.getUrl());
testRunner.setProperty(PutSlack.WEBHOOK_TEXT, WEBHOOK_TEST_TEXT);
testRunner.setProperty(PutSlack.ICON_URL, "invalid");
testRunner.enqueue(new byte[0]);
testRunner.run(1);
assertThrows(AssertionError.class, () -> testRunner.run(1));
}
@Test(expected = AssertionError.class)
@Test
public void testInvalidIconEmoji() {
testRunner.setProperty(PutSlack.WEBHOOK_URL, server.getUrl());
testRunner.setProperty(PutSlack.WEBHOOK_TEXT, WEBHOOK_TEST_TEXT);
testRunner.setProperty(PutSlack.ICON_EMOJI, "invalid");
testRunner.enqueue(new byte[0]);
testRunner.run(1);
assertThrows(AssertionError.class, () -> testRunner.run(1));
}
@Test
@ -186,7 +187,7 @@ public class PutSlackTest {
public void testGetPropertyDescriptors() throws Exception {
PutSlack processor = new PutSlack();
List<PropertyDescriptor> pd = processor.getSupportedPropertyDescriptors();
assertEquals("size should be eq", 6, pd.size());
assertEquals(6, pd.size(), "size should be eq");
assertTrue(pd.contains(PutSlack.WEBHOOK_TEXT));
assertTrue(pd.contains(PutSlack.WEBHOOK_URL));
assertTrue(pd.contains(PutSlack.CHANNEL));

View File

@ -32,8 +32,8 @@ import com.hierynomus.smbj.share.File;
import org.apache.nifi.flowfile.attributes.CoreAttributes;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.MockitoAnnotations;
import java.io.ByteArrayInputStream;
@ -47,11 +47,11 @@ import java.util.stream.Collectors;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anySet;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.times;
public class GetSmbFileTest {
private TestRunner testRunner;
@ -159,7 +159,7 @@ public class GetSmbFileTest {
return fdInfo;
}
@Before
@BeforeEach
public void init() throws IOException {
testRunner = TestRunners.newTestRunner(GetSmbFile.class);
MockitoAnnotations.initMocks(this);

View File

@ -16,37 +16,36 @@
*/
package org.apache.nifi.processors.smb;
import com.hierynomus.mssmb2.SMB2CreateDisposition;
import com.hierynomus.mssmb2.SMB2ShareAccess;
import com.hierynomus.smbj.SMBClient;
import com.hierynomus.smbj.auth.AuthenticationContext;
import com.hierynomus.smbj.connection.Connection;
import com.hierynomus.smbj.session.Session;
import com.hierynomus.smbj.share.DiskShare;
import com.hierynomus.smbj.share.File;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertArrayEquals;
import static org.mockito.ArgumentMatchers.anySet;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.any;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.MockitoAnnotations;
import org.mockito.ArgumentCaptor;
import com.hierynomus.smbj.SMBClient;
import com.hierynomus.smbj.connection.Connection;
import com.hierynomus.smbj.auth.AuthenticationContext;
import com.hierynomus.smbj.share.DiskShare;
import com.hierynomus.smbj.session.Session;
import com.hierynomus.mssmb2.SMB2CreateDisposition;
import com.hierynomus.mssmb2.SMB2ShareAccess;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anySet;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class PutSmbFileTest {
@ -129,7 +128,7 @@ public class PutSmbFileTest {
return shareAccessSet.getValue();
}
@Before
@BeforeEach
public void init() throws IOException {
testRunner = TestRunners.newTestRunner(PutSmbFile.class);
MockitoAnnotations.initMocks(this);

View File

@ -18,7 +18,7 @@ package org.apache.nifi.snmp.factory;
import org.apache.nifi.snmp.configuration.SNMPConfiguration;
import org.apache.nifi.snmp.configuration.SNMPConfigurationBuilder;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.snmp4j.Snmp;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.security.UsmUser;

View File

@ -21,8 +21,8 @@ import org.apache.nifi.snmp.dto.SNMPTreeResponse;
import org.apache.nifi.snmp.helper.SNMPTestUtils;
import org.apache.nifi.snmp.testagents.TestAgent;
import org.apache.nifi.util.MockFlowFile;
import org.junit.After;
import org.junit.Before;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.snmp4j.CommunityTarget;
import org.snmp4j.Snmp;
import org.snmp4j.agent.mo.DefaultMOFactory;
@ -36,8 +36,8 @@ import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
public abstract class SNMPRequestTest {
@ -68,7 +68,7 @@ public abstract class SNMPRequestTest {
protected abstract TestAgent getAgentInstance();
@Before
@BeforeEach
public void initAgent() throws IOException {
agent.start();
agent.registerManagedObjects(
@ -78,7 +78,7 @@ public abstract class SNMPRequestTest {
);
}
@After
@AfterEach
public void tearDown() {
agent.stop();
}

View File

@ -21,13 +21,14 @@ import org.apache.nifi.snmp.dto.SNMPTreeResponse;
import org.apache.nifi.snmp.exception.RequestTimeoutException;
import org.apache.nifi.snmp.testagents.TestAgent;
import org.apache.nifi.snmp.testagents.TestSNMPV1Agent;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.snmp4j.MessageException;
import org.snmp4j.mp.SnmpConstants;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class SNMPV1RequestTest extends SNMPRequestTest {
@ -51,14 +52,14 @@ public class SNMPV1RequestTest extends SNMPRequestTest {
assertSubTreeContainsOids(response);
}
@Test(expected = RequestTimeoutException.class)
public void testSnmpGetTimeoutReturnsNull() throws IOException {
getResponseEvent(INVALID_HOST, agent.getPort(), SnmpConstants.version1, READ_ONLY_OID_1);
@Test
public void testSnmpGetTimeoutReturnsNull() {
assertThrows(RequestTimeoutException.class, () -> getResponseEvent(INVALID_HOST, agent.getPort(), SnmpConstants.version1, READ_ONLY_OID_1));
}
@Test(expected = MessageException.class)
public void testSnmpGetWithInvalidTargetThrowsException() throws IOException {
getResponseEvent(LOCALHOST, agent.getPort(), -1, READ_ONLY_OID_1);
@Test
public void testSnmpGetWithInvalidTargetThrowsException() {
assertThrows(MessageException.class, () -> getResponseEvent(LOCALHOST, agent.getPort(), -1, READ_ONLY_OID_1));
}
@Test

View File

@ -21,13 +21,14 @@ import org.apache.nifi.snmp.dto.SNMPTreeResponse;
import org.apache.nifi.snmp.exception.RequestTimeoutException;
import org.apache.nifi.snmp.testagents.TestAgent;
import org.apache.nifi.snmp.testagents.TestSNMPV2cAgent;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.snmp4j.MessageException;
import org.snmp4j.mp.SnmpConstants;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class SNMPV2CRequestTest extends SNMPRequestTest {
@ -51,14 +52,14 @@ public class SNMPV2CRequestTest extends SNMPRequestTest {
assertSubTreeContainsOids(response);
}
@Test(expected = RequestTimeoutException.class)
public void testSnmpGetTimeoutReturnsNull() throws IOException {
getResponseEvent(INVALID_HOST, agent.getPort(), SnmpConstants.version2c, READ_ONLY_OID_1);
@Test
public void testSnmpGetTimeoutReturnsNull() {
assertThrows(RequestTimeoutException.class, () -> getResponseEvent(INVALID_HOST, agent.getPort(), SnmpConstants.version2c, READ_ONLY_OID_1));
}
@Test(expected = MessageException.class)
public void testSnmpGetWithInvalidTargetThrowsException() throws IOException {
getResponseEvent(LOCALHOST, agent.getPort(), -1, READ_ONLY_OID_1);
@Test
public void testSnmpGetWithInvalidTargetThrowsException() {
assertThrows(MessageException.class, () -> getResponseEvent(LOCALHOST, agent.getPort(), -1, READ_ONLY_OID_1));
}
@Test

View File

@ -23,7 +23,7 @@ import org.apache.nifi.snmp.helper.SNMPTestUtils;
import org.apache.nifi.snmp.testagents.TestAgent;
import org.apache.nifi.snmp.testagents.TestSNMPV3Agent;
import org.apache.nifi.util.MockFlowFile;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.snmp4j.MessageException;
import org.snmp4j.SNMP4JSettings;
import org.snmp4j.Snmp;
@ -36,7 +36,8 @@ import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class SNMPV3RequestTest extends SNMPRequestTest {
@ -63,17 +64,17 @@ public class SNMPV3RequestTest extends SNMPRequestTest {
assertSubTreeContainsOids(response);
}
@Test(expected = RequestTimeoutException.class)
@Test
public void testSnmpGetTimeoutReturnsNull() throws IOException {
final StandardSNMPRequestHandler standardSnmpRequestHandler = getSnmpV3Getter(INVALID_HOST, SnmpConstants.version3,
"SHA", "SHAAuthPassword");
standardSnmpRequestHandler.get(READ_ONLY_OID_1);
assertThrows(RequestTimeoutException.class, () -> standardSnmpRequestHandler.get(READ_ONLY_OID_1));
}
@Test(expected = MessageException.class)
@Test
public void testSnmpGetWithInvalidTargetThrowsException() throws IOException {
final StandardSNMPRequestHandler standardSnmpRequestHandler = getSnmpV3Getter(LOCALHOST, -1, "SHA", "SHAAuthPassword");
standardSnmpRequestHandler.get(READ_ONLY_OID_1);
assertThrows(MessageException.class, () -> standardSnmpRequestHandler.get(READ_ONLY_OID_1));
}
@Test

View File

@ -21,9 +21,9 @@ import org.apache.nifi.snmp.utils.SNMPUtils;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.snmp4j.agent.mo.DefaultMOFactory;
import org.snmp4j.agent.mo.MOAccessImpl;
import org.snmp4j.smi.OID;
@ -31,8 +31,8 @@ import org.snmp4j.smi.OctetString;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
public class GetSNMPTest {
@ -44,7 +44,7 @@ public class GetSNMPTest {
private static final String GET = "GET";
private static final String WALK = "WALK";
@BeforeClass
@BeforeAll
public static void setUp() throws IOException {
snmpV1Agent = new TestSNMPV1Agent("127.0.0.1");
snmpV1Agent.start();
@ -54,7 +54,7 @@ public class GetSNMPTest {
);
}
@AfterClass
@AfterAll
public static void tearDown() {
snmpV1Agent.stop();
}

View File

@ -21,9 +21,9 @@ import org.apache.nifi.snmp.utils.SNMPUtils;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.snmp4j.agent.mo.DefaultMOFactory;
import org.snmp4j.agent.mo.MOAccessImpl;
import org.snmp4j.smi.OID;
@ -33,8 +33,8 @@ import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
public class SetSNMPTest {
@ -45,7 +45,7 @@ public class SetSNMPTest {
private static final String VALID_OID_FF_ATTRIBUTE = "snmp$1.3.6.1.4.1.32437.1.5.1.4.2.0$4";
private static final String INVALID_OID_FF_ATTRIBUTE = "snmp$1.3.6.1.4.1.32437.1.5.1.4.213.0$4";
@BeforeClass
@BeforeAll
public static void setUp() throws IOException {
snmpV1Agent = new TestSNMPV1Agent("127.0.0.1");
snmpV1Agent.start();
@ -54,7 +54,7 @@ public class SetSNMPTest {
);
}
@AfterClass
@AfterAll
public static void tearDown() {
snmpV1Agent.stop();
}

View File

@ -16,12 +16,12 @@
*/
package org.apache.nifi.snmp.utils;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.snmp4j.PDU;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Test class for {@link SNMPUtils}.

View File

@ -18,7 +18,7 @@ package org.apache.nifi.processors.twitter;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class TestGetTwitter {

View File

@ -17,12 +17,14 @@
package org.apache.nifi.processors.twitter;
import com.twitter.hbc.core.endpoint.Location;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class TestLocationUtil {
@Test
@ -34,13 +36,13 @@ public class TestLocationUtil {
final String locationString = swLon + "," + swLat + "," + neLon + "," + neLat;
List<Location> locations = LocationUtil.parseLocations(locationString);
Assert.assertEquals(1, locations.size());
assertEquals(1, locations.size());
Location location = locations.get(0);
Assert.assertEquals(new Double(location.southwestCoordinate().longitude()), Double.valueOf(swLon));
Assert.assertEquals(new Double(location.southwestCoordinate().latitude()), Double.valueOf(swLat));
Assert.assertEquals(new Double(location.northeastCoordinate().longitude()), Double.valueOf(neLon));
Assert.assertEquals(new Double(location.northeastCoordinate().latitude()), Double.valueOf(neLat));
assertEquals(new Double(location.southwestCoordinate().longitude()), Double.valueOf(swLon));
assertEquals(new Double(location.southwestCoordinate().latitude()), Double.valueOf(swLat));
assertEquals(new Double(location.northeastCoordinate().longitude()), Double.valueOf(neLon));
assertEquals(new Double(location.northeastCoordinate().latitude()), Double.valueOf(neLat));
}
@Test
@ -54,7 +56,7 @@ public class TestLocationUtil {
final String locationString = "-122.75,36.8,-121.75,37.8,-74,40,-73,41,-64,30,-63,31,-54,20,-53,21";
List<Location> locations = LocationUtil.parseLocations(locationString);
Assert.assertEquals(expectedLocations.size(), locations.size());
assertEquals(expectedLocations.size(), locations.size());
for (Location expectedLocation : expectedLocations) {
boolean found = false;
@ -67,7 +69,7 @@ public class TestLocationUtil {
break;
}
}
Assert.assertTrue(found);
assertTrue(found);
}
}

View File

@ -20,8 +20,8 @@
package org.apache.nifi.processors.solr;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import com.google.gson.stream.JsonReader;
import java.io.ByteArrayInputStream;
@ -53,9 +53,9 @@ import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.apache.solr.client.solrj.impl.ZkClientClusterStateProvider;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
import org.apache.solr.common.SolrInputDocument;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.xmlunit.matchers.CompareMatcher;
@ -82,7 +82,7 @@ public class QuerySolrIT {
ZK_CONFIG_NAME = "QuerySolrIT_config";
}
@BeforeClass
@BeforeAll
public static void setup() throws IOException, SolrServerException {
CloudSolrClient solrClient = createSolrClient();
Path currentDir = Paths.get(ZK_CONFIG_PATH);
@ -128,7 +128,7 @@ public class QuerySolrIT {
return solrClient;
}
@AfterClass
@AfterAll
public static void teardown() {
try {
CloudSolrClient solrClient = createSolrClient();

View File

@ -22,11 +22,11 @@ import org.apache.nifi.serialization.record.Record;
import org.apache.nifi.serialization.record.RecordField;
import org.apache.nifi.serialization.record.RecordFieldType;
import org.apache.solr.common.SolrInputDocument;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.jupiter.MockitoExtension;
import java.math.BigDecimal;
import java.util.Collections;
@ -34,7 +34,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class SolrUtilsTest {
@Mock

View File

@ -33,9 +33,9 @@ import org.apache.nifi.util.TestRunners;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.common.SolrInputDocument;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.xmlunit.matchers.CompareMatcher;
import java.io.IOException;
@ -46,7 +46,8 @@ import java.util.Date;
import java.util.stream.StreamSupport;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class TestGetSolr {
private static final String DEFAULT_SOLR_CORE = "testCollection";
@ -57,12 +58,12 @@ public class TestGetSolr {
private static SolrClient solrClient;
@BeforeClass
@BeforeAll
public static void createSolrClient() throws Exception {
solrClient = createEmbeddedSolrClient();
}
@AfterClass
@AfterAll
public static void closeSolrClient() throws Exception {
solrClient.close();
}
@ -129,7 +130,7 @@ public class TestGetSolr {
runner.assertAllFlowFilesTransferred(GetSolr.REL_SUCCESS, 0);
}
@Test(expected = java.lang.AssertionError.class)
@Test
public void testValidation() {
final TestableProcessor proc = new TestableProcessor(solrClient);
@ -137,7 +138,7 @@ public class TestGetSolr {
runner.setProperty(GetSolr.BATCH_SIZE, "2");
runner.setProperty(GetSolr.RETURN_TYPE, GetSolr.MODE_REC.getValue());
runner.run(1, false);
assertThrows(AssertionError.class, () -> runner.run(1, false));
}
@Test

View File

@ -36,8 +36,7 @@ import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.util.NamedList;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import javax.security.auth.login.LoginException;
@ -52,6 +51,10 @@ import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
@ -237,7 +240,7 @@ public class TestPutSolrContentStream {
// prove the document got added
SolrQuery query = new SolrQuery("*:*");
QueryResponse qResponse = solrClient.query(query);
Assert.assertEquals(1, qResponse.getResults().getNumFound());
assertEquals(1, qResponse.getResults().getNumFound());
// run the processor with a delete-by-query command
runner.enqueue("<delete><query>first:bob</query></delete>".getBytes(StandardCharsets.UTF_8));
@ -245,7 +248,7 @@ public class TestPutSolrContentStream {
// prove the document got deleted
qResponse = solrClient.query(query);
Assert.assertEquals(0, qResponse.getResults().getNumFound());
assertEquals(0, qResponse.getResults().getNumFound());
}
@Test
@ -377,7 +380,7 @@ public class TestPutSolrContentStream {
runner.setProperty(SolrUtils.SOLR_LOCATION, "https://localhost:8443/solr");
runner.assertNotValid();
final SSLContextService sslContextService = Mockito.mock(SSLContextService.class);
final SSLContextService sslContextService = mock(SSLContextService.class);
Mockito.when(sslContextService.getIdentifier()).thenReturn("ssl-context");
runner.addControllerService("ssl-context", sslContextService);
runner.enableControllerService(sslContextService);
@ -393,7 +396,7 @@ public class TestPutSolrContentStream {
runner.setProperty(SolrUtils.SOLR_LOCATION, "http://localhost:8443/solr");
runner.assertValid();
final SSLContextService sslContextService = Mockito.mock(SSLContextService.class);
final SSLContextService sslContextService = mock(SSLContextService.class);
Mockito.when(sslContextService.getIdentifier()).thenReturn("ssl-context");
runner.addControllerService("ssl-context", sslContextService);
runner.enableControllerService(sslContextService);
@ -457,9 +460,9 @@ public class TestPutSolrContentStream {
proc.onScheduled(runner.getProcessContext());
final KerberosUser kerberosUser = proc.getMockKerberosKeytabUser();
Assert.assertNotNull(kerberosUser);
Assert.assertEquals(principal, kerberosUser.getPrincipal());
Assert.assertEquals(keytab, ((KerberosKeytabUser)kerberosUser).getKeytabFile());
assertNotNull(kerberosUser);
assertEquals(principal, kerberosUser.getPrincipal());
assertEquals(keytab, ((KerberosKeytabUser)kerberosUser).getKeytabFile());
}
@Test
@ -483,7 +486,7 @@ public class TestPutSolrContentStream {
proc.onScheduled(runner.getProcessContext());
final KerberosUser kerberosUser = proc.getMockKerberosKeytabUser();
Assert.assertNotNull(kerberosUser);
assertNotNull(kerberosUser);
}
@Test
@ -510,8 +513,8 @@ public class TestPutSolrContentStream {
proc.onScheduled(runner.getProcessContext());
final KerberosUser kerberosUser = proc.getMockKerberosKeytabUser();
Assert.assertNotNull(kerberosUser);
Assert.assertEquals(kerberosPrincipal, kerberosUser.getPrincipal());
assertNotNull(kerberosUser);
assertEquals(kerberosPrincipal, kerberosUser.getPrincipal());
}
@Test
@ -541,9 +544,9 @@ public class TestPutSolrContentStream {
proc.onScheduled(runner.getProcessContext());
final KerberosUser kerberosUser = proc.getMockKerberosKeytabUser();
Assert.assertNotNull(kerberosUser);
Assert.assertEquals(principal, kerberosUser.getPrincipal());
Assert.assertEquals(keytab, ((KerberosKeytabUser)kerberosUser).getKeytabFile());
assertNotNull(kerberosUser);
assertEquals(principal, kerberosUser.getPrincipal());
assertEquals(keytab, ((KerberosKeytabUser)kerberosUser).getKeytabFile());
}
@Test
@ -566,7 +569,7 @@ public class TestPutSolrContentStream {
proc.onScheduled(runner.getProcessContext());
final KerberosUser kerberosUser = proc.getMockKerberosKeytabUser();
Assert.assertNotNull(kerberosUser);
assertNotNull(kerberosUser);
}
@Test
@ -591,7 +594,7 @@ public class TestPutSolrContentStream {
proc.onScheduled(runner.getProcessContext());
final KerberosUser kerberosUser = proc.getMockKerberosKeytabUser();
Assert.assertNotNull(kerberosUser);
assertNotNull(kerberosUser);
}
@Test
@ -600,7 +603,7 @@ public class TestPutSolrContentStream {
final String keytab = "src/test/resources/foo.keytab";
// Setup a mock KerberosUser that will still execute the privileged action
final KerberosKeytabUser kerberosUser = Mockito.mock(KerberosKeytabUser.class);
final KerberosKeytabUser kerberosUser = mock(KerberosKeytabUser.class);
when(kerberosUser.getPrincipal()).thenReturn(principal);
when(kerberosUser.getKeytabFile()).thenReturn(keytab);
when(kerberosUser.doAs(any(PrivilegedExceptionAction.class))).thenAnswer((invocation -> {
@ -679,7 +682,7 @@ public class TestPutSolrContentStream {
mockSolrClient = new SolrClient() {
@Override
public NamedList<Object> request(SolrRequest solrRequest, String s) throws SolrServerException, IOException {
Assert.assertEquals(expectedCollection, solrRequest.getParams().get(PutSolrContentStream.COLLECTION_PARAM_NAME));
assertEquals(expectedCollection, solrRequest.getParams().get(PutSolrContentStream.COLLECTION_PARAM_NAME));
return new NamedList<>();
}
@ -706,15 +709,9 @@ public class TestPutSolrContentStream {
@Override
protected SolrClient createSolrClient(ProcessContext context, String solrLocation) {
mockSolrClient = Mockito.mock(SolrClient.class);
try {
when(mockSolrClient.request(any(SolrRequest.class),
eq(null))).thenThrow(throwable);
} catch (SolrServerException e) {
Assert.fail(e.getMessage());
} catch (IOException e) {
Assert.fail(e.getMessage());
}
mockSolrClient = mock(SolrClient.class);
assertDoesNotThrow(() -> when(mockSolrClient.request(any(SolrRequest.class),
eq(null))).thenThrow(throwable));
return mockSolrClient;
}
@ -783,7 +780,7 @@ public class TestPutSolrContentStream {
SolrQuery query = new SolrQuery("*:*");
QueryResponse qResponse = solrServer.query(query);
Assert.assertEquals(expectedDocuments.size(), qResponse.getResults().getNumFound());
assertEquals(expectedDocuments.size(), qResponse.getResults().getNumFound());
// verify documents have expected fields and values
for (SolrDocument expectedDoc : expectedDocuments) {
@ -801,7 +798,7 @@ public class TestPutSolrContentStream {
break;
}
}
Assert.assertTrue("Could not find " + expectedDoc, found);
assertTrue(found, "Could not find " + expectedDoc);
}
}

View File

@ -18,6 +18,9 @@
*/
package org.apache.nifi.processors.solr;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.times;
@ -54,8 +57,7 @@ import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.util.NamedList;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
/**
@ -657,7 +659,7 @@ public class TestPutSolrRecord {
mockSolrClient = new SolrClient() {
@Override
public NamedList<Object> request(SolrRequest solrRequest, String s) throws SolrServerException, IOException {
Assert.assertEquals(expectedCollection, solrRequest.getParams().get(PutSolrRecord.COLLECTION_PARAM_NAME));
assertEquals(expectedCollection, solrRequest.getParams().get(PutSolrRecord.COLLECTION_PARAM_NAME));
return new NamedList<>();
}
@ -682,7 +684,7 @@ public class TestPutSolrRecord {
SolrQuery query = new SolrQuery("*:*");
QueryResponse qResponse = solrServer.query(query);
Assert.assertEquals(expectedDocuments.size(), qResponse.getResults().getNumFound());
assertEquals(expectedDocuments.size(), qResponse.getResults().getNumFound());
// verify documents have expected fields and values
for (SolrDocument expectedDoc : expectedDocuments) {
@ -700,7 +702,7 @@ public class TestPutSolrRecord {
break;
}
}
Assert.assertTrue("Could not find " + expectedDoc, found);
assertTrue(found, String.format("Could not find %s", expectedDoc));
}
}
@ -717,12 +719,9 @@ public class TestPutSolrRecord {
@Override
protected SolrClient createSolrClient(ProcessContext context, String solrLocation) {
mockSolrClient = Mockito.mock(SolrClient.class);
try {
when(mockSolrClient.request(any(SolrRequest.class),
eq(null))).thenThrow(throwable);
} catch (SolrServerException|IOException e) {
Assert.fail(e.getMessage());
}
assertDoesNotThrow(() -> when(mockSolrClient.request(any(SolrRequest.class),
eq(null))).thenThrow(throwable));
return mockSolrClient;
}

View File

@ -21,7 +21,6 @@ package org.apache.nifi.processors.solr;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.flowfile.attributes.CoreAttributes;
import org.apache.nifi.json.JsonRecordSetWriter;
@ -33,9 +32,9 @@ import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.common.SolrInputDocument;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.xmlunit.matchers.CompareMatcher;
import java.io.ByteArrayInputStream;
@ -48,9 +47,9 @@ import java.util.Map;
import java.util.stream.StreamSupport;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class TestQuerySolr {
private static final String DEFAULT_SOLR_CORE = "testCollection";
@ -65,7 +64,7 @@ public class TestQuerySolr {
private static SolrClient solrClient;
@BeforeClass
@BeforeAll
public static void createSolrClient() throws Exception {
final String relPath = TestQuerySolr.class.getResource("/").getPath();
@ -90,7 +89,7 @@ public class TestQuerySolr {
solrClient.commit();
}
@AfterClass
@AfterAll
public static void closeSolrClient() throws IOException {
solrClient.close();
}
@ -176,22 +175,22 @@ public class TestQuerySolr {
final int facetQueriesCount = StreamSupport.stream(facetsNode.get("facet_queries").spliterator(), false)
.mapToInt(node -> node.get("count").asInt())
.sum();
assertEquals("Facet Queries Count not matched", 30, facetQueriesCount);
assertEquals(30, facetQueriesCount, "Facet Queries Count not matched");
final int facetFieldsCount = StreamSupport.stream(facetsNode.get("facet_fields").get("integer_multi").spliterator(), false)
.mapToInt(node -> node.get("count").asInt())
.sum();
assertEquals("Facet Fields Count not matched", 30, facetFieldsCount);
assertEquals(30, facetFieldsCount, "Facet Fields Count not matched");
final int facetRangesCount = StreamSupport.stream(facetsNode.get("facet_ranges").get("created").spliterator(), false)
.mapToInt(node -> node.get("count").asInt())
.sum();
assertEquals("Facet Ranges Count not matched",10, facetRangesCount);
assertEquals(10, facetRangesCount, "Facet Ranges Count not matched");
final int facetIntervalsCount = StreamSupport.stream(facetsNode.get("facet_intervals").get("integer_single").spliterator(), false)
.mapToInt(node -> node.get("count").asInt())
.sum();
assertEquals("Facet Intervals Count not matched", 7, facetIntervalsCount);
assertEquals(7, facetIntervalsCount, "Facet Intervals Count not matched");
}
@Test
@ -210,11 +209,11 @@ public class TestQuerySolr {
final MockFlowFile facetsFlowFile = runner.getFlowFilesForRelationship(QuerySolr.FACETS).get(0);
final JsonNode facetsNode = OBJECT_MAPPER.readTree(facetsFlowFile.getContent());
assertTrue("Facet Queries found", facetsNode.get("facet_queries").isEmpty());
assertTrue(facetsNode.get("facet_queries").isEmpty(), "Facet Queries found");
final MockFlowFile statsFlowFile = runner.getFlowFilesForRelationship(QuerySolr.STATS).get(0);
final JsonNode statsNode = OBJECT_MAPPER.readTree(statsFlowFile.getContent());
assertTrue("Stats found", statsNode.get("stats_fields").isEmpty());
assertTrue(statsNode.get("stats_fields").isEmpty(), "Stats found");
}
@Test
@ -235,7 +234,7 @@ public class TestQuerySolr {
final JsonNode statsNode = OBJECT_MAPPER.readTree(statsFlowFile.getContent());
final JsonNode statsFieldsNode = statsNode.get("stats_fields");
assertNotNull("Stats Fields not found", statsFieldsNode);
assertNotNull(statsFieldsNode, "Stats Fields not found");
final JsonNode configuredStatsFieldNode = statsFieldsNode.get(statsField);
assertEquals("0.0", configuredStatsFieldNode.get("min").asText());

View File

@ -19,18 +19,18 @@ package org.apache.nifi.processors.livy;
import org.apache.nifi.controller.livy.LivySessionController;
import org.apache.nifi.util.TestRunners;
import org.apache.nifi.web.util.TestServer;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TestExecuteSparkInteractive extends ExecuteSparkInteractiveTestBase {
private static TestServer server;
private static String url;
@BeforeClass
@BeforeAll
public static void beforeClass() throws Exception {
// useful for verbose logging output
// don't commit this with this property enabled, or any 'mvn test' will be really verbose
@ -44,12 +44,12 @@ public class TestExecuteSparkInteractive extends ExecuteSparkInteractiveTestBase
url = server.getUrl();
}
@AfterClass
@AfterAll
public static void afterClass() throws Exception {
server.shutdownServer();
}
@Before
@BeforeEach
public void before() throws Exception {
runner = TestRunners.newTestRunner(ExecuteSparkInteractive.class);
LivySessionController livyControllerService = new LivySessionController();
@ -62,7 +62,7 @@ public class TestExecuteSparkInteractive extends ExecuteSparkInteractiveTestBase
server.clearHandlers();
}
@After
@AfterEach
public void after() {
runner.shutdown();
}

View File

@ -26,9 +26,8 @@ import org.apache.nifi.provenance.ProvenanceEventType;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatcher;
import org.mockito.Mockito;
@ -42,6 +41,10 @@ import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.argThat;
import static org.mockito.Mockito.eq;
@ -55,7 +58,7 @@ public class TestGetSplunk {
private TestableGetSplunk proc;
private TestRunner runner;
@Before
@BeforeEach
public void setup() {
service = Mockito.mock(Service.class);
proc = new TestableGetSplunk(service);
@ -109,19 +112,19 @@ public class TestGetSplunk {
runner.assertAllFlowFilesTransferred(GetSplunk.REL_SUCCESS, 1);
final List<MockFlowFile> mockFlowFiles = runner.getFlowFilesForRelationship(GetSplunk.REL_SUCCESS);
Assert.assertEquals(1, mockFlowFiles.size());
assertEquals(1, mockFlowFiles.size());
final MockFlowFile mockFlowFile = mockFlowFiles.get(0);
mockFlowFile.assertContentEquals(resultContent);
mockFlowFile.assertAttributeEquals(GetSplunk.QUERY_ATTR, query);
mockFlowFile.assertAttributeEquals(GetSplunk.EARLIEST_TIME_ATTR, providedEarliest);
mockFlowFile.assertAttributeEquals(GetSplunk.LATEST_TIME_ATTR, providedLatest);
Assert.assertEquals(1, proc.count);
assertEquals(1, proc.count);
final List<ProvenanceEventRecord> events = runner.getProvenanceEvents();
Assert.assertEquals(1, events.size());
Assert.assertEquals(ProvenanceEventType.RECEIVE, events.get(0).getEventType());
Assert.assertEquals("https://localhost:8089", events.get(0).getTransitUri());
assertEquals(1, events.size());
assertEquals(ProvenanceEventType.RECEIVE, events.get(0).getEventType());
assertEquals("https://localhost:8089", events.get(0).getTransitUri());
}
@Test
@ -149,7 +152,7 @@ public class TestGetSplunk {
final int iterations = 3;
runner.run(iterations, false);
runner.assertAllFlowFilesTransferred(GetSplunk.REL_SUCCESS, iterations);
Assert.assertEquals(1, proc.count);
assertEquals(1, proc.count);
}
@Test
@ -175,9 +178,9 @@ public class TestGetSplunk {
// first execution with no previous state and "managed from beginning" should have a latest time and no earliest time
final JobExportArgs actualArgs1 = capture1.getValue();
Assert.assertNotNull(actualArgs1);
Assert.assertNull(actualArgs1.get("earliest_time"));
Assert.assertNotNull(actualArgs1.get("latest_time"));
assertNotNull(actualArgs1);
assertNull(actualArgs1.get("earliest_time"));
assertNotNull(actualArgs1.get("latest_time"));
// save the latest time from the first run which should be earliest time of next run
final String lastLatest = (String) actualArgs1.get("latest_time");
@ -197,9 +200,9 @@ public class TestGetSplunk {
// second execution the earliest time should be the previous latest_time
final JobExportArgs actualArgs2 = capture2.getValue();
Assert.assertNotNull(actualArgs2);
Assert.assertEquals(expectedLatest, actualArgs2.get("earliest_time"));
Assert.assertNotNull(actualArgs2.get("latest_time"));
assertNotNull(actualArgs2);
assertEquals(expectedLatest, actualArgs2.get("earliest_time"));
assertNotNull(actualArgs2.get("latest_time"));
}
@Test
@ -227,9 +230,9 @@ public class TestGetSplunk {
// first execution with no previous state and "managed from beginning" should have a latest time and no earliest time
final JobExportArgs actualArgs1 = capture1.getValue();
Assert.assertNotNull(actualArgs1);
Assert.assertNull(actualArgs1.get("earliest_time"));
Assert.assertNotNull(actualArgs1.get("latest_time"));
assertNotNull(actualArgs1);
assertNull(actualArgs1.get("earliest_time"));
assertNotNull(actualArgs1.get("latest_time"));
// save the latest time from the first run which should be earliest time of next run
final String lastLatest = (String) actualArgs1.get("latest_time");
@ -249,9 +252,9 @@ public class TestGetSplunk {
// second execution the earliest time should be the previous latest_time
final JobExportArgs actualArgs2 = capture2.getValue();
Assert.assertNotNull(actualArgs2);
Assert.assertEquals(expectedLatest, actualArgs2.get("earliest_time"));
Assert.assertNotNull(actualArgs2.get("latest_time"));
assertNotNull(actualArgs2);
assertEquals(expectedLatest, actualArgs2.get("earliest_time"));
assertNotNull(actualArgs2.get("latest_time"));
}
@Test
@ -277,9 +280,9 @@ public class TestGetSplunk {
// first execution with no previous state and "managed from beginning" should have a latest time and no earliest time
final JobExportArgs actualArgs1 = capture1.getValue();
Assert.assertNotNull(actualArgs1);
Assert.assertNull(actualArgs1.get("earliest_time"));
Assert.assertNotNull(actualArgs1.get("latest_time"));
assertNotNull(actualArgs1);
assertNull(actualArgs1.get("earliest_time"));
assertNotNull(actualArgs1.get("latest_time"));
// save the latest time from the first run which should be earliest time of next run
final String lastLatest = (String) actualArgs1.get("latest_time");
@ -299,9 +302,9 @@ public class TestGetSplunk {
// second execution the earliest time should be the previous latest_time
final JobExportArgs actualArgs2 = capture2.getValue();
Assert.assertNotNull(actualArgs2);
Assert.assertEquals(expectedLatest, actualArgs2.get("earliest_time"));
Assert.assertNotNull(actualArgs2.get("latest_time"));
assertNotNull(actualArgs2);
assertEquals(expectedLatest, actualArgs2.get("earliest_time"));
assertNotNull(actualArgs2.get("latest_time"));
}
@Test
@ -325,8 +328,8 @@ public class TestGetSplunk {
verify(service, times(0)).export(eq(query), any(JobExportArgs.class));
final StateMap state = runner.getStateManager().getState(Scope.CLUSTER);
Assert.assertNotNull(state);
Assert.assertTrue(state.getVersion() > 0);
assertNotNull(state);
assertTrue(state.getVersion() > 0);
// save the latest time from the first run which should be earliest time of next run
final String lastLatest = state.get(GetSplunk.LATEST_TIME_KEY);
@ -346,9 +349,9 @@ public class TestGetSplunk {
// second execution the earliest time should be the previous latest_time
final JobExportArgs actualArgs = capture.getValue();
Assert.assertNotNull(actualArgs);
Assert.assertEquals(expectedLatest, actualArgs.get("earliest_time"));
Assert.assertNotNull(actualArgs.get("latest_time"));
assertNotNull(actualArgs);
assertEquals(expectedLatest, actualArgs.get("earliest_time"));
assertNotNull(actualArgs.get("latest_time"));
}
@Test
@ -373,8 +376,8 @@ public class TestGetSplunk {
verify(service, times(0)).export(eq(query), any(JobExportArgs.class));
final StateMap state = runner.getStateManager().getState(Scope.CLUSTER);
Assert.assertNotNull(state);
Assert.assertTrue(state.getVersion() > 0);
assertNotNull(state);
assertTrue(state.getVersion() > 0);
// save the latest time from the first run which should be earliest time of next run
final String lastLatest = state.get(GetSplunk.LATEST_TIME_KEY);
@ -394,10 +397,10 @@ public class TestGetSplunk {
// second execution the earliest time should be the previous latest_time
final JobExportArgs actualArgs = capture.getValue();
Assert.assertNotNull(actualArgs);
assertNotNull(actualArgs);
Assert.assertEquals(expectedLatest, actualArgs.get("index_earliest"));
Assert.assertNotNull(actualArgs.get("index_latest"));
assertEquals(expectedLatest, actualArgs.get("index_earliest"));
assertNotNull(actualArgs.get("index_latest"));
}

View File

@ -27,9 +27,10 @@ import org.apache.nifi.remote.io.socket.NetworkUtils;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import java.net.InetAddress;
import java.net.UnknownHostException;
@ -39,10 +40,11 @@ import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
public class TestPutSplunk {
@ -56,12 +58,12 @@ public class TestPutSplunk {
private final static int VALID_LARGE_FILE_SIZE = 32768;
private static final String LOCALHOST = "localhost";
@Before
@BeforeEach
public void setup() {
runner = TestRunners.newTestRunner(PutSplunk.class);
}
@After
@AfterEach
public void cleanup() {
runner.shutdown();
shutdownServer();
@ -73,7 +75,8 @@ public class TestPutSplunk {
}
}
@Test(timeout = DEFAULT_TEST_TIMEOUT_PERIOD)
@Test
@Timeout(value = DEFAULT_TEST_TIMEOUT_PERIOD, unit = TimeUnit.MILLISECONDS)
public void testUDPSendWholeFlowFile() throws Exception {
createTestServer(TransportProtocol.UDP);
runner.setProperty(PutSplunk.MESSAGE_DELIMITER, OUTGOING_MESSAGE_DELIMITER);
@ -89,7 +92,8 @@ public class TestPutSplunk {
checkReceivedAllData(message);
}
@Test(timeout = DEFAULT_TEST_TIMEOUT_PERIOD)
@Test
@Timeout(value = DEFAULT_TEST_TIMEOUT_PERIOD, unit = TimeUnit.MILLISECONDS)
public void testTCPSendWholeFlowFile() throws Exception {
createTestServer(TransportProtocol.TCP);
final String message = "This is one message, should send the whole FlowFile";
@ -103,7 +107,8 @@ public class TestPutSplunk {
checkReceivedAllData(message);
}
@Test(timeout = DEFAULT_TEST_TIMEOUT_PERIOD)
@Test
@Timeout(value = DEFAULT_TEST_TIMEOUT_PERIOD, unit = TimeUnit.MILLISECONDS)
public void testTCPSendMultipleFlowFiles() throws Exception {
createTestServer(TransportProtocol.TCP);
@ -120,7 +125,8 @@ public class TestPutSplunk {
checkReceivedAllData(message, message);
}
@Test(timeout = DEFAULT_TEST_TIMEOUT_PERIOD)
@Test
@Timeout(value = DEFAULT_TEST_TIMEOUT_PERIOD, unit = TimeUnit.MILLISECONDS)
public void testTCPSendWholeFlowFileAlreadyHasNewLine() throws Exception {
createTestServer(TransportProtocol.TCP);
@ -136,7 +142,8 @@ public class TestPutSplunk {
checkReceivedAllData(message.trim());
}
@Test(timeout = DEFAULT_TEST_TIMEOUT_PERIOD)
@Test
@Timeout(value = DEFAULT_TEST_TIMEOUT_PERIOD, unit = TimeUnit.MILLISECONDS)
public void testUDPSendDelimitedMessages() throws Exception {
createTestServer(TransportProtocol.UDP);
final String delimiter = "DD";
@ -154,7 +161,8 @@ public class TestPutSplunk {
checkReceivedAllData("This is message 1", "This is message 2", "This is message 3");
}
@Test(timeout = DEFAULT_TEST_TIMEOUT_PERIOD)
@Test
@Timeout(value = DEFAULT_TEST_TIMEOUT_PERIOD, unit = TimeUnit.MILLISECONDS)
public void testTCPSendDelimitedMessages() throws Exception {
createTestServer(TransportProtocol.TCP);
final String delimiter = "DD";
@ -173,7 +181,8 @@ public class TestPutSplunk {
checkReceivedAllData("This is message 1", "This is message 2", "This is message 3");
}
@Test(timeout = DEFAULT_TEST_TIMEOUT_PERIOD)
@Test
@Timeout(value = DEFAULT_TEST_TIMEOUT_PERIOD, unit = TimeUnit.MILLISECONDS)
public void testTCPSendDelimitedMessagesWithEL() throws Exception {
createTestServer(TransportProtocol.TCP);
@ -196,7 +205,8 @@ public class TestPutSplunk {
checkReceivedAllData("This is message 1", "This is message 2", "This is message 3");
}
@Test(timeout = DEFAULT_TEST_TIMEOUT_PERIOD)
@Test
@Timeout(value = DEFAULT_TEST_TIMEOUT_PERIOD, unit = TimeUnit.MILLISECONDS)
public void testTCPSendDelimitedMessagesEndsWithDelimiter() throws Exception {
createTestServer(TransportProtocol.TCP);
final String delimiter = "DD";
@ -216,7 +226,8 @@ public class TestPutSplunk {
}
@Test(timeout = DEFAULT_TEST_TIMEOUT_PERIOD)
@Test
@Timeout(value = DEFAULT_TEST_TIMEOUT_PERIOD, unit = TimeUnit.MILLISECONDS)
public void testTCPSendDelimitedMessagesWithNewLineDelimiter() throws Exception {
createTestServer(TransportProtocol.TCP);
final String delimiter = "\\n";
@ -235,7 +246,8 @@ public class TestPutSplunk {
checkReceivedAllData("This is message 1", "This is message 2", "This is message 3");
}
@Test(timeout = DEFAULT_TEST_TIMEOUT_PERIOD)
@Test
@Timeout(value = DEFAULT_TEST_TIMEOUT_PERIOD, unit = TimeUnit.MILLISECONDS)
public void testCompletingPreviousBatchOnNextExecution() throws Exception {
createTestServer(TransportProtocol.UDP);
@ -251,7 +263,8 @@ public class TestPutSplunk {
checkReceivedAllData(message);
}
@Test(timeout = DEFAULT_TEST_TIMEOUT_PERIOD)
@Test
@Timeout(value = DEFAULT_TEST_TIMEOUT_PERIOD, unit = TimeUnit.MILLISECONDS)
public void testUnableToCreateConnectionShouldRouteToFailure() {
// Set an unreachable port
runner.setProperty(PutSplunk.PORT, String.valueOf(NetworkUtils.getAvailableUdpPort()));
@ -291,7 +304,7 @@ public class TestPutSplunk {
assertArrayEquals(item.getBytes(), packet.getMessage());
}
assertNull("Unexpected extra messages found", messages.poll());
assertNull(messages.poll(), "Unexpected extra messages found");
}
private InetAddress getListenAddress() {

View File

@ -26,16 +26,15 @@ import org.apache.nifi.processor.ProcessSession;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
@ -45,7 +44,15 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
@RunWith(MockitoJUnitRunner.class)
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
@ExtendWith(MockitoExtension.class)
public class TestPutSplunkHTTP {
private static final String ACK_ID = "1234";
private static final String EVENT = "{\"a\"=\"á\",\"c\"=\"ő\",\"e\"=\"'ű'\"}"; // Intentionally uses UTF-8 character
@ -75,7 +82,7 @@ public class TestPutSplunkHTTP {
private MockedPutSplunkHTTP processor;
private TestRunner testRunner;
@Before
@BeforeEach
public void setUp() {
processor = new MockedPutSplunkHTTP(service);
testRunner = TestRunners.newTestRunner(processor);
@ -86,7 +93,7 @@ public class TestPutSplunkHTTP {
Mockito.when(service.send(path.capture(), request.capture())).thenReturn(response);
}
@After
@AfterEach
public void tearDown() {
testRunner.shutdown();
}
@ -104,11 +111,11 @@ public class TestPutSplunkHTTP {
testRunner.assertAllFlowFilesTransferred(PutSplunkHTTP.RELATIONSHIP_SUCCESS, 1);
final MockFlowFile outgoingFlowFile = testRunner.getFlowFilesForRelationship(PutSplunkHTTP.RELATIONSHIP_SUCCESS).get(0);
Assert.assertEquals(EVENT, outgoingFlowFile.getContent());
Assert.assertEquals(ACK_ID, outgoingFlowFile.getAttribute("splunk.acknowledgement.id"));
Assert.assertNotNull(outgoingFlowFile.getAttribute("splunk.responded.at"));
Assert.assertEquals("200", outgoingFlowFile.getAttribute("splunk.status.code"));
Assert.assertEquals("application/json", request.getValue().getHeader().get("Content-Type"));
assertEquals(EVENT, outgoingFlowFile.getContent());
assertEquals(ACK_ID, outgoingFlowFile.getAttribute("splunk.acknowledgement.id"));
assertNotNull(outgoingFlowFile.getAttribute("splunk.responded.at"));
assertEquals("200", outgoingFlowFile.getAttribute("splunk.status.code"));
assertEquals("application/json", request.getValue().getHeader().get("Content-Type"));
}
@Test
@ -124,7 +131,7 @@ public class TestPutSplunkHTTP {
// then
testRunner.assertAllFlowFilesTransferred(PutSplunkHTTP.RELATIONSHIP_SUCCESS, 1);
Assert.assertEquals("/services/collector/raw?sourcetype=test%3Fsource%3Ftype&source=test_source", path.getValue());
assertEquals("/services/collector/raw?sourcetype=test%3Fsource%3Ftype&source=test_source", path.getValue());
}
@Test
@ -156,10 +163,10 @@ public class TestPutSplunkHTTP {
// then
testRunner.assertAllFlowFilesTransferred(PutSplunkHTTP.RELATIONSHIP_SUCCESS, 1);
Assert.assertEquals("/services/collector/raw?host=test_host&index=test_index&sourcetype=test%3Fsource%3Ftype&source=test_source", path.getValue());
assertEquals("/services/collector/raw?host=test_host&index=test_index&sourcetype=test%3Fsource%3Ftype&source=test_source", path.getValue());
Assert.assertEquals(EVENT, processor.getLastContent());
Assert.assertEquals(attributes.get("ff_content_type"), processor.getLastContentType());
assertEquals(EVENT, processor.getLastContent());
assertEquals(attributes.get("ff_content_type"), processor.getLastContentType());
}
@Test
@ -174,7 +181,7 @@ public class TestPutSplunkHTTP {
// then
testRunner.assertAllFlowFilesTransferred(PutSplunkHTTP.RELATIONSHIP_SUCCESS, 1);
Assert.assertEquals("text/xml", request.getValue().getHeader().get("Content-Type"));
assertEquals("text/xml", request.getValue().getHeader().get("Content-Type"));
}
@Test
@ -190,11 +197,11 @@ public class TestPutSplunkHTTP {
testRunner.assertAllFlowFilesTransferred(PutSplunkHTTP.RELATIONSHIP_FAILURE, 1);
final MockFlowFile outgoingFlowFile = testRunner.getFlowFilesForRelationship(PutSplunkHTTP.RELATIONSHIP_FAILURE).get(0);
Assert.assertEquals(EVENT, outgoingFlowFile.getContent());
Assert.assertNull(outgoingFlowFile.getAttribute("splunk.acknowledgement.id"));
Assert.assertNull(outgoingFlowFile.getAttribute("splunk.responded.at"));
Assert.assertEquals("200", outgoingFlowFile.getAttribute("splunk.status.code"));
Assert.assertEquals("13", outgoingFlowFile.getAttribute("splunk.response.code"));
assertEquals(EVENT, outgoingFlowFile.getContent());
assertNull(outgoingFlowFile.getAttribute("splunk.acknowledgement.id"));
assertNull(outgoingFlowFile.getAttribute("splunk.responded.at"));
assertEquals("200", outgoingFlowFile.getAttribute("splunk.status.code"));
assertEquals("13", outgoingFlowFile.getAttribute("splunk.response.code"));
}
@Test
@ -210,11 +217,11 @@ public class TestPutSplunkHTTP {
testRunner.assertAllFlowFilesTransferred(PutSplunkHTTP.RELATIONSHIP_FAILURE, 1);
final MockFlowFile outgoingFlowFile = testRunner.getFlowFilesForRelationship(PutSplunkHTTP.RELATIONSHIP_FAILURE).get(0);
Assert.assertEquals(EVENT, outgoingFlowFile.getContent());
Assert.assertNull(outgoingFlowFile.getAttribute("splunk.acknowledgement.id"));
Assert.assertNull(outgoingFlowFile.getAttribute("splunk.responded.at"));
Assert.assertNull(outgoingFlowFile.getAttribute("splunk.response.code"));
Assert.assertEquals("403", outgoingFlowFile.getAttribute("splunk.status.code"));
assertEquals(EVENT, outgoingFlowFile.getContent());
assertNull(outgoingFlowFile.getAttribute("splunk.acknowledgement.id"));
assertNull(outgoingFlowFile.getAttribute("splunk.responded.at"));
assertNull(outgoingFlowFile.getAttribute("splunk.response.code"));
assertEquals("403", outgoingFlowFile.getAttribute("splunk.status.code"));
}

View File

@ -23,15 +23,16 @@ import com.splunk.ServiceArgs;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
@ -41,7 +42,12 @@ import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@RunWith(MockitoJUnitRunner.class)
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
public class TestQuerySplunkIndexingStatus {
private static final String EVENT = "{\"a\"=\"b\",\"c\"=\"d\",\"e\"=\"f\"}";
@ -57,7 +63,7 @@ public class TestQuerySplunkIndexingStatus {
private ArgumentCaptor<String> path;
private ArgumentCaptor<RequestMessage> request;
@Before
@BeforeEach
public void setUp() {
processor = new MockedQuerySplunkIndexingStatus(service);
testRunner = TestRunners.newTestRunner(processor);
@ -70,7 +76,7 @@ public class TestQuerySplunkIndexingStatus {
Mockito.when(service.send(path.capture(), request.capture())).thenReturn(response);
}
@After
@AfterEach
public void tearDown() {
testRunner.shutdown();
}
@ -92,10 +98,10 @@ public class TestQuerySplunkIndexingStatus {
final List<MockFlowFile> acknowledged = testRunner.getFlowFilesForRelationship(QuerySplunkIndexingStatus.RELATIONSHIP_ACKNOWLEDGED);
final List<MockFlowFile> undetermined = testRunner.getFlowFilesForRelationship(QuerySplunkIndexingStatus.RELATIONSHIP_UNDETERMINED);
Assert.assertEquals(1, acknowledged.size());
Assert.assertEquals(1, undetermined.size());
Assert.assertFalse(acknowledged.get(0).isPenalized());
Assert.assertTrue(undetermined.get(0).isPenalized());
assertEquals(1, acknowledged.size());
assertEquals(1, undetermined.size());
assertFalse(acknowledged.get(0).isPenalized());
assertTrue(undetermined.get(0).isPenalized());
}
@Test
@ -114,8 +120,8 @@ public class TestQuerySplunkIndexingStatus {
testRunner.run();
// then
Assert.assertEquals("{\"acks\":[1,2]}", request.getValue().getContent());
Assert.assertEquals(1, testRunner.getQueueSize().getObjectCount());
assertEquals("{\"acks\":[1,2]}", request.getValue().getContent());
assertEquals(1, testRunner.getQueueSize().getObjectCount());
testRunner.assertAllFlowFilesTransferred(QuerySplunkIndexingStatus.RELATIONSHIP_ACKNOWLEDGED, 2);
}

View File

@ -20,24 +20,25 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.HashMap;
import org.apache.nifi.spring.SpringDataExchanger.SpringResponse;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class SpringContextFactoryTests {
@Test(expected = IllegalStateException.class)
@Test
public void validateACFailureDueToNotFound() {
SpringContextFactory.createSpringContextDelegate(".", "foo.xml");
assertThrows(IllegalStateException.class, () -> SpringContextFactory.createSpringContextDelegate(".", "foo.xml"));
}
@Test(expected = IllegalStateException.class)
@Test
public void validateMessageNotSentNoFromNiFiChannel() throws Exception {
SpringDataExchanger delegate = SpringContextFactory.createSpringContextDelegate(".", "context.xml");
try {
delegate.send("hello", new HashMap<String, Object>(), 1000L);
assertThrows(IllegalStateException.class, () -> delegate.send("hello", new HashMap<String, Object>(), 1000L));
} finally {
delegate.close();
}

View File

@ -16,21 +16,6 @@
*/
package org.apache.nifi.spring;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.nifi.processor.ProcessContext;
import org.apache.nifi.processor.ProcessSession;
import org.apache.nifi.processor.exception.ProcessException;
@ -38,9 +23,24 @@ import org.apache.nifi.spring.SpringDataExchanger.SpringResponse;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
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.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class SpringContextProcessorTest {
@Test
@ -59,7 +59,7 @@ public class SpringContextProcessorTest {
@SuppressWarnings("unchecked")
@Test
public void validateOneWayFromNiFi() throws Exception {
public void validateOneWayFromNiFi() {
TestRunner runner = TestRunners.newTestRunner(TestProcessor.class);
runner.setProperty(SpringContextProcessor.CTX_CONFIG_PATH, "toSpringOnly.xml");
runner.setProperty(SpringContextProcessor.CTX_LIB_PATH, ".");
@ -81,7 +81,7 @@ public class SpringContextProcessorTest {
@SuppressWarnings("unchecked")
@Test
public void validateOneWayFromSpring() throws Exception {
public void validateOneWayFromSpring() {
TestRunner runner = TestRunners.newTestRunner(TestProcessor.class);
runner.setProperty(SpringContextProcessor.CTX_CONFIG_PATH, "fromSpringOnly.xml");
runner.setProperty(SpringContextProcessor.CTX_LIB_PATH, ".");
@ -104,7 +104,7 @@ public class SpringContextProcessorTest {
@SuppressWarnings("unchecked")
@Test
public void validateBiDirectional() throws Exception {
public void validateBiDirectional() {
TestRunner runner = TestRunners.newTestRunner(TestProcessor.class);
runner.setProperty(SpringContextProcessor.CTX_CONFIG_PATH, "requestReply.xml");
runner.setProperty(SpringContextProcessor.CTX_LIB_PATH, ".");

View File

@ -43,8 +43,8 @@ import org.apache.nifi.state.MockStateManager;
import org.apache.nifi.util.MockPropertyValue;
import org.apache.nifi.util.Tuple;
import org.apache.nifi.util.db.JdbcProperties;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.mockito.stubbing.Answer;
@ -56,8 +56,8 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
@ -68,7 +68,7 @@ public class TestMetricsEventReportingTask {
private MockRulesEngineService rulesEngineService;
private ProcessGroupStatus status;
@Before
@BeforeEach
public void setup() {
status = new ProcessGroupStatus();
actionHandler = new MockPropertyContextActionHandler();
@ -147,7 +147,6 @@ public class TestMetricsEventReportingTask {
groupStatuses.add(groupStatus1);
groupStatuses.add(groupStatus3);
status.setProcessGroupStatus(groupStatuses);
}
@Test
@ -164,7 +163,6 @@ public class TestMetricsEventReportingTask {
assertEquals(2,defaultLogActions.size());
assertEquals(2,defaultAlertActions.size());
assertEquals(4,propertyContexts.size());
}
private MockMetricsEventReportingTask initTask(Map<PropertyDescriptor, String> customProperties) throws InitializationException, IOException {

View File

@ -48,8 +48,8 @@ import org.apache.nifi.util.MockProcessSession;
import org.apache.nifi.util.MockPropertyValue;
import org.apache.nifi.util.SharedSessionState;
import org.apache.nifi.util.db.JdbcProperties;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.mockito.stubbing.Answer;
@ -65,10 +65,11 @@ import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
public class TestQueryNiFiReportingTask {
@ -78,7 +79,7 @@ public class TestQueryNiFiReportingTask {
private MockRecordSinkService mockRecordSinkService;
private ProcessGroupStatus status;
@Before
@BeforeEach
public void setup() {
mockRecordSinkService = new MockRecordSinkService();
status = new ProcessGroupStatus();
@ -168,6 +169,7 @@ public class TestQueryNiFiReportingTask {
Map<String, Object> row = rows.get(0);
assertEquals(3, row.size()); // Only projected 2 columns
Object id = row.get("id");
assertTrue(id instanceof String);
assertEquals("nested", id);
assertEquals(1001, row.get("queuedCount"));
@ -214,6 +216,7 @@ public class TestQueryNiFiReportingTask {
assertEquals(1, rows.size());
Map<String, Object> row = rows.get(0);
assertEquals(11, row.size());
assertTrue(row.get(MetricNames.JVM_DAEMON_THREAD_COUNT.replace(".", "_")) instanceof Integer);
assertTrue(row.get(MetricNames.JVM_HEAP_USAGE.replace(".", "_")) instanceof Double);
}
@ -272,6 +275,7 @@ public class TestQueryNiFiReportingTask {
assertEquals(0L, row.get("eventId"));
assertEquals("CREATE", row.get("eventType"));
assertEquals(12L, row.get("entitySize"));
assertNull(row.get("contentPath"));
assertNull(row.get("previousContentPath"));
@ -317,11 +321,12 @@ public class TestQueryNiFiReportingTask {
assertEquals("controller", row.get("bulletinCategory"));
assertEquals("WARN", row.get("bulletinLevel"));
assertEquals(flowFileUuid, row.get("bulletinFlowFileUuid"));
// Validate the second row
row = rows.get(1);
assertEquals("processor", row.get("bulletinCategory"));
assertEquals("INFO", row.get("bulletinLevel"));
assertEquals(flowFileUuid, row.get("bulletinFlowFileUuid"));
// Validate the third row
row = rows.get(2);
assertEquals("controller service", row.get("bulletinCategory"));

View File

@ -23,8 +23,10 @@ import org.apache.nifi.state.MockStateManager;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import org.junit.jupiter.api.condition.OS;
import java.io.IOException;
import java.util.HashMap;
@ -34,12 +36,11 @@ import static org.apache.nifi.processors.stateful.analysis.AttributeRollingWindo
import static org.apache.nifi.processors.stateful.analysis.AttributeRollingWindow.ROLLING_WINDOW_COUNT_KEY;
import static org.apache.nifi.processors.stateful.analysis.AttributeRollingWindow.ROLLING_WINDOW_MEAN_KEY;
import static org.apache.nifi.processors.stateful.analysis.AttributeRollingWindow.ROLLING_WINDOW_VALUE_KEY;
import static org.junit.Assume.assumeFalse;
public class AttributeRollingWindowIT {
@Test
public void testFailureDueToBadAttribute() throws InterruptedException {
public void testFailureDueToBadAttribute() {
final TestRunner runner = TestRunners.newTestRunner(AttributeRollingWindow.class);
runner.setProperty(AttributeRollingWindow.VALUE_TO_TRACK, "${value}");
@ -57,7 +58,7 @@ public class AttributeRollingWindowIT {
}
@Test
public void testStateFailures() throws InterruptedException, IOException {
public void testStateFailures() throws IOException {
final TestRunner runner = TestRunners.newTestRunner(AttributeRollingWindow.class);
MockStateManager mockStateManager = runner.getStateManager();
final AttributeRollingWindow processor = (AttributeRollingWindow) runner.getProcessor();
@ -141,8 +142,8 @@ public class AttributeRollingWindowIT {
@Test
@DisabledOnOs(OS.WINDOWS)
public void testVerifyCount() throws InterruptedException {
assumeFalse(isWindowsEnvironment());
final TestRunner runner = TestRunners.newTestRunner(AttributeRollingWindow.class);
runner.setProperty(AttributeRollingWindow.VALUE_TO_TRACK, "${value}");
@ -193,10 +194,12 @@ public class AttributeRollingWindowIT {
}
@Ignore("this test is too unstable in terms of timing on different size/types of testing envs")
@EnabledIfSystemProperty(named = "nifi.test.unstable",
matches = "true",
disabledReason = "this test is too unstable in terms of timing on different size/types of testing envs")
@Test
@DisabledOnOs(OS.WINDOWS)
public void testMicroBatching() throws InterruptedException {
assumeFalse(isWindowsEnvironment());
final TestRunner runner = TestRunners.newTestRunner(AttributeRollingWindow.class);
runner.setProperty(AttributeRollingWindow.VALUE_TO_TRACK, "${value}");

View File

@ -16,9 +16,10 @@
*/
package org.apache.nifi.processors.gettcp;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import java.io.IOException;
import java.io.PrintWriter;
@ -31,26 +32,29 @@ import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
@Ignore // Ignored for full build due to artificial delays given the
// multi-threaded nature of most of the tests. Please un-Ignore and run
// when working on changes
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@EnabledIfSystemProperty(
named = "nifi.test.unstable",
matches = "true",
disabledReason = "Ignored for full build due to artificial delays given the multi-threaded nature of most of " +
"the tests. Please un-Ignore and run when working on changes"
)
public class ReceivingClientTest {
private final static byte EOM = '\r';
private ScheduledExecutorService scheduler;
@Before
@BeforeEach
public void before() {
this.scheduler = Executors.newScheduledThreadPool(1);
}
@After
@AfterEach
public void after() {
this.scheduler.shutdownNow();
}

View File

@ -17,23 +17,23 @@
package org.apache.nifi.processors.gettcp;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
public final class TestGetTCP {
private TestRunner testRunner;
private GetTCP processor;
@Before
@BeforeEach
public void setup() {
processor = new GetTCP();
testRunner = TestRunners.newTestRunner(processor);
@ -72,7 +72,11 @@ public final class TestGetTCP {
testRunner.assertValid();
}
@Ignore("test is brittle as depends on timing - not reliable across systems, in parallel builds, etc..")
@EnabledIfSystemProperty(
named = "nifi.test.unstable",
matches = "true",
disabledReason = "test is brittle as depends on timing - not reliable across systems, in parallel builds, etc.."
)
@Test
public void testSuccessInteraction() throws Exception {
int port = this.availablePort();
@ -87,7 +91,11 @@ public final class TestGetTCP {
server.stop();
}
@Ignore("test is brittle as depends on timing - not reliable across systems, in parallel builds, etc..")
@EnabledIfSystemProperty(
named = "nifi.test.unstable",
matches = "true",
disabledReason = "test is brittle as depends on timing - not reliable across systems, in parallel builds, etc.."
)
@Test
public void testPartialInteraction() throws Exception {
int port = this.availablePort();

View File

@ -16,6 +16,17 @@
*/
package org.apache.nifi.update.attributes;
import org.apache.nifi.components.state.Scope;
import org.apache.nifi.processor.ProcessSessionFactory;
import org.apache.nifi.processor.exception.ProcessException;
import org.apache.nifi.processors.attributes.UpdateAttribute;
import org.apache.nifi.state.MockStateManager;
import org.apache.nifi.update.attributes.serde.CriteriaSerDe;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collection;
@ -26,21 +37,9 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.nifi.components.state.Scope;
import org.apache.nifi.processor.ProcessSessionFactory;
import org.apache.nifi.processor.exception.ProcessException;
import org.apache.nifi.processors.attributes.UpdateAttribute;
import org.apache.nifi.state.MockStateManager;
import org.apache.nifi.update.attributes.serde.CriteriaSerDe;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.Assert;
import org.junit.Test;
import static org.apache.nifi.processors.attributes.UpdateAttribute.STORE_STATE_LOCALLY;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
*
@ -1001,7 +1000,7 @@ public class TestUpdateAttribute {
try {
runner.run();
} catch (AssertionError e) {
Assert.assertTrue(e.getMessage().contains("org.apache.nifi.processor.exception.ProcessException"));
assertTrue(e.getMessage().contains("org.apache.nifi.processor.exception.ProcessException"));
}
}

View File

@ -33,8 +33,7 @@ import org.apache.nifi.websocket.WebSocketMessage;
import org.apache.nifi.websocket.WebSocketSession;
import org.apache.nifi.websocket.jetty.JettyWebSocketClient;
import org.apache.nifi.websocket.jetty.JettyWebSocketServer;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.net.InetSocketAddress;
import java.util.HashMap;
@ -44,8 +43,9 @@ import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
@ -108,9 +108,7 @@ public class TestConnectWebSocket extends TestListenWebSocket {
List<MockFlowFile> connectedFlowFiles = transferredFlowFiles.get(AbstractWebSocketGatewayProcessor.REL_CONNECTED);
assertEquals(1, connectedFlowFiles.size());
connectedFlowFiles.forEach(ff -> {
assertFlowFile(webSocketSession, serviceId, endpointId, ff, null);
});
connectedFlowFiles.forEach(ff -> assertFlowFile(webSocketSession, serviceId, endpointId, ff, null));
List<MockFlowFile> textFlowFiles = transferredFlowFiles.get(AbstractWebSocketGatewayProcessor.REL_MESSAGE_TEXT);
assertEquals(2, textFlowFiles.size());
@ -120,9 +118,7 @@ public class TestConnectWebSocket extends TestListenWebSocket {
List<MockFlowFile> binaryFlowFiles = transferredFlowFiles.get(AbstractWebSocketGatewayProcessor.REL_MESSAGE_BINARY);
assertEquals(3, binaryFlowFiles.size());
binaryFlowFiles.forEach(ff -> {
assertFlowFile(webSocketSession, serviceId, endpointId, ff, WebSocketMessage.Type.BINARY);
});
binaryFlowFiles.forEach(ff -> assertFlowFile(webSocketSession, serviceId, endpointId, ff, WebSocketMessage.Type.BINARY));
final List<ProvenanceEventRecord> provenanceEvents = sharedSessionState.getProvenanceEvents();
assertEquals(6, provenanceEvents.size());
@ -167,7 +163,7 @@ public class TestConnectWebSocket extends TestListenWebSocket {
final List<MockFlowFile> flowFilesForRelationship = runner.getFlowFilesForRelationship(ConnectWebSocket.REL_CONNECTED);
assertEquals(1, flowFilesForRelationship.size());
final AssertionError assertionError = Assert.assertThrows(AssertionError.class, () -> runner.run(1));
final AssertionError assertionError = assertThrows(AssertionError.class, () -> runner.run(1));
assertTrue(assertionError.getCause().getLocalizedMessage().contains("Failed to renew session and connect to WebSocket service"));
runner.stop();

View File

@ -30,7 +30,7 @@ import org.apache.nifi.websocket.AbstractWebSocketSession;
import org.apache.nifi.websocket.WebSocketMessage;
import org.apache.nifi.websocket.WebSocketServerService;
import org.apache.nifi.websocket.WebSocketSession;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.net.InetSocketAddress;
import java.util.ArrayList;
@ -49,9 +49,9 @@ import static org.apache.nifi.processors.websocket.WebSocketProcessorAttributes.
import static org.apache.nifi.processors.websocket.WebSocketProcessorAttributes.ATTR_WS_MESSAGE_TYPE;
import static org.apache.nifi.processors.websocket.WebSocketProcessorAttributes.ATTR_WS_REMOTE_ADDRESS;
import static org.apache.nifi.processors.websocket.WebSocketProcessorAttributes.ATTR_WS_SESSION_ID;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
@ -108,7 +108,6 @@ public class TestListenWebSocket {
} catch (AssertionError e) {
assertTrue(e.toString().contains("'server-url-path' is invalid because Must starts with"));
}
}
@Test
@ -198,16 +197,16 @@ public class TestListenWebSocket {
// Simulate that the processor has started, and it get's triggered again
processor.onTrigger(runner.getProcessContext(), sessionFactory);
assertEquals("No session should be created", 0, createdSessions.size());
assertEquals(0, createdSessions.size(), "No session should be created");
// Simulate that the processor is stopped.
processor.onStopped(runner.getProcessContext());
assertEquals("No session should be created", 0, createdSessions.size());
assertEquals(0, createdSessions.size(), "No session should be created");
// Simulate that the processor is restarted.
// And the mock service will emit consume msg events.
processor.onTrigger(runner.getProcessContext(), sessionFactory);
assertEquals("Processor should register it with the service again", 6, createdSessions.size());
assertEquals(6, createdSessions.size(), "Processor should register it with the service again");
}
}

View File

@ -16,28 +16,6 @@
*/
package org.apache.nifi.processors.websocket;
import static org.apache.nifi.processors.websocket.WebSocketProcessorAttributes.ATTR_WS_CS_ID;
import static org.apache.nifi.processors.websocket.WebSocketProcessorAttributes.ATTR_WS_ENDPOINT_ID;
import static org.apache.nifi.processors.websocket.WebSocketProcessorAttributes.ATTR_WS_FAILURE_DETAIL;
import static org.apache.nifi.processors.websocket.WebSocketProcessorAttributes.ATTR_WS_LOCAL_ADDRESS;
import static org.apache.nifi.processors.websocket.WebSocketProcessorAttributes.ATTR_WS_MESSAGE_TYPE;
import static org.apache.nifi.processors.websocket.WebSocketProcessorAttributes.ATTR_WS_REMOTE_ADDRESS;
import static org.apache.nifi.processors.websocket.WebSocketProcessorAttributes.ATTR_WS_SESSION_ID;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.nifi.controller.ControllerService;
import org.apache.nifi.provenance.ProvenanceEventRecord;
import org.apache.nifi.util.MockFlowFile;
@ -48,7 +26,29 @@ import org.apache.nifi.websocket.SendMessage;
import org.apache.nifi.websocket.WebSocketMessage;
import org.apache.nifi.websocket.WebSocketService;
import org.apache.nifi.websocket.WebSocketSession;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.apache.nifi.processors.websocket.WebSocketProcessorAttributes.ATTR_WS_CS_ID;
import static org.apache.nifi.processors.websocket.WebSocketProcessorAttributes.ATTR_WS_ENDPOINT_ID;
import static org.apache.nifi.processors.websocket.WebSocketProcessorAttributes.ATTR_WS_FAILURE_DETAIL;
import static org.apache.nifi.processors.websocket.WebSocketProcessorAttributes.ATTR_WS_LOCAL_ADDRESS;
import static org.apache.nifi.processors.websocket.WebSocketProcessorAttributes.ATTR_WS_MESSAGE_TYPE;
import static org.apache.nifi.processors.websocket.WebSocketProcessorAttributes.ATTR_WS_REMOTE_ADDRESS;
import static org.apache.nifi.processors.websocket.WebSocketProcessorAttributes.ATTR_WS_SESSION_ID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
public class TestPutWebSocket {

View File

@ -23,9 +23,9 @@ import org.apache.nifi.websocket.TextMessageConsumer;
import org.apache.nifi.websocket.WebSocketClientService;
import org.apache.nifi.websocket.WebSocketServerService;
import org.apache.nifi.websocket.WebSocketSessionInfo;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.invocation.InvocationOnMock;
import java.net.ServerSocket;
@ -35,10 +35,9 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeFalse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
@ -46,7 +45,6 @@ import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
public class ITJettyWebSocketCommunication {
protected int serverPort;
@ -60,7 +58,7 @@ public class ITJettyWebSocketCommunication {
return false;
}
@Before
@BeforeEach
public void setup() throws Exception {
setupServer();
@ -106,7 +104,7 @@ public class ITJettyWebSocketCommunication {
protected void customizeClient() {
}
@After
@AfterEach
public void teardown() throws Exception {
clientService.stopClient();
serverService.stopServer();
@ -121,7 +119,6 @@ public class ITJettyWebSocketCommunication {
@Test
public void testClientServerCommunication() throws Exception {
assumeFalse(isWindowsEnvironment());
// Expectations.
final CountDownLatch serverIsConnectedByClient = new CountDownLatch(1);
final CountDownLatch clientConnectedServer = new CountDownLatch(1);
@ -168,21 +165,21 @@ public class ITJettyWebSocketCommunication {
clientService.connect(clientId);
assertTrue("WebSocket client should be able to fire connected event.", clientConnectedServer.await(5, TimeUnit.SECONDS));
assertTrue("WebSocket server should be able to fire connected event.", serverIsConnectedByClient.await(5, TimeUnit.SECONDS));
assertTrue(clientConnectedServer.await(5, TimeUnit.SECONDS), "WebSocket client should be able to fire connected event.");
assertTrue(serverIsConnectedByClient.await(5, TimeUnit.SECONDS), "WebSocket server should be able to fire connected event.");
clientService.sendMessage(clientId, clientSessionIdRef.get(), sender -> sender.sendString(textMessageFromClient));
clientService.sendMessage(clientId, clientSessionIdRef.get(), sender -> sender.sendBinary(ByteBuffer.wrap(textMessageFromClient.getBytes())));
assertTrue("WebSocket server should be able to consume text message.", serverReceivedTextMessageFromClient.await(5, TimeUnit.SECONDS));
assertTrue("WebSocket server should be able to consume binary message.", serverReceivedBinaryMessageFromClient.await(5, TimeUnit.SECONDS));
assertTrue(serverReceivedTextMessageFromClient.await(5, TimeUnit.SECONDS), "WebSocket server should be able to consume text message.");
assertTrue(serverReceivedBinaryMessageFromClient.await(5, TimeUnit.SECONDS), "WebSocket server should be able to consume binary message.");
serverService.sendMessage(serverPath, serverSessionIdRef.get(), sender -> sender.sendString(textMessageFromServer));
serverService.sendMessage(serverPath, serverSessionIdRef.get(), sender -> sender.sendBinary(ByteBuffer.wrap(textMessageFromServer.getBytes())));
assertTrue("WebSocket client should be able to consume text message.", clientReceivedTextMessageFromServer.await(5, TimeUnit.SECONDS));
assertTrue("WebSocket client should be able to consume binary message.", clientReceivedBinaryMessageFromServer.await(5, TimeUnit.SECONDS));
assertTrue(clientReceivedTextMessageFromServer.await(5, TimeUnit.SECONDS), "WebSocket client should be able to consume text message.");
assertTrue(clientReceivedBinaryMessageFromServer.await(5, TimeUnit.SECONDS), "WebSocket client should be able to consume binary message.");
clientService.deregisterProcessor(clientId, clientProcessor);
serverService.deregisterProcessor(serverPath, serverProcessor);
@ -190,7 +187,6 @@ public class ITJettyWebSocketCommunication {
@Test
public void testClientServerCommunicationRecovery() throws Exception {
assumeFalse(isWindowsEnvironment());
// Expectations.
final CountDownLatch serverIsConnectedByClient = new CountDownLatch(1);
final CountDownLatch clientConnectedServer = new CountDownLatch(1);
@ -237,8 +233,8 @@ public class ITJettyWebSocketCommunication {
clientService.connect(clientId, Collections.emptyMap());
assertTrue("WebSocket client should be able to fire connected event.", clientConnectedServer.await(5, TimeUnit.SECONDS));
assertTrue("WebSocket server should be able to fire connected event.", serverIsConnectedByClient.await(5, TimeUnit.SECONDS));
assertTrue(clientConnectedServer.await(5, TimeUnit.SECONDS), "WebSocket client should be able to fire connected event.");
assertTrue(serverIsConnectedByClient.await(5, TimeUnit.SECONDS), "WebSocket server should be able to fire connected event.");
// Nothing happens if maintenance is executed while sessions are alive.
((JettyWebSocketClient) clientService).maintainSessions();
@ -253,14 +249,14 @@ public class ITJettyWebSocketCommunication {
clientService.sendMessage(clientId, clientSessionIdRef.get(), sender -> sender.sendString(textMessageFromClient));
clientService.sendMessage(clientId, clientSessionIdRef.get(), sender -> sender.sendBinary(ByteBuffer.wrap(textMessageFromClient.getBytes())));
assertTrue("WebSocket server should be able to consume text message.", serverReceivedTextMessageFromClient.await(5, TimeUnit.SECONDS));
assertTrue("WebSocket server should be able to consume binary message.", serverReceivedBinaryMessageFromClient.await(5, TimeUnit.SECONDS));
assertTrue(serverReceivedTextMessageFromClient.await(5, TimeUnit.SECONDS), "WebSocket server should be able to consume text message.");
assertTrue(serverReceivedBinaryMessageFromClient.await(5, TimeUnit.SECONDS), "WebSocket server should be able to consume binary message.");
serverService.sendMessage(serverPath, serverSessionIdRef.get(), sender -> sender.sendString(textMessageFromServer));
serverService.sendMessage(serverPath, serverSessionIdRef.get(), sender -> sender.sendBinary(ByteBuffer.wrap(textMessageFromServer.getBytes())));
assertTrue("WebSocket client should be able to consume text message.", clientReceivedTextMessageFromServer.await(5, TimeUnit.SECONDS));
assertTrue("WebSocket client should be able to consume binary message.", clientReceivedBinaryMessageFromServer.await(5, TimeUnit.SECONDS));
assertTrue(clientReceivedTextMessageFromServer.await(5, TimeUnit.SECONDS), "WebSocket client should be able to consume text message.");
assertTrue(clientReceivedBinaryMessageFromServer.await(5, TimeUnit.SECONDS), "WebSocket client should be able to consume binary message.");
clientService.deregisterProcessor(clientId, clientProcessor);
serverService.deregisterProcessor(serverPath, serverProcessor);

View File

@ -17,12 +17,12 @@
package org.apache.nifi.websocket.jetty;
import org.apache.nifi.components.ValidationResult;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.Collection;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class TestJettyWebSocketClient {

View File

@ -23,16 +23,16 @@ import org.apache.nifi.util.TestRunners;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.WebSocketAdapter;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
public class TestJettyWebSocketServer {
@ -46,13 +46,13 @@ public class TestJettyWebSocketServer {
private TestRunner runner;
@Before
@BeforeEach
public void setRunner() {
final Processor processor = mock(Processor.class);
runner = TestRunners.newTestRunner(processor);
}
@After
@AfterEach
public void shutdown() {
runner.shutdown();
}
@ -112,7 +112,7 @@ public class TestJettyWebSocketServer {
session.getRemote().sendString(command);
session.close();
assertTrue("Connection not found", connected.get());
assertTrue(connected.get(), "Connection not found");
} finally {
client.stop();
runner.disableControllerService(server);

View File

@ -16,7 +16,7 @@
*/
package org.apache.nifi.websocket.util;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import util.HeaderMapExtractor;
import java.util.Arrays;
@ -25,8 +25,8 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class HeaderMapExtractorTest {