Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Integration test fix #112

Merged
merged 8 commits into from
May 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ public Promise<HttpResponse<DownloadInputStream>, HttpException> streamDownload(

@Override
public Promise<HttpResponse<ByteArrayProvider>, HttpException> readBytes() {
final ResponseContentConverter<ByteArrayProvider> converter = b -> new SimpleByteArrayProvider(b);
final ResponseContentConverter<ByteArrayProvider> converter = SimpleByteArrayProvider::new;
return createExecutor(converter);
}

Expand Down Expand Up @@ -145,7 +145,7 @@ private <R> Promise<HttpResponse<R>, HttpException> createExecutor(final Respons
}

private Promise<HttpResponse<InputStream>, HttpException> createExecutor() {
return new HttpCallExecutorImpl<>(configuration, () -> handleRequest());
return new HttpCallExecutorImpl<>(configuration, this::handleRequest);
}

private <R> HttpResponse<R> handleRequest(final ResponseContentConverter<R> converter) throws HttpException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ public void updateCookiesFromResponse(final HttpURLConnection connection) throws

public void setRequestCookies(final HttpURLConnection connection) throws URISyntaxException {
Assert.requireNonNull(connection, "connection");
LOG.debug("adding cookies from cookie store to request");
LOG.debug("Adding cookies from cookie store to request");
if (cookieStore.getCookies().size() > 0) {
final String cookieValue = cookieStore.get(connection.getURL().toURI()).stream().
map(cookie -> {
Expand All @@ -88,7 +88,9 @@ public void setRequestCookies(final HttpURLConnection connection) throws URISynt
if (!cookieValue.isEmpty()) {
LOG.debug("Adding '{}' header to request. Content: {}", SET_COOKIE_HEADER, cookieValue);
connection.setRequestProperty(COOKIE_HEADER, cookieValue);
return;
}
}
LOG.debug("No cookies to add");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,17 @@
*/
package dev.rico.integrationtests;

import dev.rico.client.Client;
import dev.rico.client.concurrent.BackgroundExecutor;
import dev.rico.docker.DockerCompose;
import dev.rico.docker.Wait;
import dev.rico.internal.core.Assert;
import dev.rico.internal.core.SimpleThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.ITest;
import org.testng.ITestContext;
import org.testng.annotations.AfterGroups;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeGroups;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
Expand All @@ -35,18 +38,22 @@
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static dev.rico.integrationtests.AbstractIntegrationTest.INTEGRATION_TESTS_TEST_GROUP;
import static dev.rico.internal.core.http.HttpStatus.HTTP_OK;

@Test(groups = INTEGRATION_TESTS_TEST_GROUP)
public class AbstractIntegrationTest {
public class AbstractIntegrationTest implements ITest {

private static final Logger LOG = LoggerFactory.getLogger(AbstractIntegrationTest.class);

private final int timeoutInMinutes = 3;
private static final ThreadLocal<String> testName = new ThreadLocal<>();

private final int timeoutInMinutes = 1;

public static final String ENDPOINTS_DATAPROVIDER = "endpoints";

Expand All @@ -61,7 +68,7 @@ public AbstractIntegrationTest() {
try {
final URL dockerComposeURL = AbstractIntegrationTest.class.getClassLoader().getResource("docker-compose.yml");
final Path dockerComposeFile = Paths.get(dockerComposeURL.toURI());
final BackgroundExecutor backgroundExecutor = Client.getService(BackgroundExecutor.class);
final Executor backgroundExecutor = Executors.newCachedThreadPool(new SimpleThreadFactory());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do not know if change is correct. We should discuss this next week.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is only in a test and the executor is only used to startup the docker containers

dockerCompose = new DockerCompose(backgroundExecutor, dockerComposeFile);
} catch (Exception e) {
throw new RuntimeException("Can not create Docker environment!", e);
Expand All @@ -83,10 +90,23 @@ protected void stopDockerContainers() {
}

@BeforeMethod
public void onTest(final Method method, final Object[] data) {
public void beforeMethod(final Method method, final Object[] data) {
Assert.requireNonNull(method, "method");
Assert.requireNonNull(data, "data");
LOG.info("Starting test " + method.getDeclaringClass().getSimpleName() +"." + method.getName() + " for " + data[0]);
final String name = method.getDeclaringClass().getSimpleName() + "." + method.getName() + "_" + data[0];
LOG.info("Starting test " + name);
testName.set(name);
}

@AfterMethod
public void afterMethod(){
final String name = testName.get();
LOG.info("DONE test " + name);
}

@Override
public String getTestName() {
return testName.get();
}

@DataProvider(name = ENDPOINTS_DATAPROVIDER, parallel = false)
Expand All @@ -97,6 +117,11 @@ public Object[][] getEndpoints() {
.toArray(new String[][]{});
}

@BeforeClass
public void setDataProviderThreadCount(ITestContext context) {
context.getCurrentXmlTest().getSuite().setDataProviderThreadCount(1);
}

public int getTimeoutInMinutes() {
return timeoutInMinutes;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,45 +1,68 @@
package dev.rico.integrationtests.remoting;

import dev.rico.client.Client;
import dev.rico.integrationtests.AbstractIntegrationTest;
import dev.rico.integrationtests.IntegrationTestToolkit;
import dev.rico.remoting.client.ClientContext;
import dev.rico.remoting.client.ClientContextFactory;
import dev.rico.remoting.client.ControllerProxy;
import dev.rico.remoting.client.Param;
import dev.rico.integrationtests.AbstractIntegrationTest;
import dev.rico.integrationtests.IntegrationTestToolkit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;

import java.io.Serializable;
import java.net.HttpCookie;
import java.net.URI;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class AbstractRemotingIntegrationTest extends AbstractIntegrationTest {

private static final Logger LOG = LoggerFactory.getLogger(AbstractRemotingIntegrationTest.class);

protected <T> ControllerProxy<T> createController(final ClientContext clientContext, final String controllerName) {
return createController(clientContext, controllerName, Collections.emptyMap());
}

@SuppressWarnings("unchecked")
protected <T> ControllerProxy<T> createController(final ClientContext clientContext, final String controllerName, final Map<String, Serializable> parameters) {
try {
LOG.trace("Cookies before create controller: " + Client.getClientConfiguration().getCookieStore().getCookies());
return (ControllerProxy<T>) clientContext.createController(controllerName, parameters).get(getTimeoutInMinutes(), TimeUnit.MINUTES);
} catch (Exception e) {
LOG.trace("Cookies when failed to create controller: " + Client.getClientConfiguration().getCookieStore().getCookies());
throw new RuntimeException("Can not create controller " + controllerName, e);
}
}

@AfterMethod
public void tearDown() {
final List<HttpCookie> cookies = Client.getClientConfiguration().getCookieStore().getCookies();
if (cookies.size() != 1) {
Assert.fail("Found unexpected number of cookies in store: " + cookies);
}
Client.getClientConfiguration().getCookieStore().removeAll();
}

protected ClientContext connect(final String endpoint) {
Client.init(new IntegrationTestToolkit());
Client.getClientConfiguration().getCookieStore().removeAll();
final List<HttpCookie> cookies = Client.getClientConfiguration().getCookieStore().getCookies();
if (!cookies.isEmpty()) {
Assert.fail("Cookie store should have been empty, but found: " + cookies);
}
try {
final ClientContext clientContext = Client.getService(ClientContextFactory.class).create(Client.getClientConfiguration(), new URI(endpoint + "/remoting"));
final long timeOutTime = System.currentTimeMillis() + Duration.ofMinutes(getTimeoutInMinutes()).toMillis();
while (System.currentTimeMillis() < timeOutTime && clientContext.getClientId() == null) {
try {
clientContext.connect().get(getTimeoutInMinutes(), TimeUnit.MINUTES);
} catch (Exception ex) {
LOG.error("Failed to connect", ex);
// do nothing since server is not up at the moment...
}
}
Expand Down Expand Up @@ -81,7 +104,7 @@ protected void disconnect(final ClientContext clientContext, final String endpoi
try {
clientContext.disconnect().get(getTimeoutInMinutes(), TimeUnit.MINUTES);
} catch (Exception e) {
//do nothing
throw new RuntimeException("Can not disconnect from endpoint " + endpoint, e);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ public class ClientIdTest extends AbstractRemotingIntegrationTest {
public void testThatClientIdIsNotNull(String containerType, String endpoint) {
ClientContext context = connect(endpoint);
Assert.assertNotNull(context.getClientId());
disconnect(context, endpoint);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
public class AllValueTypesTestControllerTest extends AbstractRemotingIntegrationTest {

@Test(dataProvider = ENDPOINTS_DATAPROVIDER)
public void testCreationWithAllParameters(final String containerType, final String endpoint) throws ExecutionException, InterruptedException {
public void testCreationWithAllParameters(final String containerType, final String endpoint) {
//given:
final Map<String, Serializable> parameters = new HashMap<>();
parameters.put(ValueTestConstants.BIG_DECIMAL_VALUE, BigDecimal.valueOf(100L));
Expand Down Expand Up @@ -83,12 +83,12 @@ public void testCreationWithAllParameters(final String containerType, final Stri
Assert.assertEquals(model.shortValue().get().shortValue(), (short) 1);
Assert.assertEquals(model.stringValue().get(), "Hello");

controller.destroy().get();
context.disconnect().get();
destroy(controller, endpoint);
disconnect(context, endpoint);
}

@Test(dataProvider = ENDPOINTS_DATAPROVIDER)
public void testCreationWithPrimitiveParameters(final String containerType, final String endpoint) throws ExecutionException, InterruptedException {
public void testCreationWithPrimitiveParameters(final String containerType, final String endpoint) {
//given:
final Map<String, Serializable> parameters = new HashMap<>();
parameters.put(ValueTestConstants.PRIMITIVE_BOOLEAN_VALUE, true);
Expand Down Expand Up @@ -126,12 +126,12 @@ public void testCreationWithPrimitiveParameters(final String containerType, fina
Assert.assertEquals(model.primitiveLongValue().get().longValue(), 100L);
Assert.assertEquals(model.primitiveShortValue().get().shortValue(), (short) 1);

controller.destroy().get();
context.disconnect().get();
}
destroy(controller, endpoint);
disconnect(context, endpoint);
}

@Test(dataProvider = ENDPOINTS_DATAPROVIDER)
public void testCreationWithEmptyParameters(final String containerType, final String endpoint) throws ExecutionException, InterruptedException {
public void testCreationWithEmptyParameters(final String containerType, final String endpoint) {
//given:
final Map<String, Serializable> parameters = new HashMap<>();

Expand Down Expand Up @@ -163,8 +163,8 @@ public void testCreationWithEmptyParameters(final String containerType, final St
Assert.assertEquals(model.primitiveLongValue().get().longValue(), 0L);
Assert.assertEquals(model.primitiveShortValue().get().shortValue(), (short) 0);

controller.destroy().get();
context.disconnect().get();
destroy(controller, endpoint);
disconnect(context, endpoint);
}

//Currently we do not handle controller creation errors on the client.
Expand All @@ -183,7 +183,7 @@ public void testCreationWithWrongTypedParameters(final String containerType, fin
}

@Test(dataProvider = ENDPOINTS_DATAPROVIDER)
public void testCreationWithoutParameters(final String containerType, final String endpoint) throws ExecutionException, InterruptedException {
public void testCreationWithoutParameters(final String containerType, final String endpoint) {
//when:
final ClientContext context = connect(endpoint);
final ControllerProxy<AllValueTypesTestControllerModel> controller = createController(context, ALL_VALUE_TYPES_CONTROLLER);
Expand Down Expand Up @@ -212,7 +212,7 @@ public void testCreationWithoutParameters(final String containerType, final Stri
Assert.assertEquals(model.primitiveLongValue().get().longValue(), 0L);
Assert.assertEquals(model.primitiveShortValue().get().shortValue(), (short) 0);

controller.destroy().get();
context.disconnect().get();
destroy(controller, endpoint);
disconnect(context, endpoint);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
import java.net.URI;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.function.Function;
import java.util.function.Supplier;

Expand Down Expand Up @@ -129,41 +130,25 @@ public synchronized BeanManager getBeanManager() {

@Override
public synchronized CompletableFuture<Void> disconnect() {
final CompletableFuture<Void> result = new CompletableFuture<>();
final BackgroundExecutor backgroundExecutor = Client.getService(BackgroundExecutor.class);
backgroundExecutor.execute(() -> {
commandHandler.invokeCommand(new DestroyContextCommand()).handle((Void aVoid, Throwable throwable) -> {

clientConnector.disconnect();
clientSessionStore.resetSession(endpoint);
if (throwable != null) {
result.completeExceptionally(new RemotingException("Can't disconnect", throwable));
} else {
result.complete(null);
}
return null;
});
});
return result;
return commandHandler.
invokeCommand(new DestroyContextCommand()).
thenAccept(aVoid -> {
clientConnector.disconnect();
clientSessionStore.resetSession(endpoint);
}).
exceptionally(throwable -> {
throw new CompletionException(new RemotingException("Can't disconnect", throwable));
});
}

@Override
public CompletableFuture<Void> connect() {

final CompletableFuture<Void> result = new CompletableFuture<>();
clientConnector.connect();
final BackgroundExecutor backgroundExecutor = Client.getService(BackgroundExecutor.class);
backgroundExecutor.execute(() -> {
commandHandler.invokeCommand(new CreateContextCommand()).handle((Void aVoid, Throwable throwable) -> {
if (throwable != null) {
result.completeExceptionally(new ClientInitializationException("Can't call init action!", throwable));
} else {
}
result.complete(null);
return null;
});
return commandHandler.
invokeCommand(new CreateContextCommand()).
exceptionally(throwable -> {
throw new CompletionException(new ClientInitializationException("Can't call init action!", throwable));
});
return result;
}

@Override
Expand Down
Loading