summaryrefslogtreecommitdiffstats
path: root/policy-utils
diff options
context:
space:
mode:
Diffstat (limited to 'policy-utils')
-rw-r--r--policy-utils/pom.xml4
-rw-r--r--policy-utils/src/main/java/org/onap/policy/drools/metrics/Metric.java4
-rw-r--r--policy-utils/src/main/java/org/onap/policy/drools/policies/DomainMaker.java27
-rw-r--r--policy-utils/src/test/java/org/onap/policy/drools/metrics/MetricTest.java32
-rw-r--r--policy-utils/src/test/java/org/onap/policy/drools/policies/DomainMakerTest.java72
-rw-r--r--policy-utils/src/test/java/org/onap/policy/drools/utils/LookupTest.java57
-rw-r--r--policy-utils/src/test/java/org/onap/policy/drools/utils/PropertyUtilTest.java125
7 files changed, 234 insertions, 87 deletions
diff --git a/policy-utils/pom.xml b/policy-utils/pom.xml
index 319711a1..09c4e142 100644
--- a/policy-utils/pom.xml
+++ b/policy-utils/pom.xml
@@ -70,5 +70,9 @@
<groupId>net.jimblackler.jsonschemafriend</groupId>
<artifactId>core</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-test</artifactId>
+ </dependency>
</dependencies>
</project>
diff --git a/policy-utils/src/main/java/org/onap/policy/drools/metrics/Metric.java b/policy-utils/src/main/java/org/onap/policy/drools/metrics/Metric.java
index 01ff58f5..c2755211 100644
--- a/policy-utils/src/main/java/org/onap/policy/drools/metrics/Metric.java
+++ b/policy-utils/src/main/java/org/onap/policy/drools/metrics/Metric.java
@@ -3,6 +3,7 @@
* ONAP
* ================================================================================
* Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -134,8 +135,7 @@ public class Metric {
}
if (endTime != null && startTime != null) {
- this.elapsedTime =
- Duration.between(startTime, endTime).toMillis();
+ this.elapsedTime = Duration.between(startTime, endTime).toMillis();
return;
}
diff --git a/policy-utils/src/main/java/org/onap/policy/drools/policies/DomainMaker.java b/policy-utils/src/main/java/org/onap/policy/drools/policies/DomainMaker.java
index 84c81cf0..27dfee49 100644
--- a/policy-utils/src/main/java/org/onap/policy/drools/policies/DomainMaker.java
+++ b/policy-utils/src/main/java/org/onap/policy/drools/policies/DomainMaker.java
@@ -31,7 +31,6 @@ import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.common.utils.resources.ResourceUtils;
import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
-import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -70,7 +69,7 @@ public class DomainMaker {
return false;
}
- return validators.get(policyType).isConformant(json);
+ return getValidator(policyType).isConformant(json);
}
/**
@@ -94,7 +93,7 @@ public class DomainMaker {
}
try {
- return validators.get(policyType).encode(domainPolicy) != null;
+ return getValidator(policyType).encode(domainPolicy) != null;
} catch (CoderException e) {
logger.info("policy {}:{} is not conformant", policyType, domainPolicy.getClass().getName(), e);
return false;
@@ -116,7 +115,7 @@ public class DomainMaker {
}
try {
- validators.get(policy.getTypeIdentifier()).conformance(rawPolicy);
+ getValidator(policy.getTypeIdentifier()).conformance(rawPolicy);
} catch (CoderException e) {
logger.error("policy {}:{}:{} is not conformant",
policy.getTypeIdentifier(), policy.getName(), policy.getVersion(), e);
@@ -137,7 +136,7 @@ public class DomainMaker {
}
try {
- validators.get(policyType).encode(domainPolicy);
+ getValidator(policyType).encode(domainPolicy);
} catch (CoderException e) {
logger.error("policy {}:{} is not conformant", policyType, domainPolicy.getClass().getName(), e);
return false;
@@ -190,29 +189,21 @@ public class DomainMaker {
public <T> T convertTo(@NonNull ToscaConceptIdentifier policyType, @NonNull String json, @NonNull Class<T> clazz)
throws CoderException {
if (isRegistered(policyType)) {
- return validators.get(policyType).decode(json, clazz);
+ return getValidator(policyType).decode(json, clazz);
} else {
return nonValCoder.decode(json, clazz);
}
}
- /**
- * Converts a Tosca Policy Type specification to a domain-specific json specification.
- */
- public String convertToSchema(@NonNull ToscaPolicyType policyType) {
- //
- // TODO: // NOSONAR
- // 1. Convert Tosca Policy Type definition schema to suitable json schema.
- // 2. Call registerValidator to register
- throw new UnsupportedOperationException("schema generation from policy type is not supported");
- }
-
public boolean isRegistered(@NonNull ToscaConceptIdentifier policyType) {
return validators.containsKey(policyType) || registerValidator(policyType);
}
+ private StandardValCoder getValidator(ToscaConceptIdentifier policyType) {
+ return validators.get(policyType);
+ }
- private String serialize(@NonNull ToscaPolicy policy) {
+ private String serialize(ToscaPolicy policy) {
String rawPolicy = null;
try {
rawPolicy = nonValCoder.encode(policy);
diff --git a/policy-utils/src/test/java/org/onap/policy/drools/metrics/MetricTest.java b/policy-utils/src/test/java/org/onap/policy/drools/metrics/MetricTest.java
index 924d1c95..f1999cce 100644
--- a/policy-utils/src/test/java/org/onap/policy/drools/metrics/MetricTest.java
+++ b/policy-utils/src/test/java/org/onap/policy/drools/metrics/MetricTest.java
@@ -48,12 +48,12 @@ class MetricTest {
void testPojo() {
PojoClass metric = PojoClassFactory.getPojoClass(Metric.class);
Validator val = ValidatorBuilder
- .create()
- .with(new SetterMustExistRule())
- .with(new GetterMustExistRule())
- .with(new SetterTester())
- .with(new GetterTester())
- .build();
+ .create()
+ .with(new SetterMustExistRule())
+ .with(new GetterMustExistRule())
+ .with(new SetterTester())
+ .with(new GetterTester())
+ .build();
val.validate(metric);
}
@@ -190,4 +190,24 @@ class MetricTest {
Instant now = Instant.now();
assertEquals(new SimpleDateFormat(Metric.DATE_FORMAT).format(Date.from(now)), Metric.toTimestamp(now));
}
+
+ @Test
+ void testElapsedTime_EndTimeStartTimeNullValues() {
+ // test seems unnecessary, but when setElapsedTime receives null,
+ // the method tries to calculate elapsed time between start and end time,
+ // which only having the values was covered.
+ Metric metric = new Metric();
+
+ metric.setElapsedTime(null);
+ assertNull(metric.getElapsedTime());
+
+ metric.setEndTime(Instant.now());
+ metric.setElapsedTime(null);
+ assertNull(metric.getElapsedTime());
+
+ metric = new Metric();
+ metric.setStartTime(Instant.now());
+ metric.setElapsedTime(null);
+ assertNull(metric.getElapsedTime());
+ }
} \ No newline at end of file
diff --git a/policy-utils/src/test/java/org/onap/policy/drools/policies/DomainMakerTest.java b/policy-utils/src/test/java/org/onap/policy/drools/policies/DomainMakerTest.java
index f8ffa503..8fbf237f 100644
--- a/policy-utils/src/test/java/org/onap/policy/drools/policies/DomainMakerTest.java
+++ b/policy-utils/src/test/java/org/onap/policy/drools/policies/DomainMakerTest.java
@@ -26,6 +26,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
import java.io.IOException;
import java.nio.file.Files;
@@ -40,7 +42,7 @@ import org.onap.policy.drools.models.domains.a.Nested;
import org.onap.policy.drools.models.domains.a.Properties;
import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
-import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
+import org.springframework.test.util.ReflectionTestUtils;
class DomainMakerTest {
@@ -62,6 +64,13 @@ class DomainMakerTest {
policyTypeId.setVersion("2.0.0");
assertFalse(domainMaker.isConformant(policyTypeId, rawJsonPolicyType));
+
+ // for code coverage
+ assertThatThrownBy(() -> domainMaker.isConformant(null, "{\"json\":\"valid\"}"))
+ .hasMessageContaining("policyType is marked non-null but is null");
+
+ assertThatThrownBy(() -> domainMaker.isConformant(policyTypeId, null))
+ .hasMessageContaining("json is marked non-null but is null");
}
@Test
@@ -93,6 +102,12 @@ class DomainMakerTest {
// not registered schema for policy type
policyTypeId.setVersion("2.0.0");
assertFalse(domainMaker.isDomainConformant(policyTypeId, domainAPolicy));
+
+ assertThatThrownBy(() -> domainMaker.isDomainConformant(null, domainAPolicy))
+ .hasMessageContaining("policyType is marked non-null but is null");
+
+ assertThatThrownBy(() -> domainMaker.isDomainConformant(policyTypeId, null))
+ .hasMessageContaining("domainPolicy is marked non-null but is null");
}
@@ -117,6 +132,12 @@ class DomainMakerTest {
policy2.setTypeVersion("4.2.5");
assertFalse(domainMaker.conformance(policy2));
assertFalse(domainMaker.conformance(policy2.getTypeIdentifier(), domainAPolicy));
+
+ assertThatThrownBy(() -> domainMaker.conformance(null, domainAPolicy))
+ .hasMessageContaining("policyType is marked non-null but is null");
+
+ assertThatThrownBy(() -> domainMaker.conformance(null))
+ .hasMessageContaining("policy is marked non-null but is null");
}
@Test
@@ -136,6 +157,15 @@ class DomainMakerTest {
assertFalse(domainMaker.isConformant(policy));
assertFalse(domainMaker.registerValidator(policy.getTypeIdentifier(), "$schema"));
+
+ assertThatThrownBy(() -> domainMaker.registerValidator(null))
+ .hasMessageContaining("policyType is marked non-null but is null");
+
+ assertThatThrownBy(() -> domainMaker.registerValidator(null, "$schema"))
+ .hasMessageContaining("policyType is marked non-null but is null");
+
+ assertThatThrownBy(() -> domainMaker.registerValidator(policy.getTypeIdentifier(), null))
+ .hasMessageContaining("schema is marked non-null but is null");
}
@Test
@@ -146,14 +176,21 @@ class DomainMakerTest {
assertNotNull(domainMaker.convertTo(getToscaPolicy("src/test/resources/policyA-no-policy-type.json"),
DomainAPolicy.class));
- }
- @Test
- void testConvertToSchema() {
- ToscaPolicyType type = new ToscaPolicyType();
- assertThatThrownBy(() -> domainMaker
- .convertToSchema(type))
- .isInstanceOf(UnsupportedOperationException.class);
+ assertThatThrownBy(() -> domainMaker.convertTo(null, DomainAPolicy.class))
+ .hasMessageContaining("toscaPolicy is marked non-null but is null");
+
+ assertThatThrownBy(() -> domainMaker.convertTo(mock(ToscaPolicy.class), null))
+ .hasMessageContaining("clazz is marked non-null but is null");
+
+ assertThatThrownBy(() -> domainMaker.convertTo(null, "json", DomainAPolicy.class))
+ .hasMessageContaining("policyType is marked non-null but is null");
+
+ assertThatThrownBy(() -> domainMaker.convertTo(mock(ToscaConceptIdentifier.class), null, DomainAPolicy.class))
+ .hasMessageContaining("json is marked non-null but is null");
+
+ assertThatThrownBy(() -> domainMaker.convertTo(mock(ToscaConceptIdentifier.class), "json", null))
+ .hasMessageContaining("clazz is marked non-null but is null");
}
@Test
@@ -166,6 +203,25 @@ class DomainMakerTest {
new ToscaConceptIdentifier("policy.type.external", "7.7.9");
assertFalse(domainMaker.isRegistered(policyTypeId2));
+ assertThatThrownBy(() -> domainMaker.isRegistered(null))
+ .hasMessageContaining("policyType is marked non-null but is null");
+ }
+
+ @Test
+ void testIsConformant_SerializeReturnsNull() throws CoderException {
+ var mockDomainMaker = mock(DomainMaker.class);
+ var mockToscaPolicy = mock(ToscaPolicy.class);
+ when(mockDomainMaker.isConformant(mockToscaPolicy)).thenCallRealMethod();
+
+ var mockCoder = mock(StandardCoder.class);
+ when(mockCoder.encode(mockToscaPolicy)).thenThrow(new CoderException("error"));
+ ReflectionTestUtils.setField(mockDomainMaker, "nonValCoder", mockCoder);
+
+ assertFalse(mockDomainMaker.isConformant(mockToscaPolicy));
+
+ when(mockDomainMaker.conformance(mockToscaPolicy)).thenCallRealMethod();
+ when(mockDomainMaker.isRegistered(mockToscaPolicy.getTypeIdentifier())).thenReturn(true);
+ assertFalse(mockDomainMaker.conformance(mockToscaPolicy));
}
private String getJsonFromFile(String filePath) throws IOException {
diff --git a/policy-utils/src/test/java/org/onap/policy/drools/utils/LookupTest.java b/policy-utils/src/test/java/org/onap/policy/drools/utils/LookupTest.java
new file mode 100644
index 00000000..dd043b47
--- /dev/null
+++ b/policy-utils/src/test/java/org/onap/policy/drools/utils/LookupTest.java
@@ -0,0 +1,57 @@
+/*-
+ * ============LICENSE_START================================================
+ * Copyright (C) 2024 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==================================================
+ */
+
+package org.onap.policy.drools.utils;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import org.junit.jupiter.api.Test;
+import org.onap.policy.common.utils.security.CryptoCoder;
+
+class LookupTest {
+
+ @Test
+ void testCryptoLookup() {
+ var cryptoCoder = new CryptoCoderValueLookup(new CryptoCoder() {
+ @Override
+ public String encrypt(String s) {
+ return String.valueOf(s.hashCode());
+ }
+
+ @Override
+ public String decrypt(String s) {
+ return s;
+ }
+ });
+
+ assertTrue(cryptoCoder.lookup("hello").startsWith("enc"));
+ assertNull(cryptoCoder.lookup(null));
+ assertNull(cryptoCoder.lookup(""));
+ }
+
+ @Test
+ void testEnvDefaultLookup() {
+ var envLookup = new EnvironmentVariableWithDefaultLookup();
+
+ assertNull(envLookup.lookup(null));
+ assertNull(envLookup.lookup(""));
+ assertEquals("", envLookup.lookup(":"));
+ }
+} \ No newline at end of file
diff --git a/policy-utils/src/test/java/org/onap/policy/drools/utils/PropertyUtilTest.java b/policy-utils/src/test/java/org/onap/policy/drools/utils/PropertyUtilTest.java
index f2676e5d..bec22237 100644
--- a/policy-utils/src/test/java/org/onap/policy/drools/utils/PropertyUtilTest.java
+++ b/policy-utils/src/test/java/org/onap/policy/drools/utils/PropertyUtilTest.java
@@ -22,6 +22,8 @@
package org.onap.policy.drools.utils;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
@@ -93,7 +95,8 @@ public class PropertyUtilTest {
// create a directory for temporary files
directory = new File(UUID.randomUUID().toString());
- directory.mkdir();
+ var isDirCreated = directory.mkdir();
+ logger.info("directory created: {}", isDirCreated);
}
/**
@@ -141,8 +144,7 @@ public class PropertyUtilTest {
public void propertiesChanged(Properties properties, Set<String> changedKeys) {
// When a notification is received, store the values in the
// 'returns' array, and signal using the same array.
- logger.info("Listener invoked: properties=" + properties
- + ", changedKeys=" + changedKeys);
+ logger.info("Listener invoked: properties={}, changedKeys={}", properties, changedKeys);
returns[0] = properties;
returns[1] = changedKeys;
synchronized (returns) {
@@ -181,6 +183,73 @@ public class PropertyUtilTest {
}
+ /**
+ * This tests the 'PropertyUtil.Listener' interface.
+ */
+ @Test
+ void testListenerInterface() throws Exception {
+ logger.info("testListenerInterface: test receipt of dynamic updates");
+
+ // create initial property file
+ Properties prop1 = new Properties();
+ prop1.setProperty("p1", "p1 value");
+ prop1.setProperty("p2", "p2 value");
+ prop1.setProperty("p3", "p3 value");
+ logger.info("Create initial properties file: {}", prop1);
+ File file1 = createFile("createAndReadPropertyFile-2", prop1);
+
+ // create a listener for the notification interface
+ Object[] returns = new Object[2];
+ PropertyUtil.Listener listener = createListenerThread(returns);
+
+ // read it in, and do a comparison
+ Properties prop2 = PropertyUtil.getProperties(file1, listener);
+ logger.info("Read in properties: {}", prop2);
+ assertEquals(prop1, prop2);
+ assertEquals("p1 value", prop2.getProperty("p1"));
+ assertEquals("p2 value", prop2.getProperty("p2"));
+ assertEquals("p3 value", prop2.getProperty("p3"));
+
+ // make some changes, and update the file (p3 is left unchanged)
+ prop2.remove("p1"); // remove one property
+ prop2.setProperty("p2", "new p2 value"); // change one property
+ prop2.setProperty("p4", "p4 value"); // add a new property
+ logger.info("Modified properties: {}", prop2);
+
+ // now, update the file, and wait for notification
+ synchronized (returns) {
+ createFile("createAndReadPropertyFile-2", prop2);
+
+ // wait up to 60 seconds, although we should receive notification
+ // in 10 seconds or less (if things are working)
+ returns.wait(60000L);
+ }
+
+ // verify we have the updates
+ assertEquals(prop2, returns[0]);
+
+ // verify that we have the expected set of keys
+ assertEquals(new TreeSet<>(Arrays.asList("p1", "p2", "p4")), returns[1]);
+
+ String filePath = file1.getAbsolutePath();
+ PropertyUtil.stopListening(filePath, listener);
+ }
+
+ @Test
+ void testGetProperties_ListenerNull() throws IOException {
+ String filepath = "src/test/resources/interpolation.properties";
+ File propertiesFile = new File(filepath);
+ assertNotNull(propertiesFile);
+ PropertyUtil.Listener listener = null;
+ var result = PropertyUtil.getProperties(propertiesFile, listener);
+ assertNotNull(result);
+ assertInstanceOf(Properties.class, result);
+
+ var anotherResult = PropertyUtil.getProperties(filepath, listener);
+ assertNotNull(anotherResult);
+ assertInstanceOf(Properties.class, anotherResult);
+ }
+
private void testGetDefaultCryptoSystemProps() throws IOException {
// system properties + default crypto coder
PropertyUtil.setDefaultCryptoCoder(new CryptoUtils(INTERPOLATION_CRYPTO_KEY));
@@ -251,54 +320,4 @@ public class PropertyUtilTest {
assertEquals(System.getProperty("user.home"), props.getProperty(INTERPOLATION_SYS));
assertEquals(INTERPOLATION_ENVD_DEFAULT_VALUE, props.getProperty(INTERPOLATION_ENVD_DEFAULT));
}
-
- /**
- * This tests the 'PropertyUtil.Listener' interface.
- */
- @Test
- void testListenerInterface() throws Exception {
- logger.info("testListenerInterface: test receipt of dynamic updates");
-
- // create initial property file
- Properties prop1 = new Properties();
- prop1.setProperty("p1", "p1 value");
- prop1.setProperty("p2", "p2 value");
- prop1.setProperty("p3", "p3 value");
- logger.info("Create initial properties file: " + prop1);
- File file1 = createFile("createAndReadPropertyFile-2", prop1);
-
- // create a listener for the notification interface
- Object[] returns = new Object[2];
- PropertyUtil.Listener listener = createListenerThread(returns);
-
- // read it in, and do a comparison
- Properties prop2 = PropertyUtil.getProperties(file1, listener);
- logger.info("Read in properties: " + prop2);
- assertEquals(prop1, prop2);
- assertEquals("p1 value", prop2.getProperty("p1"));
- assertEquals("p2 value", prop2.getProperty("p2"));
- assertEquals("p3 value", prop2.getProperty("p3"));
-
- // make some changes, and update the file (p3 is left unchanged)
- prop2.remove("p1"); // remove one property
- prop2.setProperty("p2", "new p2 value"); // change one property
- prop2.setProperty("p4", "p4 value"); // add a new property
- logger.info("Modified properties: " + prop2);
-
- // now, update the file, and wait for notification
- synchronized (returns) {
- createFile("createAndReadPropertyFile-2", prop2);
-
- // wait up to 60 seconds, although we should receive notification
- // in 10 seconds or less (if things are working)
- returns.wait(60000L);
- }
-
- // verify we have the updates
- assertEquals(prop2, returns[0]);
-
- // verify that we have the expected set of keys
- assertEquals(new TreeSet<String>(Arrays.asList(new String[]{"p1", "p2", "p4"})),
- returns[1]);
- }
}