Migrated tests to JUnit5 and removed PowerMock

* Unit tests are using JUnit Jupiter framework
 * Enabled support for legacy rules for now
 * Replaced PowerMock with custom ByteBuddy redefinition for the offline test
This commit is contained in:
Stefan Kalscheuer 2017-11-26 18:01:30 +01:00
parent 470dcb48ba
commit 50cd400ba3
15 changed files with 145 additions and 104 deletions

32
pom.xml
View File

@ -61,7 +61,14 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20.1</version>
<version>2.19.1</version>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>1.0.2</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</pluginManagement>
@ -90,11 +97,16 @@
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.0.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-migrationsupport</artifactId>
<version>5.0.2</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-junit</artifactId>
@ -108,15 +120,15 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>2.0.0-beta.5</version>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.12.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>2.0.0-beta.5</version>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>2.12.0</version>
<scope>test</scope>
</dependency>
</dependencies>

View File

@ -20,6 +20,9 @@ import de.stklcode.jvault.connector.exception.InvalidRequestException;
import de.stklcode.jvault.connector.exception.InvalidResponseException;
import de.stklcode.jvault.connector.exception.PermissionDeniedException;
import de.stklcode.jvault.connector.exception.VaultConnectorException;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.agent.ByteBuddyAgent;
import net.bytebuddy.dynamic.loading.ClassReloadingStrategy;
import org.apache.http.ProtocolVersion;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.entity.ContentType;
@ -27,12 +30,9 @@ import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicStatusLine;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import javax.net.ssl.SSLContext;
import java.io.IOException;
@ -40,15 +40,15 @@ import java.lang.reflect.Field;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import static net.bytebuddy.implementation.MethodDelegation.to;
import static net.bytebuddy.matcher.ElementMatchers.named;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.mockito.Mockito.*;
/**
* JUnit test for HTTP Vault connector.
@ -57,20 +57,46 @@ import static org.powermock.api.mockito.PowerMockito.mockStatic;
* @author Stefan Kalscheuer
* @since 0.7.0
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({HttpClientBuilder.class})
@PowerMockIgnore({"javax.net.ssl.*"})
public class HTTPVaultConnectorOfflineTest {
private static final String INVALID_URL = "foo:/\\1nv4l1d_UrL";
@Mock
private HttpClientBuilder httpMockBuilder;
private static HttpClientBuilder httpMockBuilder = mock(HttpClientBuilder.class);
private static CloseableHttpClient httpMock = mock(CloseableHttpClient.class);
private CloseableHttpResponse responseMock = mock(CloseableHttpResponse.class);
@Mock
private CloseableHttpClient httpMock;
@BeforeAll
public static void initByteBuddy() {
// Install ByteBuddy Agent.
ByteBuddyAgent.install();
}
@Mock
private CloseableHttpResponse responseMock;
/**
* Helper method for redefinition of {@link HttpClientBuilder#create()} from {@link #initHttpMock()}.
*
* @return Mocked HTTP client builder.
*/
public static HttpClientBuilder create() {
return httpMockBuilder;
}
@BeforeEach
public void initHttpMock() {
// Redefine static method to return Mock on HttpClientBuilder creation.
new ByteBuddy().redefine(HttpClientBuilder.class)
.method(named("create"))
.intercept(to(HTTPVaultConnectorOfflineTest.class))
.make()
.load(HttpClientBuilder.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
// Ignore SSL context settings.
when(httpMockBuilder.setSSLContext(null)).thenReturn(httpMockBuilder);
// Re-initialize HTTP mock to ensure fresh (empty) results.
httpMock = mock(CloseableHttpClient.class);
// Mock actual client creation.
when(httpMockBuilder.build()).thenReturn(httpMock);
}
/**
* Test exceptions thrown during request.
@ -80,7 +106,6 @@ public class HTTPVaultConnectorOfflineTest {
HTTPVaultConnector connector = new HTTPVaultConnector("http://127.0.0.1", null, 0, 250);
// Test invalid response code.
initHttpMock();
final int responseCode = 400;
mockResponse(responseCode, "", ContentType.APPLICATION_JSON);
try {
@ -189,7 +214,7 @@ public class HTTPVaultConnectorOfflineTest {
connector = new HTTPVaultConnector("https://127.0.0.1", null, 0, 250);
// Simulate NULL response (mock not supplied with data).
initHttpMock();
try {
connector.sealStatus();
fail("Querying seal status succeeded on invalid instance");
@ -216,7 +241,6 @@ public class HTTPVaultConnectorOfflineTest {
connector = new HTTPVaultConnector("https://127.0.0.1", null, 0, 250);
// Simulate NULL response (mock not supplied with data).
initHttpMock();
try {
connector.getHealth();
fail("Querying health status succeeded on invalid instance");
@ -235,7 +259,6 @@ public class HTTPVaultConnectorOfflineTest {
// Mock authorization.
setPrivate(connector, "authorized", true);
// Mock response.
initHttpMock();
mockResponse(200, "invalid", ContentType.APPLICATION_JSON);
// Now test the methods.
@ -359,7 +382,6 @@ public class HTTPVaultConnectorOfflineTest {
// Mock authorization.
setPrivate(connector, "authorized", true);
// Mock response.
initHttpMock();
mockResponse(200, "{}", ContentType.APPLICATION_JSON);
// Now test the methods expecting a 204.
@ -453,13 +475,6 @@ public class HTTPVaultConnectorOfflineTest {
}
}
private void initHttpMock() {
mockStatic(HttpClientBuilder.class);
when(HttpClientBuilder.create()).thenReturn(httpMockBuilder);
when(httpMockBuilder.setSSLContext(null)).thenReturn(httpMockBuilder);
when(httpMockBuilder.build()).thenReturn(httpMock);
}
private void mockResponse(int status, String body, ContentType type) throws IOException {
when(httpMock.execute(any())).thenReturn(responseMock);
when(responseMock.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), status, ""));

View File

@ -17,15 +17,16 @@
package de.stklcode.jvault.connector;
import de.stklcode.jvault.connector.exception.*;
import de.stklcode.jvault.connector.factory.HTTPVaultConnectorFactory;
import de.stklcode.jvault.connector.factory.VaultConnectorFactory;
import de.stklcode.jvault.connector.model.*;
import de.stklcode.jvault.connector.model.response.*;
import de.stklcode.jvault.connector.factory.HTTPVaultConnectorFactory;
import de.stklcode.jvault.connector.test.Credentials;
import de.stklcode.jvault.connector.test.VaultConfiguration;
import de.stklcode.jvault.connector.factory.VaultConnectorFactory;
import org.junit.*;
import org.junit.Rule;
import org.junit.jupiter.api.*;
import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport;
import org.junit.rules.TemporaryFolder;
import org.junit.rules.TestName;
import java.io.*;
import java.lang.reflect.Field;
@ -35,10 +36,14 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
import static org.junit.Assume.*;
import static org.hamcrest.junit.MatcherAssume.assumeThat;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
/**
* JUnit test for HTTP Vault connector.
@ -47,6 +52,7 @@ import static org.junit.Assume.*;
* @author Stefan Kalscheuer
* @since 0.1
*/
@EnableRuleMigrationSupport
public class HTTPVaultConnectorTest {
private static final String VAULT_VERISON = "0.9.0"; // the vault version this test is supposed to run against
private static final String KEY = "81011a8061e5c028bd0d9503eeba40bd9054b9af0408d080cb24f57405c27a61";
@ -73,17 +79,14 @@ public class HTTPVaultConnectorTest {
@Rule
public TemporaryFolder tmpDir = new TemporaryFolder();
@Rule
public TestName testName = new TestName();
/**
* Initialize Vault instance with generated configuration and provided file backend.
* Requires "vault" binary to be in current user's executable path. Not using MLock, so no extended rights required.
*/
@Before
public void setUp() throws VaultConnectorException {
@BeforeEach
public void setUp(TestInfo testInfo) throws VaultConnectorException {
/* Determine, if TLS is required */
boolean isTls = testName.getMethodName().equals("tlsConnectionTest");
boolean isTls = testInfo.getTags().contains("tls");
/* Initialize Vault */
VaultConfiguration config = initializeVault(isTls);
@ -104,11 +107,11 @@ public class HTTPVaultConnectorTest {
/* Unseal Vault and check result */
SealResponse sealStatus = connector.unseal(KEY);
assumeNotNull(sealStatus);
assumeTrue(sealStatus != null);
assumeFalse(sealStatus.isSealed());
}
@After
@AfterEach
public void tearDown() {
if (vaultProcess != null && vaultProcess.isAlive())
vaultProcess.destroy();
@ -217,7 +220,7 @@ public class HTTPVaultConnectorTest {
try {
res = connector.authToken(TOKEN_ROOT);
assertNotNull("Login failed with valid token", res);
assertNotNull(res, "Login failed with valid token");
assertThat("Login failed with valid token", connector.isAuthorized(), is(true));
} catch (VaultConnectorException ignored) {
fail("Login failed with valid token");
@ -246,7 +249,7 @@ public class HTTPVaultConnectorTest {
} catch (VaultConnectorException ignored) {
fail("Login failed with valid credentials: Exception thrown");
}
assertNotNull("Login failed with valid credentials: Response not available", res.getAuth());
assertNotNull(res.getAuth(), "Login failed with valid credentials: Response not available");
assertThat("Login failed with valid credentials: Connector not authorized", connector.isAuthorized(), is(true));
}
@ -636,6 +639,7 @@ public class HTTPVaultConnectorTest {
* Test reading of secrets.
*/
@Test
@SuppressWarnings("deprecation")
public void readSecretTest() {
authUser();
assumeTrue(connector.isAuthorized());
@ -728,6 +732,7 @@ public class HTTPVaultConnectorTest {
* Test writing secrets.
*/
@Test
@SuppressWarnings("deprecation")
public void writeSecretTest() {
authUser();
assumeTrue(connector.isAuthorized());
@ -909,6 +914,7 @@ public class HTTPVaultConnectorTest {
* Test TLS connection with custom certificate chain.
*/
@Test
@Tag("tls")
public void tlsConnectionTest() {
TokenResponse res;
try {
@ -919,7 +925,7 @@ public class HTTPVaultConnectorTest {
try {
res = connector.authToken(TOKEN_ROOT);
assertNotNull("Login failed with valid token", res);
assertNotNull(res, "Login failed with valid token");
assertThat("Login failed with valid token", connector.isAuthorized(), is(true));
} catch (VaultConnectorException ignored) {
fail("Login failed with valid token");

View File

@ -16,12 +16,12 @@
package de.stklcode.jvault.connector.exception;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Common JUnit test for Exceptions extending {@link VaultConnectorException}.

View File

@ -19,10 +19,10 @@ package de.stklcode.jvault.connector.factory;
import de.stklcode.jvault.connector.HTTPVaultConnector;
import de.stklcode.jvault.connector.exception.TlsException;
import de.stklcode.jvault.connector.exception.VaultConnectorException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport;
import org.junit.rules.TemporaryFolder;
import java.io.IOException;
@ -30,7 +30,8 @@ import java.lang.reflect.Field;
import java.nio.file.NoSuchFileException;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.fail;
/**
* JUnit test for HTTP Vault connector factory
@ -38,6 +39,7 @@ import static org.junit.Assert.*;
* @author Stefan Kalscheuer
* @since 0.6.0
*/
@EnableRuleMigrationSupport
public class HTTPVaultConnectorFactoryTest {
private static String VAULT_ADDR = "https://localhost:8201";
private static Integer VAULT_MAX_RETRIES = 13;

View File

@ -18,13 +18,14 @@ package de.stklcode.jvault.connector.model;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.*;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
/**
* JUnit Test for AppRole Builder.
@ -53,7 +54,7 @@ public class AppRoleBuilderTest {
private static final String JSON_FULL = String.format("{\"role_name\":\"%s\",\"role_id\":\"%s\",\"bind_secret_id\":%s,\"bound_cidr_list\":\"%s\",\"policies\":\"%s\",\"secret_id_num_uses\":%d,\"secret_id_ttl\":%d,\"token_ttl\":%d,\"token_max_ttl\":%d,\"period\":%d}",
NAME, ID, BIND_SECRET_ID, CIDR_1, POLICY, SECRET_ID_NUM_USES, SECRET_ID_TTL, TOKEN_TTL, TOKEN_MAX_TTL, PERIOD);
@BeforeClass
@BeforeAll
public static void init() {
BOUND_CIDR_LIST.add(CIDR_1);
POLICIES.add(POLICY);

View File

@ -16,11 +16,9 @@
package de.stklcode.jvault.connector.model;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.lang.reflect.Field;
@ -29,12 +27,11 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.hamcrest.Matchers.emptyString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.junit.MatcherAssume.assumeThat;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.fail;
/**
* JUnit Test for AppRoleSecret model.

View File

@ -16,10 +16,10 @@
package de.stklcode.jvault.connector.model;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
/**
* JUnit Test for AuthBackend model.

View File

@ -18,16 +18,16 @@ package de.stklcode.jvault.connector.model;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
/**
* JUnit Test for Token Builder.
@ -55,7 +55,7 @@ public class TokenBuilderTest {
private static final Boolean RENEWABLE = true;
private static final String JSON_FULL = "{\"id\":\"test-id\",\"display_name\":\"display-name\",\"no_parent\":false,\"no_default_policy\":false,\"ttl\":123,\"num_uses\":4,\"policies\":[\"policy\"],\"meta\":{\"key\":\"value\"},\"renewable\":true}";
@BeforeClass
@BeforeAll
public static void init() {
POLICIES.add(POLICY);
META.put(META_KEY, META_VALUE);

View File

@ -3,15 +3,15 @@ package de.stklcode.jvault.connector.model.response;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.stklcode.jvault.connector.exception.InvalidResponseException;
import de.stklcode.jvault.connector.model.AppRole;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.fail;
/**
* JUnit Test for {@link AppRoleResponse} model.

View File

@ -3,18 +3,18 @@ package de.stklcode.jvault.connector.model.response;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.stklcode.jvault.connector.exception.InvalidResponseException;
import de.stklcode.jvault.connector.model.AuthBackend;
import de.stklcode.jvault.connector.model.response.embedded.AuthData;
import de.stklcode.jvault.connector.model.response.embedded.AuthMethod;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.fail;
;
/**
* JUnit Test for {@link AuthMethodsResponse} model.

View File

@ -3,15 +3,17 @@ package de.stklcode.jvault.connector.model.response;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.stklcode.jvault.connector.exception.InvalidResponseException;
import de.stklcode.jvault.connector.model.response.embedded.AuthData;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.fail;
;
/**
* JUnit Test for {@link AuthResponse} model.

View File

@ -1,14 +1,16 @@
package de.stklcode.jvault.connector.model.response;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.fail;
;
/**
* JUnit Test for {@link AuthResponse} model.

View File

@ -2,16 +2,18 @@ package de.stklcode.jvault.connector.model.response;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.stklcode.jvault.connector.exception.InvalidResponseException;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.fail;
;
/**
* JUnit Test for {@link SecretResponse} model.

View File

@ -3,15 +3,17 @@ package de.stklcode.jvault.connector.model.response;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.stklcode.jvault.connector.exception.InvalidResponseException;
import de.stklcode.jvault.connector.model.response.embedded.TokenData;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.fail;
;
/**
* JUnit Test for {@link TokenResponse} model.