A1 Policy Management Service - Introduction
*******************************************
-The A1 Policy Management Service ("Policy Agent") is an SMO/NONRTRIC service above the NONRTRIC A1 Adaptor/Controller
+The A1 Policy Management Service ("Policy Agent") is an SMO/NONRTRIC service above the NONRTRIC A1 Adapter/Controller
that provides:
* Unified REST & DMAAP APIs for managing A1 Policies in all Near |nbh| RT |nbsp| RICs
* Synchronized view of policy types in all Near |nbh| RT |nbsp| RICs
* Policy Query API (e.g. per Near |nbh| RT |nbsp| RIC, per "service", per policy type)
* An initial interface for unified Near |nbh| RT |nbsp| RIC ID to Near |nbh| RT |nbsp| RIC address mapping.
- (Note: may also later act as adaptor to A&AI, CMDBs etc. to "find" Near |nbh| RT |nbsp| RICs - TBC)
+ (Note: may also later act as adapter to A&AI, CMDBs etc. to "find" Near |nbh| RT |nbsp| RICs - TBC)
* An Initial "O1 ManagedElement" mapping database & interface to find appropriate Near |nbh| RT |nbsp| RIC for RAN elements.
- (Note: may also later act as adaptor to A&AI, RuntimeDB, other CMDBs etc. - TBC)
+ (Note: may also later act as adapter to A&AI, RuntimeDB, other CMDBs etc. - TBC)
* Monitors all Near |nbh| RT |nbsp| RICs and recovers from inconsistencies (Note: e.g. Near |nbh| RT |nbsp| RIC restarts)
* Support for different Southbound connectors on a per Near |nbh| RT |nbsp| RIC basis. (Note: e.g. different A1
versions, different Near |nbh| RT |nbsp| RIC versions, different A1 adapters, different or proprietary A1
Policies can be queried, created, updated, and deleted. A policy is always created in a specific
Near |nbh| RT |nbsp| RIC.
+A policy is defined by its policy type schema.
+
When a policy is created, the Policy Agent stores information about it in its internal repository. At regular intervals,
it then checks with all Near |nbh| RT |nbsp| RICs that this repository is synchronized. If, for some reason, there is an
-inconsistency, the Policy Agent will start a synchronization job and try to reflect the status of the
-Near |nbh| RT |nbsp| RIC. If this fails, the Policy Agent will delete all policies for the specific
-Near |nbh| RT |nbsp| RIC in the internal repository and set its state to *UNKNOWN*. This means that no interaction with
-the Near |nbh| RT |nbsp| RIC is possible until the Policy Agent has been able to contact it again and re-synchronize its
-state in the repository.
-
-A policy is defined by its type schema.
-
-Once a service has created a policy, it is the service's responsibility to maintain its life cycle. Since policies are
-transient, they will not survive a restart of a Near |nbh| RT |nbsp| RIC. But this is handled by the Policy Agent. When
-a Near |nbh| RT |nbsp| RIC has been restarted, the Policy Agent will try to recreate the policies in the
-Near |nbh| RT |nbsp| RIC that are stored in its local repository. This means that the service always must delete any
-policy it has created. There are only two exceptions, see below:
-
-- The service has registered a "*Keep Alive Interval*", then its policies will be deleted if it fails to notify the
- Policy Agent in due time.
-- The Policy Agent completely fails to synchronize with a Near |nbh| RT |nbsp| RIC.
+inconsistency, the Policy Agent will start a synchronization job and try to inconsistency, the Policy Agent will start a
+synchronization job and try to reset the Near |nbh| RT |nbsp| RIC to its last-known-good status. If this fails, the
+Policy Agent will clear all policies for the specific Near |nbh| RT |nbsp| RIC in the internal repository and set its
+state to *UNKNOWN*. This means that no interaction with the Near |nbh| RT |nbsp| RIC is possible until the Policy Agent
+has been able to contact it again and re-synchronize its state in the repository.
+
+Once a service has created a policy, it is the service's responsibility to maintain its life cycle. When a Near |nbh| RT
+|nbsp| RIC has been restarted, the Policy Agent will try to recreate policies in the Near |nbh| RT |nbsp| RIC according
+to the policies maintained in its local repository.
+This means that the service must delete any policies it has created.
+A policy may be created as a "transient policy", whereby if this policy "disappears" at any stage it will not be
+re-synchronized to the Near |nbh| RT |nbsp| RIC.
+For example, this is useful if the policy should not survive a restart of the Near |nbh| RT |nbsp| RIC.
+A non-transient policy will continue to be maintained in the Near |nbh| RT |nbsp| RIC until it is explicitly deleted
+(or the service that created it fails to update its Keep Alive status).
+
+There are some exceptions where policy instances are not re-synchronized after a Near |nbh| RT |nbsp| RIC restart or
+when some inconsistency is identified:
+
+- The service has registered a "*Keep Alive Interval*", but the service then fails to update its Keep Alive status.
+- The Policy Agent completely fails to synchronize with a Near |nbh| RT |nbsp| RIC, as described above.
+- Policies that are marked as transient policies.
/policies
~~~~~~~~~
The name of the service creating the policy.
+transient: (*Optional*)
+
+If the policy is transient or not (boolean defaulted to false).
+A policy is transient if it will be forgotten when the service needs to reconnect to the Near |nbh| RT |nbsp| RIC.
+
type: (*Optional*)
The name of the policy type.
endpoints:
web:
exposure:
- include: "loggers,logfile,health,info,metrics,threaddump"
+ include: "loggers,logfile,health,info,metrics,threaddump,heapdump"
logging:
level:
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.lang.Nullable;
import org.springframework.util.ResourceUtils;
+import org.springframework.web.reactive.function.client.ExchangeStrategies;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClient.RequestHeadersSpec;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Mono;
import reactor.netty.http.client.HttpClient;
+import reactor.netty.resources.ConnectionProvider;
import reactor.netty.tcp.TcpClient;
/**
}
private Mono<ResponseEntity<String>> retrieve(Object traceTag, RequestHeadersSpec<?> request) {
+ final Class<String> clazz = String.class;
return request.retrieve() //
- .toEntity(String.class) //
- .doOnNext(entity -> logger.trace("{} Received: {}", traceTag, entity.getBody()))
+ .toEntity(clazz) //
+ .doOnNext(entity -> logger.trace("{} Received: {}", traceTag, entity.getBody())) //
.doOnError(throwable -> onHttpError(traceTag, throwable));
}
}
private WebClient createWebClient(String baseUrl, SslContext sslContext) {
- TcpClient tcpClient = TcpClient.create() //
+ ConnectionProvider connectionProvider = ConnectionProvider.newConnection();
+ TcpClient tcpClient = TcpClient.create(connectionProvider) //
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10_000) //
.secure(c -> c.sslContext(sslContext)) //
+
.doOnConnected(connection -> {
connection.addHandlerLast(new ReadTimeoutHandler(30));
connection.addHandlerLast(new WriteTimeoutHandler(30));
HttpClient httpClient = HttpClient.from(tcpClient);
ReactorClientHttpConnector connector = new ReactorClientHttpConnector(httpClient);
+ ExchangeStrategies exchangeStrategies = ExchangeStrategies.builder() //
+ .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(-1)) //
+ .build();
+
return WebClient.builder() //
.clientConnector(connector) //
.baseUrl(baseUrl) //
+ .exchangeStrategies(exchangeStrategies) //
.build();
}
.policyTypeId(policy.type().name()) //
.policyInstanceId(policy.id()) //
.policyInstance(policy.json()) //
- .properties(new ArrayList<String>()) //
+ .properties(new ArrayList<>()) //
.build();
String inputJsonString = SdncJsonHelper.createInputJsonString(inputParams);
/**
* Constructor that creates the REST client to use.
*
- * @param protocolType the southbound protocol of the controller. Supported
- * protocols are SDNC_OSC_STD_V1_1 and SDNC_OSC_OSC_V1
+ * @param protocolType the southbound protocol of the controller. Supported protocols are SDNC_OSC_STD_V1_1 and
+ * SDNC_OSC_OSC_V1
* @param ricConfig the configuration of the Ric to communicate with
* @param controllerConfig the configuration of the SDNC controller to use
+ *
+ * @throws IllegalArgumentException when the protocolType is wrong.
*/
public SdncOscA1Client(A1ProtocolType protocolType, RicConfig ricConfig, ControllerConfig controllerConfig) {
this(protocolType, ricConfig, controllerConfig,
/**
* Constructor where the REST client to use is provided.
*
- * @param protocolType the southbound protocol of the controller. Supported
- * protocols are SDNC_OSC_STD_V1_1 and SDNC_OSC_OSC_V1
+ * @param protocolType the southbound protocol of the controller. Supported protocols are SDNC_OSC_STD_V1_1 and
+ * SDNC_OSC_OSC_V1
* @param ricConfig the configuration of the Ric to communicate with
* @param controllerConfig the configuration of the SDNC controller to use
* @param restClient the REST client to use
+ *
+ * @throws IllegalArgumentException when the protocolType is wrong.
*/
public SdncOscA1Client(A1ProtocolType protocolType, RicConfig ricConfig, ControllerConfig controllerConfig,
AsyncRestClient restClient) {
+ if (!(A1ProtocolType.SDNC_OSC_STD_V1_1.equals(protocolType)
+ || A1ProtocolType.SDNC_OSC_OSC_V1.equals(protocolType))) {
+ throw new IllegalArgumentException("Protocol type must be " + A1ProtocolType.SDNC_OSC_STD_V1_1 + " or "
+ + A1ProtocolType.SDNC_OSC_OSC_V1 + ", was: " + protocolType);
+ }
this.restClient = restClient;
this.ricConfig = ricConfig;
this.protocolType = protocolType;
public Mono<List<String>> getPolicyTypeIdentities() {
if (this.protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) {
return Mono.just(Arrays.asList(""));
- } else if (this.protocolType == A1ProtocolType.SDNC_OSC_OSC_V1) {
+ } else {
OscA1Client.UriBuilder uri = new OscA1Client.UriBuilder(ricConfig);
final String ricUrl = uri.createPolicyTypesUri();
return post(GET_POLICY_RPC, ricUrl, Optional.empty()) //
.flatMapMany(SdncJsonHelper::parseJsonArrayOfString) //
.collectList();
- } else {
- return Mono.error(createIllegalProtocolException());
}
}
- private Exception createIllegalProtocolException() {
- return new NullPointerException("Bug, unhandeled protocoltype: " + this.protocolType);
- }
-
@Override
public Mono<List<String>> getPolicyIdentities() {
return getPolicyIds() //
public Mono<String> getPolicyTypeSchema(String policyTypeId) {
if (this.protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) {
return Mono.just("{}");
- } else if (this.protocolType == A1ProtocolType.SDNC_OSC_OSC_V1) {
+ } else {
OscA1Client.UriBuilder uri = new OscA1Client.UriBuilder(ricConfig);
final String ricUrl = uri.createGetSchemaUri(policyTypeId);
return post(GET_POLICY_RPC, ricUrl, Optional.empty()) //
.flatMap(response -> OscA1Client.extractCreateSchema(response, policyTypeId));
- } else {
- return Mono.error(createIllegalProtocolException());
}
}
if (this.protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) {
return getPolicyIds() //
.flatMap(policyId -> deletePolicyById("", policyId), CONCURRENCY_RIC); //
- } else if (this.protocolType == A1ProtocolType.SDNC_OSC_OSC_V1) {
+ } else {
OscA1Client.UriBuilder uriBuilder = new OscA1Client.UriBuilder(ricConfig);
return getPolicyTypeIdentities() //
.flatMapMany(Flux::fromIterable) //
.flatMap(type -> oscDeleteInstancesForType(uriBuilder, type), CONCURRENCY_RIC);
- } else {
- return Flux.error(createIllegalProtocolException());
}
}
private Mono<A1UriBuilder> getUriBuilder() {
if (protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) {
return Mono.just(new StdA1ClientVersion1.UriBuilder(ricConfig));
- } else if (this.protocolType == A1ProtocolType.SDNC_OSC_OSC_V1) {
- return Mono.just(new OscA1Client.UriBuilder(ricConfig));
} else {
- return Mono.error(createIllegalProtocolException());
+ return Mono.just(new OscA1Client.UriBuilder(ricConfig));
}
}
final String ricUrl = uri.createGetPolicyIdsUri();
return post(GET_POLICY_RPC, ricUrl, Optional.empty()) //
.flatMapMany(SdncJsonHelper::parseJsonArrayOfString);
- } else if (this.protocolType == A1ProtocolType.SDNC_OSC_OSC_V1) {
+ } else {
OscA1Client.UriBuilder uri = new OscA1Client.UriBuilder(ricConfig);
return getPolicyTypeIdentities() //
.flatMapMany(Flux::fromIterable)
.flatMap(type -> post(GET_POLICY_RPC, uri.createGetPolicyIdsUri(type), Optional.empty())) //
.flatMap(SdncJsonHelper::parseJsonArrayOfString);
- } else {
- return Flux.error(createIllegalProtocolException());
}
}
} else {
logger.debug("Error response: {} {}", output.httpStatus(), body);
byte[] responseBodyBytes = body.getBytes(StandardCharsets.UTF_8);
- WebClientResponseException e = new WebClientResponseException(output.httpStatus(), "statusText", null,
- responseBodyBytes, StandardCharsets.UTF_8, null);
+ WebClientResponseException responseException = new WebClientResponseException(output.httpStatus(),
+ "statusText", null, responseBodyBytes, StandardCharsets.UTF_8, null);
- return Mono.error(e);
+ return Mono.error(responseException);
}
}
JsonObject agentConfigJson = root.getAsJsonObject(CONFIG);
+ if (agentConfigJson == null) {
+ throw new ServiceException("Missing root configuration \"" + CONFIG + "\" in JSON: " + root);
+ }
+
JsonObject json = agentConfigJson.getAsJsonObject("streams_publishes");
if (json != null) {
dmaapPublisherConfig = parseDmaapConfig(json);
public synchronized void put(Service service) {
logger.debug("Put service: {}", service.getName());
+ service.keepAlive();
registeredServices.put(service.getName(), service);
}
import org.oransc.policyagent.configuration.ApplicationConfig.RicConfigUpdate;
import org.oransc.policyagent.configuration.ApplicationConfigParser;
import org.oransc.policyagent.configuration.RicConfig;
-import org.oransc.policyagent.exceptions.ServiceException;
import org.oransc.policyagent.repository.Policies;
import org.oransc.policyagent.repository.PolicyTypes;
import org.oransc.policyagent.repository.Ric;
import reactor.core.publisher.Mono;
/**
- * Regularly refreshes the configuration from Consul or from a local
- * configuration file.
+ * Regularly refreshes the configuration from Consul or from a local configuration file.
*/
@Component
public class RefreshConfigTask {
}
private Mono<JsonObject> getFromCbs(CbsClient cbsClient) {
- final CbsRequest getConfigRequest = CbsRequests.getAll(RequestDiagnosticContext.create());
try {
+ final CbsRequest getConfigRequest = CbsRequests.getAll(RequestDiagnosticContext.create());
return cbsClient.get(getConfigRequest) //
.onErrorResume(this::ignoreErrorMono);
} catch (Exception e) {
appParser.parse(rootObject);
logger.debug("Local configuration file loaded: {}", filepath);
return Flux.just(rootObject);
- } catch (IOException | ServiceException e) {
+ } catch (Exception e) {
logger.error("Local configuration file not loaded: {}, {}", filepath, e.getMessage());
return Flux.empty();
}
@SuppressWarnings("squid:S2629") // Invoke method(s) only conditionally
public class ServiceSupervision {
private static final Logger logger = LoggerFactory.getLogger(ServiceSupervision.class);
+ static final int CONCURRENCY_RIC = 1; // How may paralell requests that is sent
private final Services services;
private final Policies policies;
private A1ClientFactory a1ClientFactory;
.doOnNext(service -> logger.info("Service is expired: {}", service.getName())) //
.doOnNext(service -> services.remove(service.getName())) //
.flatMap(this::getAllPoliciesForService) //
- .flatMap(this::deletePolicy);
+ .flatMap(this::deletePolicy, CONCURRENCY_RIC);
}
@SuppressWarnings("squid:S2629") // Invoke method(s) only conditionally
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
-public class ApplicationTest {
+class ApplicationTest {
private static final Logger logger = LoggerFactory.getLogger(ApplicationTest.class);
@Autowired
private int port;
@BeforeEach
- public void reset() {
+ void reset() {
rics.clear();
policies.clear();
policyTypes.clear();
}
@AfterEach
- public void verifyNoRicLocks() {
+ void verifyNoRicLocks() {
for (Ric ric : this.rics.getRics()) {
ric.getLock().lockBlocking(LockType.EXCLUSIVE);
ric.getLock().unlockBlocking();
}
@Test
- public void testGetRics() throws Exception {
+ void testGetRics() throws Exception {
addRic("ric1");
this.addPolicyType("type1", "ric1");
String url = "/rics?policyType=type1";
}
@Test
- public void testSynchronization() throws Exception {
+ void testSynchronization() throws Exception {
// Two polictypes will be put in the NearRT RICs
PolicyTypes nearRtRicPolicyTypes = new PolicyTypes();
nearRtRicPolicyTypes.put(createPolicyType("typeName"));
}
@Test
- public void testGetRicForManagedElement_thenReturnCorrectRic() throws Exception {
+ void testGetRicForManagedElement_thenReturnCorrectRic() throws Exception {
String ricName = "ric1";
String managedElementId = "kista_1";
addRic(ricName, managedElementId);
}
@Test
- public void testPutPolicy() throws Exception {
+ void testPutPolicy() throws Exception {
String serviceName = "service1";
String ricName = "ric1";
String policyTypeName = "type1";
*
* @throws ServiceException
*/
- public void testErrorFromRIC() throws ServiceException {
+ void testErrorFromRIC() throws ServiceException {
putService("service1");
addPolicyType("type1", "ric1");
}
@Test
- public void testPutTypelessPolicy() throws Exception {
+ void testPutTypelessPolicy() throws Exception {
putService("service1");
addPolicyType("", "ric1");
String url = putPolicyUrl("service1", "ric1", "", "id1");
}
@Test
- public void testRefuseToUpdatePolicy() throws Exception {
+ void testRefuseToUpdatePolicy() throws Exception {
// Test that only the json can be changed for a already created policy
// In this case service is attempted to be changed
this.addRic("ric1");
}
@Test
- public void testGetPolicy() throws Exception {
+ void testGetPolicy() throws Exception {
String url = "/policy?id=id";
Policy policy = addPolicy("id", "typeName", "service1", "ric1");
{
}
@Test
- public void testDeletePolicy() throws Exception {
+ void testDeletePolicy() throws Exception {
addPolicy("id", "typeName", "service1", "ric1");
assertThat(policies.size()).isEqualTo(1);
}
@Test
- public void testGetPolicySchemas() throws Exception {
+ void testGetPolicySchemas() throws Exception {
addPolicyType("type1", "ric1");
addPolicyType("type2", "ric2");
}
@Test
- public void testGetPolicySchema() throws Exception {
+ void testGetPolicySchema() throws Exception {
addPolicyType("type1", "ric1");
addPolicyType("type2", "ric2");
}
@Test
- public void testGetPolicyTypes() throws Exception {
+ void testGetPolicyTypes() throws Exception {
addPolicyType("type1", "ric1");
addPolicyType("type2", "ric2");
}
@Test
- public void testGetPolicies() throws Exception {
+ void testGetPolicies() throws Exception {
addPolicy("id1", "type1", "service1");
String url = "/policies";
}
@Test
- public void testGetPoliciesFilter() throws Exception {
+ void testGetPoliciesFilter() throws Exception {
addPolicy("id1", "type1", "service1");
addPolicy("id2", "type1", "service2");
addPolicy("id3", "type2", "service1");
}
@Test
- public void testGetPolicyIdsFilter() throws Exception {
+ void testGetPolicyIdsFilter() throws Exception {
addPolicy("id1", "type1", "service1", "ric1");
addPolicy("id2", "type1", "service2", "ric1");
addPolicy("id3", "type2", "service1", "ric1");
}
@Test
- public void testPutAndGetService() throws Exception {
+ void testPutAndGetService() throws Exception {
// PUT
putService("name", 0, HttpStatus.CREATED);
putService("name", 0, HttpStatus.OK);
}
@Test
- public void testServiceSupervision() throws Exception {
+ void testServiceSupervision() throws Exception {
putService("service1", 1, HttpStatus.CREATED);
addPolicyType("type1", "ric1");
}
@Test
- public void testGetPolicyStatus() throws Exception {
+ void testGetPolicyStatus() throws Exception {
addPolicy("id", "typeName", "service1", "ric1");
assertThat(policies.size()).isEqualTo(1);
}
@Test
- public void testConcurrency() throws Exception {
+ void testConcurrency() throws Exception {
final Instant startTime = Instant.now();
List<Thread> threads = new ArrayList<>();
a1ClientFactory.setResponseDelay(Duration.ofMillis(1));
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
-public class MockPolicyAgent {
+class MockPolicyAgent {
private static final Logger logger = LoggerFactory.getLogger(MockPolicyAgent.class);
@Autowired
@Test
@SuppressWarnings("squid:S2699") // Tests should include assertions. This test is only for keeping the server
- // alive,
- // so it will only be confusing to add an assertion.
- public void runMock() throws Exception {
+ // alive, so it will only be confusing to add an assertion.
+ void runMock() throws Exception {
keepServerAlive();
}
--- /dev/null
+package org.oransc.policyagent.aspect;
+
+import static ch.qos.logback.classic.Level.TRACE;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import ch.qos.logback.classic.spi.ILoggingEvent;
+import ch.qos.logback.core.read.ListAppender;
+
+import org.aspectj.lang.ProceedingJoinPoint;
+import org.aspectj.lang.reflect.MethodSignature;
+import org.junit.Rule;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnit;
+import org.mockito.junit.MockitoRule;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.oransc.policyagent.utils.LoggingUtils;
+
+@ExtendWith(MockitoExtension.class)
+class LogAspectTest {
+ @Rule
+ MockitoRule mockitoRule = MockitoJUnit.rule();
+
+ @Mock
+ private ProceedingJoinPoint proceedingJoinPoint;
+
+ @Mock
+ private MethodSignature methodSignature;
+
+ private LogAspect sampleAspect = new LogAspect();
+
+ @Test
+ void testExecutetimeTime_shouldLogTime() throws Throwable {
+ when(proceedingJoinPoint.getSignature()).thenReturn(methodSignature);
+ when(methodSignature.getDeclaringType()).thenReturn(this.getClass());
+
+ final ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(LogAspect.class, TRACE);
+
+ sampleAspect.executimeTime(proceedingJoinPoint);
+ // 'proceed()' is called exactly once
+ verify(proceedingJoinPoint, times(1)).proceed();
+ // 'proceed(Object[])' is never called
+ verify(proceedingJoinPoint, never()).proceed(null);
+
+ assertThat(logAppender.list.toString().contains("Execution time of")).isTrue();
+ }
+
+ @Test
+ void testEntryLog_shouldLogEntry() throws Throwable {
+ when(proceedingJoinPoint.getSignature()).thenReturn(methodSignature);
+ String signature = "signature";
+ when(methodSignature.getName()).thenReturn(signature);
+
+ final ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(LogAspect.class, TRACE);
+
+ sampleAspect.entryLog(proceedingJoinPoint);
+
+ assertThat(logAppender.list.toString().contains("Entering method: " + signature)).isTrue();
+ }
+
+ @Test
+ void testExitLog_shouldLogExit() throws Throwable {
+ when(proceedingJoinPoint.getSignature()).thenReturn(methodSignature);
+ String signature = "signature";
+ when(methodSignature.getName()).thenReturn(signature);
+
+ final ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(LogAspect.class, TRACE);
+
+ sampleAspect.exitLog(proceedingJoinPoint);
+
+ assertThat(logAppender.list.toString().contains("Exiting method: " + signature)).isTrue();
+ }
+}
import reactor.test.StepVerifier;
@ExtendWith(MockitoExtension.class)
-public class A1ClientFactoryTest {
+class A1ClientFactoryTest {
private static final String RIC_NAME = "Name";
private static final String EXCEPTION_MESSAGE = "Error";
}
@BeforeEach
- public void createFactoryUnderTest() {
+ void createFactoryUnderTest() {
factoryUnderTest = spy(new A1ClientFactory(applicationConfigMock));
this.ric = new Ric(ricConfig(""));
}
@Test
- public void getProtocolVersion_ok() throws ServiceException {
+ void getProtocolVersion_ok() throws ServiceException {
whenGetProtocolVersionThrowException(clientMock1);
whenGetProtocolVersionReturn(clientMock2, A1ProtocolType.STD_V1_1);
doReturn(clientMock1, clientMock2).when(factoryUnderTest).createClient(any(), any());
}
@Test
- public void getProtocolVersion_ok_Last() throws ServiceException {
+ void getProtocolVersion_ok_Last() throws ServiceException {
whenGetProtocolVersionThrowException(clientMock1, clientMock2, clientMock3);
whenGetProtocolVersionReturn(clientMock4, A1ProtocolType.STD_V1_1);
doReturn(clientMock1, clientMock2, clientMock3, clientMock4).when(factoryUnderTest).createClient(any(), any());
}
@Test
- public void getProtocolVersion_error() throws ServiceException {
+ void getProtocolVersion_error() throws ServiceException {
whenGetProtocolVersionThrowException(clientMock1, clientMock2, clientMock3, clientMock4);
doReturn(clientMock1, clientMock2, clientMock3, clientMock4).when(factoryUnderTest).createClient(any(), any());
}
@Test
- public void create_check_types() throws ServiceException {
+ void create_check_types() throws ServiceException {
assertTrue(createClient(A1ProtocolType.STD_V1_1) instanceof StdA1ClientVersion1);
assertTrue(createClient(A1ProtocolType.OSC_V1) instanceof OscA1Client);
}
@Test
- public void create_check_types_controllers() throws ServiceException {
+ void create_check_types_controllers() throws ServiceException {
this.ric = new Ric(ricConfig("anythingButEmpty"));
whenGetGetControllerConfigReturn();
assertTrue(createClient(A1ProtocolType.SDNC_ONAP) instanceof SdncOnapA1Client);
import reactor.test.StepVerifier;
import reactor.util.Loggers;
-public class AsyncRestClientTest {
+class AsyncRestClientTest {
private static final String BASE_URL = "BaseUrl";
private static final String REQUEST_URL = "/test";
private static final String USERNAME = "username";
private static AsyncRestClient clientUnderTest;
@BeforeAll
- public static void init() {
+ static void init() {
// skip a lot of unnecessary logs from MockWebServer
InternalLoggerFactory.setDefaultFactory(JdkLoggerFactory.INSTANCE);
Loggers.useJdkLoggers();
}
@AfterAll
- public static void tearDown() throws IOException {
+ static void tearDown() throws IOException {
mockWebServer.shutdown();
}
@Test
- public void testGetNoError() {
+ void testGetNoError() {
mockWebServer.enqueue(new MockResponse().setResponseCode(SUCCESS_CODE) //
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) //
.setBody(TEST_JSON));
}
@Test
- public void testGetError() {
+ void testGetError() {
mockWebServer.enqueue(new MockResponse().setResponseCode(ERROR_CODE));
Mono<String> returnedMono = clientUnderTest.get(REQUEST_URL);
}
@Test
- public void testPutNoError() {
+ void testPutNoError() {
mockWebServer.enqueue(new MockResponse().setResponseCode(SUCCESS_CODE) //
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) //
.setBody(TEST_JSON));
}
@Test
- public void testPutError() {
+ void testPutError() {
mockWebServer.enqueue(new MockResponse().setResponseCode(ERROR_CODE));
Mono<String> returnedMono = clientUnderTest.put(REQUEST_URL, TEST_JSON);
}
@Test
- public void testDeleteNoError() {
+ void testDeleteNoError() {
mockWebServer.enqueue(new MockResponse().setResponseCode(SUCCESS_CODE));
Mono<String> returnedMono = clientUnderTest.delete(REQUEST_URL);
}
@Test
- public void testDeleteError() {
+ void testDeleteError() {
mockWebServer.enqueue(new MockResponse().setResponseCode(ERROR_CODE));
Mono<String> returnedMono = clientUnderTest.delete(REQUEST_URL);
}
@Test
- public void testPostNoError() {
+ void testPostNoError() {
mockWebServer.enqueue(new MockResponse().setResponseCode(SUCCESS_CODE) //
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) //
.setBody(TEST_JSON));
}
@Test
- public void testPostError() {
+ void testPostError() {
mockWebServer.enqueue(new MockResponse().setResponseCode(ERROR_CODE));
Mono<String> returnedMono = clientUnderTest.post(REQUEST_URL, TEST_JSON);
}
@Test
- public void testPostWithAuthHeaderNoError() {
+ void testPostWithAuthHeaderNoError() {
mockWebServer.enqueue(new MockResponse().setResponseCode(SUCCESS_CODE) //
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) //
.setBody(TEST_JSON));
}
@Test
- public void testPostWithAuthHeaderError() {
+ void testPostWithAuthHeaderError() {
mockWebServer.enqueue(new MockResponse().setResponseCode(ERROR_CODE));
Mono<String> returnedMono = clientUnderTest.postWithAuthHeader(REQUEST_URL, TEST_JSON, USERNAME, PASSWORD);
import reactor.test.StepVerifier;
@ExtendWith(MockitoExtension.class)
-public class OscA1ClientTest {
+class OscA1ClientTest {
private static final String RIC_URL = "RicUrl";
AsyncRestClient asyncRestClientMock;
@BeforeEach
- public void init() {
+ void init() {
RicConfig ricConfig = ImmutableRicConfig.builder() //
.name("name") //
.baseUrl("RicBaseUrl") //
}
@Test
- public void testGetPolicyTypeIdentities() {
+ void testGetPolicyTypeIdentities() {
List<String> policyTypeIds = Arrays.asList(POLICY_TYPE_1_ID, POLICY_TYPE_2_ID);
Mono<String> policyTypeIdsResp = Mono.just(policyTypeIds.toString());
when(asyncRestClientMock.get(anyString())).thenReturn(policyTypeIdsResp);
}
@Test
- public void testGetPolicyIdentities() {
+ void testGetPolicyIdentities() {
Mono<String> policyTypeIdsResp = Mono.just(Arrays.asList(POLICY_TYPE_1_ID, POLICY_TYPE_2_ID).toString());
Mono<String> policyIdsType1Resp = Mono.just(Arrays.asList(POLICY_1_ID).toString());
Mono<String> policyIdsType2Resp = Mono.just(Arrays.asList(POLICY_2_ID).toString());
}
@Test
- public void testGetValidPolicyType() {
+ void testGetValidPolicyType() {
String policyType = "{\"create_schema\": " + POLICY_TYPE_SCHEMA_VALID + "}";
Mono<String> policyTypeResp = Mono.just(policyType);
}
@Test
- public void testGetInValidPolicyTypeJson() {
+ void testGetInValidPolicyTypeJson() {
String policyType = "{\"create_schema\": " + POLICY_TYPE_SCHEMA_INVALID + "}";
Mono<String> policyTypeResp = Mono.just(policyType);
}
@Test
- public void testGetPolicyTypeWithoutCreateSchema() {
+ void testGetPolicyTypeWithoutCreateSchema() {
Mono<String> policyTypeResp = Mono.just(POLICY_TYPE_SCHEMA_VALID);
when(asyncRestClientMock.get(anyString())).thenReturn(policyTypeResp);
}
@Test
- public void testPutPolicy() {
+ void testPutPolicy() {
when(asyncRestClientMock.put(anyString(), anyString())).thenReturn(Mono.empty());
clientUnderTest
}
@Test
- public void testDeletePolicy() {
+ void testDeletePolicy() {
when(asyncRestClientMock.delete(anyString())).thenReturn(Mono.empty());
Mono<String> returnedMono = clientUnderTest
}
@Test
- public void testDeleteAllPolicies() {
+ void testDeleteAllPolicies() {
Mono<String> policyTypeIdsResp = Mono.just(Arrays.asList(POLICY_TYPE_1_ID, POLICY_TYPE_2_ID).toString());
Mono<String> policyIdsType1Resp = Mono.just(Arrays.asList(POLICY_1_ID).toString());
Mono<String> policyIdsType2Resp = Mono.just(Arrays.asList(POLICY_2_ID).toString());
import reactor.test.StepVerifier;
@ExtendWith(MockitoExtension.class)
-public class SdncOnapA1ClientTest {
+class SdncOnapA1ClientTest {
private static final String CONTROLLER_USERNAME = "username";
private static final String CONTROLLER_PASSWORD = "password";
private static final String RIC_1_URL = "RicUrl";
AsyncRestClient asyncRestClientMock;
@BeforeEach
- public void init() {
+ void init() {
asyncRestClientMock = mock(AsyncRestClient.class);
ControllerConfig controllerCfg = ImmutableControllerConfig.builder() //
.name("name") //
}
@Test
- public void testGetPolicyTypeIdentities() {
+ void testGetPolicyTypeIdentities() {
SdncOnapA1Client.SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() //
.nearRtRicId(RIC_1_URL) //
.build();
}
@Test
- public void testGetPolicyIdentities() {
+ void testGetPolicyIdentities() {
SdncOnapA1Client.SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() //
.nearRtRicId(RIC_1_URL) //
.build();
}
@Test
- public void testGetValidPolicyType() {
+ void testGetValidPolicyType() {
SdncOnapA1Client.SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() //
.nearRtRicId(RIC_1_URL) //
.policyTypeId(POLICY_TYPE_1_ID) //
}
@Test
- public void testGetInvalidPolicyType() {
+ void testGetInvalidPolicyType() {
SdncOnapA1Client.SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() //
.nearRtRicId(RIC_1_URL) //
.policyTypeId(POLICY_TYPE_1_ID) //
}
@Test
- public void testPutPolicy() {
+ void testPutPolicy() {
SdncOnapA1Client.SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() //
.nearRtRicId(RIC_1_URL) //
.policyTypeId(POLICY_TYPE_1_ID) //
}
@Test
- public void testDeletePolicy() {
+ void testDeletePolicy() {
SdncOnapA1Client.SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() //
.nearRtRicId(RIC_1_URL) //
.policyTypeId(POLICY_TYPE_1_ID) //
}
@Test
- public void testDeleteAllPolicies() {
+ void testDeleteAllPolicies() {
SdncOnapA1Client.SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() //
.nearRtRicId(RIC_1_URL) //
.build();
package org.oransc.policyagent.clients;
+import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
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.jupiter.MockitoExtension;
import org.mockito.stubbing.OngoingStubbing;
import org.oransc.policyagent.clients.A1Client.A1ProtocolType;
+import org.oransc.policyagent.clients.ImmutableAdapterOutput.Builder;
import org.oransc.policyagent.clients.SdncOscA1Client.AdapterOutput;
import org.oransc.policyagent.clients.SdncOscA1Client.AdapterRequest;
import org.oransc.policyagent.configuration.ControllerConfig;
import org.oransc.policyagent.configuration.ImmutableControllerConfig;
import org.oransc.policyagent.repository.Policy;
import org.oransc.policyagent.repository.Ric;
+import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
@ExtendWith(MockitoExtension.class)
-public class SdncOscA1ClientTest {
+class SdncOscA1ClientTest {
private static final String CONTROLLER_USERNAME = "username";
private static final String CONTROLLER_PASSWORD = "password";
private static final String RIC_1_URL = "RicUrl";
SdncOscA1Client clientUnderTest;
+ @Mock
AsyncRestClient asyncRestClientMock;
private ControllerConfig controllerConfig() {
}
@BeforeEach
- public void init() {
- asyncRestClientMock = mock(AsyncRestClient.class);
+ void init() {
Ric ric = A1ClientHelper.createRic(RIC_1_URL);
clientUnderTest = new SdncOscA1Client(A1ProtocolType.SDNC_OSC_STD_V1_1, ric.getConfig(), controllerConfig(),
}
@Test
- public void testGetPolicyTypeIdentities_STD() {
+ void createClientWithWrongProtocol_thenErrorIsThrown() {
+ try {
+ new SdncOscA1Client(A1ProtocolType.STD_V1_1, null, null, null);
+ fail("Should have thrown exception.");
+ } catch (IllegalArgumentException e) {
+ return;
+ }
+ }
+
+ @Test
+ void getPolicyTypeIdentities_STD() {
List<String> policyTypeIds = clientUnderTest.getPolicyTypeIdentities().block();
assertEquals(1, policyTypeIds.size(), "should hardcoded to one");
assertEquals("", policyTypeIds.get(0), "should hardcoded to empty");
}
@Test
- public void testGetPolicyTypeIdentities_OSC() {
+ void getPolicyTypeIdentities_OSC() {
clientUnderTest = new SdncOscA1Client(A1ProtocolType.SDNC_OSC_OSC_V1, //
A1ClientHelper.createRic(RIC_1_URL).getConfig(), //
controllerConfig(), asyncRestClientMock);
- String response = createResponse(Arrays.asList(POLICY_TYPE_1_ID));
+ String response = createOkResponseWithBody(Arrays.asList(POLICY_TYPE_1_ID));
whenAsyncPostThenReturn(Mono.just(response));
List<String> policyTypeIds = clientUnderTest.getPolicyTypeIdentities().block();
+
assertEquals(1, policyTypeIds.size(), "");
assertEquals(POLICY_TYPE_1_ID, policyTypeIds.get(0), "");
CONTROLLER_PASSWORD);
}
- private String loadFile(String fileName) throws IOException {
- ClassLoader loader = Thread.currentThread().getContextClassLoader();
- URL url = loader.getResource(fileName);
- File file = new File(url.getFile());
- return new String(Files.readAllBytes(file.toPath()));
+ @Test
+ void getTypeSchema_STD() {
+ String policyType = clientUnderTest.getPolicyTypeSchema("").block();
+
+ assertEquals("{}", policyType, "");
}
@Test
- public void testGetTypeSchema_OSC() throws IOException {
+ void getTypeSchema_OSC() throws IOException {
clientUnderTest = new SdncOscA1Client(A1ProtocolType.SDNC_OSC_OSC_V1, //
A1ClientHelper.createRic(RIC_1_URL).getConfig(), //
controllerConfig(), asyncRestClientMock);
String ricResponse = loadFile("test_osc_get_schema_response.json");
JsonElement elem = gson().fromJson(ricResponse, JsonElement.class);
- String responseFromController = createResponse(elem);
+ String responseFromController = createOkResponseWithBody(elem);
whenAsyncPostThenReturn(Mono.just(responseFromController));
String response = clientUnderTest.getPolicyTypeSchema("policyTypeId").block();
+
JsonElement respJson = gson().fromJson(response, JsonElement.class);
assertEquals("policyTypeId", respJson.getAsJsonObject().get("title").getAsString(),
"title should be updated to contain policyType ID");
assertEquals("1", result.get(1), "");
}
- private String policiesUrl() {
- return RIC_1_URL + "/A1-P/v1/policies";
- }
-
- private Gson gson() {
- return SdncOscA1Client.gson;
- }
-
- private String createResponse(Object body) {
- AdapterOutput output = ImmutableAdapterOutput.builder() //
- .body(gson().toJson(body)) //
- .httpStatus(200) //
- .build();
- return SdncJsonHelper.createOutputJsonString(output);
- }
-
@Test
- public void testGetPolicyIdentities() {
+ void getPolicyIdentities_STD() {
- String policyIdsResp = createResponse(Arrays.asList(POLICY_1_ID, POLICY_2_ID));
+ String policyIdsResp = createOkResponseWithBody(Arrays.asList(POLICY_1_ID, POLICY_2_ID));
whenAsyncPostThenReturn(Mono.just(policyIdsResp));
List<String> returned = clientUnderTest.getPolicyIdentities().block();
+
assertEquals(2, returned.size(), "");
ImmutableAdapterRequest expectedParams = ImmutableAdapterRequest.builder() //
}
@Test
- public void testGetValidPolicyType() {
- String policyType = clientUnderTest.getPolicyTypeSchema("").block();
- assertEquals("{}", policyType, "");
+ void getPolicyIdentities_OSC() {
+ clientUnderTest = new SdncOscA1Client(A1ProtocolType.SDNC_OSC_OSC_V1, //
+ A1ClientHelper.createRic(RIC_1_URL).getConfig(), //
+ controllerConfig(), asyncRestClientMock);
+
+ String policytypeIdsResp = createOkResponseWithBody(Arrays.asList(POLICY_TYPE_1_ID));
+ String policyIdsResp = createOkResponseWithBody(Arrays.asList(POLICY_1_ID, POLICY_2_ID));
+ whenAsyncPostThenReturn(Mono.just(policytypeIdsResp)).thenReturn(Mono.just(policyIdsResp));
+
+ List<String> returned = clientUnderTest.getPolicyIdentities().block();
+
+ assertEquals(2, returned.size(), "");
+
+ ImmutableAdapterRequest expectedParams = ImmutableAdapterRequest.builder() //
+ .nearRtRicUrl(RIC_1_URL + "/a1-p/policytypes/type1/policies") //
+ .build();
+ String expInput = SdncJsonHelper.createInputJsonString(expectedParams);
+ verify(asyncRestClientMock).postWithAuthHeader(GET_A1_POLICY_URL, expInput, CONTROLLER_USERNAME,
+ CONTROLLER_PASSWORD);
}
@Test
- public void testPutPolicyValidResponse() {
+ void putPolicyValidResponse() {
whenPostReturnOkResponse();
String returned = clientUnderTest
.putPolicy(A1ClientHelper.createPolicy(RIC_1_URL, POLICY_1_ID, POLICY_JSON_VALID, POLICY_TYPE_1_ID))
.block();
+
assertEquals("OK", returned, "");
final String expUrl = policiesUrl() + "/" + POLICY_1_ID;
AdapterRequest expectedInputParams = ImmutableAdapterRequest.builder() //
}
@Test
- public void testPutPolicyRejected() {
+ void putPolicyRejected() {
final String policyJson = "{}";
AdapterOutput adapterOutput = ImmutableAdapterOutput.builder() //
.body("NOK") //
- .httpStatus(400) // ERROR
+ .httpStatus(HttpStatus.BAD_REQUEST.value()) // ERROR
.build();
String resp = SdncJsonHelper.createOutputJsonString(adapterOutput);
}
@Test
- public void testDeletePolicy() {
+ void deletePolicy() {
whenPostReturnOkResponse();
String returned = clientUnderTest
.deletePolicy(A1ClientHelper.createPolicy(RIC_1_URL, POLICY_1_ID, POLICY_JSON_VALID, POLICY_TYPE_1_ID))
.block();
+
assertEquals("OK", returned, "");
final String expUrl = policiesUrl() + "/" + POLICY_1_ID;
AdapterRequest expectedInputParams = ImmutableAdapterRequest.builder() //
}
@Test
- public void testGetStatus() {
+ void getStatus() {
whenPostReturnOkResponse();
Policy policy = A1ClientHelper.createPolicy(RIC_1_URL, POLICY_1_ID, POLICY_JSON_VALID, POLICY_TYPE_1_ID);
}
@Test
- public void testGetVersion() {
+ void getVersion_STD() {
whenPostReturnOkResponse();
+
A1ProtocolType returnedVersion = clientUnderTest.getProtocolVersion().block();
- assertEquals(A1ProtocolType.SDNC_OSC_STD_V1_1, returnedVersion, "");
+
+ assertEquals(A1ProtocolType.SDNC_OSC_STD_V1_1, returnedVersion);
whenPostReturnOkResponseNoBody();
+
returnedVersion = clientUnderTest.getProtocolVersion().block();
- assertEquals(A1ProtocolType.SDNC_OSC_STD_V1_1, returnedVersion, "");
+
+ assertEquals(A1ProtocolType.SDNC_OSC_STD_V1_1, returnedVersion);
}
- private void whenPostReturnOkResponse() {
- AdapterOutput adapterOutput = ImmutableAdapterOutput.builder() //
- .body("OK") //
- .httpStatus(200) //
- .build();
+ @Test
+ void getVersion_OSC() {
+ clientUnderTest = new SdncOscA1Client(A1ProtocolType.SDNC_OSC_OSC_V1, //
+ A1ClientHelper.createRic(RIC_1_URL).getConfig(), //
+ controllerConfig(), asyncRestClientMock);
- String resp = SdncJsonHelper.createOutputJsonString(adapterOutput);
- whenAsyncPostThenReturn(Mono.just(resp));
+ whenAsyncPostThenReturn(Mono.error(new Exception("Error"))).thenReturn(Mono.just(createOkResponseString(true)));
+
+ A1ProtocolType returnedVersion = clientUnderTest.getProtocolVersion().block();
+
+ assertEquals(A1ProtocolType.SDNC_OSC_OSC_V1, returnedVersion);
+ }
+
+ private String policiesUrl() {
+ return RIC_1_URL + "/A1-P/v1/policies";
+ }
+
+ private Gson gson() {
+ return SdncOscA1Client.gson;
+ }
+
+ private String loadFile(String fileName) throws IOException {
+ ClassLoader loader = Thread.currentThread().getContextClassLoader();
+ URL url = loader.getResource(fileName);
+ File file = new File(url.getFile());
+ return new String(Files.readAllBytes(file.toPath()));
+ }
+
+ private void whenPostReturnOkResponse() {
+ whenAsyncPostThenReturn(Mono.just(createOkResponseString(true)));
}
private void whenPostReturnOkResponseNoBody() {
- AdapterOutput adapterOutput = ImmutableAdapterOutput.builder() //
- .httpStatus(200) //
- .body(Optional.empty()) //
+ whenAsyncPostThenReturn(Mono.just(createOkResponseString(false)));
+ }
+
+ private String createOkResponseWithBody(Object body) {
+ AdapterOutput output = ImmutableAdapterOutput.builder() //
+ .body(gson().toJson(body)) //
+ .httpStatus(HttpStatus.OK.value()) //
.build();
+ return SdncJsonHelper.createOutputJsonString(output);
+ }
- String resp = SdncJsonHelper.createOutputJsonString(adapterOutput);
- whenAsyncPostThenReturn(Mono.just(resp));
+ private String createOkResponseString(boolean withBody) {
+ Builder responseBuilder = ImmutableAdapterOutput.builder().httpStatus(HttpStatus.OK.value());
+ if (withBody) {
+ responseBuilder.body(HttpStatus.OK.name());
+ } else {
+ responseBuilder.body(Optional.empty());
+ }
+ return SdncJsonHelper.createOutputJsonString(responseBuilder.build());
}
private OngoingStubbing<Mono<String>> whenAsyncPostThenReturn(Mono<String> response) {
import reactor.test.StepVerifier;
@ExtendWith(MockitoExtension.class)
-public class StdA1ClientTest {
+class StdA1ClientTest {
private static final String RIC_URL = "RicUrl";
private static final String POLICY_TYPE_1_NAME = "type1";
private static final String POLICY_1_ID = "policy1";
RicConfig ricConfigMock;
@BeforeEach
- public void init() {
+ void init() {
clientUnderTest = new StdA1ClientVersion1(asyncRestClientMock, ricConfigMock);
}
}
@Test
- public void testGetPolicyTypeIdentities() {
+ void testGetPolicyTypeIdentities() {
List<String> policyTypeIds = clientUnderTest.getPolicyTypeIdentities().block();
assertEquals(1, policyTypeIds.size(), "should hardcoded to one");
assertEquals("", policyTypeIds.get(0), "should hardcoded to empty");
}
@Test
- public void testGetPolicyIdentities() {
+ void testGetPolicyIdentities() {
doReturn(RIC_URL).when(ricConfigMock).baseUrl();
Mono<String> policyIds = Mono.just(Arrays.asList(POLICY_1_ID, POLICY_2_ID).toString());
when(asyncRestClientMock.get(anyString())).thenReturn(policyIds);
}
@Test
- public void testGetValidPolicyType() {
+ void testGetValidPolicyType() {
String policyType = clientUnderTest.getPolicyTypeSchema(POLICY_TYPE_1_NAME).block();
assertEquals("{}", policyType, "");
}
@Test
- public void testPutPolicyValidResponse() {
+ void testPutPolicyValidResponse() {
doReturn(RIC_URL).when(ricConfigMock).baseUrl();
when(asyncRestClientMock.put(anyString(), anyString())).thenReturn(Mono.just(POLICY_JSON));
}
@Test
- public void testDeletePolicy() {
+ void testDeletePolicy() {
doReturn(RIC_URL).when(ricConfigMock).baseUrl();
final String url = policiesBaseUrl() + POLICY_1_ID;
when(asyncRestClientMock.delete(url)).thenReturn(Mono.empty());
}
@Test
- public void testDeleteAllPolicies() {
+ void testDeleteAllPolicies() {
doReturn(RIC_URL).when(ricConfigMock).baseUrl();
Mono<String> policyIds = Mono.just(Arrays.asList(POLICY_1_ID, POLICY_2_ID).toString());
when(asyncRestClientMock.get(policiesUrl())).thenReturn(policyIds);
import org.oransc.policyagent.exceptions.ServiceException;
import org.springframework.http.MediaType;
-public class ApplicationConfigParserTest {
+class ApplicationConfigParserTest {
ApplicationConfigParser parserUnderTest = new ApplicationConfigParser();
@Test
- public void whenCorrectConfig() throws Exception {
+ void whenCorrectConfig() throws Exception {
JsonObject jsonRootObject = getJsonRootObject();
ApplicationConfigParser.ConfigParserResult result = parserUnderTest.parse(jsonRootObject);
}
@Test
- public void whenDmaapConfigHasSeveralStreamsPublishing() throws Exception {
+ void whenDmaapConfigHasSeveralStreamsPublishing() throws Exception {
JsonObject jsonRootObject = getJsonRootObject();
JsonObject json = jsonRootObject.getAsJsonObject("config").getAsJsonObject("streams_publishes");
JsonObject fake_info_object = new JsonObject();
private JsonObject dmaap_publisher;
private JsonObject fake_info_object;
+ @Override
public String toString() {
return String.format("[dmaap_publisher=%s, fake_info_object=%s]", dmaap_publisher.toString(),
fake_info_object.toString());
}
@Test
- public void whenDmaapConfigHasSeveralStreamsSubscribing() throws Exception {
+ void whenDmaapConfigHasSeveralStreamsSubscribing() throws Exception {
JsonObject jsonRootObject = getJsonRootObject();
JsonObject json = jsonRootObject.getAsJsonObject("config").getAsJsonObject("streams_subscribes");
JsonObject fake_info_object = new JsonObject();
private JsonObject dmaap_subscriber;
private JsonObject fake_info_object;
+ @Override
public String toString() {
return String.format("[dmaap_subscriber=%s, fake_info_object=%s]", dmaap_subscriber.toString(),
fake_info_object.toString());
}
@Test
- public void whenMalformedUrlStreamsSubscribing() throws Exception {
+ void whenMalformedUrlStreamsSubscribing() throws Exception {
JsonObject jsonRootObject = getJsonRootObject();
final String wrongTopicUrl = "WrongTopicUrl";
JsonObject json = getDmaapInfo(jsonRootObject, "streams_subscribes", "dmaap_subscriber");
}
@Test
- public void whenMalformedUrlStreamsPublishing() throws Exception {
+ void whenMalformedUrlStreamsPublishing() throws Exception {
JsonObject jsonRootObject = getJsonRootObject();
final String wrongTopicUrl = "WrongTopicUrl";
JsonObject json = getDmaapInfo(jsonRootObject, "streams_publishes", "dmaap_publisher");
}
@Test
- public void whenWrongMemberNameInObject() throws Exception {
+ void whenWrongMemberNameInObject() throws Exception {
JsonObject jsonRootObject = getJsonRootObject();
JsonObject json = jsonRootObject.getAsJsonObject("config");
json.remove("ric");
}
@Test
- public void whenWrongUrlPathStreamsSubscribing() throws Exception {
+ void whenWrongUrlPathStreamsSubscribing() throws Exception {
JsonObject jsonRootObject = getJsonRootObject();
final String wrongTopicUrlString =
"http://admin:admin@localhost:6845/events/A1-POLICY-AGENT-READ/users/policy-agent/wrong-topic-url";
}
@Test
- public void whenWrongUrlPathStreamsPublishing() throws Exception {
+ void whenWrongUrlPathStreamsPublishing() throws Exception {
JsonObject jsonRootObject = getJsonRootObject();
final String wrongTopicUrlString =
"http://admin:admin@localhost:6845/events/A1-POLICY-AGENT-WRITE/wrong-topic-url";
"Wrong error message when the streams publishes' URL has incorrect syntax");
}
- public JsonObject getDmaapInfo(JsonObject jsonRootObject, String streamsPublishesOrSubscribes,
+ JsonObject getDmaapInfo(JsonObject jsonRootObject, String streamsPublishesOrSubscribes,
String dmaapPublisherOrSubscriber) throws Exception {
return jsonRootObject.getAsJsonObject("config").getAsJsonObject(streamsPublishesOrSubscribes)
.getAsJsonObject(dmaapPublisherOrSubscriber).getAsJsonObject("dmaap_info");
import org.oransc.policyagent.exceptions.ServiceException;
@ExtendWith(MockitoExtension.class)
-public class ApplicationConfigTest {
+class ApplicationConfigTest {
private static final ImmutableRicConfig RIC_CONFIG_1 = ImmutableRicConfig.builder() //
.name("ric1") //
}
@Test
- public void gettingNotAddedRicShouldThrowException() {
+ void gettingNotAddedRicShouldThrowException() {
ApplicationConfig appConfigUnderTest = new ApplicationConfig();
appConfigUnderTest.setConfiguration(configParserResult(RIC_CONFIG_1));
}
@Test
- public void addRicShouldNotifyAllObserversOfRicAdded() throws Exception {
+ void addRicShouldNotifyAllObserversOfRicAdded() throws Exception {
ApplicationConfig appConfigUnderTest = new ApplicationConfig();
RicConfigUpdate update = appConfigUnderTest.setConfiguration(configParserResult(RIC_CONFIG_1)).blockFirst();
}
@Test
- public void changedRicShouldNotifyAllObserversOfRicChanged() throws Exception {
+ void changedRicShouldNotifyAllObserversOfRicChanged() throws Exception {
ApplicationConfig appConfigUnderTest = new ApplicationConfig();
appConfigUnderTest.setConfiguration(configParserResult(RIC_CONFIG_1));
}
@Test
- public void removedRicShouldNotifyAllObserversOfRicRemoved() {
+ void removedRicShouldNotifyAllObserversOfRicRemoved() {
ApplicationConfig appConfigUnderTest = new ApplicationConfig();
ImmutableRicConfig ricConfig2 = ImmutableRicConfig.builder() //
import org.springframework.http.HttpStatus;
@ExtendWith(MockitoExtension.class)
-public class DmaapMessageConsumerTest {
+class DmaapMessageConsumerTest {
@Mock
private ApplicationConfig applicationConfigMock;
@Mock
private DmaapMessageConsumer messageConsumerUnderTest;
@AfterEach
- public void resetLogging() {
+ void resetLogging() {
LoggingUtils.getLogListAppender(DmaapMessageConsumer.class);
}
@Test
- public void dmaapNotConfigured_thenSleepAndRetryUntilConfig() throws Exception {
+ void dmaapNotConfigured_thenSleepAndRetryUntilConfig() throws Exception {
messageConsumerUnderTest = spy(new DmaapMessageConsumer(applicationConfigMock));
doNothing().when(messageConsumerUnderTest).sleep(any(Duration.class));
}
@Test
- public void dmaapConfigurationRemoved_thenStopPollingDmaapSleepAndRetry() throws Exception {
+ void dmaapConfigurationRemoved_thenStopPollingDmaapSleepAndRetry() throws Exception {
messageConsumerUnderTest = spy(new DmaapMessageConsumer(applicationConfigMock));
doNothing().when(messageConsumerUnderTest).sleep(any(Duration.class));
}
@Test
- public void dmaapConfiguredAndNoMessages_thenPollOnce() throws Exception {
+ void dmaapConfiguredAndNoMessages_thenPollOnce() throws Exception {
setUpMrConfig();
messageConsumerUnderTest = spy(new DmaapMessageConsumer(applicationConfigMock));
}
@Test
- public void dmaapConfiguredAndErrorGettingMessages_thenLogWarningAndSleep() throws Exception {
+ void dmaapConfiguredAndErrorGettingMessages_thenLogWarningAndSleep() throws Exception {
setUpMrConfig();
messageConsumerUnderTest = spy(new DmaapMessageConsumer(applicationConfigMock));
}
@Test
- public void dmaapConfiguredAndOneMessage_thenPollOnceAndProcessMessage() throws Exception {
+ void dmaapConfiguredAndOneMessage_thenPollOnceAndProcessMessage() throws Exception {
setUpMrConfig();
messageConsumerUnderTest = spy(new DmaapMessageConsumer(applicationConfigMock));
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
-public class DmaapMessageHandlerTest {
+class DmaapMessageHandlerTest {
private static final Logger logger = LoggerFactory.getLogger(DmaapMessageHandlerTest.class);
private static final String URL = "url";
}
@Test
- public void testMessageParsing() {
+ void testMessageParsing() {
String message = dmaapInputMessage(Operation.DELETE);
logger.info(message);
DmaapRequestMessage parsedMessage = gson.fromJson(message, ImmutableDmaapRequestMessage.class);
- assertTrue(parsedMessage != null);
+ assertNotNull(parsedMessage);
assertFalse(parsedMessage.payload().isPresent());
message = dmaapInputMessage(Operation.PUT);
logger.info(message);
parsedMessage = gson.fromJson(message, ImmutableDmaapRequestMessage.class);
- assertTrue(parsedMessage != null);
+ assertNotNull(parsedMessage);
assertTrue(parsedMessage.payload().isPresent());
}
@Test
- public void unparseableMessage_thenWarning() {
+ void unparseableMessage_thenWarning() {
final ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(DmaapMessageHandler.class);
testedObject.handleDmaapMsg("bad message");
}
@Test
- public void successfulDelete() throws IOException {
+ void successfulDelete() throws IOException {
doReturn(okResponse()).when(agentClient).deleteForEntity(anyString());
doReturn(1).when(dmaapClient).send(anyString());
doReturn(new MRPublisherResponse()).when(dmaapClient).sendBatchWithResponse();
}
@Test
- public void successfulGet() throws IOException {
+ void successfulGet() throws IOException {
doReturn(okResponse()).when(agentClient).getForEntity(anyString());
doReturn(1).when(dmaapClient).send(anyString());
doReturn(new MRPublisherResponse()).when(dmaapClient).sendBatchWithResponse();
}
@Test
- public void successfulPut() throws IOException {
+ void successfulPut() throws IOException {
doReturn(okResponse()).when(agentClient).putForEntity(anyString(), anyString());
doReturn(1).when(dmaapClient).send(anyString());
doReturn(new MRPublisherResponse()).when(dmaapClient).sendBatchWithResponse();
}
@Test
- public void successfulPost() throws IOException {
+ void successfulPost() throws IOException {
doReturn(okResponse()).when(agentClient).postForEntity(anyString(), anyString());
doReturn(1).when(dmaapClient).send(anyString());
doReturn(new MRPublisherResponse()).when(dmaapClient).sendBatchWithResponse();
}
@Test
- public void exceptionWhenCallingPolicyAgent_thenNotFoundResponse() throws IOException {
+ void exceptionWhenCallingPolicyAgent_thenNotFoundResponse() throws IOException {
WebClientResponseException except = new WebClientResponseException(400, "Refused", null, null, null, null);
doReturn(Mono.error(except)).when(agentClient).putForEntity(anyString(), any());
doReturn(1).when(dmaapClient).send(anyString());
}
@Test
- public void unsupportedOperationInMessage_thenNotFoundResponseWithNotImplementedOperation() throws Exception {
+ void unsupportedOperationInMessage_thenNotFoundResponseWithNotImplementedOperation() throws Exception {
String message = dmaapInputMessage(Operation.PUT).toString();
String badOperation = "BAD";
message = message.replace(Operation.PUT.toString(), badOperation);
}
@Test
- public void putWithoutPayload_thenNotFoundResponseWithWarning() throws Exception {
+ void putWithoutPayload_thenNotFoundResponseWithWarning() throws Exception {
String message = dmaapInputMessage(Operation.PUT).toString();
message = message.replace(",\"payload\":{\"name\":\"name\",\"schema\":\"schema\"}", "");
import reactor.test.StepVerifier;
@ExtendWith(MockitoExtension.class)
-public class LockTest {
+class LockTest {
@SuppressWarnings("squid:S2925") // "Thread.sleep" should not be used in tests.
private void sleep() {
}
@Test
- public void testLock() throws IOException, ServiceException {
+ void testLock() throws IOException, ServiceException {
Lock lock = new Lock();
lock.lockBlocking(LockType.SHARED);
lock.unlockBlocking();
}
@Test
- public void testReactiveLock() {
+ void testReactiveLock() {
Lock lock = new Lock();
Mono<Lock> seq = lock.lock(LockType.EXCLUSIVE) //
import org.oransc.policyagent.utils.LoggingUtils;
import reactor.test.StepVerifier;
-public class EnvironmentProcessorTest {
+class EnvironmentProcessorTest {
private static final String CONSUL_HOST = "CONSUL_HOST";
private static final String CONSUL_HOST_VALUE = "consulHost";
private static final String HOSTNAME_VALUE = "hostname";
@Test
- public void allPropertiesAvailableWithHostname_thenAllPropertiesAreReturnedWithGivenConsulPort() {
+ void allPropertiesAvailableWithHostname_thenAllPropertiesAreReturnedWithGivenConsulPort() {
Properties systemEnvironment = new Properties();
String consulPort = "8080";
systemEnvironment.put(CONSUL_HOST, CONSUL_HOST_VALUE);
}
@Test
- public void consulHostMissing_thenExceptionReturned() {
+ void consulHostMissing_thenExceptionReturned() {
Properties systemEnvironment = new Properties();
StepVerifier.create(EnvironmentProcessor.readEnvironmentVariables(systemEnvironment))
}
@Test
- public void withAllPropertiesExceptConsulPort_thenAllPropertiesAreReturnedWithDefaultConsulPortAndWarning() {
+ void withAllPropertiesExceptConsulPort_thenAllPropertiesAreReturnedWithDefaultConsulPortAndWarning() {
Properties systemEnvironment = new Properties();
systemEnvironment.put(CONSUL_HOST, CONSUL_HOST_VALUE);
systemEnvironment.put(CONFIG_BINDING_SERVICE, CONFIG_BINDING_SERVICE_VALUE);
}
@Test
- public void configBindingServiceMissing_thenExceptionReturned() {
+ void configBindingServiceMissing_thenExceptionReturned() {
Properties systemEnvironment = new Properties();
systemEnvironment.put(CONSUL_HOST, CONSUL_HOST_VALUE);
}
@Test
- public void allPropertiesAvailableWithServiceName_thenAllPropertiesAreReturned() {
+ void allPropertiesAvailableWithServiceName_thenAllPropertiesAreReturned() {
Properties systemEnvironment = new Properties();
String consulPort = "8080";
systemEnvironment.put(CONSUL_HOST, CONSUL_HOST_VALUE);
}
@Test
- public void serviceNameAndHostnameMissing_thenExceptionIsReturned() {
+ void serviceNameAndHostnameMissing_thenExceptionIsReturned() {
Properties systemEnvironment = new Properties();
systemEnvironment.put(CONSUL_HOST, CONSUL_HOST_VALUE);
systemEnvironment.put(CONFIG_BINDING_SERVICE, CONFIG_BINDING_SERVICE_VALUE);
import reactor.test.StepVerifier;
@ExtendWith(MockitoExtension.class)
-public class RefreshConfigTaskTest {
+class RefreshConfigTaskTest {
private static final boolean CONFIG_FILE_EXISTS = true;
private static final boolean CONFIG_FILE_DOES_NOT_EXIST = false;
CbsClient cbsClient;
private static final String RIC_1_NAME = "ric1";
- public static final ImmutableRicConfig CORRECT_RIC_CONIFG = ImmutableRicConfig.builder() //
+ private static final ImmutableRicConfig CORRECT_RIC_CONIFG = ImmutableRicConfig.builder() //
.name(RIC_1_NAME) //
.baseUrl("http://localhost:8080/") //
.managedElementIds(new Vector<String>(Arrays.asList("kista_1", "kista_2"))) //
}
@Test
- public void startWithStubbedRefresh_thenTerminationLogged() {
+ void startWithStubbedRefresh_thenTerminationLogged() {
refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_DOES_NOT_EXIST, null, null, false);
doReturn(Flux.empty()).when(refreshTaskUnderTest).createRefreshTask();
}
@Test
- public void startWithStubbedRefreshReturnError_thenErrorAndTerminationLogged() {
+ void startWithStubbedRefreshReturnError_thenErrorAndTerminationLogged() {
refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_DOES_NOT_EXIST, null, null, false);
doReturn(Flux.error(new Exception("Error"))).when(refreshTaskUnderTest).createRefreshTask();
}
@Test
- public void stop_thenTaskIsDisposed() throws Exception {
+ void stop_thenTaskIsDisposed() throws Exception {
refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_DOES_NOT_EXIST, null, null, false);
refreshTaskUnderTest.systemEnvironment = new Properties();
}
@Test
- public void whenTheConfigurationFits_thenConfiguredRicsArePutInRepository() throws Exception {
+ void whenTheConfigurationFits_thenConfiguredRicsArePutInRepository() throws Exception {
refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_EXISTS);
refreshTaskUnderTest.systemEnvironment = new Properties();
// When
doReturn(getCorrectJson()).when(refreshTaskUnderTest).createInputStream(any());
doReturn("fileName").when(appConfig).getLocalConfigurationFilePath();
- StepVerifier.create(refreshTaskUnderTest.createRefreshTask()) //
+ StepVerifier //
+ .create(refreshTaskUnderTest.createRefreshTask()) //
.expectSubscription() //
.expectNext(Type.ADDED) //
.expectNext(Type.ADDED) //
}
@Test
- public void whenFileExistsButJsonIsIncorrect_thenNoRicsArePutInRepository() throws Exception {
+ void whenFileExistsButJsonIsIncorrect_thenNoRicsArePutInRepositoryAndErrorIsLogged() throws Exception {
refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_EXISTS);
refreshTaskUnderTest.systemEnvironment = new Properties();
doReturn(getIncorrectJson()).when(refreshTaskUnderTest).createInputStream(any());
doReturn("fileName").when(appConfig).getLocalConfigurationFilePath();
- StepVerifier.create(refreshTaskUnderTest.createRefreshTask()) //
+ final ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(RefreshConfigTask.class, ERROR);
+
+ StepVerifier //
+ .create(refreshTaskUnderTest.createRefreshTask()) //
.expectSubscription() //
.expectNoEvent(Duration.ofMillis(100)) //
.thenCancel() //
// Then
verify(refreshTaskUnderTest).loadConfigurationFromFile();
assertThat(appConfig.getRicConfigs().size()).isEqualTo(0);
+
+ assertThat(logAppender.list.toString().contains("Local configuration file not loaded: fileName, ")).isTrue();
}
@Test
- public void whenPeriodicConfigRefreshNoConsul_thenErrorIsLogged() {
+ void whenPeriodicConfigRefreshNoConsul_thenErrorIsLogged() {
refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_DOES_NOT_EXIST);
refreshTaskUnderTest.systemEnvironment = new Properties();
when(cbsClient.get(any())).thenReturn(Mono.error(new IOException()));
final ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(RefreshConfigTask.class, WARN);
- Flux<Type> task = refreshTaskUnderTest.createRefreshTask();
StepVerifier //
- .create(task) //
+ .create(refreshTaskUnderTest.createRefreshTask()) //
.expectSubscription() //
.expectNoEvent(Duration.ofMillis(1000)) //
.thenCancel() //
}
@Test
- public void whenPeriodicConfigRefreshSuccess_thenNewConfigIsCreatedAndRepositoryUpdated() throws Exception {
+ void whenPeriodicConfigRefreshSuccess_thenNewConfigIsCreatedAndRepositoryUpdated() throws Exception {
Rics rics = new Rics();
Policies policies = new Policies();
refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_DOES_NOT_EXIST, rics, policies, false);
doReturn(Mono.just(props)).when(refreshTaskUnderTest).getEnvironment(any());
doReturn(Mono.just(cbsClient)).when(refreshTaskUnderTest).createCbsClient(props);
- JsonObject configAsJson = getJsonRootObject();
+ JsonObject configAsJson = getJsonRootObject(true);
String newBaseUrl = "newBaseUrl";
modifyTheRicConfiguration(configAsJson, newBaseUrl);
when(cbsClient.get(any())).thenReturn(Mono.just(configAsJson));
doNothing().when(refreshTaskUnderTest).runRicSynchronization(any(Ric.class));
- Flux<Type> task = refreshTaskUnderTest.createRefreshTask();
-
StepVerifier //
- .create(task) //
+ .create(refreshTaskUnderTest.createRefreshTask()) //
.expectSubscription() //
.expectNext(Type.CHANGED) //
.expectNext(Type.ADDED) //
assertThat(policies.size()).isEqualTo(0);
}
+ @Test
+ void whenPeriodicConfigRefreshInvalidJson_thenErrorIsLogged() throws Exception {
+ Rics rics = new Rics();
+ Policies policies = new Policies();
+ refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_DOES_NOT_EXIST, rics, policies, false);
+ refreshTaskUnderTest.systemEnvironment = new Properties();
+
+ appConfig.setConfiguration(configParserResult());
+
+ EnvProperties props = properties();
+ doReturn(Mono.just(props)).when(refreshTaskUnderTest).getEnvironment(any());
+ doReturn(Mono.just(cbsClient)).when(refreshTaskUnderTest).createCbsClient(props);
+
+ JsonObject configAsJson = getJsonRootObject(false);
+ when(cbsClient.get(any())).thenReturn(Mono.just(configAsJson));
+
+ final ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(RefreshConfigTask.class, ERROR);
+
+ StepVerifier //
+ .create(refreshTaskUnderTest.createRefreshTask()) //
+ .expectSubscription() //
+ .expectNoEvent(Duration.ofMillis(1000)) //
+ .thenCancel() //
+ .verify();
+
+ assertThat(logAppender.list.toString()
+ .contains("Could not parse configuration org.oransc.policyagent.exceptions.ServiceException: ")).isTrue();
+ }
+
private RicConfig getRicConfig(String name) {
RicConfig ricConfig = ImmutableRicConfig.builder() //
.name(name) //
.addProperty("baseUrl", newBaseUrl);
}
- private JsonObject getJsonRootObject() throws JsonIOException, JsonSyntaxException, IOException {
- JsonObject rootObject = JsonParser.parseReader(new InputStreamReader(getCorrectJson())).getAsJsonObject();
+ private JsonObject getJsonRootObject(boolean valid) throws JsonIOException, JsonSyntaxException, IOException {
+ JsonObject rootObject = JsonParser
+ .parseReader(new InputStreamReader(valid ? getCorrectJson() : getIncorrectJson())).getAsJsonObject();
return rootObject;
}
}
private static InputStream getIncorrectJson() {
- String string = "{" + //
- " \"config\": {" + //
- " \"ric\": {"; //
+ String string = "{}"; //
return new ByteArrayInputStream((string.getBytes(StandardCharsets.UTF_8)));
}
}
import reactor.core.publisher.Mono;
@ExtendWith(MockitoExtension.class)
-public class RicSupervisionTest {
+class RicSupervisionTest {
private static final String POLICY_TYPE_1_NAME = "type1";
private static final PolicyType POLICY_TYPE_1 = ImmutablePolicyType.builder() //
.name(POLICY_TYPE_1_NAME) //
private Rics rics = new Rics();
@BeforeEach
- public void init() {
+ void init() {
types.clear();
policies.clear();
rics.clear();
}
@AfterEach
- public void verifyNoRicLocks() {
+ void verifyNoRicLocks() {
for (Ric ric : this.rics.getRics()) {
ric.getLock().lockBlocking(LockType.EXCLUSIVE);
ric.getLock().unlockBlocking();
}
@Test
- public void whenRicIdleAndNoChangedPoliciesOrPolicyTypes_thenNoSynchronization() {
+ void whenRicIdleAndNoChangedPoliciesOrPolicyTypes_thenNoSynchronization() {
doReturn(Mono.just(a1ClientMock)).when(a1ClientFactory).createA1Client(any(Ric.class));
RIC_1.setState(RicState.AVAILABLE);
RIC_1.addSupportedPolicyType(POLICY_TYPE_1);
}
@Test
- public void whenRicUndefined_thenSynchronization() {
+ void whenRicUndefined_thenSynchronization() {
doReturn(Mono.just(a1ClientMock)).when(a1ClientFactory).createA1Client(any(Ric.class));
RIC_1.setState(RicState.UNAVAILABLE);
rics.put(RIC_1);
}
@Test
- public void whenRicSynchronizing_thenNoSynchronization() {
+ void whenRicSynchronizing_thenNoSynchronization() {
doReturn(Mono.just(a1ClientMock)).when(a1ClientFactory).createA1Client(any(Ric.class));
RIC_1.setState(RicState.SYNCHRONIZING);
rics.put(RIC_1);
}
@Test
- public void whenRicIdleAndErrorGettingPolicyIdentities_thenNoSynchronization() {
+ void whenRicIdleAndErrorGettingPolicyIdentities_thenNoSynchronization() {
doReturn(Mono.just(a1ClientMock)).when(a1ClientFactory).createA1Client(any(Ric.class));
RIC_1.setState(RicState.AVAILABLE);
RIC_1.addSupportedPolicyType(POLICY_TYPE_1);
}
@Test
- public void whenRicIdleAndNotSameAmountOfPolicies_thenSynchronization() {
+ void whenRicIdleAndNotSameAmountOfPolicies_thenSynchronization() {
doReturn(Mono.just(a1ClientMock)).when(a1ClientFactory).createA1Client(any(Ric.class));
RIC_1.setState(RicState.AVAILABLE);
rics.put(RIC_1);
}
@Test
- public void whenRicIdleAndSameAmountOfPoliciesButNotSamePolicies_thenSynchronization() {
+ void whenRicIdleAndSameAmountOfPoliciesButNotSamePolicies_thenSynchronization() {
doReturn(Mono.just(a1ClientMock)).when(a1ClientFactory).createA1Client(any(Ric.class));
RIC_1.setState(RicState.AVAILABLE);
rics.put(RIC_1);
}
@Test
- public void whenRicIdleAndErrorGettingPolicyTypes_thenNoSynchronization() {
+ void whenRicIdleAndErrorGettingPolicyTypes_thenNoSynchronization() {
doReturn(Mono.just(a1ClientMock)).when(a1ClientFactory).createA1Client(any(Ric.class));
RIC_1.setState(RicState.AVAILABLE);
RIC_1.addSupportedPolicyType(POLICY_TYPE_1);
}
@Test
- public void whenRicIdleAndNotSameAmountOfPolicyTypes_thenSynchronization() {
+ void whenRicIdleAndNotSameAmountOfPolicyTypes_thenSynchronization() {
doReturn(Mono.just(a1ClientMock)).when(a1ClientFactory).createA1Client(any(Ric.class));
RIC_1.setState(RicState.AVAILABLE);
RIC_1.addSupportedPolicyType(POLICY_TYPE_1);
}
@Test
- public void whenRicIdleAndSameAmountOfPolicyTypesButNotSameTypes_thenSynchronization() {
+ void whenRicIdleAndSameAmountOfPolicyTypesButNotSameTypes_thenSynchronization() {
doReturn(Mono.just(a1ClientMock)).when(a1ClientFactory).createA1Client(any(Ric.class));
PolicyType policyType2 = ImmutablePolicyType.builder() //
.name("policyType2") //
import reactor.core.publisher.Mono;
@ExtendWith(MockitoExtension.class)
-public class RicSynchronizationTaskTest {
+class RicSynchronizationTaskTest {
private static final String POLICY_TYPE_1_NAME = "type1";
private static final PolicyType POLICY_TYPE_1 = ImmutablePolicyType.builder() //
.name(POLICY_TYPE_1_NAME) //
.controllerName("controllerName") //
.build());
- private static Policy createPolicy(boolean isTransient) {
+ private static Policy createPolicy(String policyId, boolean isTransient) {
return ImmutablePolicy.builder() //
- .id("policyId1") //
+ .id(policyId) //
.json("") //
.ownerServiceName("service") //
.ric(RIC_1) //
.build();
}
- private static final Policy POLICY_1 = createPolicy(false);
+ private static final Policy POLICY_1 = createPolicy("policyId1", false);
private static final String SERVICE_1_NAME = "service1";
private static final String SERVICE_1_CALLBACK_URL = "callbackUrl";
private Services services;
@BeforeEach
- public void init() {
+ void init() {
policyTypes = new PolicyTypes();
policies = new Policies();
services = new Services();
}
@Test
- public void ricAlreadySynchronizing_thenNoSynchronization() {
+ void ricAlreadySynchronizing_thenNoSynchronization() {
RIC_1.setState(RicState.SYNCHRONIZING);
RIC_1.addSupportedPolicyType(POLICY_TYPE_1);
}
@Test
- public void ricIdlePolicyTypeInRepo_thenSynchronizationWithReuseOfTypeFromRepoAndCorrectServiceNotified() {
+ void ricIdlePolicyTypeInRepo_thenSynchronizationWithReuseOfTypeFromRepoAndCorrectServiceNotified() {
RIC_1.setState(RicState.AVAILABLE);
policyTypes.put(POLICY_TYPE_1);
}
@Test
- public void ricIdlePolicyTypeNotInRepo_thenSynchronizationWithTypeFromRic() throws Exception {
+ void ricIdlePolicyTypeNotInRepo_thenSynchronizationWithTypeFromRic() throws Exception {
RIC_1.setState(RicState.AVAILABLE);
setUpCreationOfA1Client();
}
@Test
- public void ricIdleAndHavePolicies_thenSynchronizationWithRecreationOfPolicies() {
+ void ricIdleAndHavePolicies_thenSynchronizationWithRecreationOfPolicies() {
RIC_1.setState(RicState.AVAILABLE);
- Policy transientPolicy = createPolicy(true);
+ Policy transientPolicy = createPolicy("transientPolicyId", true);
policies.put(transientPolicy);
policies.put(POLICY_1);
}
@Test
- public void ricIdleAndErrorDeletingPoliciesFirstTime_thenSynchronizationWithDeletionOfPolicies() {
+ void ricIdleAndErrorDeletingPoliciesFirstTime_thenSynchronizationWithDeletionOfPolicies() {
RIC_1.setState(RicState.AVAILABLE);
policies.put(POLICY_1);
}
@Test
- public void ricIdleAndErrorDeletingPoliciesAllTheTime_thenSynchronizationWithFailedRecovery() {
+ void ricIdleAndErrorDeletingPoliciesAllTheTime_thenSynchronizationWithFailedRecovery() {
RIC_1.setState(RicState.AVAILABLE);
policies.put(POLICY_1);
}
@Test
- public void ricIdlePolicyTypeInRepo_thenSynchronizationWithErrorOnServiceNotificationErrorLogged() {
+ void ricIdlePolicyTypeInRepo_thenSynchronizationWithErrorOnServiceNotificationErrorLogged() {
RIC_1.setState(RicState.AVAILABLE);
policyTypes.put(POLICY_TYPE_1);
import reactor.core.publisher.Mono;
@ExtendWith(MockitoExtension.class)
-public class ServiceSupervisionTest {
+class ServiceSupervisionTest {
private static final String SERVICE_NAME = "Service name";
private static final String RIC_NAME = "name";
.build();
@Test
- public void serviceExpired_policyAndServiceAreDeletedInRepoAndPolicyIsDeletedInRic() {
+ void serviceExpired_policyAndServiceAreDeletedInRepoAndPolicyIsDeletedInRic() {
setUpRepositoryWithKeepAliveInterval(Duration.ofSeconds(2));
setUpCreationOfA1Client();
}
@Test
- public void serviceExpiredButDeleteInRicFails_policyAndServiceAreDeletedInRepoAndErrorLoggedForRic() {
+ void serviceExpiredButDeleteInRicFails_policyAndServiceAreDeletedInRepoAndErrorLoggedForRic() {
setUpRepositoryWithKeepAliveInterval(Duration.ofSeconds(2));
setUpCreationOfA1Client();
}
@Test
- public void serviceNotExpired_shouldNotBeChecked() {
+ void serviceNotExpired_shouldNotBeChecked() {
setUpRepositoryWithKeepAliveInterval(Duration.ofSeconds(2));
ServiceSupervision serviceSupervisionUnderTest =
}
@Test
- public void serviceWithoutKeepAliveInterval_shouldNotBeChecked() {
+ void serviceWithoutKeepAliveInterval_shouldNotBeChecked() {
setUpRepositoryWithKeepAliveInterval(Duration.ofSeconds(0));
ServiceSupervision serviceSupervisionUnderTest =
<?xml version="1.0" encoding="UTF-8"?>
+<!--<![CDATA[
+========================LICENSE_START=================================
+O-RAN-SC
+%%
+Modifications Copyright (C) 2020 Nordix Foundation
+%%
+Licensed 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.
+========================LICENSE_END===================================
+]]>-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.o-ran-sc.nonrtric.sdnc-a1.northbound</groupId>
<artifactId>features-sdnc-a1-northbound</artifactId>
- <version>1.7.3-SNAPSHOT</version>
+ <version>1.7.5-SNAPSHOT</version>
<packaging>feature</packaging>
<name>sdnc-a1-northbound :: features :: ${project.artifactId}</name>
<?xml version="1.0" encoding="UTF-8"?>
+<!--<![CDATA[
+========================LICENSE_START=================================
+O-RAN-SC
+%%
+Modifications Copyright (C) 2020 Nordix Foundation
+%%
+Licensed 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.
+========================LICENSE_END===================================
+]]>-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.o-ran-sc.nonrtric.sdnc-a1.northbound</groupId>
<artifactId>sdnc-a1-northbound-features-installer</artifactId>
- <version>1.7.3-SNAPSHOT</version>
+ <version>1.7.5-SNAPSHOT</version>
<packaging>pom</packaging>
<name>sdnc-a1-northbound :: features :: ${project.artifactId}</name>
#!/bin/bash
+# ============LICENSE_START===============================================
+# Modifications Copyright (C) 2020 Nordix Foundation. All rights reserved.
+# ========================================================================
+# Licensed 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.
+# ============LICENSE_END=================================================
+#
+
ODL_HOME=${ODL_HOME:-/opt/opendaylight/current}
ODL_KARAF_CLIENT=${ODL_KARAF_CLIENT:-${ODL_HOME}/bin/client}
INSTALLERDIR=$(dirname $0)
<?xml version="1.0" encoding="UTF-8"?>
+<!--<![CDATA[
+========================LICENSE_START=================================
+O-RAN-SC
+%%
+Modifications Copyright (C) 2020 Nordix Foundation
+%%
+Licensed 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.
+========================LICENSE_END===================================
+]]>-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.o-ran-sc.nonrtric.sdnc-a1.northbound</groupId>
<artifactId>sdnc-northbound-feature-aggregator</artifactId>
- <version>1.7.3-SNAPSHOT</version>
+ <version>1.7.5-SNAPSHOT</version>
<packaging>pom</packaging>
<name>sdnc-a1-northbound :: features</name>
<?xml version="1.0" encoding="UTF-8"?>
+<!--<![CDATA[
+========================LICENSE_START=================================
+O-RAN-SC
+%%
+Modifications Copyright (C) 2020 Nordix Foundation
+%%
+Licensed 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.
+========================LICENSE_END===================================
+]]>-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.o-ran-sc.nonrtric.sdnc-a1.northbound</groupId>
<artifactId>sdnc-a1-northbound-all</artifactId>
- <version>1.7.3-SNAPSHOT</version>
+ <version>1.7.5-SNAPSHOT</version>
<packaging>feature</packaging>
<name>sdnc-a1-northbound :: features :: ${project.artifactId}</name>
<groupId>org.o-ran-sc.nonrtric.sdnc-a1.northbound</groupId>
<artifactId>features-nonrt-ric-api</artifactId>
- <version>1.7.3-SNAPSHOT</version>
+ <version>1.7.5-SNAPSHOT</version>
<packaging>feature</packaging>
<name>sdnc-a1-northbound :: nonrt-ric-api :: ${project.artifactId}</name>
<groupId>org.o-ran-sc.nonrtric.sdnc-a1.northbound</groupId>
<artifactId>nonrt-ric-api-features</artifactId>
- <version>1.7.3-SNAPSHOT</version>
+ <version>1.7.5-SNAPSHOT</version>
<packaging>pom</packaging>
<name>sdnc-a1-northbound :: nonrt-ric-api :: ${project.artifactId}</name>
<groupId>org.o-ran-sc.nonrtric.sdnc-a1.northbound</groupId>
<artifactId>sdnc-nonrt-ric-api</artifactId>
- <version>1.7.3-SNAPSHOT</version>
+ <version>1.7.5-SNAPSHOT</version>
<packaging>feature</packaging>
<name>sdnc-a1-northbound :: nonrt-ric-api :: ${project.artifactId}</name>
<groupId>org.o-ran-sc.nonrtric.sdnc-a1.northbound</groupId>
<artifactId>nonrt-ric-api-installer</artifactId>
- <version>1.7.3-SNAPSHOT</version>
+ <version>1.7.5-SNAPSHOT</version>
<packaging>pom</packaging>
<name>sdnc-a1-northbound :: nonrt-ric-api :: ${project.artifactId}</name>
<groupId>org.o-ran-sc.nonrtric.sdnc-a1.northbound</groupId>
<artifactId>nonrt-ric-api-model</artifactId>
- <version>1.7.3-SNAPSHOT</version>
+ <version>1.7.5-SNAPSHOT</version>
<packaging>bundle</packaging>
<name>sdnc-a1-northbound :: nonrt-ric-api :: ${project.artifactId}</name>
<groupId>org.o-ran-sc.nonrtric.sdnc-a1.northbound</groupId>
<artifactId>nonrt-ric-api</artifactId>
- <version>1.7.3-SNAPSHOT</version>
+ <version>1.7.5-SNAPSHOT</version>
<packaging>pom</packaging>
<name>sdnc-a1-northbound :: nonrt-ric-api</name>
<groupId>org.o-ran-sc.nonrtric.sdnc-a1.northbound</groupId>
<artifactId>nonrt-ric-api-provider</artifactId>
- <version>1.7.3-SNAPSHOT</version>
+ <version>1.7.5-SNAPSHOT</version>
<packaging>bundle</packaging>
<name>sdnc-a1-northbound :: nonrt-ric-api :: ${project.artifactId}</name>
package org.o_ran_sc.nonrtric.sdnc_a1.northbound.provider;
+import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;
import java.util.concurrent.ExecutionException;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
public class NonrtRicApiProviderTest extends AbstractConcurrentDataBrokerTest {
protected static final Logger LOG = LoggerFactory.getLogger(NonrtRicApiProviderTest.class);
+
+ private static final Integer HTTP_OK_AS_INTEGER = HttpStatus.OK.value();
+
protected NonrtRicApiProvider nonrtRicApiProvider;
protected DataBroker dataBroker;
@Mock
ResponseEntity<Object> getResponse = new ResponseEntity<>(returnedBody, HttpStatus.OK);
when(restAdapter.get(eq(nearRtRicUrl.getValue()), eq(String.class))).thenReturn(getResponse);
GetA1PolicyOutput result = nonrtRicApiProvider.getA1Policy(inputBuilder.build()).get().getResult();
- Assert.assertEquals(returnedBody, result.getBody());
- Assert.assertTrue(HttpStatus.OK.value() == result.getHttpStatus());
+ assertEquals(returnedBody, result.getBody());
+ assertEquals(HTTP_OK_AS_INTEGER, result.getHttpStatus());
}
@Test
ResponseEntity<Object> getResponse = new ResponseEntity<>(returnedBody, HttpStatus.OK);
when(restAdapter.get(eq(nearRtRicUrl.getValue()), eq(String.class))).thenReturn(getResponse);
GetA1PolicyTypeOutput result = nonrtRicApiProvider.getA1PolicyType(inputBuilder.build()).get().getResult();
- Assert.assertEquals(returnedBody, result.getBody());
- Assert.assertTrue(HttpStatus.OK.value() == result.getHttpStatus());
+ assertEquals(returnedBody, result.getBody());
+ assertEquals(HTTP_OK_AS_INTEGER, result.getHttpStatus());
}
@Test
ResponseEntity<Object> getResponse = new ResponseEntity<>(returnedBody, HttpStatus.OK);
when(restAdapter.get(eq(nearRtRicUrl.getValue()), eq(String.class))).thenReturn(getResponse);
GetA1PolicyStatusOutput result = nonrtRicApiProvider.getA1PolicyStatus(inputBuilder.build()).get().getResult();
- Assert.assertEquals(returnedBody, result.getBody());
- Assert.assertTrue(HttpStatus.OK.value() == result.getHttpStatus());
+ assertEquals(returnedBody, result.getBody());
+ assertEquals(HTTP_OK_AS_INTEGER, result.getHttpStatus());
}
@Test
inputBuilder.setNearRtRicUrl(nearRtRicUrl);
Whitebox.setInternalState(nonrtRicApiProvider, "restAdapter", restAdapter);
String returnedBody = "GET failed";
- int returnedStatusCode = 404;
+ Integer notFoundStatusCode = HttpStatus.NOT_FOUND.value();
when(restAdapter.get(eq(nearRtRicUrl.getValue()), eq(String.class)))
- .thenThrow(new RestClientResponseException(null, returnedStatusCode, null, null, returnedBody.getBytes(), null));
+ .thenThrow(new RestClientResponseException(null, notFoundStatusCode, null, null, returnedBody.getBytes(), null));
GetA1PolicyOutput result = nonrtRicApiProvider.getA1(inputBuilder.build());
- Assert.assertEquals(returnedBody, result.getBody());
- Assert.assertTrue(returnedStatusCode == result.getHttpStatus());
+ assertEquals(returnedBody, result.getBody());
+ assertEquals(notFoundStatusCode, result.getHttpStatus());
}
@Test
inputBuilder.setBody(testPolicy);
Whitebox.setInternalState(nonrtRicApiProvider, "restAdapter", restAdapter);
String returnedBody = "returned body";
+ Integer createdStatusCode = HttpStatus.CREATED.value();
ResponseEntity<String> putResponse = new ResponseEntity<>(returnedBody, HttpStatus.CREATED);
when(restAdapter.put(eq(nearRtRicUrl.getValue()), eq(testPolicy), eq(String.class))).thenReturn(putResponse);
PutA1PolicyOutput result = nonrtRicApiProvider.putA1Policy(inputBuilder.build()).get().getResult();
- Assert.assertEquals(returnedBody, result.getBody());
- Assert.assertTrue(HttpStatus.CREATED.value() == result.getHttpStatus());
+ assertEquals(returnedBody, result.getBody());
+ assertEquals(createdStatusCode, result.getHttpStatus());
}
@Test
inputBuilder.setBody(testPolicy);
Whitebox.setInternalState(nonrtRicApiProvider, "restAdapter", restAdapter);
String returnedBody = "PUT failed";
- int returnedStatusCode = 400;
+ Integer badRequestStatusCode = HttpStatus.BAD_REQUEST.value();
when(restAdapter.put(eq(nearRtRicUrl.getValue()), eq(testPolicy), eq(String.class)))
- .thenThrow(new RestClientResponseException(null, returnedStatusCode, null, null, returnedBody.getBytes(), null));
+ .thenThrow(new RestClientResponseException(null, badRequestStatusCode, null, null, returnedBody.getBytes(), null));
PutA1PolicyOutput result = nonrtRicApiProvider.putA1Policy(inputBuilder.build()).get().getResult();
- Assert.assertEquals(returnedBody, result.getBody());
- Assert.assertTrue(returnedStatusCode == result.getHttpStatus());
+ assertEquals(returnedBody, result.getBody());
+ assertEquals(badRequestStatusCode, result.getHttpStatus());
}
@Test
ResponseEntity<Object> getResponseOk = new ResponseEntity<>(returnedBody, HttpStatus.OK);
when(restAdapter.delete(nearRtRicUrl.getValue())).thenReturn(getResponseNoContent).thenReturn(getResponseOk);
DeleteA1PolicyOutput resultNoContent = nonrtRicApiProvider.deleteA1Policy(inputBuilder.build()).get().getResult();
- Assert.assertTrue(HttpStatus.NO_CONTENT.value() == resultNoContent.getHttpStatus());
+ assertEquals(Integer.valueOf(HttpStatus.NO_CONTENT.value()), resultNoContent.getHttpStatus());
DeleteA1PolicyOutput resultOk = nonrtRicApiProvider.deleteA1Policy(inputBuilder.build()).get().getResult();
- Assert.assertEquals(returnedBody, resultOk.getBody());
- Assert.assertTrue(HttpStatus.OK.value() == resultOk.getHttpStatus());
+ assertEquals(returnedBody, resultOk.getBody());
+ assertEquals(HTTP_OK_AS_INTEGER, resultOk.getHttpStatus());
}
@Test
inputBuilder.setNearRtRicUrl(nearRtRicUrl);
Whitebox.setInternalState(nonrtRicApiProvider, "restAdapter", restAdapter);
String returnedBody = "DELETE failed";
- int returnedStatusCode = 404;
+ Integer notFoundStatusCode = HttpStatus.NOT_FOUND.value();
when(restAdapter.delete(nearRtRicUrl.getValue()))
- .thenThrow(new RestClientResponseException(null, returnedStatusCode, null, null, returnedBody.getBytes(), null));
+ .thenThrow(new RestClientResponseException(null, notFoundStatusCode, null, null, returnedBody.getBytes(), null));
DeleteA1PolicyOutput result = nonrtRicApiProvider.deleteA1Policy(inputBuilder.build()).get().getResult();
- Assert.assertEquals(returnedBody, result.getBody());
- Assert.assertTrue(returnedStatusCode == result.getHttpStatus());
+ assertEquals(returnedBody, result.getBody());
+ assertEquals(notFoundStatusCode, result.getHttpStatus());
}
}
package org.o_ran_sc.nonrtric.sdnc_a1.northbound.restadapter;
+import static org.junit.Assert.assertEquals;
import java.io.IOException;
+import okhttp3.mockwebserver.MockResponse;
+import okhttp3.mockwebserver.MockWebServer;
+import okhttp3.mockwebserver.RecordedRequest;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestClientException;
-import okhttp3.mockwebserver.MockResponse;
-import okhttp3.mockwebserver.MockWebServer;
-import okhttp3.mockwebserver.RecordedRequest;
public class RestAdapterImplTest {
private static MockWebServer mockWebServer;
private static final String INVALID_PROTOCOL = "ftp";
private static final String REQUEST_URL = "/test";
private static final String TEST_BODY = "test";
- private static final int SUCCESS_CODE = 200;
- private static final int ERROR_CODE = 500;
+ private static final Integer SUCCESS_CODE = 200;
+ private static final Integer ERROR_CODE = 500;
@Before
public void init() throws IOException {
public void testInvalidUrlOrProtocol() throws InterruptedException {
ResponseEntity<String> response = adapterUnderTest.get("://localhost:" + mockWebServer.getPort() + REQUEST_URL,
String.class);
- Assert.assertTrue(HttpStatus.BAD_REQUEST.value() == response.getStatusCodeValue());
+ assertEquals(HttpStatus.BAD_REQUEST.value(), response.getStatusCodeValue());
response = adapterUnderTest.get(INVALID_PROTOCOL + "://localhost:" + mockWebServer.getPort() + REQUEST_URL,
String.class);
- Assert.assertTrue(HttpStatus.BAD_REQUEST.value() == response.getStatusCodeValue());
+ assertEquals(HttpStatus.BAD_REQUEST.value(), response.getStatusCodeValue());
}
@Test
ResponseEntity<String> response = adapterUnderTest.get(VALID_PROTOCOL + "://localhost:"
+ mockWebServer.getPort() + REQUEST_URL, String.class);
RecordedRequest recordedRequest = mockWebServer.takeRequest();
- Assert.assertEquals(TEST_BODY, response.getBody());
- Assert.assertTrue(SUCCESS_CODE == response.getStatusCodeValue());
- Assert.assertEquals("GET", recordedRequest.getMethod());
- Assert.assertEquals(REQUEST_URL, recordedRequest.getPath());
+ assertEquals(TEST_BODY, response.getBody());
+ assertEquals(SUCCESS_CODE.intValue(), response.getStatusCodeValue());
+ assertEquals("GET", recordedRequest.getMethod());
+ assertEquals(REQUEST_URL, recordedRequest.getPath());
}
@Test(expected = RestClientException.class)
ResponseEntity<String> response = adapterUnderTest.put(VALID_PROTOCOL + "://localhost:"
+ mockWebServer.getPort() + REQUEST_URL, TEST_BODY, String.class);
RecordedRequest recordedRequest = mockWebServer.takeRequest();
- Assert.assertEquals(TEST_BODY, response.getBody());
- Assert.assertTrue(SUCCESS_CODE == response.getStatusCodeValue());
- Assert.assertEquals("PUT", recordedRequest.getMethod());
- Assert.assertEquals(REQUEST_URL, recordedRequest.getPath());
- Assert.assertEquals(TEST_BODY, recordedRequest.getBody().readUtf8());
+ assertEquals(TEST_BODY, response.getBody());
+ assertEquals(SUCCESS_CODE.intValue(), response.getStatusCodeValue());
+ assertEquals("PUT", recordedRequest.getMethod());
+ assertEquals(REQUEST_URL, recordedRequest.getPath());
+ assertEquals(TEST_BODY, recordedRequest.getBody().readUtf8());
}
@Test(expected = RestClientException.class)
ResponseEntity<String> response = adapterUnderTest.delete(VALID_PROTOCOL + "://localhost:"
+ mockWebServer.getPort() + REQUEST_URL);
RecordedRequest recordedRequest = mockWebServer.takeRequest();
- Assert.assertTrue(SUCCESS_CODE == response.getStatusCodeValue());
- Assert.assertEquals("DELETE", recordedRequest.getMethod());
- Assert.assertEquals(REQUEST_URL, recordedRequest.getPath());
+ assertEquals(SUCCESS_CODE.intValue(), response.getStatusCodeValue());
+ assertEquals("DELETE", recordedRequest.getMethod());
+ assertEquals(REQUEST_URL, recordedRequest.getPath());
}
@Test(expected = RestClientException.class)
<groupId>org.o-ran-sc.nonrtric.sdnc-a1.northbound</groupId>
<artifactId>sdnc-a1-northbound</artifactId>
- <version>1.7.3-SNAPSHOT</version>
+ <version>1.7.5-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<packaging>pom</packaging>
<groupId>org.o-ran-sc.nonrtric.sdnc-a1.oam</groupId>
<artifactId>installation</artifactId>
- <version>1.7.3-SNAPSHOT</version>
+ <version>1.7.5-SNAPSHOT</version>
<name>sdnc-a1-oam :: installation</name>
<description>Installs SDN-C on local file system</description>
<packaging>pom</packaging>
<groupId>org.o-ran-sc.nonrtric.sdnc-a1.oam</groupId>
<artifactId>installation-sdnc-a1</artifactId>
- <version>1.7.3-SNAPSHOT</version>
+ <version>1.7.5-SNAPSHOT</version>
<name>sdnc-a1-oam :: installation :: ${project.artifactId}</name>
<description>Creates SDN Controller Docker container</description>
<properties>
- <standalone.image.name>o-ran-sc/nonrtric-a1-controller</standalone.image.name>
- <standalone.image.version>1.7.4-SNAPSHOT</standalone.image.version>
- <sdnc.project.version>${project.version}</sdnc.project.version>
- <sdnc.build.timestamp>${maven.build.timestamp}</sdnc.build.timestamp>
- <sdnc.northbound.version>1.7.3-SNAPSHOT</sdnc.northbound.version>
- <ccsdk.docker.version>0.7.0</ccsdk.docker.version>
- <docker.push.phase>deploy</docker.push.phase>
+ <standalone.image.name>o-ran-sc/nonrtric-a1-controller</standalone.image.name>
+ <standalone.image.version>1.7.5-SNAPSHOT</standalone.image.version>
+ <sdnc.project.version>${project.version}</sdnc.project.version>
+ <sdnc.build.timestamp>${maven.build.timestamp}</sdnc.build.timestamp>
+ <sdnc.northbound.version>1.7.5-SNAPSHOT</sdnc.northbound.version>
+ <ccsdk.docker.version>0.7.0</ccsdk.docker.version>
+ <docker.push.phase>deploy</docker.push.phase>
</properties>
<dependencies>
+# ============LICENSE_START===============================================
+# Modifications Copyright (C) 2020 Nordix Foundation. All rights reserved.
+# ========================================================================
+# Licensed 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.
+# ============LICENSE_END=================================================
+#
+
# Prepare stage for multistage image build
## START OF STAGE0 ##
FROM nexus3.onap.org:10001/onap/ccsdk-odlsli-alpine-image:${ccsdk.docker.version} AS stage0
+++ /dev/null
-###
-# ============LICENSE_START=======================================================
-# openECOMP : SDN-C
-# ================================================================================
-# Copyright (C) 2017 AT&T Intellectual Property. All rights
-# reserved.
-# ================================================================================
-# Licensed 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.
-# ============LICENSE_END=========================================================
-###
-
-#
-# Configuration file for A&AI Client
-#
-
-#
-# Certificate keystore and truststore
-#
-org.onap.ccsdk.sli.adaptors.aai.ssl.trust=/opt/onap/sdnc/data/stores/truststoreONAPall.jks
-org.onap.ccsdk.sli.adaptors.aai.ssl.trust.psswd=changeit
-org.onap.ccsdk.sli.adaptors.aai.host.certificate.ignore=true
-
-org.onap.ccsdk.sli.adaptors.aai.client.name=sdnc@sdnc.onap.org
-org.onap.ccsdk.sli.adaptors.aai.client.psswd=demo123456!
-
-org.onap.ccsdk.sli.adaptors.aai.application=openECOMP
-#
-# Configuration file for A&AI Client
-#
-org.onap.ccsdk.sli.adaptors.aai.uri=https://aai.api.simpledemo.openecomp.org:8443
-connection.timeout=60000
-read.timeout=60000
-
-# query
-org.onap.ccsdk.sli.adaptors.aai.path.query=/aai/v13/search/sdn-zone-query
-org.onap.ccsdk.sli.adaptors.aai.query.nodes=/aai/v13/search/nodes-query?search-node-type={node-type}&filter={entity-identifier}:EQUALS:{entity-name}
-org.onap.ccsdk.sli.adaptors.aai.query.generic=/aai/v13/search/generic-query?key={identifier}:{value}&start-node-type={start-node-type}&include=complex&depth=3
-
-# named query
-org.onap.ccsdk.sli.adaptors.aai.query.named=/aai/search/named-query
-
-#update
-org.onap.ccsdk.sli.adaptors.aai.update=/aai/v13/actions/update
-
-# UBB Notify
-org.onap.ccsdk.sli.adaptors.aai.path.notify=/aai/v13/actions/notify
-org.onap.ccsdk.sli.adaptors.aai.notify.selflink.fqdn=<%= @ubbUri %>/restconf/config/L3SDN-API:services/layer3-service-list/{service-instance-id}
-org.onap.ccsdk.sli.adaptors.aai.notify.selflink.avpn=<%= @ubbUri %>/restconf/config/L3AVPN-EVC-API:services/service-list/{service-instance-id}/service-data/avpn-logicalchannel-information
-
-# P-Interfaces
-org.onap.ccsdk.sli.adaptors.aai.path.pserver.pinterfaces=/aai/v13/cloud-infrastructure/pservers/pserver/{hostname}/p-interfaces
-org.onap.ccsdk.sli.adaptors.aai.path.pserver.pinterface=/aai/v13/cloud-infrastructure/pservers/pserver/{hostname}/p-interfaces/p-interface/{interface-name}
-
-# VNF IMAGES
-org.onap.ccsdk.sli.adaptors.aai.path.vnf.images=/aai/v13/service-design-and-creation/vnf-images
-org.onap.ccsdk.sli.adaptors.aai.path.vnf.image=/aai/v13/service-design-and-creation/vnf-images/vnf-image/{att-uuid}
-org.onap.ccsdk.sli.adaptors.aai.path.vnf.image.query=/aai/v13/service-design-and-creation/vnf-images/vnf-image?application={application_model}&application-vendor={application_vendor}
-
-# service instance
-org.onap.ccsdk.sli.adaptors.aai.path.svcinst.query=/aai/v13/search/generic-query?key=service-instance.service-instance-id:{svc-instance-id}&start-node-type=service-instance&include=service-instance
-org.onap.ccsdk.sli.adaptors.aai.path.service.instance=/aai/v13/business/customers/customer/{global-customer-id}/service-subscriptions/service-subscription/{service-type}/service-instances/service-instance/{service-instance-id}
-
-# VNF IMAGES QUERY
-org.onap.ccsdk.sli.adaptors.aai.path.vnf.image.query=/aai/v13/service-design-and-creation/vnf-images/vnf-image?application={application_model}&application-vendor={application_vendor}
-
-#
-# Formatting
-#
-org.onap.ccsdk.sli.adaptors.aai.param.format=filter=%s:%s
-org.onap.ccsdk.sli.adaptors.aai.param.vnf_type=vnf-type
-org.onap.ccsdk.sli.adaptors.aai.param.physical.location.id=physical-location-id
-org.onap.ccsdk.sli.adaptors.aai.param.service.type=service-type
+++ /dev/null
-###
-# Copyright � 2017-2018 AT&T Intellectual Property.
-# Modifications Copyright � 2018 IBM.
-#
-# Licensed 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.
-###
-#
-# Configuration file for SDNC Controller Module
-#
-
-org.onap.ccsdk.features.blueprints.adaptors.envtype=solo
-
-# Config Generator Microservices
-org.onap.ccsdk.features.blueprints.adaptors.modelservice.type=generic
-org.onap.ccsdk.features.blueprints.adaptors.modelservice.enable=true
-org.onap.ccsdk.features.blueprints.adaptors.modelservice.url=http://controller-blueprints:8080/api/v1/
-org.onap.ccsdk.features.blueprints.adaptors.modelservice.user=ccsdkapps
-org.onap.ccsdk.features.blueprints.adaptors.modelservice.passwd=ccsdkapps
-
-# Generic RESTCONF Adaptor
-org.onap.ccsdk.features.blueprints.adaptors.restconf.type=generic
-org.onap.ccsdk.features.blueprints.adaptors.restconf.enable=true
-org.onap.ccsdk.features.blueprints.adaptors.restconf.user=admin
-org.onap.ccsdk.features.blueprints.adaptors.restconf.passwd=Kp8bJ4SXszM0WXlhak3eHlcse2gAw84vaoGGmJvUy2U
-org.onap.ccsdk.features.blueprints.adaptors.restconf.url=http://sdnc:8282/restconf/
max-file: "5"
a1-controller:
- image: o-ran-sc/nonrtric-a1-controller:1.7.4-SNAPSHOT
+ image: o-ran-sc/nonrtric-a1-controller:1.7.5-SNAPSHOT
depends_on :
- db
container_name: a1-controller-container
<groupId>org.o-ran-sc.nonrtric.sdnc-a1.oam</groupId>
<artifactId>platform-logic-installer</artifactId>
- <version>1.7.3-SNAPSHOT</version>
+ <version>1.7.5-SNAPSHOT</version>
<packaging>pom</packaging>
<name>sdnc-a1-oam :: platform-logic :: ${project.artifactId}</name>
<groupId>org.o-ran-sc.nonrtric.sdnc-a1.oam</groupId>
<artifactId>platform-logic</artifactId>
- <version>1.7.3-SNAPSHOT</version>
+ <version>1.7.5-SNAPSHOT</version>
<packaging>pom</packaging>
<name>sdnc-a1-oam :: platform-logic</name>
<groupId>org.o-ran-sc.nonrtric.sdnc-a1.oam</groupId>
<artifactId>platform-logic-setup</artifactId>
- <version>1.7.3-SNAPSHOT</version>
+ <version>1.7.5-SNAPSHOT</version>
<packaging>pom</packaging>
<name>sdnc-a1-oam :: platform-logic :: ${project.artifactId}</name>
#! /bin/bash
+# ============LICENSE_START===============================================
+# Modifications Copyright (C) 2020 Nordix Foundation. All rights reserved.
+# ========================================================================
+# Licensed 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.
+# ============LICENSE_END=================================================
+#
+
updateFile() {
sed -i .orig -e '
s/openecomp.org/onap.org/g
#! /bin/bash
+# ============LICENSE_START===============================================
+# Modifications Copyright (C) 2020 Nordix Foundation. All rights reserved.
+# ========================================================================
+# Licensed 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.
+# ============LICENSE_END=================================================
+#
+
updateFile() {
sed -i .orig -e '
s/\(plugin=.\)org.openecomp.sdnc.\(prop\)/\org.onap.ccsdk.sli.plugins.\2/g
<groupId>org.o-ran-sc.nonrtric.sdnc-a1.oam</groupId>
<artifactId>sdnc-a1-oam</artifactId>
- <version>1.7.3-SNAPSHOT</version>
+ <version>1.7.5-SNAPSHOT</version>
<packaging>pom</packaging>
<name>sdnc-a1-oam</name>
<description>The SDN-C OAM component contains the components needed to operate, administer and maintain the SDN-C platform.</description>
- <url>https://wiki.onap.org</url>
- <organization>
- <name>AT&T</name>
- </organization>
<modules>
<module>platform-logic</module>
<groupId>org.o-ran-sc.nonrtric.sdnc-a1</groupId>
<artifactId>sdnc-a1</artifactId>
- <version>1.7.4-SNAPSHOT</version>
+ <version>1.7.5-SNAPSHOT</version>
<packaging>pom</packaging>
<name>sdnc-a1</name>
-----------------------------------------------------------
The ../common/testcase_common.sh contains all functions needed for the test case file. See the README.md file in
-the ../common dir for a description of all available functions.
\ No newline at end of file
+the ../common dir for a description of all available functions.
+
+## License
+
+Copyright (C) 2020 Nordix Foundation. All rights reserved.
+Licensed 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.
\ No newline at end of file
#!/bin/bash
+# ============LICENSE_START===============================================
+# Copyright (C) 2020 Nordix Foundation. All rights reserved.
+# ========================================================================
+# Licensed 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.
+# ============LICENSE_END=================================================
+#
+
TS_ONELINE_DESCR="Test suite - interface testing. Agent REST, DMAAP and SNDC controller resconf"
. ../common/testsuite_common.sh
separate logs stored at different steps in the test script.
If logs need to be stored in several locations, use different prefix to easily identify the location
when the logs where taken.
+
+## License
+
+Copyright (C) 2020 Nordix Foundation. All rights reserved.
+Licensed 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.
\ No newline at end of file
### Basic test ###
-Basic test is made with the script ```basic_test.sh``` which tests all the available urls with a subset of the possible operations. Use the script ```cr-build-start.sh``` to start the callback-receiver in a container first.
\ No newline at end of file
+Basic test is made with the script ```basic_test.sh``` which tests all the available urls with a subset of the possible operations. Use the script ```cr-build-start.sh``` to start the callback-receiver in a container first.
+
+## License
+
+Copyright (C) 2020 Nordix Foundation. All rights reserved.
+Licensed 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.
\ No newline at end of file
FROM python:3.8-slim-buster
COPY app/ /usr/src/app/
+COPY cert/ /usr/src/app/cert/
WORKDIR /usr/src/app/
```docker run -it -p 3905:3905 mrstub```
>Start the image on http and https<br>
+By default, this image has default certificates under /usr/src/app/cert
+file "cert.crt" is the certificate file
+file "key.crt" is the key file
+file "generate_cert_and_key.sh" is a shell script to generate certificate and key
+file "pass" stores the password when you run the shell script
+
+Start the a1-interface container without specifing external certificates:
+```docker run -it -p 3905:3905 -p 3906:3906 mrstub```
+
+It will listen to http 3905 port and https 3906 port(using default certificates) at the same time.
+
+This certificates/key can be overriden by mounting a volume when using "docker run" or "docker-compose"
+In 'docker run', use field:
+--volume "$PWD/certificate:/usr/src/app/cert" a1test
```docker run -it -p 3905:3905 -p 3906:3906 -v "/PATH_TO_CERT/cert:/usr/src/app/cert" mrstub```
+In 'docker-compose.yml', use field:
+volumes:
+ - ./certificate:/usr/src/app/cert:ro
The script ```mrstub-build-start.sh``` do the build and docker run in one go. This starts the stub container in stand-alone mode for basic test.<br>If the mrstub should be executed manually with the agent, replace docker run with this command to connect to the docker network with the correct service name (--name shall be the same as configured in consul for the read and write streams).
```docker run -it -p 3905:3905 --network nonrtric-docker-net --name message-router mrstub```
### Basic test ###
-Basic test is made with the script ```basic_test.sh nonsecure|secure``` which tests all the available urls with a subset of the possible operations. Choose nonsecure for http and secure for https. Use the script ```mrstub-build-start.sh``` to start the mrstub in a container first.
\ No newline at end of file
+Basic test is made with the script ```basic_test.sh nonsecure|secure``` which tests all the available urls with a subset of the possible operations. Choose nonsecure for http and secure for https. Use the script ```mrstub-build-start.sh``` to start the mrstub in a container first.
+
+## License
+
+Copyright (C) 2020 Nordix Foundation. All rights reserved.
+Licensed 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.
\ No newline at end of file
--- /dev/null
+#!/bin/bash
+
+# ============LICENSE_START===============================================
+# Copyright (C) 2020 Nordix Foundation. All rights reserved.
+# ========================================================================
+# Licensed 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.
+# ============LICENSE_END=================================================
+#
+
+# This will generate a self-signed certificate with password 'test'
+openssl req -x509 -passout pass:"test" -newkey rsa:2048 -keyout key.crt -out cert.crt -days 9999