NIFI-10697 Refactored nifi-toolkit tests to use JUnit 5

- Removed RegistryManualIT for nifi-toolkit-cli
- Simplified EncryptConfigMainTest to avoid duplication with ConfigEncryptionToolTest

Signed-off-by: Matthew Burgess <mattyb149@apache.org>

This closes #6579
This commit is contained in:
exceptionfactory 2022-10-25 13:53:55 -05:00 committed by Matthew Burgess
parent b6026f5709
commit 969e2dc7cc
No known key found for this signature in database
GPG Key ID: 05D3DEB8126DAD24
33 changed files with 432 additions and 1159 deletions

View File

@ -16,7 +16,6 @@
*/
package org.apache.nifi.toolkit.cli;
import org.apache.commons.lang3.SystemUtils;
import org.apache.nifi.registry.client.NiFiRegistryClient;
import org.apache.nifi.toolkit.cli.api.ClientFactory;
import org.apache.nifi.toolkit.cli.api.Command;
@ -35,9 +34,10 @@ import org.apache.nifi.util.StringUtils;
import org.jline.reader.Candidate;
import org.jline.reader.LineReader;
import org.jline.reader.ParsedLine;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.BeforeAll;
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 java.util.ArrayList;
@ -46,17 +46,17 @@ import java.util.Collections;
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;
@DisabledOnOs(OS.WINDOWS)
public class TestCLICompleter {
private static CLICompleter completer;
private static LineReader lineReader;
@BeforeClass
@BeforeAll
public static void setupCompleter() {
Assume.assumeTrue("Test only runs on *nix", !SystemUtils.IS_OS_WINDOWS);
final Session session = new InMemorySession();
final ClientFactory<NiFiClient> niFiClientFactory = new NiFiClientFactory();
final ClientFactory<NiFiRegistryClient> nifiRegClientFactory = new NiFiRegistryClientFactory();

View File

@ -28,10 +28,9 @@ import org.apache.nifi.toolkit.cli.impl.command.nifi.AbstractNiFiCommand;
import org.apache.nifi.toolkit.cli.impl.context.StandardContext;
import org.apache.nifi.toolkit.cli.impl.session.InMemorySession;
import org.glassfish.jersey.client.ClientProperties;
import org.junit.After;
import org.junit.Assert;
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.Mockito;
import javax.ws.rs.client.Client;
@ -39,16 +38,17 @@ import java.util.Collections;
import java.util.Map;
import java.util.Properties;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
public class TestClientTimeout {
private Context context;
private ClientFactory<NiFiClient> nifiClientFactory;
private ClientFactory<NiFiRegistryClient> nifiRegClientFactory;
private final Client[] client = new Client[1];
@Before
@BeforeEach
public void setUp() throws Exception {
nifiClientFactory = Mockito.spy(new NiFiClientFactory());
final ClientFactory<NiFiClient> nifiClientFactory = Mockito.spy(new NiFiClientFactory());
Mockito.doAnswer(invocationOnMock -> {
final JerseyNiFiClient nifiClient = Mockito.spy((JerseyNiFiClient) invocationOnMock.callRealMethod());
Mockito.doNothing().when(nifiClient).close(); // avoid closing the client before getting the configuration in the test method
@ -56,7 +56,7 @@ public class TestClientTimeout {
return nifiClient;
}).when(nifiClientFactory).createClient(Mockito.any(Properties.class));
nifiRegClientFactory = Mockito.mock(NiFiRegistryClientFactory.class);
final ClientFactory<NiFiRegistryClient> nifiRegClientFactory = Mockito.mock(NiFiRegistryClientFactory.class);
context = new StandardContext.Builder()
.output(System.out)
@ -67,13 +67,10 @@ public class TestClientTimeout {
.build();
}
@After
@AfterEach
public void tearDown() {
if (client[0] != null) {
try {
client[0].close();
} catch (Throwable th) {
}
client[0].close();
client[0] = null;
}
}
@ -98,10 +95,10 @@ public class TestClientTimeout {
final CommandProcessor processor = new CommandProcessor(Collections.singletonMap("test", command), Collections.emptyMap(), context);
processor.process(new String[] { "test", "-cto", "1", "-rto", "2", "-baseUrl", "http://localhost:9999" });
Assert.assertNotNull(client[0]);
assertNotNull(client[0]);
final Map<String, Object> clientProperties = client[0].getConfiguration().getProperties();
Assert.assertEquals(1, clientProperties.get(ClientProperties.CONNECT_TIMEOUT));
Assert.assertEquals(2, clientProperties.get(ClientProperties.READ_TIMEOUT));
assertEquals(1, clientProperties.get(ClientProperties.CONNECT_TIMEOUT));
assertEquals(2, clientProperties.get(ClientProperties.READ_TIMEOUT));
}
}

View File

@ -16,8 +16,10 @@
*/
package org.apache.nifi.toolkit.cli.impl.client.nifi;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class TestProcessGroupBox {
@ -25,62 +27,62 @@ public class TestProcessGroupBox {
public void testIntersectsWhenCompletelyAbove() {
final ProcessGroupBox pg1 = new ProcessGroupBox(0, 0);
final ProcessGroupBox pg2 = new ProcessGroupBox(0, ProcessGroupBox.PG_SIZE_HEIGHT * 2 + 10);
Assert.assertFalse(pg1.intersects(pg2));
assertFalse(pg1.intersects(pg2));
}
@Test
public void testIntersectsWhenCompletelyBelow() {
final ProcessGroupBox pg1 = new ProcessGroupBox(0, ProcessGroupBox.PG_SIZE_HEIGHT * 2 + 10);
final ProcessGroupBox pg2 = new ProcessGroupBox(0, 0);
Assert.assertFalse(pg1.intersects(pg2));
assertFalse(pg1.intersects(pg2));
}
@Test
public void testIntersectsWhenCompletelyLeft() {
final ProcessGroupBox pg1 = new ProcessGroupBox(0, 0);
final ProcessGroupBox pg2 = new ProcessGroupBox(ProcessGroupBox.PG_SIZE_WIDTH * 2 + 10,0);
Assert.assertFalse(pg1.intersects(pg2));
assertFalse(pg1.intersects(pg2));
}
@Test
public void testIntersectsWhenCompletelyRight() {
final ProcessGroupBox pg1 = new ProcessGroupBox(ProcessGroupBox.PG_SIZE_WIDTH * 2 + 10,0);
final ProcessGroupBox pg2 = new ProcessGroupBox(0,0);
Assert.assertFalse(pg1.intersects(pg2));
assertFalse(pg1.intersects(pg2));
}
@Test
public void testIntersectsWhenCompletelyOverlapping() {
final ProcessGroupBox pg1 = new ProcessGroupBox(0,0);
final ProcessGroupBox pg2 = new ProcessGroupBox(0,0);
Assert.assertTrue(pg1.intersects(pg2));
assertTrue(pg1.intersects(pg2));
}
@Test
public void testIntersectsWhenPartiallyOverlappingVertically() {
final ProcessGroupBox pg1 = new ProcessGroupBox(0,0);
final ProcessGroupBox pg2 = new ProcessGroupBox(0,ProcessGroupBox.PG_SIZE_HEIGHT / 2);
Assert.assertTrue(pg1.intersects(pg2));
assertTrue(pg1.intersects(pg2));
}
@Test
public void testIntersectsWhenBottomAndTopSame() {
final ProcessGroupBox pg1 = new ProcessGroupBox(0,0);
final ProcessGroupBox pg2 = new ProcessGroupBox(0,ProcessGroupBox.PG_SIZE_HEIGHT);
Assert.assertTrue(pg1.intersects(pg2));
assertTrue(pg1.intersects(pg2));
}
@Test
public void testIntersectsWhenPartiallyOverlappingHorizontally() {
final ProcessGroupBox pg1 = new ProcessGroupBox(0,0);
final ProcessGroupBox pg2 = new ProcessGroupBox(ProcessGroupBox.PG_SIZE_WIDTH / 2,0);
Assert.assertTrue(pg1.intersects(pg2));
assertTrue(pg1.intersects(pg2));
}
@Test
public void testIntersectsWhenRightAndLeftSame() {
final ProcessGroupBox pg1 = new ProcessGroupBox(0,0);
final ProcessGroupBox pg2 = new ProcessGroupBox(ProcessGroupBox.PG_SIZE_WIDTH,0);
Assert.assertTrue(pg1.intersects(pg2));
assertTrue(pg1.intersects(pg2));
}
}

View File

@ -19,14 +19,15 @@ package org.apache.nifi.toolkit.cli.impl.command;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.ParseException;
import org.apache.nifi.toolkit.cli.api.Context;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class TestCommandProcessor {
@Test
@ -53,7 +54,7 @@ public class TestCommandProcessor {
command);
final CommandLine cli1 = command.getCli();
Assert.assertEquals("foo1", cli1.getOptionValue(CommandOption.BUCKET_ID.getShortName()));
assertEquals("foo1", cli1.getOptionValue(CommandOption.BUCKET_ID.getShortName()));
// run it again and &2 should be resolved to foo1
processor.processCommand(
@ -64,7 +65,7 @@ public class TestCommandProcessor {
command);
final CommandLine cli2 = command.getCli();
Assert.assertEquals("foo2", cli2.getOptionValue(CommandOption.BUCKET_ID.getShortName()));
assertEquals("foo2", cli2.getOptionValue(CommandOption.BUCKET_ID.getShortName()));
// run it again and &1 should be resolved to foo1
processor.processCommand(
@ -77,7 +78,7 @@ public class TestCommandProcessor {
command);
final CommandLine cli3 = command.getCli();
Assert.assertEquals("foo1", cli3.getOptionValue(CommandOption.FLOW_ID.getShortName()));
assertEquals("foo1", cli3.getOptionValue(CommandOption.FLOW_ID.getShortName()));
}
}

View File

@ -1,363 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nifi.toolkit.cli.impl.command.registry;
import org.apache.nifi.toolkit.cli.CLIMain;
import org.apache.nifi.util.StringUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.StringJoiner;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class RegistryManualIT {
public static final String TRUSTSTORE = "";
public static final String TRUSTSTORE_PASSWD = "";
public static final String KEYSTORE = "";
public static final String KEYSTORE_PASSWD = "";
private String basicSettings = "--baseUrl https://localhost:18443 --verbose";
private String securitySettings = "--truststore " + TRUSTSTORE +
" --truststoreType jks --truststorePasswd " + TRUSTSTORE_PASSWD +
" --keystore " + KEYSTORE +
" --keystorePasswd " + KEYSTORE_PASSWD +
" --keystoreType PKCS12";
private static final String TEST_USER_NAME = "testUser";
private static final String TEST_USER_GROUP_NAME = "testUserGroup";
private String testUserId;
private String testUserGroupId;
private static final String TEST_BUCKET_NAME = "testBucket";
private String testBucketId;
private PrintStream originalStdOut;
private ByteArrayOutputStream out;
@Before
public void setUp() throws Exception {
assertFalse("truststore not set", StringUtils.isBlank(TRUSTSTORE));
assertFalse("truststorePasswd not set", StringUtils.isBlank(TRUSTSTORE_PASSWD));
assertFalse("keystore not set", StringUtils.isBlank(KEYSTORE));
assertFalse("keystorePassed not set", StringUtils.isBlank(KEYSTORE_PASSWD));
}
@After
public void tearDown() throws Exception {
resetStdOut();
}
@Ignore("Run first and only once")
@Test
public void testCreateUser() throws Exception {
String userName = TEST_USER_NAME;
runRegistryCommand("create-user",
"--userName " + userName
);
testListUsers(userName);
}
@Ignore("Run first and only once")
@Test
public void testCreateUseGroup() throws Exception {
String expectedUserGroup = TEST_USER_GROUP_NAME;
runRegistryCommand("create-user-group",
"--userGroupName " + expectedUserGroup +
" --userNameList " + TEST_USER_NAME +
" --userIdList " + testUserId
);
testListUserGroup(expectedUserGroup);
}
@Ignore("Run first and only once")
@Test
public void testCreateBucket() throws Exception {
runRegistryCommand("create-bucket", "--bucketName " + TEST_BUCKET_NAME);
testListBuckets(TEST_BUCKET_NAME);
}
@Test
public void testListUsers() throws Exception {
testListUsers(TEST_USER_NAME);
}
@Test
public void testUpdateUser() throws Exception {
String originalUserName = TEST_USER_NAME;
String updatedUserName = "updatedTestUser";
testListUsers(originalUserName);
runRegistryCommand("update-user",
"--userName " + updatedUserName +
" --userId " + testUserId
);
testListUsers(updatedUserName);
runRegistryCommand("update-user",
"--userName " + originalUserName +
" --userId " + testUserId
);
testListUsers(originalUserName);
}
@Test
public void testListUserGroups() throws Exception {
testListUserGroup(TEST_USER_GROUP_NAME);
}
@Test
public void testUpdateUserGroup() throws Exception {
runRegistryCommand("update-user-group",
"--userGroupName " + TEST_USER_GROUP_NAME +
" --userNameList " + TEST_USER_NAME +
" --userIdLis " + testUserId +
" --userGroupId " + testUserGroupId
);
testListUserGroup(TEST_USER_GROUP_NAME);
}
@Test
public void testGetAccessPolicy() throws Exception {
String action = "read";
String resource = "/testResource";
testGetAccessPolicy(action, resource);
}
@Test
public void testCreateOrUpdateAccessPolicy() throws Exception {
String action = "read";
String resource = "/testResource";
runRegistryCommand("update-policy",
"--accessPolicyResource " + resource +
" --accessPolicyAction " + action +
" --userNameList " + TEST_USER_NAME +
" --userIdList " + testUserId +
" --groupNameList " + TEST_USER_GROUP_NAME +
" --groupIdList " + testUserGroupId
);
testGetAccessPolicy(action, resource);
// Users are not removed if none is specified
runRegistryCommand("update-policy",
"--accessPolicyResource " + resource +
" --accessPolicyAction " + action +
" --groupNameList " + TEST_USER_GROUP_NAME +
" --groupIdList " + testUserGroupId
);
testGetAccessPolicy(action, resource);
// Groups are not removed if none is specified
runRegistryCommand("update-policy",
"--accessPolicyResource " + resource +
" --accessPolicyAction " + action +
" --userNameList " + TEST_USER_NAME +
" --userIdList " + testUserId
);
testGetAccessPolicy(action, resource);
}
@Test
public void testUpdateBucketPolicyByName() throws Exception {
String action = "/read";
runRegistryCommand("update-bucket-policy",
"--bucketName " + TEST_BUCKET_NAME +
" --accessPolicyAction " + action +
" --userNameList " + TEST_USER_NAME +
" --userIdList " + testUserId
);
testGetAccessPolicy(action, testBucketId);
}
@Test public void testUpdateBucketPolicyById() throws Exception {
String action = "/write";
runRegistryCommand("update-bucket-policy",
"--bucketId " + testBucketId +
" --accessPolicyAction " + action +
" --groupNameList " + TEST_USER_GROUP_NAME +
" --groupIdList " + testUserGroupId
);
testGetAccessPolicy(action, testBucketId);
}
@Test
public void testListBuckets() throws Exception {
testListBuckets(TEST_BUCKET_NAME);
}
private void testListUsers(String expectedUserName) throws IOException {
runCommand(
"\\s{3,}",
() -> runRegistryCommand("list-users", ""),
words -> {
if (words.length > 2 && words[1].equals(expectedUserName)) {
testUserId = words[2];
}
},
() -> {
assertNotNull(testUserId);
assertTrue("User id shouldn't be blank!", !StringUtils.isBlank(testUserId));
}
);
}
private void testListUserGroup(String expectedUserGroupName) throws IOException {
runCommand(
"\\s{3,}",
() -> runRegistryCommand("list-user-groups", ""),
words -> {
if (words.length > 3 && words[1].equals(expectedUserGroupName)) {
testUserGroupId = words[2];
}
},
() -> {
assertNotNull(testUserGroupId);
assertTrue("Group id shouldn't be blank!", !StringUtils.isBlank(testUserGroupId));
}
);
}
private void testListBuckets(String expectedBucketName) throws IOException {
runCommand("\\s{3,}",
() -> runRegistryCommand("list-buckets",""),
words -> {
if (words.length > 2 && words[1].equals(expectedBucketName)) {
testBucketId = words[2];
}
},
() -> {
assertNotNull(testBucketId);
assertTrue("Bucket ID should not be blank!", !StringUtils.isBlank(testBucketId));
});
}
private void testGetAccessPolicy(String action, String resource) throws IOException {
AtomicReference<String> resourceR = new AtomicReference<>();
AtomicReference<String> actionR = new AtomicReference<>();
AtomicReference<String> usersR = new AtomicReference<>();
AtomicReference<String> groupsR = new AtomicReference<>();
runCommand(
"\\s*:\\s+",
() -> runRegistryCommand("get-policy",
"--accessPolicyResource " + resource +
" --accessPolicyAction " + action
),
words -> {
if (words.length > 1) {
if (words[0].equals("Users")) {
usersR.set(words[1]);
} else if (words[0].equals("Groups")) {
groupsR.set(words[1]);
} else if (words[0].equals("Resource")) {
resourceR.set(words[1]);
} else if (words[0].equals("Action")) {
actionR.set(words[1]);
}
}
},
() -> {
resourceR.get().equals(resource);
actionR.get().contains(action);
usersR.get().contains(TEST_USER_NAME);
groupsR.get().contains(TEST_USER_GROUP_NAME);
}
);
}
private void runCommand(String delimiter, Runnable commandRunner, Consumer<String[]> outputLineHandler, Runnable check) throws IOException {
try {
// GIVEN
startCaptureStdOut();
// WHEN
commandRunner.run();
// THEN
BufferedReader bufferedOutput = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(out.toByteArray())));
String line;
while ((line = bufferedOutput.readLine()) != null) {
originalStdOut.println(line);
String[] words = line.split(delimiter);
outputLineHandler.accept(words);
}
check.run();
} finally {
resetStdOut();
}
}
private void runRegistryCommand(String command, String commandArguments) {
// GIVEN
String arguments = new StringJoiner(" ")
.add("registry")
.add(command)
.add(commandArguments)
.add(basicSettings)
.add(securitySettings)
.toString();
String[] args = arguments.split("\\s+");
// WHEN
CLIMain.runSingleCommand(args);
// THEN
}
private void startCaptureStdOut() {
originalStdOut = System.out;
out = new ByteArrayOutputStream();
System.setOut(new PrintStream(out));
}
private void resetStdOut() {
if (originalStdOut != null) {
System.setOut(originalStdOut);
}
}
}

View File

@ -17,7 +17,7 @@
package org.apache.nifi.toolkit.cli.impl.command.registry.tenant;
import org.apache.nifi.registry.authorization.Tenant;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
@ -25,12 +25,11 @@ import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class TestTenantHelper {
@Test
public void testSelectExistingTenantsWithEmptyNamesAndIds() throws Exception {
// GIVEN
public void testSelectExistingTenantsWithEmptyNamesAndIds() {
String names = "";
String ids = "";
@ -41,14 +40,11 @@ public class TestTenantHelper {
List<Tenant> expected = Collections.emptyList();
// WHEN
// THEN
testSelectExistingTenants(names, ids, allTenants, expected);
}
@Test
public void testSelectExistingTenantsWithNames() throws Exception {
// GIVEN
public void testSelectExistingTenantsWithNames() {
String names = "name1,name3";
String ids = "";
@ -69,14 +65,11 @@ public class TestTenantHelper {
tenantFoundByName3
);
// WHEN
// THEN
testSelectExistingTenants(names, ids, allTenants, expected);
}
@Test
public void testSelectExistingTenantsWithIds() throws Exception {
// GIVEN
public void testSelectExistingTenantsWithIds() {
String names = "";
String ids = "id1,id2";
@ -97,14 +90,11 @@ public class TestTenantHelper {
tenantFoundById2
);
// WHEN
// THEN
testSelectExistingTenants(names, ids, allTenants, expected);
}
@Test
public void testSelectExistingTenantsWithComplexScenario() throws Exception {
// GIVEN
public void testSelectExistingTenantsWithComplexScenario() {
String names = "name1,name3";
String ids = "id1,id2";
@ -126,19 +116,14 @@ public class TestTenantHelper {
tenantFoundByName
);
// WHEN
// THEN
testSelectExistingTenants(names, ids, allTenants, expected);
}
private void testSelectExistingTenants(String names, String ids, List<Tenant> allTenants, List<Tenant> expectedTenants) {
// GIVEN
Set<Tenant> expected = new HashSet<>(expectedTenants);
// WHEN
Set<Tenant> actual = TenantHelper.selectExistingTenants(names, ids, allTenants);
// THEN
assertEquals(expected, actual);
}

View File

@ -16,15 +16,13 @@
*/
package org.apache.nifi.toolkit.cli.impl.result;
import org.apache.commons.lang3.SystemUtils;
import org.apache.nifi.registry.bucket.Bucket;
import org.apache.nifi.toolkit.cli.api.ResultType;
import org.apache.nifi.toolkit.cli.impl.result.registry.BucketsResult;
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 java.io.ByteArrayOutputStream;
import java.io.IOException;
@ -34,17 +32,15 @@ import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
@DisabledOnOs(OS.WINDOWS)
public class TestBucketsResult {
private ByteArrayOutputStream outputStream;
private PrintStream printStream;
@BeforeClass
public static void setupCompleter() {
Assume.assumeTrue("Test only runs on *nix", !SystemUtils.IS_OS_WINDOWS);
}
@Before
@BeforeEach
public void setup() {
this.outputStream = new ByteArrayOutputStream();
this.printStream = new PrintStream(outputStream, true);
@ -79,7 +75,6 @@ public class TestBucketsResult {
"2 Bucket 2 ddf5f289-7502-46df-9798-4b0457c1816b (empty) \n" +
"\n";
Assert.assertEquals(expected, resultOut);
assertEquals(expected, resultOut);
}
}

View File

@ -16,15 +16,13 @@
*/
package org.apache.nifi.toolkit.cli.impl.result;
import org.apache.commons.lang3.SystemUtils;
import org.apache.nifi.registry.flow.VersionedFlowSnapshotMetadata;
import org.apache.nifi.toolkit.cli.api.ResultType;
import org.apache.nifi.toolkit.cli.impl.result.registry.RegisteredFlowSnapshotMetadataResult;
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 java.io.ByteArrayOutputStream;
import java.io.IOException;
@ -35,17 +33,15 @@ import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertTrue;
@DisabledOnOs(OS.WINDOWS)
public class TestRegisteredFlowSnapshotMetadataResult {
private ByteArrayOutputStream outputStream;
private PrintStream printStream;
@BeforeClass
public static void setupCompleter() {
Assume.assumeTrue("Test only runs on *nix", !SystemUtils.IS_OS_WINDOWS);
}
@Before
@BeforeEach
public void setup() {
this.outputStream = new ByteArrayOutputStream();
this.printStream = new PrintStream(outputStream, true);
@ -75,7 +71,6 @@ public class TestRegisteredFlowSnapshotMetadataResult {
result.write(printStream);
final String resultOut = new String(outputStream.toByteArray(), StandardCharsets.UTF_8);
//System.out.println(resultOut);
// can't get the time zone to line up on travis, so ignore this for now
final String expectedPattern = "^\\n" +
@ -85,6 +80,6 @@ public class TestRegisteredFlowSnapshotMetadataResult {
//"2 Wed, Feb 14 2018 12:30 EST user2 This is v2 \n" +
"(.|\\n)+$";
Assert.assertTrue(resultOut.matches(expectedPattern));
assertTrue(resultOut.matches(expectedPattern));
}
}

View File

@ -16,17 +16,15 @@
*/
package org.apache.nifi.toolkit.cli.impl.result;
import org.apache.commons.lang3.SystemUtils;
import org.apache.nifi.toolkit.cli.api.ResultType;
import org.apache.nifi.toolkit.cli.impl.result.nifi.RegistryClientsResult;
import org.apache.nifi.web.api.dto.FlowRegistryClientDTO;
import org.apache.nifi.web.api.entity.FlowRegistryClientEntity;
import org.apache.nifi.web.api.entity.FlowRegistryClientsEntity;
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 java.io.ByteArrayOutputStream;
import java.io.IOException;
@ -36,22 +34,21 @@ import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
@DisabledOnOs(OS.WINDOWS)
public class TestRegistryClientResult {
private ByteArrayOutputStream outputStream;
private PrintStream printStream;
@BeforeClass
public static void setupCompleter() {
Assume.assumeTrue("Test only runs on *nix", !SystemUtils.IS_OS_WINDOWS);
}
@Before
@BeforeEach
public void setup() {
this.outputStream = new ByteArrayOutputStream();
this.printStream = new PrintStream(outputStream, true);
}
@SuppressWarnings("deprecation")
@Test
public void testWriteSimpleRegistryClientsResult() throws IOException {
final FlowRegistryClientDTO r1 = new FlowRegistryClientDTO();
@ -83,7 +80,6 @@ public class TestRegistryClientResult {
result.write(printStream);
final String resultOut = new String(outputStream.toByteArray(), StandardCharsets.UTF_8);
//System.out.println(resultOut);
final String expected = "\n" +
"# Name Id Uri \n" +
@ -92,7 +88,7 @@ public class TestRegistryClientResult {
"2 Registry 2 with a longer than usu... ddf5f289-7502-46df-9798-4b0457c1816b http://localhost:18080 \n" +
"\n";
Assert.assertEquals(expected, resultOut);
assertEquals(expected, resultOut);
}
}

View File

@ -16,18 +16,16 @@
*/
package org.apache.nifi.toolkit.cli.impl.result;
import org.apache.commons.lang3.SystemUtils;
import org.apache.nifi.registry.flow.VersionedFlow;
import org.apache.nifi.toolkit.cli.api.Context;
import org.apache.nifi.toolkit.cli.api.ReferenceResolver;
import org.apache.nifi.toolkit.cli.api.ResultType;
import org.apache.nifi.toolkit.cli.impl.command.CommandOption;
import org.apache.nifi.toolkit.cli.impl.result.registry.VersionedFlowsResult;
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 java.io.ByteArrayOutputStream;
@ -38,18 +36,16 @@ import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
@DisabledOnOs(OS.WINDOWS)
public class TestVersionedFlowsResult {
private ByteArrayOutputStream outputStream;
private PrintStream printStream;
private List<VersionedFlow> flows;
@BeforeClass
public static void setupCompleter() {
Assume.assumeTrue("Test only runs on *nix", !SystemUtils.IS_OS_WINDOWS);
}
@Before
@BeforeEach
public void setup() {
this.outputStream = new ByteArrayOutputStream();
this.printStream = new PrintStream(outputStream, true);
@ -79,7 +75,6 @@ public class TestVersionedFlowsResult {
result.write(printStream);
final String resultOut = new String(outputStream.toByteArray(), StandardCharsets.UTF_8);
//System.out.println(resultOut);
final String expected = "\n" +
"# Name Id Description \n" +
@ -88,7 +83,7 @@ public class TestVersionedFlowsResult {
"2 Flow 2 ddf5f289-7502-46df-9798-4b0457c1816b (empty) \n" +
"\n";
Assert.assertEquals(expected, resultOut);
assertEquals(expected, resultOut);
}
@Test
@ -97,19 +92,18 @@ public class TestVersionedFlowsResult {
final ReferenceResolver resolver = result.createReferenceResolver(Mockito.mock(Context.class));
// should default to flow id when no option is specified
Assert.assertEquals("ea752054-22c6-4fc0-b851-967d9a3837cb", resolver.resolve(null, 1).getResolvedValue());
Assert.assertEquals("ddf5f289-7502-46df-9798-4b0457c1816b", resolver.resolve(null, 2).getResolvedValue());
assertEquals("ea752054-22c6-4fc0-b851-967d9a3837cb", resolver.resolve(null, 1).getResolvedValue());
assertEquals("ddf5f289-7502-46df-9798-4b0457c1816b", resolver.resolve(null, 2).getResolvedValue());
// should use flow id when flow id is specified
Assert.assertEquals("ea752054-22c6-4fc0-b851-967d9a3837cb", resolver.resolve(CommandOption.FLOW_ID, 1).getResolvedValue());
Assert.assertEquals("ddf5f289-7502-46df-9798-4b0457c1816b", resolver.resolve(CommandOption.FLOW_ID, 2).getResolvedValue());
assertEquals("ea752054-22c6-4fc0-b851-967d9a3837cb", resolver.resolve(CommandOption.FLOW_ID, 1).getResolvedValue());
assertEquals("ddf5f289-7502-46df-9798-4b0457c1816b", resolver.resolve(CommandOption.FLOW_ID, 2).getResolvedValue());
// should resolve the bucket id when bucket id option is used
Assert.assertEquals("b1", resolver.resolve(CommandOption.BUCKET_ID, 1).getResolvedValue());
Assert.assertEquals("b2", resolver.resolve(CommandOption.BUCKET_ID, 2).getResolvedValue());
assertEquals("b1", resolver.resolve(CommandOption.BUCKET_ID, 1).getResolvedValue());
assertEquals("b2", resolver.resolve(CommandOption.BUCKET_ID, 2).getResolvedValue());
// should resolve to null when position doesn't exist
Assert.assertEquals(null, resolver.resolve(CommandOption.FLOW_ID, 3));
assertEquals(null, resolver.resolve(CommandOption.FLOW_ID, 3));
}
}

View File

@ -16,17 +16,18 @@
*/
package org.apache.nifi.toolkit.cli.impl.result.writer;
import org.apache.commons.lang3.SystemUtils;
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 java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.assertEquals;
@DisabledOnOs(OS.WINDOWS)
public class TestDynamicTableWriter {
private Table table;
@ -35,12 +36,7 @@ public class TestDynamicTableWriter {
private ByteArrayOutputStream outputStream;
private PrintStream printStream;
@BeforeClass
public static void setupCompleter() {
Assume.assumeTrue("Test only runs on *nix", !SystemUtils.IS_OS_WINDOWS);
}
@Before
@BeforeEach
public void setup() {
this.table = new Table.Builder()
.column("#", 3, 3, false)
@ -60,14 +56,13 @@ public class TestDynamicTableWriter {
tableWriter.write(table, printStream);
final String result = new String(outputStream.toByteArray(), StandardCharsets.UTF_8);
//System.out.println(result);
final String expected = "\n" +
"# Name Id Description \n" +
"--- -------------------- ------------------------------------ ----------- \n" +
"\n";
Assert.assertEquals(expected, result);
assertEquals(expected, result);
}
@Test
@ -96,7 +91,6 @@ public class TestDynamicTableWriter {
tableWriter.write(table, printStream);
final String result = new String(outputStream.toByteArray(), StandardCharsets.UTF_8);
//System.out.println(result);
final String expected = "\n" +
"# Name Id Description \n" +
@ -106,7 +100,7 @@ public class TestDynamicTableWriter {
"3 Bucket 3 12345-12345-12345-12345-12345-12345 (empty) \n" +
"\n";
Assert.assertEquals(expected, result);
assertEquals(expected, result);
}
@Test
@ -116,7 +110,6 @@ public class TestDynamicTableWriter {
tableWriter.write(table, printStream);
final String result = new String(outputStream.toByteArray(), StandardCharsets.UTF_8);
//System.out.println(result);
final String expected ="\n" +
"# Name Id Description \n" +
@ -125,7 +118,7 @@ public class TestDynamicTableWriter {
"2 Bucket 2 12345-12345-12345-12345-12345-12345 (empty) \n" +
"\n";
Assert.assertEquals(expected, result);
assertEquals(expected, result);
}
}

View File

@ -16,76 +16,34 @@
*/
package org.apache.nifi.toolkit.encryptconfig
import groovy.test.GroovyTestCase
import org.apache.nifi.properties.NiFiPropertiesLoader
import org.apache.nifi.properties.ProtectedPropertyContext
import org.apache.nifi.properties.SensitivePropertyProvider
import org.apache.nifi.properties.scheme.StandardProtectionScheme
import org.apache.nifi.toolkit.encryptconfig.util.BootstrapUtil
import org.apache.nifi.util.NiFiProperties
import org.bouncycastle.jce.provider.BouncyCastleProvider
import org.junit.BeforeClass
import org.junit.Rule
import org.junit.Test
import org.junit.contrib.java.lang.system.Assertion
import org.junit.contrib.java.lang.system.ExpectedSystemExit
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.junit.jupiter.api.Test
import java.nio.file.Files
import java.security.Security
@RunWith(JUnit4.class)
class EncryptConfigMainTest extends GroovyTestCase {
private static final Logger logger = LoggerFactory.getLogger(EncryptConfigMainTest.class)
@Rule
public final ExpectedSystemExit exit = ExpectedSystemExit.none()
@BeforeClass
static void setUpOnce() throws Exception {
Security.addProvider(new BouncyCastleProvider())
logger.metaClass.methodMissing = { String name, args ->
logger.info("[${name?.toUpperCase()}] ${(args as List).join(" ")}")
}
TestUtil.setupTmpDir()
}
class EncryptConfigMainTest {
@Test
void testDetermineModeFromArgsWithLegacyMode() {
// Arrange
def argsList = "-b conf/bootstrap.conf -n conf/nifi.properties".split(" ").toList()
// Act
def toolMode = EncryptConfigMain.determineModeFromArgs(argsList)
// Assert
toolMode != null
toolMode instanceof LegacyMode
}
@Test
void testDetermineModeFromArgsWithNifiRegistryMode() {
// Arrange
def argsList = "--nifiRegistry".split(" ").toList()
// Act
def toolMode = EncryptConfigMain.determineModeFromArgs(argsList)
// Assert
toolMode != null
toolMode instanceof NiFiRegistryMode
!argsList.contains("--nifiRegistry")
/* Test when --nifiRegistry is not first flag */
// Arrange
argsList = "-b conf/bootstrap.conf -p --nifiRegistry -r conf/nifi-registry.properties".split(" ").toList()
// Act
toolMode = EncryptConfigMain.determineModeFromArgs(argsList)
// Assert
toolMode != null
toolMode instanceof NiFiRegistryMode
!argsList.contains("--nifiRegistry")
@ -93,23 +51,19 @@ class EncryptConfigMainTest extends GroovyTestCase {
@Test
void testDetermineModeFromArgsWithNifiRegistryDecryptMode() {
// Arrange
def argsList = "--nifiRegistry --decrypt".split(" ").toList()
// Act
def toolMode = EncryptConfigMain.determineModeFromArgs(argsList)
// Assert
toolMode != null
toolMode instanceof NiFiRegistryDecryptMode
!argsList.contains("--nifiRegistry")
!argsList.contains("--decrypt")
/* Test when --decrypt comes before --nifiRegistry */
// Arrange
argsList = "--b conf/bootstrap.conf --decrypt --nifiRegistry".split(" ").toList()
// Act
toolMode = EncryptConfigMain.determineModeFromArgs(argsList)
// Assert
toolMode != null
toolMode instanceof NiFiRegistryDecryptMode
!argsList.contains("--nifiRegistry")
@ -118,166 +72,10 @@ class EncryptConfigMainTest extends GroovyTestCase {
@Test
void testDetermineModeFromArgsReturnsNullOnDecryptWithoutNifiRegistryPresent() {
// Arrange
def argsList = "--decrypt".split(" ").toList()
// Act
def toolMode = EncryptConfigMain.determineModeFromArgs(argsList)
// Assert
toolMode == null
}
@Test
void testShouldPerformFullOperationForNiFiPropertiesAndLoginIdentityProvidersAndAuthorizers() {
// Arrange
exit.expectSystemExitWithStatus(0)
File tmpDir = TestUtil.setupTmpDir()
File emptyKeyFile = new File("src/test/resources/bootstrap_with_empty_root_key.conf")
File bootstrapFile = new File("target/tmp/tmp_bootstrap.conf")
bootstrapFile.delete()
Files.copy(emptyKeyFile.toPath(), bootstrapFile.toPath())
final List<String> originalBootstrapLines = bootstrapFile.readLines()
String originalKeyLine = originalBootstrapLines.find {
it.startsWith("${BootstrapUtil.NIFI_BOOTSTRAP_KEY_PROPERTY}=")
}
logger.info("Original key line from bootstrap.conf: ${originalKeyLine}")
assert originalKeyLine == "${BootstrapUtil.NIFI_BOOTSTRAP_KEY_PROPERTY}="
final String EXPECTED_KEY_LINE = "${BootstrapUtil.NIFI_BOOTSTRAP_KEY_PROPERTY}=${TestUtil.KEY_HEX}"
// Set up the NFP file
File inputPropertiesFile = new File("src/test/resources/nifi_with_sensitive_properties_unprotected.properties")
File outputPropertiesFile = new File("target/tmp/tmp_nifi.properties")
outputPropertiesFile.delete()
NiFiProperties inputProperties = new NiFiPropertiesLoader().load(inputPropertiesFile)
logger.info("Loaded ${inputProperties.size()} properties from input file")
// Set up the LIP file
File inputLIPFile = new File("src/test/resources/login-identity-providers-populated.xml")
File outputLIPFile = new File("target/tmp/tmp-lip.xml")
outputLIPFile.delete()
String originalLipXmlContent = inputLIPFile.text
logger.info("Original LIP XML content: ${originalLipXmlContent}")
// Set up the Authorizers file
File inputAuthorizersFile = new File("src/test/resources/authorizers-populated.xml")
File outputAuthorizersFile = new File("target/tmp/tmp-authorizers.xml")
outputAuthorizersFile.delete()
String originalAuthorizersXmlContent = inputAuthorizersFile.text
logger.info("Original Authorizers XML content: ${originalAuthorizersXmlContent}")
String[] args = [
"-n", inputPropertiesFile.path,
"-l", inputLIPFile.path,
"-a", inputAuthorizersFile.path,
"-b", bootstrapFile.path,
"-o", outputPropertiesFile.path,
"-i", outputLIPFile.path,
"-u", outputAuthorizersFile.path,
"-k", TestUtil.KEY_HEX,
"-v"]
SensitivePropertyProvider spp = org.apache.nifi.properties.StandardSensitivePropertyProviderFactory.withKey(TestUtil.KEY_HEX)
.getProvider(new StandardProtectionScheme("aes/gcm"))
exit.checkAssertionAfterwards(new Assertion() {
void checkAssertion() {
/*** NiFi Properties Assertions ***/
final List<String> updatedPropertiesLines = outputPropertiesFile.readLines()
// Check that the output values for sensitive properties are not the same as the original (i.e. it was encrypted)
NiFiProperties updatedProperties = NiFiPropertiesLoader.withKey(TestUtil.KEY_HEX).load(outputPropertiesFile)
assert updatedProperties.size() >= inputProperties.size()
// Check that the new NiFiProperties instance matches the output file (values still encrypted)
updatedProperties.getPropertyKeys().every { String key ->
assert updatedPropertiesLines.contains("${key}=${updatedProperties.getProperty(key)}".toString())
}
/*** Login Identity Providers Assertions ***/
final String updatedLipXmlContent = outputLIPFile.text
logger.info("Updated LIP XML content: ${updatedLipXmlContent}")
// Check that the output values for sensitive properties are not the same as the original (i.e. it was encrypted)
def originalLipParsedXml = new XmlSlurper().parseText(originalLipXmlContent)
def updatedLipParsedXml = new XmlSlurper().parseText(updatedLipXmlContent)
assert originalLipParsedXml != updatedLipParsedXml
assert originalLipParsedXml.'**'.findAll { it.@encryption } != updatedLipParsedXml.'**'.findAll {
it.@encryption
}
def lipEncryptedValues = updatedLipParsedXml.provider.find {
it.identifier == 'ldap-provider'
}.property.findAll {
it.@name =~ "Password" && it.@encryption =~ "aes/gcm/\\d{3}"
}
lipEncryptedValues.each {
assert spp.unprotect((String) it.text(), ProtectedPropertyContext.defaultContext((String) it.@name)) == TestUtil.PASSWORD
}
// Check that the comments are still there
def lipTrimmedLines = inputLIPFile.readLines().collect { it.trim() }.findAll { it }
def lipTrimmedSerializedLines = updatedLipXmlContent.split("\n").collect { it.trim() }.findAll { it }
assert lipTrimmedLines.size() == lipTrimmedSerializedLines.size()
/*** Authorizers Assertions ***/
final String updatedAuthorizersXmlContent = outputAuthorizersFile.text
logger.info("Updated Authorizers XML content: ${updatedAuthorizersXmlContent}")
// Check that the output values for sensitive properties are not the same as the original (i.e. it was encrypted)
def originalAuthorizersParsedXml = new XmlSlurper().parseText(originalAuthorizersXmlContent)
def updatedAuthorizersParsedXml = new XmlSlurper().parseText(updatedAuthorizersXmlContent)
assert originalAuthorizersParsedXml != updatedAuthorizersParsedXml
assert originalAuthorizersParsedXml.'**'.findAll { it.@encryption } != updatedAuthorizersParsedXml.'**'.findAll {
it.@encryption
}
def authorizersEncryptedValues = updatedAuthorizersParsedXml.userGroupProvider.find {
it.identifier == 'ldap-user-group-provider'
}.property.findAll {
it.@name =~ "Password" && it.@encryption =~ "aes/gcm/\\d{3}"
}
authorizersEncryptedValues.each {
assert spp.unprotect((String) it.text(), (ProtectedPropertyContext) ProtectedPropertyContext.defaultContext((String) it.@name)) == TestUtil.PASSWORD
}
// Check that the comments are still there
def authorizersTrimmedLines = inputAuthorizersFile.readLines().collect { it.trim() }.findAll { it }
def authorizersTrimmedSerializedLines = updatedAuthorizersXmlContent.split("\n").collect { it.trim() }.findAll { it }
assert authorizersTrimmedLines.size() == authorizersTrimmedSerializedLines.size()
/*** Bootstrap assertions ***/
// Check that the key was persisted to the bootstrap.conf
final List<String> updatedBootstrapLines = bootstrapFile.readLines()
String updatedKeyLine = updatedBootstrapLines.find {
it.startsWith(BootstrapUtil.NIFI_BOOTSTRAP_KEY_PROPERTY)
}
logger.info("Updated key line: ${updatedKeyLine}")
assert updatedKeyLine == EXPECTED_KEY_LINE
assert originalBootstrapLines.size() == updatedBootstrapLines.size()
// Clean up
outputPropertiesFile.deleteOnExit()
outputLIPFile.deleteOnExit()
outputAuthorizersFile.deleteOnExit()
bootstrapFile.deleteOnExit()
tmpDir.deleteOnExit()
}
})
// Act
EncryptConfigMain.main(args)
logger.info("Invoked #main with ${args.join(" ")}")
// Assert
// Assertions defined above
}
}

View File

@ -16,12 +16,12 @@
*/
package org.apache.nifi.toolkit;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigDecimal;
import org.apache.nifi.toolkit.flowanalyzer.FlowAnalyzerDriver;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class FlowAnalyzerDriverTest {

View File

@ -17,35 +17,29 @@
package org.apache.nifi.toolkit.repos.flowfile;
import org.apache.commons.lang3.SystemUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import org.junit.BeforeClass;
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.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
@DisabledOnOs(OS.WINDOWS)
public class TestRepairCorruptedFileEndings {
private final File targetFile = new File("target/1.bin");
@BeforeClass
public static void setupInstance() {
Assume.assumeTrue("Test only runs on *nix", !SystemUtils.IS_OS_WINDOWS);
}
@Before
@After
@BeforeEach
@AfterEach
public void cleanup() {
if (targetFile.exists()) {
Assert.assertTrue(targetFile.delete());
assertTrue(targetFile.delete());
}
}

View File

@ -19,7 +19,7 @@ package org.apache.nifi.toolkit.s2s;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.nifi.remote.protocol.DataPacket;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
@ -30,8 +30,8 @@ import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
public class DataPacketDtoTest {
public static DataPacketDto create(byte[] data) {

View File

@ -18,8 +18,8 @@
package org.apache.nifi.toolkit.s2s;
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.FileOutputStream;
@ -30,13 +30,13 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class DataPacketImplTest {
private Map<String, String> testAttributes;
@Before
@BeforeEach
public void setup() {
testAttributes = new HashMap<>();
testAttributes.put("testKey", "testVal");

View File

@ -25,15 +25,15 @@ import org.apache.nifi.remote.client.SiteToSiteClient;
import org.apache.nifi.remote.client.SiteToSiteClientConfig;
import org.apache.nifi.remote.protocol.SiteToSiteTransportProtocol;
import org.apache.nifi.remote.protocol.http.HttpProxy;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.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;
public class SiteToSiteCliMainTest {
private String expectedUrl;
@ -56,7 +56,7 @@ public class SiteToSiteCliMainTest {
private long expectedBatchSize;
private HttpProxy expectedHttpProxy;
@Before
@BeforeEach
public void setup() {
SiteToSiteClient.Builder builder = new SiteToSiteClient.Builder();
expectedUrl = SiteToSiteCliMain.URL_OPTION_DEFAULT;

View File

@ -24,11 +24,11 @@ import org.apache.nifi.remote.Transaction;
import org.apache.nifi.remote.TransactionCompletion;
import org.apache.nifi.remote.TransferDirection;
import org.apache.nifi.remote.client.SiteToSiteClient;
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.ByteArrayOutputStream;
import java.io.IOException;
@ -37,13 +37,13 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.function.Supplier;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class SiteToSiteReceiverTest {
private final ObjectMapper objectMapper = new ObjectMapper().setDefaultPropertyInclusion(Value.construct(Include.NON_NULL, Include.ALWAYS));;
private final ObjectMapper objectMapper = new ObjectMapper().setDefaultPropertyInclusion(Value.construct(Include.NON_NULL, Include.ALWAYS));
@Mock
SiteToSiteClient siteToSiteClient;
@Mock
@ -54,7 +54,7 @@ public class SiteToSiteReceiverTest {
private final Supplier<SiteToSiteReceiver> receiverSupplier = () -> new SiteToSiteReceiver(siteToSiteClient, data);
ByteArrayOutputStream expectedData;
@Before
@BeforeEach
public void setup() throws IOException {
data = new ByteArrayOutputStream();
expectedData = new ByteArrayOutputStream();
@ -81,7 +81,7 @@ public class SiteToSiteReceiverTest {
assertEquals(transactionCompletion, receiverSupplier.get().receiveFiles());
objectMapper.writeValue(expectedData, Arrays.asList(dataPacketDto));
objectMapper.writeValue(expectedData, Collections.singletonList(dataPacketDto));
assertEquals(expectedData.toString(), data.toString());
}

View File

@ -23,11 +23,11 @@ import org.apache.nifi.remote.TransactionCompletion;
import org.apache.nifi.remote.TransferDirection;
import org.apache.nifi.remote.client.SiteToSiteClient;
import org.apache.nifi.remote.protocol.DataPacket;
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.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@ -38,7 +38,8 @@ import java.util.Collections;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.never;
@ -46,7 +47,7 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class SiteToSiteSenderTest {
private final ObjectMapper objectMapper = new ObjectMapper();
@Mock
@ -58,19 +59,16 @@ public class SiteToSiteSenderTest {
ByteArrayOutputStream data;
private final Supplier<SiteToSiteSender> senderSupplier = () -> new SiteToSiteSender(siteToSiteClient, new ByteArrayInputStream(data.toByteArray()));
@Before
@BeforeEach
public void setup() throws IOException {
data = new ByteArrayOutputStream();
when(siteToSiteClient.createTransaction(TransferDirection.SEND)).thenReturn(transaction);
when(transaction.complete()).thenAnswer(invocation -> {
verify(siteToSiteClient).createTransaction(TransferDirection.SEND);
verify(transaction).confirm();
return transactionCompletion;
});
}
@Test
public void testEmptyList() throws IOException {
setTransactionCompletion();
objectMapper.writeValue(data, Collections.emptyList());
assertEquals(transactionCompletion, senderSupplier.get().sendFiles());
verify(transaction, never()).send(any(DataPacket.class));
@ -80,6 +78,8 @@ public class SiteToSiteSenderTest {
@Test
public void testSingleElement() throws IOException {
setTransactionCompletion();
DataPacketDto dataPacketDto = new DataPacketDto("test-data".getBytes(StandardCharsets.UTF_8)).putAttribute("key", "value");
objectMapper.writeValue(data, Arrays.stream(new DataPacketDto[]{dataPacketDto}).collect(Collectors.toList()));
assertEquals(transactionCompletion, senderSupplier.get().sendFiles());
@ -90,6 +90,8 @@ public class SiteToSiteSenderTest {
@Test
public void testMultipleElements() throws IOException {
setTransactionCompletion();
DataPacketDto dataPacketDto = new DataPacketDto("test-data".getBytes(StandardCharsets.UTF_8)).putAttribute("key", "value");
DataPacketDto dataPacketDto2 = new DataPacketDto("test-data2".getBytes(StandardCharsets.UTF_8)).putAttribute("key2", "value2");
objectMapper.writeValue(data, Arrays.stream(new DataPacketDto[]{dataPacketDto, dataPacketDto2}).collect(Collectors.toList()));
@ -100,31 +102,31 @@ public class SiteToSiteSenderTest {
verifyNoMoreInteractions(siteToSiteClient, transaction, transactionCompletion);
}
@Test(expected = IOException.class)
@Test
public void testIOException() throws IOException {
IOException test = new IOException("test");
DataPacketDto dataPacketDto = new DataPacketDto("test-data".getBytes(StandardCharsets.UTF_8)).putAttribute("key", "value");
objectMapper.writeValue(data, Arrays.stream(new DataPacketDto[]{dataPacketDto}).collect(Collectors.toList()));
doThrow(test).when(transaction).send(any(DataPacket.class));
try {
senderSupplier.get().sendFiles();
} catch (IOException e) {
assertEquals(test, e);
throw e;
}
assertThrows(IOException.class, () -> senderSupplier.get().sendFiles());
}
@Test(expected = IOException.class)
@Test
public void testRuntimeException() throws IOException {
RuntimeException test = new RuntimeException("test");
DataPacketDto dataPacketDto = new DataPacketDto("test-data".getBytes(StandardCharsets.UTF_8)).putAttribute("key", "value");
objectMapper.writeValue(data, Arrays.stream(new DataPacketDto[]{dataPacketDto}).collect(Collectors.toList()));
doThrow(test).when(transaction).send(any(DataPacket.class));
try {
senderSupplier.get().sendFiles();
} catch (IOException e) {
assertEquals(test, e.getCause());
throw e;
}
assertThrows(IOException.class, () -> senderSupplier.get().sendFiles());
}
private void setTransactionCompletion() throws IOException {
when(transaction.complete()).thenAnswer(invocation -> {
verify(siteToSiteClient).createTransaction(TransferDirection.SEND);
verify(transaction).confirm();
return transactionCompletion;
});
}
}

View File

@ -20,11 +20,10 @@ package org.apache.nifi.toolkit.tls;
import org.apache.nifi.toolkit.tls.commandLine.ExitCode;
import java.io.Closeable;
import java.io.IOException;
import java.security.Permission;
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.assertThrows;
public class SystemExitCapturer implements Closeable {
private final SecurityManager originalSecurityManager;
@ -52,16 +51,13 @@ public class SystemExitCapturer implements Closeable {
}
public void runAndAssertExitCode(Runnable runnable, ExitCode exitCode) {
try {
runnable.run();
fail("Expecting exit code " + exitCode);
} catch (ExitException e) {
assertEquals("Expecting exit code: " + exitCode + ", got " + ExitCode.values()[e.getExitCode()], exitCode.ordinal(), e.getExitCode());
}
final ExitException e = assertThrows(ExitException.class, runnable::run);
assertEquals(exitCode.ordinal(), e.getExitCode(), "Expecting exit code: " + exitCode + ", got " + ExitCode.values()[e.getExitCode()]);
}
@Override
public void close() throws IOException {
public void close() {
System.setSecurityManager(originalSecurityManager);
}
}

View File

@ -19,28 +19,28 @@ package org.apache.nifi.toolkit.tls;
import org.apache.nifi.toolkit.tls.commandLine.ExitCode;
import org.apache.nifi.util.StringUtils;
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.io.IOException;
import static org.junit.Assert.assertArrayEquals;
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.assertArrayEquals;
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 TlsToolkitMainTest {
private TlsToolkitMain tlsToolkitMain;
private SystemExitCapturer systemExitCapturer;
@Before
@BeforeEach
public void setup() {
systemExitCapturer = new SystemExitCapturer();
tlsToolkitMain = new TlsToolkitMain();
}
@After
@AfterEach
public void tearDown() throws IOException {
systemExitCapturer.close();
}
@ -61,9 +61,7 @@ public class TlsToolkitMainTest {
@Test
public void testAllMainClassesHaveMain() {
tlsToolkitMain.getMainMap().keySet().stream().map(String::toLowerCase).forEach(service -> {
assertNotNull(tlsToolkitMain.getMain(service));
});
tlsToolkitMain.getMainMap().keySet().stream().map(String::toLowerCase).forEach(service -> assertNotNull(tlsToolkitMain.getMain(service)));
}
@Test

View File

@ -17,16 +17,17 @@
package org.apache.nifi.toolkit.tls.configuration;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@ -44,26 +45,26 @@ public class InstanceDefinitionTest {
@Test
public void testCreateDefinitionsSingleHostSingleName() {
testCreateDefinitions(Arrays.asList("hostname"), Arrays.asList("hostname"), Arrays.asList(1), false);
testCreateDefinitions(Collections.singletonList("hostname"), Collections.singletonList("hostname"), Collections.singletonList(1), false);
}
@Test
public void testCreateDefinitionsSingleHostnameOneNumberInParens() {
testCreateDefinitions(Arrays.asList("hostname(20)"),
testCreateDefinitions(Collections.singletonList("hostname(20)"),
IntStream.range(1, 21).mapToObj(operand -> "hostname").collect(Collectors.toList()),
integerRange(1, 20).collect(Collectors.toList()), false);
}
@Test
public void testCreateDefinitionsSingleHostnameTwoNumbersInParens() {
testCreateDefinitions(Arrays.asList("hostname(5-20)"),
testCreateDefinitions(Collections.singletonList("hostname(5-20)"),
IntStream.range(5, 21).mapToObj(operand -> "hostname").collect(Collectors.toList()),
integerRange(5, 20).collect(Collectors.toList()), false);
}
@Test
public void testCreateDefinitionsMultipleHostnamesWithMultipleNumbers() {
testCreateDefinitions(Arrays.asList("host[10]name[02-5](20)"),
testCreateDefinitions(Collections.singletonList("host[10]name[02-5](20)"),
integerRange(1, 10).flatMap(v -> integerRange(2, 5).flatMap(v2 -> integerRange(1, 20).map(v3 -> "host" + v + "name" + String.format("%02d", v2)))).collect(Collectors.toList()),
integerRange(1, 10).flatMap(val -> integerRange(2, 5).flatMap(val2 -> integerRange(1, 20))).collect(Collectors.toList()), false);
}
@ -92,8 +93,8 @@ public class InstanceDefinitionTest {
}
List<String> trustStorePasswords = IntStream.range(0, expectedHostnames.size()).mapToObj(value -> "testTrustStorePassword" + value).collect(Collectors.toList());
List<InstanceDefinition> instanceDefinitions = InstanceDefinition.createDefinitions(null, hostnameExpressions.stream(),
mockSupplier(keyStorePasswords.toArray(new String[keyStorePasswords.size()])), keyPasswords == null ? null : mockSupplier(keyPasswords.toArray(new String[keyPasswords.size()])),
mockSupplier(trustStorePasswords.toArray(new String[trustStorePasswords.size()])));
mockSupplier(keyStorePasswords.toArray(new String[0])), keyPasswords == null ? null : mockSupplier(keyPasswords.toArray(new String[0])),
mockSupplier(trustStorePasswords.toArray(new String[0])));
testCreateDefinitionsOutput(instanceDefinitions, expectedHostnames, expectedNumbers, keyStorePasswords, keyPasswords, trustStorePasswords);
}

View File

@ -17,9 +17,10 @@
package org.apache.nifi.toolkit.tls.configuration;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
@ -28,7 +29,8 @@ import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class InstanceIdentifierTest {
@ -62,9 +64,9 @@ public class InstanceIdentifierTest {
testExtractHostnames("test[002]", "test001", "test002");
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testExtractHostnamesNoNumber() {
testExtractHostnames("test[]", "test");
assertThrows(IllegalArgumentException.class, () -> testExtractHostnames("test[]", "test"));
}
@Test
@ -72,43 +74,43 @@ public class InstanceIdentifierTest {
testExtractHostnames("test[1-3]name[1-3]", "test1name1", "test1name2", "test1name3", "test2name1", "test2name2", "test2name3", "test3name1", "test3name2", "test3name3");
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testExtractHostnamesUnmatched() {
testExtractHostnames("test[");
assertThrows(IllegalArgumentException.class, () -> testExtractHostnames("test["));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testExtractHostnamesSpace() {
testExtractHostnames("test[ 1-2]");
assertThrows(IllegalArgumentException.class, () -> testExtractHostnames("test[ 1-2]"));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testExtractHostnamesMultipleHyphens() {
testExtractHostnames("test[1-2-3]");
assertThrows(IllegalArgumentException.class, () -> testExtractHostnames("test[1-2-3]"));
}
@Test
public void testCreateDefinitionsSingleHostSingleName() {
testCreateIdentifiers(Arrays.asList("hostname"), Arrays.asList("hostname"), Arrays.asList(1));
testCreateIdentifiers(Collections.singletonList("hostname"), Collections.singletonList("hostname"), Collections.singletonList(1));
}
@Test
public void testCreateDefinitionsSingleHostnameOneNumberInParens() {
testCreateIdentifiers(Arrays.asList("hostname(20)"),
testCreateIdentifiers(Collections.singletonList("hostname(20)"),
IntStream.range(1, 21).mapToObj(operand -> "hostname").collect(Collectors.toList()),
integerRange(1, 20).collect(Collectors.toList()));
}
@Test
public void testCreateDefinitionsSingleHostnameTwoNumbersInParens() {
testCreateIdentifiers(Arrays.asList("hostname(5-20)"),
testCreateIdentifiers(Collections.singletonList("hostname(5-20)"),
IntStream.range(5, 21).mapToObj(operand -> "hostname").collect(Collectors.toList()),
integerRange(5, 20).collect(Collectors.toList()));
}
@Test
public void testCreateDefinitionsMultipleHostnamesWithMultipleNumbers() {
testCreateIdentifiers(Arrays.asList("host[10]name[02-5](20)"),
testCreateIdentifiers(Collections.singletonList("host[10]name[02-5](20)"),
integerRange(1, 10).flatMap(v -> integerRange(2, 5).flatMap(v2 -> integerRange(1, 20).map(v3 -> "host" + v + "name" + String.format("%02d", v2)))).collect(Collectors.toList()),
integerRange(1, 10).flatMap(val -> integerRange(2, 5).flatMap(val2 -> integerRange(1, 20))).collect(Collectors.toList()));
}
@ -137,9 +139,9 @@ public class InstanceIdentifierTest {
InstanceIdentifier.extractHostnames(b).map(s -> new InstanceIdentifier(s, 1)).forEach(action);
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testCreateIdentifiersCharactersAfterNumber() {
InstanceIdentifier.createIdentifiers(Stream.of("test(2)a")).count();
assertThrows(IllegalArgumentException.class, () -> InstanceIdentifier.createIdentifiers(Stream.of("test(2)a")).count());
}
private Stream<Integer> integerRange(int start, int endInclusive) {

View File

@ -23,11 +23,11 @@ import org.apache.nifi.toolkit.tls.properties.NiFiPropertiesWriter;
import org.apache.nifi.toolkit.tls.properties.NiFiPropertiesWriterFactory;
import org.apache.nifi.toolkit.tls.util.OutputStreamFactory;
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.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@ -36,11 +36,11 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class NifiPropertiesTlsClientConfigWriterTest {
@Mock
NiFiPropertiesWriterFactory niFiPropertiesWriterFactory;
@ -62,7 +62,7 @@ public class NifiPropertiesTlsClientConfigWriterTest {
private String keyStoreType;
private String trustStoreType;
@Before
@BeforeEach
public void setup() throws IOException {
testHostname = "testHostname";
hostNum = 22;
@ -103,12 +103,6 @@ public class NifiPropertiesTlsClientConfigWriterTest {
assertNotEquals(0, nifiPropertiesTlsClientConfigWriter.getIncrementingPropertyMap().size());
}
@Test(expected = NumberFormatException.class)
public void testBadPortNum() throws IOException {
nifiPropertiesTlsClientConfigWriter.getOverlayProperties().setProperty(nifiPropertiesTlsClientConfigWriter.getIncrementingPropertyMap().keySet().iterator().next(), "notAnInt");
nifiPropertiesTlsClientConfigWriter.write(tlsClientConfig, outputStreamFactory);
}
@Test
public void testNoHostnameProperties() throws IOException {
nifiPropertiesTlsClientConfigWriter.getOverlayProperties().setProperty(NifiPropertiesTlsClientConfigWriter.HOSTNAME_PROPERTIES, "");

View File

@ -18,9 +18,9 @@
package org.apache.nifi.toolkit.tls.properties;
import org.apache.nifi.util.NiFiProperties;
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.BeforeAll;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@ -31,18 +31,18 @@ import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class NifiPropertiesWriterTest {
private static NiFiPropertiesWriterFactory nifiPropertiesWriterFactory;
private NiFiPropertiesWriter niFiPropertiesWriter;
@BeforeClass
public static void beforeClass() throws IOException {
@BeforeAll
public static void setFactory() throws IOException {
nifiPropertiesWriterFactory = new NiFiPropertiesWriterFactory();
}
@Before
@BeforeEach
public void setup() throws IOException {
niFiPropertiesWriter = nifiPropertiesWriterFactory.create();
}

View File

@ -18,6 +18,7 @@
package org.apache.nifi.toolkit.tls.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.nifi.remote.io.socket.NetworkUtils;
import org.apache.nifi.security.util.KeystoreType;
import org.apache.nifi.security.util.KeyStoreUtils;
import org.apache.nifi.toolkit.tls.configuration.TlsClientConfig;
@ -28,8 +29,8 @@ import org.apache.nifi.toolkit.tls.service.server.TlsCertificateAuthorityService
import org.apache.nifi.toolkit.tls.standalone.TlsToolkitStandalone;
import org.apache.nifi.toolkit.tls.util.InputStreamFactory;
import org.apache.nifi.toolkit.tls.util.OutputStreamFactory;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@ -37,7 +38,6 @@ import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.KeyStore;
@ -53,13 +53,13 @@ import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
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.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.AdditionalMatchers.or;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@ -80,7 +80,7 @@ public class TlsCertificateAuthorityTest {
private ByteArrayOutputStream clientConfigFileOutputStream;
private String subjectAlternativeName;
@Before
@BeforeEach
public void setup() throws FileNotFoundException {
objectMapper = new ObjectMapper();
serverConfigFile = new File("fake.server.config");
@ -96,7 +96,7 @@ public class TlsCertificateAuthorityTest {
subjectAlternativeName = "nifi.apache.org";
String myTestTokenUseSomethingStronger = "myTestTokenUseSomethingStronger";
int port = availablePort();
int port = NetworkUtils.getAvailableTcpPort();
serverConfig = new TlsConfig();
serverConfig.setCaHostname("localhost");
@ -113,7 +113,7 @@ public class TlsCertificateAuthorityTest {
clientConfig.setKeyStore(clientKeyStore);
clientConfig.setTrustStore(clientTrustStore);
clientConfig.setToken(myTestTokenUseSomethingStronger);
clientConfig.setDomainAlternativeNames(Arrays.asList(subjectAlternativeName));
clientConfig.setDomainAlternativeNames(Collections.singletonList(subjectAlternativeName));
clientConfig.setPort(port);
clientConfig.setKeySize(2048);
clientConfig.initDefaults();
@ -194,14 +194,10 @@ public class TlsCertificateAuthorityTest {
}
@Test
public void testTokenMismatch() throws Exception {
public void testTokenMismatch() {
serverConfig.setToken("a different token...");
try {
testClientGetCertSamePasswordsForKeyAndKeyStore();
fail("Expected error with mismatching token");
} catch (IOException e) {
assertTrue(e.getMessage().contains("forbidden"));
}
assertThrows(IOException.class, () -> testClientGetCertSamePasswordsForKeyAndKeyStore());
}
private void validate() throws CertificateException, InvalidKeyException, NoSuchAlgorithmException, KeyStoreException, SignatureException,
@ -283,24 +279,4 @@ public class TlsCertificateAuthorityTest {
}
return containsSAN;
}
/**
* Will determine the available port used by ca server
*/
private int availablePort() {
ServerSocket s = null;
try {
s = new ServerSocket(0);
s.setReuseAddress(true);
return s.getLocalPort();
} catch (Exception e) {
throw new IllegalStateException("Failed to discover available port.", e);
} finally {
try {
s.close();
} catch (IOException e) {
// ignore
}
}
}
}

View File

@ -23,23 +23,22 @@ import org.apache.nifi.toolkit.tls.commandLine.ExitCode;
import org.apache.nifi.toolkit.tls.configuration.TlsClientConfig;
import org.apache.nifi.toolkit.tls.configuration.TlsConfig;
import org.apache.nifi.toolkit.tls.service.BaseCertificateAuthorityCommandLine;
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 java.io.IOException;
import java.net.InetAddress;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class TlsCertificateAuthorityClientCommandLineTest {
private TlsCertificateAuthorityClientCommandLine tlsCertificateAuthorityClientCommandLine;
private String testToken;
@Before
@BeforeEach
public void setup() {
tlsCertificateAuthorityClientCommandLine = new TlsCertificateAuthorityClientCommandLine();
testToken = "testToken16bytes";
@ -47,12 +46,9 @@ public class TlsCertificateAuthorityClientCommandLineTest {
@Test
public void testNoToken() {
try {
tlsCertificateAuthorityClientCommandLine.parse(new String[0]);
fail("Expected failure with no token argument");
} catch (CommandLineParseException e) {
assertEquals(ExitCode.ERROR_TOKEN_ARG_EMPTY, e.getExitCode());
}
final CommandLineParseException e = assertThrows(CommandLineParseException.class, () -> tlsCertificateAuthorityClientCommandLine.parse());
assertEquals(ExitCode.ERROR_TOKEN_ARG_EMPTY, e.getExitCode());
}
@Test
@ -61,7 +57,7 @@ public class TlsCertificateAuthorityClientCommandLineTest {
TlsClientConfig clientConfig = tlsCertificateAuthorityClientCommandLine.createClientConfig();
assertEquals(TlsConfig.DEFAULT_HOSTNAME, clientConfig.getCaHostname());
Assert.assertEquals(new TlsConfig().calcDefaultDn(InetAddress.getLocalHost().getHostName()), clientConfig.getDn());
assertEquals(new TlsConfig().calcDefaultDn(InetAddress.getLocalHost().getHostName()), clientConfig.getDn());
assertEquals(TlsCertificateAuthorityClientCommandLine.KEYSTORE + TlsConfig.DEFAULT_KEY_STORE_TYPE.toLowerCase(), clientConfig.getKeyStore());
assertEquals(TlsConfig.DEFAULT_KEY_STORE_TYPE, clientConfig.getKeyStoreType());
assertNull(clientConfig.getKeyStorePassword());
@ -94,12 +90,9 @@ public class TlsCertificateAuthorityClientCommandLineTest {
@Test
public void testHelp() {
try {
tlsCertificateAuthorityClientCommandLine.parse("-h");
fail("Expected exception");
} catch (CommandLineParseException e) {
assertEquals(ExitCode.HELP, e.getExitCode());
}
final CommandLineParseException e = assertThrows(CommandLineParseException.class, () -> tlsCertificateAuthorityClientCommandLine.parse("-h"));
assertEquals(ExitCode.HELP, e.getExitCode());
}
@Test

View File

@ -34,11 +34,11 @@ import org.apache.nifi.toolkit.tls.util.TlsHelper;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest;
import org.eclipse.jetty.server.Response;
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.ByteArrayOutputStream;
import java.io.IOException;
@ -51,15 +51,15 @@ import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
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.assertThrows;
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.mock;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class TlsCertificateSigningRequestPerformerTest {
@Mock
Supplier<HttpClientBuilder> httpClientBuilderSupplier;
@ -90,7 +90,7 @@ public class TlsCertificateSigningRequestPerformerTest {
private byte[] testHmac;
private String testSignedCsr;
@Before
@BeforeEach
public void setup() throws GeneralSecurityException, OperatorCreationException, IOException {
objectMapper = new ObjectMapper();
keyPair = TlsHelper.generateKeyPair(TlsConfig.DEFAULT_KEY_PAIR_ALGORITHM, TlsConfig.DEFAULT_KEY_SIZE);
@ -151,79 +151,61 @@ public class TlsCertificateSigningRequestPerformerTest {
}
@Test
public void testBadStatusCode() throws Exception {
public void testBadStatusCode() {
statusCode = Response.SC_FORBIDDEN;
tlsCertificateAuthorityResponse = new TlsCertificateAuthorityResponse();
try {
tlsCertificateSigningRequestPerformer.perform(keyPair);
fail("Expected IOE");
} catch (IOException e) {
assertTrue(e.getMessage().startsWith(TlsCertificateSigningRequestPerformer.RECEIVED_RESPONSE_CODE + statusCode));
}
final IOException e = assertThrows(IOException.class, () -> tlsCertificateSigningRequestPerformer.perform(keyPair));
assertTrue(e.getMessage().startsWith(TlsCertificateSigningRequestPerformer.RECEIVED_RESPONSE_CODE + statusCode));
}
@Test
public void test0CertSize() throws Exception {
public void test0CertSize() {
statusCode = Response.SC_OK;
tlsCertificateAuthorityResponse = new TlsCertificateAuthorityResponse();
try {
tlsCertificateSigningRequestPerformer.perform(keyPair);
fail("Expected IOE");
} catch (IOException e) {
assertEquals(TlsCertificateSigningRequestPerformer.EXPECTED_ONE_CERTIFICATE, e.getMessage());
}
final IOException e = assertThrows(IOException.class, () -> tlsCertificateSigningRequestPerformer.perform(keyPair));
assertEquals(TlsCertificateSigningRequestPerformer.EXPECTED_ONE_CERTIFICATE, e.getMessage());
}
@Test
public void test2CertSize() throws Exception {
public void test2CertSize() {
certificates.add(caCertificate);
certificates.add(caCertificate);
statusCode = Response.SC_OK;
tlsCertificateAuthorityResponse = new TlsCertificateAuthorityResponse();
try {
tlsCertificateSigningRequestPerformer.perform(keyPair);
fail("Expected IOE");
} catch (IOException e) {
assertEquals(TlsCertificateSigningRequestPerformer.EXPECTED_ONE_CERTIFICATE, e.getMessage());
}
final IOException e = assertThrows(IOException.class, () -> tlsCertificateSigningRequestPerformer.perform(keyPair));
assertEquals(TlsCertificateSigningRequestPerformer.EXPECTED_ONE_CERTIFICATE, e.getMessage());
}
@Test
public void testNoHmac() throws Exception {
public void testNoHmac() {
certificates.add(caCertificate);
statusCode = Response.SC_OK;
tlsCertificateAuthorityResponse = new TlsCertificateAuthorityResponse(null, testSignedCsr);
try {
tlsCertificateSigningRequestPerformer.perform(keyPair);
fail("Expected IOE");
} catch (IOException e) {
assertEquals(TlsCertificateSigningRequestPerformer.EXPECTED_RESPONSE_TO_CONTAIN_HMAC, e.getMessage());
}
final IOException e = assertThrows(IOException.class, () -> tlsCertificateSigningRequestPerformer.perform(keyPair));
assertEquals(TlsCertificateSigningRequestPerformer.EXPECTED_RESPONSE_TO_CONTAIN_HMAC, e.getMessage());
}
@Test
public void testBadHmac() throws Exception {
public void testBadHmac() {
certificates.add(caCertificate);
statusCode = Response.SC_OK;
tlsCertificateAuthorityResponse = new TlsCertificateAuthorityResponse("badHmac".getBytes(StandardCharsets.UTF_8), testSignedCsr);
try {
tlsCertificateSigningRequestPerformer.perform(keyPair);
fail("Expected IOE");
} catch (IOException e) {
assertEquals(TlsCertificateSigningRequestPerformer.UNEXPECTED_HMAC_RECEIVED_POSSIBLE_MAN_IN_THE_MIDDLE, e.getMessage());
}
final IOException e = assertThrows(IOException.class, () -> tlsCertificateSigningRequestPerformer.perform(keyPair));
assertEquals(TlsCertificateSigningRequestPerformer.UNEXPECTED_HMAC_RECEIVED_POSSIBLE_MAN_IN_THE_MIDDLE, e.getMessage());
}
@Test
public void testNoCertificate() throws Exception {
public void testNoCertificate() {
certificates.add(caCertificate);
statusCode = Response.SC_OK;
tlsCertificateAuthorityResponse = new TlsCertificateAuthorityResponse(testHmac, null);
try {
tlsCertificateSigningRequestPerformer.perform(keyPair);
fail("Expected IOE");
} catch (IOException e) {
assertEquals(TlsCertificateSigningRequestPerformer.EXPECTED_RESPONSE_TO_CONTAIN_CERTIFICATE, e.getMessage());
}
final IOException e = assertThrows(IOException.class, () -> tlsCertificateSigningRequestPerformer.perform(keyPair));
assertEquals(TlsCertificateSigningRequestPerformer.EXPECTED_RESPONSE_TO_CONTAIN_CERTIFICATE, e.getMessage());
}
}

View File

@ -21,18 +21,18 @@ import org.apache.nifi.toolkit.tls.commandLine.CommandLineParseException;
import org.apache.nifi.toolkit.tls.configuration.TlsConfig;
import org.apache.nifi.toolkit.tls.service.BaseCertificateAuthorityCommandLine;
import org.apache.nifi.toolkit.tls.util.InputStreamFactory;
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 static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class TlsCertificateAuthorityServiceCommandLineTest {
@Mock
InputStreamFactory inputStreamFactory;
@ -41,7 +41,7 @@ public class TlsCertificateAuthorityServiceCommandLineTest {
String testToken;
@Before
@BeforeEach
public void setup() {
tlsCertificateAuthorityServiceCommandLine = new TlsCertificateAuthorityServiceCommandLine(inputStreamFactory);
testToken = "testToken16bytes";

View File

@ -17,10 +17,11 @@
package org.apache.nifi.toolkit.tls.service.server;
import static org.junit.Assert.assertArrayEquals;
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.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.verify;
@ -34,11 +35,8 @@ import java.io.StringReader;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.List;
@ -54,31 +52,30 @@ import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.Extensions;
import org.bouncycastle.cert.crmf.CRMFException;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest;
import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Response;
import org.junit.After;
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.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.jupiter.MockitoExtension;
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class TlsCertificateAuthorityServiceHandlerTest {
X509Certificate caCert;
@Mock
Request baseRequest;
@Mock
@Mock(lenient = true)
HttpServletRequest httpServletRequest;
@Mock
@Mock(lenient = true)
HttpServletResponse httpServletResponse;
JcaPKCS10CertificationRequest jcaPKCS10CertificationRequest;
@ -108,7 +105,7 @@ public class TlsCertificateAuthorityServiceHandlerTest {
private static final String SUBJECT_DN = "CN=NiFi Test Server,OU=Security,O=Apache,ST=CA,C=US";
private static final List<String> SUBJECT_ALT_NAMES = Arrays.asList("127.0.0.1", "nifi.nifi.apache.org");
@Before
@BeforeEach
public void setup() throws Exception {
testToken = "testTokenTestToken";
testPemEncodedSignedCertificate = "testPemEncodedSignedCertificate";
@ -139,7 +136,7 @@ public class TlsCertificateAuthorityServiceHandlerTest {
}
@Test
public void testSuccess() throws IOException, ServletException, GeneralSecurityException, CRMFException {
public void testSuccess() throws IOException, ServletException, GeneralSecurityException {
tlsCertificateAuthorityRequest = new TlsCertificateAuthorityRequest(testHmac, testPemEncodedCsr);
tlsCertificateAuthorityServiceHandler.handle(null, baseRequest, httpServletRequest, httpServletResponse);
assertEquals(Response.SC_OK, statusCode);
@ -167,21 +164,20 @@ public class TlsCertificateAuthorityServiceHandlerTest {
}
@Test
public void testForbidden() throws IOException, ServletException, NoSuchAlgorithmException, CRMFException, NoSuchProviderException, InvalidKeyException {
public void testForbidden() throws IOException, ServletException {
tlsCertificateAuthorityRequest = new TlsCertificateAuthorityRequest("badHmac".getBytes(StandardCharsets.UTF_8), testPemEncodedCsr);
tlsCertificateAuthorityServiceHandler.handle(null, baseRequest, httpServletRequest, httpServletResponse);
assertEquals(Response.SC_FORBIDDEN, statusCode);
assertEquals(TlsCertificateAuthorityServiceHandler.FORBIDDEN, getResponse().getError());
}
@Test(expected = ServletException.class)
public void testServletException() throws IOException, ServletException {
tlsCertificateAuthorityServiceHandler.handle(null, baseRequest, httpServletRequest, httpServletResponse);
@Test
public void testServletException() {
assertThrows(ServletException.class, () -> tlsCertificateAuthorityServiceHandler.handle(null, baseRequest, httpServletRequest, httpServletResponse));
}
@Test
public void testSANAgainUsingCertificationRequestMethod() throws GeneralSecurityException, IOException, OperatorCreationException {
// Arrange
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
KeyPair keyPair = generator.generateKeyPair();
Extensions exts = TlsHelper.createDomainAlternativeNamesExtensions(SUBJECT_ALT_NAMES, SUBJECT_DN);
@ -197,18 +193,16 @@ public class TlsCertificateAuthorityServiceHandlerTest {
JcaPKCS10CertificationRequest jcaPKCS10CertificationDecoded = TlsHelper.parseCsr(tlsCertificateAuthorityRequest.getCsr());
// Act
Extensions extensions = CertificateUtils.getExtensionsFromCSR(jcaPKCS10CertificationDecoded);
// Satisfy @After requirement
baseRequest.setHandled(true);
// Assert
assertNotNull("The extensions parsed from the CSR were found to be null when they should have been present.", extensions);
assertNotNull("The Subject Alternate Name parsed from the CSR was found to be null when it should have been present.", extensions.getExtension(Extension.subjectAlternativeName));
assertNotNull(extensions, "The extensions parsed from the CSR were found to be null when they should have been present.");
assertNotNull(extensions.getExtension(Extension.subjectAlternativeName), "The Subject Alternate Name parsed from the CSR was found to be null when it should have been present.");
assertTrue(extensions.equivalent(exts));
}
@After
@AfterEach
public void verifyHandled() {
verify(baseRequest).setHandled(true);
}

View File

@ -17,17 +17,18 @@
package org.apache.nifi.toolkit.tls.standalone;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyStoreException;
@ -36,6 +37,7 @@ import java.security.UnrecoverableKeyException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.function.Function;
import java.util.stream.Collectors;
@ -47,53 +49,40 @@ import org.apache.nifi.toolkit.tls.configuration.StandaloneConfig;
import org.apache.nifi.toolkit.tls.configuration.TlsConfig;
import org.apache.nifi.toolkit.tls.properties.NiFiPropertiesWriter;
import org.apache.nifi.toolkit.tls.util.PasswordUtil;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
public class TlsToolkitStandaloneCommandLineTest {
private SecureRandom secureRandom;
private TlsToolkitStandaloneCommandLine tlsToolkitStandaloneCommandLine;
final String CHANGEIT = "changeit";
final String keyPass = CHANGEIT;
final String keystorePass = CHANGEIT;
final String wrongPass = "wrongpass";
private File outputFolder = null;
final String keystoreFile = getClass().getClassLoader().getResource("keystore.jks").getFile();
final String keystoreFile = Objects.requireNonNull(getClass().getClassLoader().getResource("keystore.jks")).getFile();
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
@Before
public void setup() throws IOException {
secureRandom = new SecureRandom();
@BeforeEach
public void setup(@TempDir Path tempDir) throws IOException {
final SecureRandom secureRandom = new SecureRandom();
tlsToolkitStandaloneCommandLine = new TlsToolkitStandaloneCommandLine(new PasswordUtil(secureRandom));
outputFolder = tempFolder.newFolder("splitKeystoreOutputDir");
final Path outputDir = Files.createTempDirectory(tempDir, "splitKeystoreOutputDir");
outputFolder = outputDir.toFile();
}
@Test
public void testHelp() {
try {
tlsToolkitStandaloneCommandLine.parse("-h");
fail("Expected usage and help exit");
} catch (CommandLineParseException e) {
Assert.assertEquals(ExitCode.HELP, e.getExitCode());
}
final CommandLineParseException e = assertThrows(CommandLineParseException.class, () -> tlsToolkitStandaloneCommandLine.parse("-h"));
assertEquals(ExitCode.HELP, e.getExitCode());
}
@Test
public void testUnknownArg() {
try {
tlsToolkitStandaloneCommandLine.parse("--unknownArg");
fail("Expected error parsing command line");
} catch (CommandLineParseException e) {
assertEquals(ExitCode.ERROR_PARSING_COMMAND_LINE, e.getExitCode());
}
final CommandLineParseException e = assertThrows(CommandLineParseException.class, () -> tlsToolkitStandaloneCommandLine.parse("--unknownArg"));
assertEquals(ExitCode.ERROR_PARSING_COMMAND_LINE, e.getExitCode());
}
@Test
@ -105,30 +94,27 @@ public class TlsToolkitStandaloneCommandLineTest {
@Test
public void testKeySizeArgNotInteger() {
try {
tlsToolkitStandaloneCommandLine.parse("-k", "badVal");
fail("Expected bad keysize exit code");
} catch (CommandLineParseException e) {
assertEquals(ExitCode.ERROR_PARSING_INT_ARG, e.getExitCode());
}
final CommandLineParseException e = assertThrows(CommandLineParseException.class, () -> tlsToolkitStandaloneCommandLine.parse("-k", "badVal"));
assertEquals(ExitCode.ERROR_PARSING_INT_ARG, e.getExitCode());
}
@Test
public void testKeySize() throws CommandLineParseException, IOException {
public void testKeySize() throws CommandLineParseException {
int testKeySize = 4096;
tlsToolkitStandaloneCommandLine.parse("-k", Integer.toString(testKeySize));
assertEquals(testKeySize, tlsToolkitStandaloneCommandLine.createConfig().getKeySize());
}
@Test
public void testSigningAlgorithm() throws CommandLineParseException, IOException {
public void testSigningAlgorithm() throws CommandLineParseException {
String testSigningAlgorithm = "testSigningAlgorithm";
tlsToolkitStandaloneCommandLine.parse("-s", testSigningAlgorithm);
assertEquals(testSigningAlgorithm, tlsToolkitStandaloneCommandLine.createConfig().getSigningAlgorithm());
}
@Test
public void testSAN() throws CommandLineParseException, IOException {
public void testSAN() throws CommandLineParseException {
String dnsSAN = "nifi.apache.org";
tlsToolkitStandaloneCommandLine.parse("--subjectAlternativeNames", dnsSAN);
assertEquals(dnsSAN, tlsToolkitStandaloneCommandLine.createConfig().getDomainAlternativeNames().get(0));
@ -136,11 +122,9 @@ public class TlsToolkitStandaloneCommandLineTest {
@Test
public void testDaysNotInteger() {
try {
tlsToolkitStandaloneCommandLine.parse("-d", "badVal");
} catch (CommandLineParseException e) {
assertEquals(ExitCode.ERROR_PARSING_INT_ARG, e.getExitCode());
}
final CommandLineParseException e = assertThrows(CommandLineParseException.class, () -> tlsToolkitStandaloneCommandLine.parse("-d", "badVal"));
assertEquals(ExitCode.ERROR_PARSING_INT_ARG, e.getExitCode());
}
@Test
@ -191,12 +175,9 @@ public class TlsToolkitStandaloneCommandLineTest {
@Test
public void testBadNifiPropertiesFile() {
try {
tlsToolkitStandaloneCommandLine.parse("-f", "/this/file/should/not/exist.txt");
fail("Expected error when unable to read file");
} catch (CommandLineParseException e) {
assertEquals(ExitCode.ERROR_READING_NIFI_PROPERTIES, e.getExitCode());
}
final CommandLineParseException e = assertThrows(CommandLineParseException.class, () -> tlsToolkitStandaloneCommandLine.parse("-f", "/this/file/should/not/exist.txt"));
assertEquals(ExitCode.ERROR_READING_NIFI_PROPERTIES, e.getExitCode());
}
@Test
@ -429,9 +410,9 @@ public class TlsToolkitStandaloneCommandLineTest {
assertEquals(16, other06.getNumber());
}
@Test(expected = IllegalArgumentException.class)
public void testBadGlobalOrder() throws CommandLineParseException {
tlsToolkitStandaloneCommandLine.parse("-n", "notInGlobalOrder", "-G", "nifi[1-3]");
@Test
public void testBadGlobalOrder() {
assertThrows(IllegalArgumentException.class, () -> tlsToolkitStandaloneCommandLine.parse("-n", "notInGlobalOrder", "-G", "nifi[1-3]"));
}
@Test
@ -468,21 +449,17 @@ public class TlsToolkitStandaloneCommandLineTest {
TlsToolkitStandalone toolkit = new TlsToolkitStandalone();
toolkit.splitKeystore(standaloneConfig);
assertTrue(outputFolder.listFiles().length == 3);
assertEquals(3, Objects.requireNonNull(outputFolder.listFiles()).length);
// Validity checking of the output is done in TlsHelperTest
for(File file : outputFolder.listFiles()) {
for (File file : Objects.requireNonNull(outputFolder.listFiles())) {
assertTrue(file.length() > 0);
}
}
@Test(expected = CommandLineParseException.class)
public void testSplitKeystoreMissingPasswords() throws Exception {
tlsToolkitStandaloneCommandLine.parse("-splitKeystore", keystoreFile, "-o", outputFolder.getPath());
StandaloneConfig standaloneConfig = tlsToolkitStandaloneCommandLine.createSplitKeystoreConfig();
TlsToolkitStandalone toolkit = new TlsToolkitStandalone();
toolkit.splitKeystore(standaloneConfig);
@Test
public void testSplitKeystoreMissingPasswords() {
assertThrows(CommandLineParseException.class, () -> tlsToolkitStandaloneCommandLine.parse("-splitKeystore", keystoreFile, "-o", outputFolder.getPath()));
}
@Test
@ -494,44 +471,33 @@ public class TlsToolkitStandaloneCommandLineTest {
toolkit.splitKeystore(standaloneConfig);
}
@Test(expected = UnrecoverableKeyException.class)
@Test
public void testSplitKeystoreWrongKeyPass() throws Exception {
tlsToolkitStandaloneCommandLine.parse("-splitKeystore", keystoreFile, "-S", keystorePass, "-K", wrongPass, "-o", outputFolder.getPath());
StandaloneConfig standaloneConfig = tlsToolkitStandaloneCommandLine.createSplitKeystoreConfig();
TlsToolkitStandalone toolkit = new TlsToolkitStandalone();
toolkit.splitKeystore(standaloneConfig);
assertThrows(UnrecoverableKeyException.class, () -> toolkit.splitKeystore(standaloneConfig));
}
@Test(expected = IOException.class)
@Test
public void testSplitKeystoreWrongKeystorePass() throws Exception {
tlsToolkitStandaloneCommandLine.parse("-splitKeystore", keystoreFile, "-S", wrongPass, "-K", keyPass, "-o", outputFolder.getPath());
StandaloneConfig standaloneConfig = tlsToolkitStandaloneCommandLine.createSplitKeystoreConfig();
TlsToolkitStandalone toolkit = new TlsToolkitStandalone();
toolkit.splitKeystore(standaloneConfig);
assertThrows(IOException.class, () -> toolkit.splitKeystore(standaloneConfig));
}
@Rule
public ExpectedException expectedEx = ExpectedException.none();
@Test
public void testSplitKeystoreNoKeystore() throws Exception {
expectedEx.expect(CommandLineParseException.class);
expectedEx.expectMessage("Error parsing command line. (Missing argument for option: splitKeystore)");
tlsToolkitStandaloneCommandLine.parse("-splitKeystore", "-S", keystorePass, "-K", keyPass, "-o", outputFolder.getPath());
StandaloneConfig standaloneConfig = tlsToolkitStandaloneCommandLine.createSplitKeystoreConfig();
TlsToolkitStandalone toolkit = new TlsToolkitStandalone();
toolkit.splitKeystore(standaloneConfig);
public void testSplitKeystoreNoKeystore() {
assertThrows(CommandLineParseException.class, () -> tlsToolkitStandaloneCommandLine.parse("-splitKeystore", "-S", keystorePass, "-K", keyPass, "-o", outputFolder.getPath()));
}
@Test
public void testSplitKeystoreEmptyKeystore() throws Exception {
expectedEx.expect(KeyStoreException.class);
expectedEx.expectMessage("was empty. No cert/key pairs to output to file.");
tlsToolkitStandaloneCommandLine.parse(
"-splitKeystore", new File("src/test/resources/empty-keystore.jks").getPath(), "-S", keystorePass, "-K", keyPass, "-o", outputFolder.getPath());
StandaloneConfig standaloneConfig = tlsToolkitStandaloneCommandLine.createSplitKeystoreConfig();
@ -540,7 +506,7 @@ public class TlsToolkitStandaloneCommandLineTest {
assertEquals(keyPass, standaloneConfig.getKeyPassword());
assertEquals(keystorePass, standaloneConfig.getKeyStorePassword());
TlsToolkitStandalone toolkit = new TlsToolkitStandalone();
toolkit.splitKeystore(standaloneConfig);
}
assertThrows(KeyStoreException.class, () -> toolkit.splitKeystore(standaloneConfig));
}
}

View File

@ -32,9 +32,9 @@ import org.apache.nifi.toolkit.tls.util.TlsHelper;
import org.apache.nifi.toolkit.tls.util.TlsHelperTest;
import org.apache.nifi.util.NiFiProperties;
import org.bouncycastle.asn1.x509.GeneralName;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -45,13 +45,11 @@ import java.io.IOException;
import java.io.InputStream;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
@ -60,10 +58,10 @@ import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
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.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class TlsToolkitStandaloneTest {
public static final String NIFI_FAKE_PROPERTY = "nifi.fake.property";
@ -74,7 +72,7 @@ public class TlsToolkitStandaloneTest {
private File tempDir;
@Before
@BeforeEach
public void setup() throws IOException {
tempDir = File.createTempFile("tls-test", UUID.randomUUID().toString());
if (!tempDir.delete()) {
@ -87,7 +85,7 @@ public class TlsToolkitStandaloneTest {
systemExitCapturer = new SystemExitCapturer();
}
@After
@AfterEach
public void teardown() throws IOException {
systemExitCapturer.close();
FileUtils.deleteDirectory(tempDir);
@ -434,13 +432,13 @@ public class TlsToolkitStandaloneTest {
}
@Test
public void testDynamicHostnameDynamicSansNonNumeric() throws Exception {
public void testDynamicHostnameDynamicSansNonNumeric() {
String nodeNames = "node[1-2].nifi.apache.org";
String saNames = "alternative[A-B].nifi.apache.org";
runAndAssertExitCode(ExitCode.ERROR_PARSING_INT_ARG, "-o", tempDir.getAbsolutePath(), "-n", nodeNames, "--subjectAlternativeName", saNames);
}
private X509Certificate checkLoadCertPrivateKey(String algorithm) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException {
private X509Certificate checkLoadCertPrivateKey(String algorithm) throws IOException, CertificateException {
KeyPair keyPair = TlsHelperTest.loadKeyPair(new File(tempDir, TlsToolkitStandalone.NIFI_KEY + ".key"));
assertEquals(algorithm, keyPair.getPrivate().getAlgorithm());

View File

@ -19,14 +19,15 @@ package org.apache.nifi.toolkit.tls.status;
import org.apache.nifi.toolkit.tls.commandLine.CommandLineParseException;
import org.apache.nifi.toolkit.tls.commandLine.ExitCode;
import org.apache.nifi.toolkit.tls.configuration.GetStatusConfig;
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 javax.net.ssl.SSLContext;
import java.net.URI;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class TlsToolkitGetStatusCommandLineTest {
@ -36,89 +37,72 @@ public class TlsToolkitGetStatusCommandLineTest {
private TlsToolkitGetStatusCommandLine commandLine;
@Before
@BeforeEach
public void setup() {
commandLine = new TlsToolkitGetStatusCommandLine();
}
@Test
public void testHelp() {
try {
commandLine.parse("-h");
fail("Expected usage and help exit");
} catch (CommandLineParseException e) {
Assert.assertEquals(ExitCode.HELP, e.getExitCode());
}
final CommandLineParseException e = assertThrows(CommandLineParseException.class, () -> commandLine.parse("-h"));
assertEquals(ExitCode.HELP, e.getExitCode());
}
@Test
public void testSuccess() {
try {
final String urlStr = "https://localhost:8443/test";
commandLine.parse(
"-u", urlStr,
"-ts", TRUSTSTORE_PATH,
"-tst", JKS_TYPE,
"-tsp", TRUSTSTORE_PASSWORD);
public void testSuccess() throws CommandLineParseException {
final String urlStr = "https://localhost:8443/test";
commandLine.parse(
"-u", urlStr,
"-ts", TRUSTSTORE_PATH,
"-tst", JKS_TYPE,
"-tsp", TRUSTSTORE_PASSWORD);
final GetStatusConfig config = commandLine.createConfig();
Assert.assertNotNull(config);
final GetStatusConfig config = commandLine.createConfig();
assertNotNull(config);
final URI url = config.getUrl();
Assert.assertNotNull(url);
Assert.assertEquals(urlStr, url.toString());
final URI url = config.getUrl();
assertNotNull(url);
assertEquals(urlStr, url.toString());
final SSLContext sslContext = config.getSslContext();
Assert.assertNotNull(sslContext);
} catch (CommandLineParseException e) {
fail("Expected success");
}
final SSLContext sslContext = config.getSslContext();
assertNotNull(sslContext);
}
@Test
public void testMissingUrl() {
try {
commandLine.parse(
"-ts", TRUSTSTORE_PATH,
"-tst", JKS_TYPE,
"-tsp", TRUSTSTORE_PASSWORD);
final CommandLineParseException e = assertThrows(CommandLineParseException.class, () -> commandLine.parse(
"-ts", TRUSTSTORE_PATH,
"-tst", JKS_TYPE,
"-tsp", TRUSTSTORE_PASSWORD)
);
fail("Expected invalid args");
} catch (CommandLineParseException e) {
Assert.assertEquals(ExitCode.INVALID_ARGS, e.getExitCode());
}
assertEquals(ExitCode.INVALID_ARGS, e.getExitCode());
}
@Test
public void testTruststoreDoesNotExist() {
try {
final String urlStr = "https://localhost:8443/test";
commandLine.parse(
"-u", urlStr,
"-ts", "does/not/exist/truststore.jks",
"-tst", JKS_TYPE,
"-tsp", TRUSTSTORE_PASSWORD);
final CommandLineParseException e = assertThrows(CommandLineParseException.class, () -> commandLine.parse(
fail("Expected invalid args");
} catch (CommandLineParseException e) {
Assert.assertEquals(ExitCode.INVALID_ARGS, e.getExitCode());
}
"-u", "https://localhost:8443/test",
"-ts", "does/not/exist/truststore.jks",
"-tst", JKS_TYPE,
"-tsp", TRUSTSTORE_PASSWORD)
);
assertEquals(ExitCode.INVALID_ARGS, e.getExitCode());
}
@Test
public void testInvalidTruststoreType() {
try {
final String urlStr = "https://localhost:8443/test";
commandLine.parse(
"-u", urlStr,
"-ts", TRUSTSTORE_PATH,
"-tst", "INVALID",
"-tsp", TRUSTSTORE_PASSWORD);
final CommandLineParseException e = assertThrows(CommandLineParseException.class, () -> commandLine.parse(
fail("Expected invalid args");
} catch (CommandLineParseException e) {
Assert.assertEquals(ExitCode.INVALID_ARGS, e.getExitCode());
}
"-u", "https://localhost:8443/test",
"-ts", TRUSTSTORE_PATH,
"-tst", "INVALID",
"-tsp", TRUSTSTORE_PASSWORD)
);
assertEquals(ExitCode.INVALID_ARGS, e.getExitCode());
}
}