Migration to JUnit5 as default test runtime (#1082)

* Migrate tests to JUnit5

Signed-off-by: Dominic Schabel <dominic.schabel@bosch.io>

* REST docs tests migrated to JUnit5

Signed-off-by: Dominic Schabel <dominic.schabel@bosch.io>

* Migrated security and UI tests to JUnit5

Signed-off-by: Dominic Schabel <dominic.schabel@bosch.io>

* Migrated management tests to JUnit5

Signed-off-by: Dominic Schabel <dominic.schabel@bosch.io>

* Reflecting changes from JUnit5 migration

Signed-off-by: Dominic Schabel <dominic.schabel@bosch.io>

* Fix RabbitMQ test detection

Signed-off-by: Dominic Schabel <dominic.schabel@bosch.io>

* Drop support for JUnit4

Signed-off-by: Dominic Schabel <dominic.schabel@bosch.io>
This commit is contained in:
Dominic Schabel
2021-03-15 13:40:40 +01:00
committed by GitHub
parent 82ab18cf42
commit 81defa10a6
140 changed files with 572 additions and 657 deletions

View File

@@ -9,9 +9,6 @@
package org.eclipse.hawkbit.amqp;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
@@ -51,7 +48,8 @@ import org.eclipse.hawkbit.repository.model.TenantMetaData;
import org.eclipse.hawkbit.repository.test.util.AbstractIntegrationTest;
import org.eclipse.hawkbit.repository.test.util.TestdataFactory;
import org.eclipse.hawkbit.util.IpUtil;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.springframework.amqp.core.Message;
@@ -89,9 +87,9 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTest {
private Target testTarget;
@Override
public void before() throws Exception {
super.before();
@BeforeEach
public void beforeEach() throws Exception {
testTarget = targetManagement.create(entityFactory.target().create().controllerId(CONTROLLER_ID)
.securityToken(TEST_TOKEN).address(AMQP_URI.toString()));
@@ -146,22 +144,19 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTest {
assertThat(downloadAndUpdateRequest.getTargetSecurityToken()).isEqualTo(TEST_TOKEN);
for (final org.eclipse.hawkbit.dmf.json.model.DmfSoftwareModule softwareModule : downloadAndUpdateRequest
.getSoftwareModules()) {
assertTrue("Artifact list for softwaremodule should be empty", softwareModule.getArtifacts().isEmpty());
assertThat(softwareModule.getArtifacts().isEmpty()).as("Artifact list for softwaremodule should be empty").isTrue();
assertThat(softwareModule.getMetadata()).containsExactly(
new DmfMetadata(TestdataFactory.VISIBLE_SM_MD_KEY, TestdataFactory.VISIBLE_SM_MD_VALUE));
for (final SoftwareModule softwareModule2 : action.getDistributionSet().getModules()) {
assertNotNull("Software module ID should be set", softwareModule.getModuleId());
if (!softwareModule.getModuleId().equals(softwareModule2.getId())) {
continue;
}
assertEquals(
"Software module type in event should be the same as the softwaremodule in the distribution set",
softwareModule.getModuleType(), softwareModule2.getType().getKey());
assertEquals(
"Software module version in event should be the same as the softwaremodule in the distribution set",
softwareModule.getModuleVersion(), softwareModule2.getVersion());
assertThat(softwareModule.getModuleType()).isEqualTo(softwareModule2.getType().getKey()).as(
"Software module type in event should be the same as the softwaremodule in the distribution set");
assertThat(softwareModule.getModuleVersion()).isEqualTo(softwareModule2.getVersion()).as(
"Software module version in event should be the same as the softwaremodule in the distribution set");
}
}
}
@@ -190,8 +185,7 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTest {
final DmfDownloadAndUpdateRequest downloadAndUpdateRequest = assertDownloadAndInstallMessage(sendMessage,
action.getId());
assertEquals("DownloadAndUpdateRequest event should contains 3 software modules", 3,
downloadAndUpdateRequest.getSoftwareModules().size());
assertThat(downloadAndUpdateRequest.getSoftwareModules()).hasSize(3).as("DownloadAndUpdateRequest event should contains 3 software modules");
assertThat(downloadAndUpdateRequest.getTargetSecurityToken()).isEqualTo(TEST_TOKEN);
for (final DmfSoftwareModule softwareModule : downloadAndUpdateRequest.getSoftwareModules()) {
@@ -291,14 +285,14 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTest {
private void assertCancelMessage(final Message sendMessage) {
assertEventMessage(sendMessage);
final DmfActionRequest actionId = convertMessage(sendMessage, DmfActionRequest.class);
assertEquals("Action ID should be 1", actionId.getActionId(), Long.valueOf(1));
assertEquals("The topic in the message should be a CANCEL_DOWNLOAD value", EventTopic.CANCEL_DOWNLOAD,
sendMessage.getMessageProperties().getHeaders().get(MessageHeaderKey.TOPIC));
assertThat( actionId.getActionId()).isEqualTo(Long.valueOf(1)).as("Action ID should be 1");
assertThat(sendMessage.getMessageProperties().getHeaders().get(MessageHeaderKey.TOPIC)).isEqualTo(EventTopic.CANCEL_DOWNLOAD)
.as("The topc in the message should be a CANCEL_DOWNLOAD value");
}
private void assertDeleteMessage(final Message sendMessage) {
assertNotNull(sendMessage);
assertThat(sendMessage).isNotNull();
assertThat(sendMessage.getMessageProperties().getHeaders().get(MessageHeaderKey.THING_ID))
.isEqualTo(CONTROLLER_ID);
assertThat(sendMessage.getMessageProperties().getHeaders().get(MessageHeaderKey.TENANT)).isEqualTo(TENANT);
@@ -310,32 +304,30 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTest {
assertEventMessage(sendMessage);
final DmfDownloadAndUpdateRequest downloadAndUpdateRequest = convertMessage(sendMessage,
DmfDownloadAndUpdateRequest.class);
assertEquals(downloadAndUpdateRequest.getActionId(), action);
assertEquals("The topic of the event should contain DOWNLOAD_AND_INSTALL", EventTopic.DOWNLOAD_AND_INSTALL,
sendMessage.getMessageProperties().getHeaders().get(MessageHeaderKey.TOPIC));
assertEquals("Security token of target", TEST_TOKEN, downloadAndUpdateRequest.getTargetSecurityToken());
assertThat(downloadAndUpdateRequest.getActionId()).isEqualTo(action);
assertThat(sendMessage.getMessageProperties().getHeaders().get(MessageHeaderKey.TOPIC)).isEqualTo( EventTopic.DOWNLOAD_AND_INSTALL)
.as("The topic of the event should contain DOWNLOAD_AND_INSTALL");
assertThat(downloadAndUpdateRequest.getTargetSecurityToken()).isEqualTo(TEST_TOKEN).as("Security token of target");
return downloadAndUpdateRequest;
}
private void assertUpdateAttributesMessage(final Message sendMessage) {
assertEventMessage(sendMessage);
assertEquals("The topic of the event should contain REQUEST_ATTRIBUTES_UPDATE",
EventTopic.REQUEST_ATTRIBUTES_UPDATE,
sendMessage.getMessageProperties().getHeaders().get(MessageHeaderKey.TOPIC));
assertThat(sendMessage.getMessageProperties().getHeaders().get(MessageHeaderKey.TOPIC)).isEqualTo(EventTopic.REQUEST_ATTRIBUTES_UPDATE)
.as("The topic of the event should contain REQUEST_ATTRIBUTES_UPDATE");
}
private void assertEventMessage(final Message sendMessage) {
assertNotNull("The message should not be null", sendMessage);
assertThat(sendMessage).isNotNull().as("The message should not be null");
assertEquals("The value of the message header THING_ID should be " + CONTROLLER_ID, CONTROLLER_ID,
sendMessage.getMessageProperties().getHeaders().get(MessageHeaderKey.THING_ID));
assertEquals("The value of the message header TYPE should be EVENT", MessageType.EVENT,
sendMessage.getMessageProperties().getHeaders().get(MessageHeaderKey.TYPE));
assertEquals("The content type message should be " + MessageProperties.CONTENT_TYPE_JSON,
MessageProperties.CONTENT_TYPE_JSON, sendMessage.getMessageProperties().getContentType());
assertThat(sendMessage.getMessageProperties().getHeaders().get(MessageHeaderKey.THING_ID)).isEqualTo(CONTROLLER_ID)
.as("The value of the message header THING_ID should be " + CONTROLLER_ID);
assertThat(sendMessage.getMessageProperties().getHeaders().get(MessageHeaderKey.TYPE)).isEqualTo(MessageType.EVENT)
.as("The value of the message header TYPE should be EVENT");
assertThat(sendMessage.getMessageProperties().getContentType()).isEqualTo(MessageProperties.CONTENT_TYPE_JSON)
.as("The content type message should be " + MessageProperties.CONTENT_TYPE_JSON);
}
protected Message createArgumentCapture(final URI uri) {

View File

@@ -15,6 +15,7 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -59,13 +60,13 @@ import org.eclipse.hawkbit.security.SecurityContextTenantAware;
import org.eclipse.hawkbit.security.SecurityTokenGenerator;
import org.eclipse.hawkbit.security.SystemSecurityContext;
import org.eclipse.hawkbit.tenancy.TenantAware;
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.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.amqp.AmqpRejectAndDontRequeueException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
@@ -79,7 +80,7 @@ import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
@Feature("Component Tests - Device Management Federation API")
@Story("AmqpMessage Handler Service Test")
public class AmqpMessageHandlerServiceTest {
@@ -144,15 +145,14 @@ public class AmqpMessageHandlerServiceTest {
@Captor
private ArgumentCaptor<UpdateMode> modeCaptor;
@Before
@BeforeEach
@SuppressWarnings({ "rawtypes", "unchecked" })
public void before() throws Exception {
messageConverter = new Jackson2JsonMessageConverter();
when(rabbitTemplate.getMessageConverter()).thenReturn(messageConverter);
when(artifactManagementMock.findFirstBySHA1(SHA1)).thenReturn(Optional.empty());
lenient().when(rabbitTemplate.getMessageConverter()).thenReturn(messageConverter);
final TenantConfigurationValue multiAssignmentConfig = TenantConfigurationValue.builder().value(Boolean.FALSE)
.global(Boolean.FALSE).build();
when(tenantConfigurationManagement.getConfigurationValue(MULTI_ASSIGNMENTS_ENABLED, Boolean.class))
lenient().when(tenantConfigurationManagement.getConfigurationValue(MULTI_ASSIGNMENTS_ENABLED, Boolean.class))
.thenReturn(multiAssignmentConfig);
final SecurityContextTenantAware tenantAware = new SecurityContextTenantAware();

View File

@@ -10,6 +10,7 @@ package org.eclipse.hawkbit.amqp;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.when;
import org.eclipse.hawkbit.dmf.json.model.DmfActionStatus;
@@ -17,11 +18,12 @@ import org.eclipse.hawkbit.dmf.json.model.DmfActionUpdateStatus;
import org.eclipse.hawkbit.repository.event.remote.entity.TargetCreatedEvent;
import org.eclipse.hawkbit.repository.test.matcher.Expect;
import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents;
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.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
@@ -32,7 +34,7 @@ import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
@Feature("Component Tests - Device Management Federation API")
@Story("Base Amqp Service Test")
public class BaseAmqpServiceTest {
@@ -42,11 +44,10 @@ public class BaseAmqpServiceTest {
private BaseAmqpService baseAmqpService;
@Before
@BeforeEach
public void setup() {
when(rabbitTemplate.getMessageConverter()).thenReturn(new Jackson2JsonMessageConverter());
lenient().when(rabbitTemplate.getMessageConverter()).thenReturn(new Jackson2JsonMessageConverter());
baseAmqpService = new BaseAmqpService(rabbitTemplate);
}
@Test

View File

@@ -18,6 +18,7 @@ import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Callable;
import org.assertj.core.api.HamcrestCondition;
import org.eclipse.hawkbit.amqp.DmfApiConfiguration;
import org.eclipse.hawkbit.dmf.amqp.api.AmqpSettings;
import org.eclipse.hawkbit.dmf.amqp.api.EventTopic;
@@ -43,13 +44,13 @@ import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
import org.eclipse.hawkbit.repository.test.TestConfiguration;
import org.eclipse.hawkbit.repository.test.util.TestdataFactory;
import org.eclipse.hawkbit.repository.test.util.WithSpringAuthorityRule;
import org.eclipse.hawkbit.util.IpUtil;
import org.junit.Assert;
import org.junit.Before;
import org.junit.jupiter.api.BeforeEach;
import org.mockito.Mockito;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.junit.BrokerRunningSupport;
import org.springframework.amqp.rabbit.test.RabbitListenerTestHarness;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.test.binder.TestSupportBinderAutoConfiguration;
@@ -77,10 +78,7 @@ public abstract class AbstractAmqpServiceIntegrationTest extends AbstractAmqpInt
@Autowired
private RabbitListenerTestHarness harness;
@Autowired
private ConnectionFactory connectionFactory;
@Before
@BeforeEach
public void initListener() {
deadletterListener = harness.getSpy(DeadletterListener.LISTENER_ID);
assertThat(deadletterListener).isNotNull();
@@ -93,10 +91,11 @@ public abstract class AbstractAmqpServiceIntegrationTest extends AbstractAmqpInt
}
private <T> T waitUntilIsPresent(final Callable<Optional<T>> callable) {
createConditionFactory().until(() -> securityRule.runAsPrivileged(() -> callable.call().isPresent()));
createConditionFactory().until(() -> WithSpringAuthorityRule.runAsPrivileged(() -> callable.call().isPresent()));
try {
return securityRule.runAsPrivileged(() -> callable.call().get());
return WithSpringAuthorityRule.runAsPrivileged(() -> callable.call().get());
} catch (final Exception e) {
return null;
}
@@ -189,7 +188,7 @@ public abstract class AbstractAmqpServiceIntegrationTest extends AbstractAmqpInt
protected void assertDmfDownloadAndUpdateRequest(final DmfDownloadAndUpdateRequest request,
final Set<SoftwareModule> softwareModules, final String controllerId) {
Assert.assertThat(softwareModules, SoftwareModuleJsonMatcher.containsExactly(request.getSoftwareModules()));
assertThat(softwareModules).is(new HamcrestCondition<>(SoftwareModuleJsonMatcher.containsExactly(request.getSoftwareModules())));
request.getSoftwareModules().forEach(dmfModule -> assertThat(dmfModule.getMetadata()).containsExactly(
new DmfMetadata(TestdataFactory.VISIBLE_SM_MD_KEY, TestdataFactory.VISIBLE_SM_MD_VALUE)));
final Target updatedTarget = waitUntilIsPresent(() -> targetManagement.getByControllerID(controllerId));
@@ -299,7 +298,7 @@ public abstract class AbstractAmqpServiceIntegrationTest extends AbstractAmqpInt
assertThat(target.getCreatedBy()).isEqualTo(createdBy);
assertThat(target.getUpdateStatus()).isEqualTo(updateStatus);
assertThat(target.getAddress()).isEqualTo(
IpUtil.createAmqpUri(connectionFactory.getVirtualHost(), DmfTestConfiguration.REPLY_TO_EXCHANGE));
IpUtil.createAmqpUri(getVirtualHost(), DmfTestConfiguration.REPLY_TO_EXCHANGE));
}
protected Message createTargetMessage(final String target, final String tenant) {
@@ -364,7 +363,7 @@ public abstract class AbstractAmqpServiceIntegrationTest extends AbstractAmqpInt
createConditionFactory().untilAsserted(() -> {
try {
final Map<String, String> controllerAttributes = securityRule
final Map<String, String> controllerAttributes = WithSpringAuthorityRule
.runAsPrivileged(() -> targetManagement.getControllerAttributes(controllerId));
assertThat(controllerAttributes.size()).isEqualTo(attributes.size());
attributes.forEach((k, v) -> assertKeyValueInMap(k, v, controllerAttributes));

View File

@@ -25,8 +25,8 @@ import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.security.DmfTenantSecurityToken;
import org.eclipse.hawkbit.security.DmfTenantSecurityToken.FileResource;
import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationProperties.TenantConfigurationKey;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
@@ -52,7 +52,7 @@ public class AmqpAuthenticationMessageHandlerIntegrationTest extends AbstractAmq
@Autowired
private AmqpProperties amqpProperties;
@Before
@BeforeEach
public void testSetup() {
enableTargetTokenAuthentication();
}

View File

@@ -49,7 +49,8 @@ import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
import org.eclipse.hawkbit.repository.test.matcher.Expect;
import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents;
import org.junit.Test;
import org.eclipse.hawkbit.repository.test.util.WithSpringAuthorityRule;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.amqp.core.Message;
@@ -533,7 +534,7 @@ public class AmqpMessageDispatcherServiceIntegrationTest extends AbstractAmqpSer
}
private void waitUntil(final Callable<Boolean> callable) {
createConditionFactory().until(() -> securityRule.runAsPrivileged(callable));
createConditionFactory().until(() -> WithSpringAuthorityRule.runAsPrivileged(callable));
}
private void assertLatestMultiActionMessageContainsInstallMessages(final String controllerId,

View File

@@ -59,7 +59,8 @@ import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
import org.eclipse.hawkbit.repository.test.matcher.Expect;
import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents;
import org.junit.Test;
import org.eclipse.hawkbit.repository.test.util.WithSpringAuthorityRule;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
@@ -966,7 +967,7 @@ public class AmqpMessageHandlerServiceIntegrationTest extends AbstractAmqpServic
private void assertAction(final Long actionId, final int messages, final Status... expectedActionStates) {
createConditionFactory().await().untilAsserted(() -> {
try {
securityRule.runAsPrivileged(() -> {
WithSpringAuthorityRule.runAsPrivileged(() -> {
final List<ActionStatus> actionStatusList = deploymentManagement
.findActionStatusByAction(PAGE, actionId).getContent();

View File

@@ -16,14 +16,13 @@ import org.awaitility.core.ConditionFactory;
import org.eclipse.hawkbit.repository.jpa.RepositoryApplicationConfiguration;
import org.eclipse.hawkbit.repository.test.TestConfiguration;
import org.eclipse.hawkbit.repository.test.util.AbstractIntegrationTest;
import org.junit.Before;
import org.junit.Rule;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.junit.BrokerRunning;
import org.springframework.amqp.rabbit.junit.RabbitAvailable;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.test.binder.TestSupportBinderAutoConfiguration;
@@ -31,17 +30,15 @@ import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.ContextConfiguration;
@RabbitAvailable
@ContextConfiguration(classes = { RepositoryApplicationConfiguration.class, AmqpTestConfiguration.class,
TestConfiguration.class, TestSupportBinderAutoConfiguration.class })
// Dirty context is necessary to create a new vhost and recreate all necessary
// beans after every test class.
@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
public abstract class AbstractAmqpIntegrationTest extends AbstractIntegrationTest {
private static final Duration TIMEOUT = Duration.ofSeconds(5);
@Rule
@Autowired
public BrokerRunning brokerRunning;
private static final Duration TIMEOUT = Duration.ofSeconds(5);
@Autowired
private ConnectionFactory connectionFactory;
@@ -51,7 +48,7 @@ public abstract class AbstractAmqpIntegrationTest extends AbstractIntegrationTes
private RabbitTemplate dmfClient;
@Before
@BeforeEach
public void setup() {
dmfClient = createDmfClient();
}

View File

@@ -17,16 +17,10 @@ import java.util.concurrent.TimeUnit;
import org.eclipse.hawkbit.HawkbitServerProperties;
import org.eclipse.hawkbit.api.HostnameResolver;
import org.eclipse.hawkbit.rabbitmq.test.RabbitMqSetupService.AlivenessException;
import org.eclipse.hawkbit.repository.jpa.model.helper.SystemSecurityContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.junit.BrokerRunning;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
@@ -43,8 +37,6 @@ import com.google.common.base.Throwables;
@Configuration
public class AmqpTestConfiguration {
private static final Logger LOG = LoggerFactory.getLogger(AmqpTestConfiguration.class);
@Bean
SystemSecurityContextHolder systemSecurityContextHolder() {
return SystemSecurityContextHolder.getInstance();
@@ -82,26 +74,13 @@ public class AmqpTestConfiguration {
}
@Bean
ConnectionFactory rabbitConnectionFactory(final RabbitMqSetupService rabbitmqSetupService) {
final CachingConnectionFactory factory = new CachingConnectionFactory();
factory.setHost(rabbitmqSetupService.getHostname());
factory.setPort(5672);
factory.setUsername(rabbitmqSetupService.getUsername());
factory.setPassword(rabbitmqSetupService.getPassword());
try {
factory.setVirtualHost(rabbitmqSetupService.createVirtualHost());
// All exception are catched. The BrokerRunning decide if the
// test should break or not
} catch (@SuppressWarnings("squid:S2221") final Exception e) {
Throwables.propagateIfInstanceOf(e, AlivenessException.class);
LOG.error("Cannot create virtual host.", e);
}
return factory;
ConnectionFactory rabbitConnectionFactory(RabbitMqSetupService rabbitMqSetupService) {
return rabbitMqSetupService.newVirtualHostWithConnectionFactory();
}
@Bean
RabbitMqSetupService rabbitmqSetupService(final RabbitProperties properties) {
return new RabbitMqSetupService(properties);
RabbitMqSetupService rabbitMqSetupService(){
return new RabbitMqSetupService();
}
@Bean
@@ -113,14 +92,4 @@ public class AmqpTestConfiguration {
rabbitTemplate.setReceiveTimeout(TimeUnit.SECONDS.toMillis(3));
return rabbitTemplate;
}
@Bean
BrokerRunning brokerRunning(final RabbitMqSetupService rabbitmqSetupService) {
final BrokerRunning brokerRunning = BrokerRunning.isRunning();
brokerRunning.setHostName(rabbitmqSetupService.getHostname());
brokerRunning.getConnectionFactory().setUsername(rabbitmqSetupService.getUsername());
brokerRunning.getConnectionFactory().setPassword(rabbitmqSetupService.getPassword());
return brokerRunning;
}
}

View File

@@ -14,10 +14,11 @@ import java.util.UUID;
import javax.annotation.PreDestroy;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.junit.BrokerRunningSupport;
import org.springframework.util.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Throwables;
import com.rabbitmq.http.client.Client;
import com.rabbitmq.http.client.domain.UserPermissions;
@@ -25,18 +26,15 @@ import com.rabbitmq.http.client.domain.UserPermissions;
/**
* Creates and deletes a new virtual host if the rabbit mq management api is
* available.
*
*/
// exception squid:S2068 - Test instance passwd
@SuppressWarnings("squid:S2068")
public class RabbitMqSetupService {
private static final String GUEST = "guest";
private static final String DEFAULT_USER = GUEST;
private static final String DEFAULT_PASSWORD = GUEST;
private Client rabbitmqHttpClient;
private final com.rabbitmq.client.ConnectionFactory connectionFactory;
private String virtualHost;
private final String hostname;
@@ -45,18 +43,13 @@ public class RabbitMqSetupService {
private String password;
public RabbitMqSetupService(final RabbitProperties properties) {
hostname = properties.getHost();
username = properties.getUsername();
if (StringUtils.isEmpty(username)) {
username = DEFAULT_USER;
}
password = properties.getPassword();
if (StringUtils.isEmpty(password)) {
password = DEFAULT_PASSWORD;
}
public RabbitMqSetupService() {
BrokerRunningSupport brokerSupport = BrokerRunningSupport.isRunning();
connectionFactory = brokerSupport.getConnectionFactory();
hostname = brokerSupport.getHostName();
username = brokerSupport.getUser();
password = brokerSupport.getPassword();
}
private synchronized Client getRabbitmqHttpClient() {
@@ -74,17 +67,12 @@ public class RabbitMqSetupService {
return "http://" + getHostname() + ":15672/api/";
}
@SuppressWarnings("squid:S1162")
public String createVirtualHost() throws JsonProcessingException {
if (!getRabbitmqHttpClient().alivenessTest("/")) {
throw new AlivenessException(getHostname());
}
public ConnectionFactory newVirtualHostWithConnectionFactory() {
virtualHost = UUID.randomUUID().toString();
getRabbitmqHttpClient().createVhost(virtualHost);
getRabbitmqHttpClient().updatePermissions(virtualHost, getUsername(), createUserPermissionsFullAccess());
return virtualHost;
connectionFactory.setVirtualHost(virtualHost);
return new CachingConnectionFactory(connectionFactory);
}
@PreDestroy
@@ -95,15 +83,15 @@ public class RabbitMqSetupService {
getRabbitmqHttpClient().deleteVhost(virtualHost);
}
public String getHostname() {
private String getHostname() {
return hostname;
}
public String getPassword() {
private String getPassword() {
return password;
}
public String getUsername() {
private String getUsername() {
return username;
}
@@ -115,14 +103,4 @@ public class RabbitMqSetupService {
permissions.setWrite(".*");
return permissions;
}
static class AlivenessException extends RuntimeException {
private static final long serialVersionUID = 1L;
public AlivenessException(final String hostname) {
super("Aliveness test failed for " + hostname
+ ":15672 guest/quest; rabbit mq management api not available");
}
}
}