Fix sonar test renaming issues 86/74686/1
authorliamfallon <liam.fallon@est.tech>
Sat, 15 Dec 2018 09:47:58 +0000 (09:47 +0000)
committerliamfallon <liam.fallon@est.tech>
Sat, 15 Dec 2018 09:48:04 +0000 (09:48 +0000)
Renaming tests introduced Sonar issues:
 - Tests where coverage was <80% flagged as they are new code
 - Support test classes with names ending in "Test" flagged
   becasue they did not contain test cases

Issue-ID: POLICY-1263
Change-Id: I17a4b27b2952a4978fab1c76579a013478b60ae1
Signed-off-by: liamfallon <liam.fallon@est.tech>
24 files changed:
model/basic-model/pom.xml
model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelReader.java
model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelWriter.java
model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/test/TestApexModel.java
model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/AxConceptGetterImplTest.java [new file with mode: 0644]
model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/AxKeyInfoTest.java
model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/AxKeyTest.java
model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/AxReferenceKeyTest.java
model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelReaderTest.java
model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelWriterTest.java
model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/SupportApexModelCreator0.java [moved from model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestApexModelCreator0Test.java with 96% similarity]
model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/SupportApexModelCreator1.java [moved from model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestApexModelCreator1Test.java with 97% similarity]
model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/SupportApexModelCreator2.java [moved from model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestApexModelCreator2Test.java with 96% similarity]
model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/SupportBasicModelTester.java
model/policy-model/src/test/java/org/onap/policy/apex/model/policymodel/concepts/PoliciesTest.java
model/policy-model/src/test/java/org/onap/policy/apex/model/policymodel/concepts/PolicyModelTest.java
model/policy-model/src/test/java/org/onap/policy/apex/model/policymodel/handling/ApexPolicyModelTest.java
model/policy-model/src/test/java/org/onap/policy/apex/model/policymodel/handling/PolicyAnalyserTest.java
model/policy-model/src/test/java/org/onap/policy/apex/model/policymodel/handling/PolicyModelComparerTest.java
model/policy-model/src/test/java/org/onap/policy/apex/model/policymodel/handling/PolicyModelMergerTest.java
model/policy-model/src/test/java/org/onap/policy/apex/model/policymodel/handling/PolicyModelSplitterTest.java
model/policy-model/src/test/java/org/onap/policy/apex/model/policymodel/handling/SupportApexPolicyModelCreator.java [moved from model/policy-model/src/test/java/org/onap/policy/apex/model/policymodel/handling/ApexPolicyModelCreatorTest.java with 99% similarity]
testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/file/TestFile2FileFiltered.java
testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/restclient/TestRest2File.java

index 3f33759..ca90e25 100644 (file)
             <groupId>org.eclipse.persistence</groupId>
             <artifactId>eclipselink</artifactId>
         </dependency>
+        <dependency>
+            <groupId>org.mockito</groupId>
+            <artifactId>mockito-all</artifactId>
+            <scope>test</scope>
+        </dependency>
     </dependencies>
 
     <build>
index e76d00e..f340f73 100644 (file)
@@ -260,7 +260,7 @@ public class ApexModelReader<C extends AxConcept> {
             }
             catch (final Exception e) {
                 LOGGER.warn("JAXB error setting marshaller for JSON Input", e);
-                throw new ApexModelException("JAXB error setting marshaller for JSON Input", e);
+                throw new ApexModelException("JAXB error setting unmarshaller for JSON input", e);
             }
         }
         else if (Pattern.compile(XML_INPUT_TYPE_REGEXP).matcher(apexConceptString).find()) {
@@ -270,7 +270,7 @@ public class ApexModelReader<C extends AxConcept> {
             }
             catch (final Exception e) {
                 LOGGER.warn("JAXB error setting marshaller for XML Input", e);
-                throw new ApexModelException("JAXB error setting marshaller for XML Input", e);
+                throw new ApexModelException("JAXB error setting unmarshaller for XML input", e);
             }
         }
         else {
index 6cc5422..eded9fd 100644 (file)
@@ -217,8 +217,8 @@ public class ApexModelWriter<C extends AxConcept> {
                             cdataFieldSet.toString().replaceAll("[\\[\\]\\,]", " "));
             domTransformer.transform(new DOMSource(document), new StreamResult(apexConceptWriter));
         } catch (JAXBException | TransformerException | ParserConfigurationException e) {
-            LOGGER.warn("Unable to marshal Apex concept XML", e);
-            throw new ApexModelException("Unable to marshal Apex concept XML", e);
+            LOGGER.warn("Unable to marshal Apex concept to XML", e);
+            throw new ApexModelException("Unable to marshal Apex concept to XML", e);
         }
         LOGGER.debug("wrote Apex concept XML");
     }
@@ -254,8 +254,8 @@ public class ApexModelWriter<C extends AxConcept> {
         try {
             marshaller.marshal(concept, apexConceptWriter);
         } catch (final JAXBException e) {
-            LOGGER.warn("Unable to marshal Apex concept JSON", e);
-            throw new ApexModelException("Unable to marshal Apex concept JSON", e);
+            LOGGER.warn("Unable to marshal Apex concept to JSON", e);
+            throw new ApexModelException("Unable to marshal Apex concept to JSON", e);
         }
         LOGGER.debug("wrote Apex concept JSON");
     }
index 24c682d..6bab169 100644 (file)
@@ -108,10 +108,7 @@ public class TestApexModel<M extends AxModel> {
         try {
             final URL apexModelUrl = ResourceUtils.getLocalFile(xmlFile.getAbsolutePath());
             final M fileModel = modelReader.read(apexModelUrl.openStream());
-            if (!model.equals(fileModel)) {
-                LOGGER.warn(TEST_MODEL_UNEQUAL_STR + xmlFile.getAbsolutePath());
-                throw new ApexException(TEST_MODEL_UNEQUAL_STR + xmlFile.getAbsolutePath());
-            }
+            checkModelEquality(model, fileModel, TEST_MODEL_UNEQUAL_STR + xmlFile.getAbsolutePath());
         } catch (final Exception e) {
             LOGGER.warn(ERROR_PROCESSING_FILE + xmlFile.getAbsolutePath(), e);
             throw new ApexException(ERROR_PROCESSING_FILE + xmlFile.getAbsolutePath(), e);
@@ -126,10 +123,8 @@ public class TestApexModel<M extends AxModel> {
         modelWriter.write(model, baOutputStream);
         final ByteArrayInputStream baInputStream = new ByteArrayInputStream(baOutputStream.toByteArray());
         final M byteArrayModel = modelReader.read(baInputStream);
-        if (!model.equals(byteArrayModel)) {
-            LOGGER.warn("test model does not equal XML marshalled and unmarshalled model");
-            throw new ApexException("test model does not equal XML marshalled and unmarshalled model");
-        }
+
+        checkModelEquality(model, byteArrayModel, "test model does not equal XML marshalled and unmarshalled model");
 
         LOGGER.debug("ran testApexModelWriteReadXML");
     }
@@ -161,11 +156,7 @@ public class TestApexModel<M extends AxModel> {
         try {
             final URL apexModelUrl = ResourceUtils.getLocalFile(jsonFile.getAbsolutePath());
             final M fileModel = modelReader.read(apexModelUrl.openStream());
-            if (!model.equals(fileModel)) {
-                LOGGER.warn(TEST_MODEL_UNEQUAL_STR + jsonFile.getAbsolutePath());
-                throw new ApexException(
-                                TEST_MODEL_UNEQUAL_STR + jsonFile.getAbsolutePath());
-            }
+            checkModelEquality(model, fileModel, TEST_MODEL_UNEQUAL_STR + jsonFile.getAbsolutePath());
         } catch (final Exception e) {
             LOGGER.warn(ERROR_PROCESSING_FILE + jsonFile.getAbsolutePath(), e);
             throw new ApexException(ERROR_PROCESSING_FILE + jsonFile.getAbsolutePath(), e);
@@ -178,10 +169,8 @@ public class TestApexModel<M extends AxModel> {
         modelWriter.write(model, baOutputStream);
         final ByteArrayInputStream baInputStream = new ByteArrayInputStream(baOutputStream.toByteArray());
         final M byteArrayModel = modelReader.read(baInputStream);
-        if (!model.equals(byteArrayModel)) {
-            LOGGER.warn("test model does not equal JSON marshalled and unmarshalled model");
-            throw new ApexException("test model does not equal JSON marshalled and unmarshalled model");
-        }
+        
+        checkModelEquality(model, byteArrayModel, "test model does not equal JSON marshalled and unmarshalled model");
 
         LOGGER.debug("ran testApexModelWriteReadJSON");
     }
@@ -204,10 +193,7 @@ public class TestApexModel<M extends AxModel> {
         final M dbJpaModel = apexDao.get(rootModelClass, model.getKey());
         apexDao.close();
 
-        if (!model.equals(dbJpaModel)) {
-            LOGGER.warn("test model does not equal model written and read using generic JPA");
-            throw new ApexException("test model does not equal model written and read using generic JPA");
-        }
+        checkModelEquality(model, dbJpaModel, "test model does not equal model written and read using generic JPA");
 
         LOGGER.debug("ran testApexModelWriteReadJPA");
     }
@@ -331,4 +317,20 @@ public class TestApexModel<M extends AxModel> {
         LOGGER.debug("ran testApexModelVaidateInvalidModel");
         return result;
     }
+
+    /**
+     * Check if two models are equal.
+     * 
+     * @param leftModel the left model
+     * @param rightModel the right model
+     * @param errorMessage the error message to output on inequality
+     * @throws ApexException the exception to throw on inequality
+     */
+    public void checkModelEquality(final M leftModel, final M rightModel, final String errorMessage)
+        throws ApexException {
+        if (!leftModel.equals(rightModel)) {
+            LOGGER.warn(errorMessage);
+            throw new ApexException(errorMessage);
+        }
+    }
 }
diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/AxConceptGetterImplTest.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/AxConceptGetterImplTest.java
new file mode 100644 (file)
index 0000000..b00e7db
--- /dev/null
@@ -0,0 +1,96 @@
+/*-
+ * ============LICENSE_START=======================================================
+ *  Copyright (C) 2018 Ericsson. 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.
+ * 
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.apex.model.basicmodel.concepts;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.fail;
+
+import java.util.NavigableMap;
+import java.util.TreeMap;
+import java.util.TreeSet;
+
+import org.junit.Test;
+
+/**
+ * Test the AxConceptGetterImpl class.
+ */
+public class AxConceptGetterImplTest {
+
+    @Test
+    public void testAxConceptGetterImpl() {
+        NavigableMap<AxArtifactKey, AxArtifactKey> keyMap = new TreeMap<>();
+
+        AxConceptGetterImpl<AxArtifactKey> getter = new AxConceptGetterImpl<>(keyMap);
+        assertNotNull(getter);
+        
+        AxArtifactKey keyA = new AxArtifactKey("A", "0.0.1");
+        assertNull(getter.get(keyA));
+        
+        try {
+            getter.get((String)null);
+            fail("test should throw an exception here");
+        }
+        catch (Exception getException) {
+            assertEquals("conceptKeyName may not be null", getException.getMessage());
+        }
+
+        assertNull(getter.get("W"));
+
+        AxArtifactKey keyZ = new AxArtifactKey("Z", "0.0.1");
+        keyMap.put(keyZ, keyZ);
+        assertNull(getter.get("W"));
+
+        AxArtifactKey keyW001 = new AxArtifactKey("W", "0.0.1");
+        keyMap.put(keyW001, keyW001);
+        assertEquals(keyW001, getter.get("W"));
+
+        AxArtifactKey keyW002 = new AxArtifactKey("W", "0.0.2");
+        keyMap.put(keyW002, keyW002);
+        assertEquals(keyW002, getter.get("W"));
+
+        keyMap.remove(keyZ);
+        assertEquals(keyW002, getter.get("W"));
+
+        try {
+            getter.get((String)null, "0.0.1");
+            fail("test should throw an exception here");
+        }
+        catch (Exception getException) {
+            assertEquals("conceptKeyName may not be null", getException.getMessage());
+        }
+
+        assertEquals(keyW002, getter.get("W", "0.0.2"));
+        assertEquals(keyW002, getter.get("W", (String)null));
+        
+        assertEquals(new TreeSet<AxArtifactKey>(keyMap.values()), getter.getAll(null));
+        assertEquals(new TreeSet<AxArtifactKey>(keyMap.values()), getter.getAll(null, null));
+        
+        assertEquals(keyW001, getter.getAll("W", null).iterator().next());
+        assertEquals(keyW002, getter.getAll("W", "0.0.2").iterator().next());
+        assertEquals(0, getter.getAll("A", null).size());
+        assertEquals(0, getter.getAll("Z", null).size());
+
+        keyMap.put(keyZ, keyZ);
+        assertEquals(keyW002, getter.getAll("W", "0.0.2").iterator().next());
+    }
+}
index 3f1635c..b00be2f 100644 (file)
@@ -44,6 +44,7 @@ public class AxKeyInfoTest {
         AxKeyInfo testKeyInfo = new AxKeyInfo();
         testKeyInfo.setKey((new AxArtifactKey("PN", "0.0.1")));
         assertEquals("PN:0.0.1", testKeyInfo.getKey().getId());
+        assertTrue(testKeyInfo.matchesId("PN:0.0.1"));
 
         AxArtifactKey key = new AxArtifactKey("key", "0.0.1");
         testKeyInfo.setKey(key);
index ea09cc6..c3c87b9 100644 (file)
@@ -26,6 +26,8 @@ import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
+import java.lang.reflect.Field;
+
 import org.junit.Test;
 import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
 import org.onap.policy.apex.model.basicmodel.concepts.AxKey;
@@ -124,4 +126,42 @@ public class AxKeyTest {
         assertFalse(((AxKey) someKey0).equals(new AxReferenceKey()));
     }
 
+
+    @Test
+    public void testValidation() {
+        AxArtifactKey testKey = new AxArtifactKey("TheKey", "0.0.1");
+        assertEquals("TheKey:0.0.1", testKey.getId());
+
+        try {
+            Field nameField = testKey.getClass().getDeclaredField("name");
+            nameField.setAccessible(true);
+            nameField.set(testKey, "Key Name");
+            AxValidationResult validationResult = new AxValidationResult();
+            testKey.validate(validationResult);
+            nameField.set(testKey, "TheKey");
+            nameField.setAccessible(false);
+            assertEquals(
+                "name invalid-parameter name with value Key Name "
+                    + "does not match regular expression [A-Za-z0-9\\-_\\.]+",
+                validationResult.getMessageList().get(0).getMessage());
+        } catch (Exception validationException) {
+            fail("test should not throw an exception");
+        }
+
+        try {
+            Field versionField = testKey.getClass().getDeclaredField("version");
+            versionField.setAccessible(true);
+            versionField.set(testKey, "Key Version");
+            AxValidationResult validationResult = new AxValidationResult();
+            testKey.validate(validationResult);
+            versionField.set(testKey, "0.0.1");
+            versionField.setAccessible(false);
+            assertEquals(
+                "version invalid-parameter version with value Key Version "
+                    + "does not match regular expression [A-Za-z0-9.]+",
+                validationResult.getMessageList().get(0).getMessage());
+        } catch (Exception validationException) {
+            fail("test should not throw an exception");
+        }
+    }
 }
index 68be4cd..27726a9 100644 (file)
@@ -25,6 +25,9 @@ import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotEquals;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.lang.reflect.Field;
 
 import org.junit.Test;
 import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
@@ -83,7 +86,7 @@ public class AxReferenceKeyTest {
 
         AxReferenceKey clonedReferenceKey = new AxReferenceKey(testReferenceKey);
         assertEquals("AxReferenceKey:(parentKeyName=NPKN,parentKeyVersion=0.0.1,parentLocalName=NPKLN,localName=NLN)",
-                        clonedReferenceKey.toString());
+            clonedReferenceKey.toString());
 
         assertFalse(testReferenceKey.hashCode() == 0);
 
@@ -106,5 +109,101 @@ public class AxReferenceKeyTest {
         assertEquals(0, testReferenceKey.compareTo(new AxReferenceKey("NPKN", "0.0.1", "NPKLN", "NLN")));
 
         assertNotNull(testReferenceKey.getKeys());
+
+        try {
+            testReferenceKey.equals(null);
+            fail("test should throw an exception here");
+        } catch (Exception iae) {
+            assertEquals("comparison object may not be null", iae.getMessage());
+        }
+
+        try {
+            testReferenceKey.copyTo(null);
+            fail("test should throw an exception here");
+        } catch (Exception iae) {
+            assertEquals("target may not be null", iae.getMessage());
+        }
+
+        try {
+            testReferenceKey.copyTo(new AxArtifactKey("Key", "0.0.1"));
+            fail("test should throw an exception here");
+        } catch (Exception iae) {
+            assertEquals("org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey is not an instance of "
+                + "org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey", iae.getMessage());
+        }
+
+        AxReferenceKey targetRefKey = new AxReferenceKey();
+        assertEquals(testReferenceKey, testReferenceKey.copyTo(targetRefKey));
+    }
+
+    @Test
+    public void testValidation() {
+        AxReferenceKey testReferenceKey = new AxReferenceKey();
+        testReferenceKey.setParentArtifactKey(new AxArtifactKey("PN", "0.0.1"));
+        assertEquals("PN:0.0.1", testReferenceKey.getParentArtifactKey().getId());
+
+        try {
+            Field parentNameField = testReferenceKey.getClass().getDeclaredField("parentKeyName");
+            parentNameField.setAccessible(true);
+            parentNameField.set(testReferenceKey, "Parent Name");
+            AxValidationResult validationResult = new AxValidationResult();
+            testReferenceKey.validate(validationResult);
+            parentNameField.set(testReferenceKey, "ParentName");
+            parentNameField.setAccessible(false);
+            assertEquals(
+                "parentKeyName invalid-parameter parentKeyName with value Parent Name "
+                    + "does not match regular expression [A-Za-z0-9\\-_\\.]+",
+                validationResult.getMessageList().get(0).getMessage());
+        } catch (Exception validationException) {
+            fail("test should not throw an exception");
+        }
+
+        try {
+            Field parentVersionField = testReferenceKey.getClass().getDeclaredField("parentKeyVersion");
+            parentVersionField.setAccessible(true);
+            parentVersionField.set(testReferenceKey, "Parent Version");
+            AxValidationResult validationResult = new AxValidationResult();
+            testReferenceKey.validate(validationResult);
+            parentVersionField.set(testReferenceKey, "0.0.1");
+            parentVersionField.setAccessible(false);
+            assertEquals(
+                "parentKeyVersion invalid-parameter parentKeyVersion with value Parent Version "
+                    + "does not match regular expression [A-Za-z0-9.]+",
+                validationResult.getMessageList().get(0).getMessage());
+        } catch (Exception validationException) {
+            fail("test should not throw an exception");
+        }
+
+        try {
+            Field parentLocalNameField = testReferenceKey.getClass().getDeclaredField("parentLocalName");
+            parentLocalNameField.setAccessible(true);
+            parentLocalNameField.set(testReferenceKey, "Parent Local Name");
+            AxValidationResult validationResult = new AxValidationResult();
+            testReferenceKey.validate(validationResult);
+            parentLocalNameField.set(testReferenceKey, "ParentLocalName");
+            parentLocalNameField.setAccessible(false);
+            assertEquals(
+                "parentLocalName invalid-parameter parentLocalName with value "
+                    + "Parent Local Name does not match regular expression [A-Za-z0-9\\-_\\.]+|^$",
+                validationResult.getMessageList().get(0).getMessage());
+        } catch (Exception validationException) {
+            fail("test should not throw an exception");
+        }
+
+        try {
+            Field localNameField = testReferenceKey.getClass().getDeclaredField("localName");
+            localNameField.setAccessible(true);
+            localNameField.set(testReferenceKey, "Local Name");
+            AxValidationResult validationResult = new AxValidationResult();
+            testReferenceKey.validate(validationResult);
+            localNameField.set(testReferenceKey, "LocalName");
+            localNameField.setAccessible(false);
+            assertEquals(
+                "localName invalid-parameter localName with value Local Name "
+                    + "does not match regular expression [A-Za-z0-9\\-_\\.]+|^$",
+                validationResult.getMessageList().get(0).getMessage());
+        } catch (Exception validationException) {
+            fail("test should not throw an exception");
+        }
     }
 }
index 20815ae..d560f62 100644 (file)
@@ -32,14 +32,25 @@ import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileReader;
 import java.io.IOException;
+import java.lang.reflect.Field;
+
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.PropertyException;
+import javax.xml.bind.Unmarshaller;
+import javax.xml.transform.stream.StreamSource;
 
 import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
 import org.onap.policy.apex.model.basicmodel.concepts.AxModel;
 import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader;
 import org.onap.policy.apex.model.basicmodel.handling.ApexModelWriter;
 
 public class ApexModelReaderTest {
+    @Mock
+    private Unmarshaller unmarshallerMock;
 
     @Test
     public void testModelReader() throws IOException, ApexException {
@@ -149,4 +160,48 @@ public class ApexModelReaderTest {
         
         modelReader.setSchema("xml/example.xsd");
     }
+
+    @Test
+    public void testSetInputTypeError() throws ApexModelException {
+        MockitoAnnotations.initMocks(this);
+
+        ApexModelReader<AxModel> modelReader = new ApexModelReader<AxModel>(AxModel.class, true);
+
+        try {
+            Field marshallerField = modelReader.getClass().getDeclaredField("unmarshaller");
+            marshallerField.setAccessible(true);
+            marshallerField.set(modelReader, unmarshallerMock);
+            marshallerField.setAccessible(false);
+        } catch (Exception validationException) {
+            fail("test should not throw an exception");
+        }
+
+        try {
+            Mockito.doThrow(new JAXBException("Exception marshalling to JSON")).when(unmarshallerMock)
+                .unmarshal((StreamSource)Mockito.anyObject(), Mockito.anyObject());
+
+            modelReader.read("{Hello}");
+            fail("Test should throw an exception here");
+        } catch (Exception jaxbe) {
+            assertEquals("Unable to unmarshal Apex concept ", jaxbe.getMessage());
+        }
+
+        try {
+            Mockito.doThrow(new PropertyException("Exception setting JAXB property")).when(unmarshallerMock)
+                .setProperty(Mockito.anyString(), Mockito.anyString());
+            modelReader.read("{Hello}");
+            fail("Test should throw an exception here");
+        } catch (Exception jaxbe) {
+            assertEquals("JAXB error setting unmarshaller for JSON input", jaxbe.getMessage());
+        }
+
+        try {
+            Mockito.doThrow(new PropertyException("Exception setting JAXB property")).when(unmarshallerMock)
+                .setProperty(Mockito.anyString(), Mockito.anyString());
+            modelReader.read("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
+            fail("Test should throw an exception here");
+        } catch (Exception jaxbe) {
+            assertEquals("JAXB error setting unmarshaller for XML input", jaxbe.getMessage());
+        }
+    }
 }
index d7ff4c0..d25e191 100644 (file)
@@ -27,13 +27,25 @@ import static org.junit.Assert.fail;
 
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
+import java.io.Writer;
+import java.lang.reflect.Field;
+
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Marshaller;
+import javax.xml.bind.PropertyException;
 
 import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
 import org.onap.policy.apex.model.basicmodel.concepts.AxModel;
 import org.onap.policy.apex.model.basicmodel.handling.ApexModelWriter;
+import org.w3c.dom.Document;
 
 public class ApexModelWriterTest {
+    @Mock
+    private Marshaller marshallerMock;
 
     @Test
     public void testModelWriter() throws IOException, ApexException {
@@ -89,4 +101,103 @@ public class ApexModelWriterTest {
             assertEquals("concept stream may not be null", e.getMessage());
         }
     }
+
+    @Test
+    public void testSetOutputTypeError() throws ApexModelException {
+        MockitoAnnotations.initMocks(this);
+
+        ApexModelWriter<AxModel> modelWriter = new ApexModelWriter<AxModel>(AxModel.class);
+
+        try {
+            Field marshallerField = modelWriter.getClass().getDeclaredField("marshaller");
+            marshallerField.setAccessible(true);
+            marshallerField.set(modelWriter, marshallerMock);
+            marshallerField.setAccessible(false);
+        } catch (Exception validationException) {
+            fail("test should not throw an exception");
+        }
+
+        try {
+            Mockito.doThrow(new PropertyException("Exception setting JAXB property")).when(marshallerMock)
+                .setProperty(Mockito.anyString(), Mockito.anyString());
+            modelWriter.setJsonOutput(true);
+            fail("Test should throw an exception here");
+        } catch (Exception jaxbe) {
+            assertEquals("JAXB error setting marshaller for JSON output", jaxbe.getMessage());
+        }
+
+        try {
+            Mockito.doThrow(new PropertyException("Exception setting JAXB property")).when(marshallerMock)
+                .setProperty(Mockito.anyString(), Mockito.anyString());
+            modelWriter.setJsonOutput(false);
+            fail("Test should throw an exception here");
+        } catch (Exception jaxbe) {
+            assertEquals("JAXB error setting marshaller for XML output", jaxbe.getMessage());
+        }
+    }
+
+    @Test
+    public void testOutputJsonError() throws ApexModelException {
+        MockitoAnnotations.initMocks(this);
+
+        ApexModelWriter<AxModel> modelWriter = new ApexModelWriter<AxModel>(AxModel.class);
+
+        try {
+            Field marshallerField = modelWriter.getClass().getDeclaredField("marshaller");
+            marshallerField.setAccessible(true);
+            marshallerField.set(modelWriter, marshallerMock);
+            marshallerField.setAccessible(false);
+        } catch (Exception validationException) {
+            fail("test should not throw an exception");
+        }
+
+        modelWriter.setValidateFlag(false);
+        modelWriter.setJsonOutput(true);
+
+        try {
+            ByteArrayOutputStream baos = new ByteArrayOutputStream();
+            AxModel model = new DummyApexBasicModelCreator().getModel();
+
+            Mockito.doThrow(new JAXBException("Exception marshalling to JSON")).when(marshallerMock)
+                .marshal((AxModel)Mockito.anyObject(), (Writer)Mockito.anyObject());
+
+            modelWriter.write(model, baos);
+            fail("Test should throw an exception here");
+        } catch (Exception jaxbe) {
+            assertEquals("Unable to marshal Apex concept to JSON", jaxbe.getMessage());
+        }
+    }
+
+    @Test
+    public void testOutputXmlError() throws ApexModelException {
+        MockitoAnnotations.initMocks(this);
+
+        ApexModelWriter<AxModel> modelWriter = new ApexModelWriter<AxModel>(AxModel.class);
+        modelWriter.setJsonOutput(false);
+
+        try {
+            Field marshallerField = modelWriter.getClass().getDeclaredField("marshaller");
+            marshallerField.setAccessible(true);
+            marshallerField.set(modelWriter, marshallerMock);
+            marshallerField.setAccessible(false);
+        } catch (Exception validationException) {
+            fail("test should not throw an exception");
+        }
+
+        modelWriter.setValidateFlag(false);
+        modelWriter.setJsonOutput(false);
+
+        try {
+            ByteArrayOutputStream baos = new ByteArrayOutputStream();
+            AxModel model = new DummyApexBasicModelCreator().getModel();
+
+            Mockito.doThrow(new JAXBException("Exception marshalling to JSON")).when(marshallerMock)
+                .marshal((AxModel)Mockito.anyObject(), (Document)Mockito.anyObject());
+
+            modelWriter.write(model, baos);
+            fail("Test should throw an exception here");
+        } catch (Exception jaxbe) {
+            assertEquals("Unable to marshal Apex concept to XML", jaxbe.getMessage());
+        }
+    }
 }
@@ -26,7 +26,7 @@ import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation;
 import org.onap.policy.apex.model.basicmodel.concepts.AxModel;
 import org.onap.policy.apex.model.basicmodel.test.TestApexModelCreator;
 
-public class TestApexModelCreator0Test implements TestApexModelCreator<AxModel> {
+public class SupportApexModelCreator0 implements TestApexModelCreator<AxModel> {
 
     @Override
     public AxModel getModel() {
@@ -28,7 +28,7 @@ import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation;
 import org.onap.policy.apex.model.basicmodel.concepts.AxModel;
 import org.onap.policy.apex.model.basicmodel.test.TestApexModelCreator;
 
-public class TestApexModelCreator1Test implements TestApexModelCreator<AxModel> {
+public class SupportApexModelCreator1 implements TestApexModelCreator<AxModel> {
 
     @Override
     public AxModel getModel() {
@@ -26,7 +26,7 @@ import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation;
 import org.onap.policy.apex.model.basicmodel.concepts.AxModel;
 import org.onap.policy.apex.model.basicmodel.test.TestApexModelCreator;
 
-public class TestApexModelCreator2Test implements TestApexModelCreator<AxModel> {
+public class SupportApexModelCreator2 implements TestApexModelCreator<AxModel> {
 
     @Override
     public AxModel getModel() {
index e632a52..57df960 100644 (file)
@@ -34,7 +34,7 @@ public class SupportBasicModelTester {
     @Test
     public void testNormalModelCreator() throws ApexException {
         final TestApexModel<AxModel> testApexModel = new TestApexModel<AxModel>(AxModel.class,
-                        new DummyApexBasicModelCreator());
+            new DummyApexBasicModelCreator());
 
         testApexModel.testApexModelValid();
         try {
@@ -51,10 +51,28 @@ public class SupportBasicModelTester {
         testApexModel.testApexModelWriteReadXml();
     }
 
+    @Test
+    public void testModelsUnequal() throws ApexException {
+        final TestApexModel<AxModel> testApexModel0 = new TestApexModel<AxModel>(AxModel.class,
+            new DummyApexBasicModelCreator());
+        final TestApexModel<AxModel> testApexModel1 = new TestApexModel<AxModel>(AxModel.class,
+            new DummyApexBasicModelCreator());
+
+        testApexModel1.getModel().getKey().setVersion("0.0.2");
+
+        try {
+            testApexModel0.checkModelEquality(testApexModel0.getModel(), testApexModel1.getModel(),
+                "Models are not equal");
+            fail("test should throw an exception here");
+        } catch (ApexException ae) {
+            assertEquals("Models are not equal", ae.getMessage());
+        }
+    }
+
     @Test
     public void testModelCreator0() throws ApexException {
         final TestApexModel<AxModel> testApexModel = new TestApexModel<AxModel>(AxModel.class,
-                        new TestApexModelCreator0Test());
+            new SupportApexModelCreator0());
 
         testApexModel.testApexModelValid();
         try {
@@ -86,7 +104,7 @@ public class SupportBasicModelTester {
     @Test
     public void testModelCreator1() throws ApexException {
         final TestApexModel<AxModel> testApexModel = new TestApexModel<AxModel>(AxModel.class,
-                        new TestApexModelCreator1Test());
+            new SupportApexModelCreator1());
 
         try {
             testApexModel.testApexModelValid();
@@ -113,7 +131,7 @@ public class SupportBasicModelTester {
     @Test
     public void testModelCreator2() throws ApexException {
         final TestApexModel<AxModel> testApexModel = new TestApexModel<AxModel>(AxModel.class,
-                        new TestApexModelCreator2Test());
+            new SupportApexModelCreator2());
 
         testApexModel.testApexModelValid();
         testApexModel.testApexModelVaidateObservation();
@@ -128,7 +146,7 @@ public class SupportBasicModelTester {
     @Test
     public void testModelCreator1XmlJson() throws ApexException {
         final TestApexModel<AxModel> testApexModel = new TestApexModel<AxModel>(AxModel.class,
-                        new TestApexModelCreator1Test());
+            new SupportApexModelCreator1());
 
         try {
             testApexModel.testApexModelWriteReadJson();
index edf045a..e1264e8 100644 (file)
@@ -41,7 +41,7 @@ import org.onap.policy.apex.model.policymodel.concepts.AxPolicy;
 import org.onap.policy.apex.model.policymodel.concepts.AxState;
 import org.onap.policy.apex.model.policymodel.concepts.AxStateOutput;
 import org.onap.policy.apex.model.policymodel.concepts.AxStateTree;
-import org.onap.policy.apex.model.policymodel.handling.ApexPolicyModelCreatorTest;
+import org.onap.policy.apex.model.policymodel.handling.SupportApexPolicyModelCreator;
 
 /**
  * Test apex policies.
@@ -113,7 +113,7 @@ public class PoliciesTest {
 
         assertEquals("PolicyName:0.0.1", policy.getKeys().get(0).getId());
 
-        policy = new ApexPolicyModelCreatorTest().getModel().getPolicies().get("policy");
+        policy = new SupportApexPolicyModelCreator().getModel().getPolicies().get("policy");
 
         AxValidationResult result = new AxValidationResult();
         result = policy.validate(result);
index e1f1f90..6c93efd 100644 (file)
@@ -46,7 +46,7 @@ import org.onap.policy.apex.model.policymodel.concepts.AxStateTaskOutputType;
 import org.onap.policy.apex.model.policymodel.concepts.AxStateTaskReference;
 import org.onap.policy.apex.model.policymodel.concepts.AxTaskSelectionLogic;
 import org.onap.policy.apex.model.policymodel.concepts.AxTasks;
-import org.onap.policy.apex.model.policymodel.handling.ApexPolicyModelCreatorTest;
+import org.onap.policy.apex.model.policymodel.handling.SupportApexPolicyModelCreator;
 
 /**
  * Test policy models.
@@ -148,7 +148,7 @@ public class PolicyModelTest {
                         new AxKeyInformation(keyInfoKey), new AxEvents(eventsKey), new AxContextAlbums(albumsKey),
                         new AxTasks(tasksKey), new AxPolicies(policiesKey))));
 
-        model = new ApexPolicyModelCreatorTest().getModel();
+        model = new SupportApexPolicyModelCreator().getModel();
 
         AxValidationResult result = new AxValidationResult();
         result = model.validate(result);
index 997664b..7a240e1 100644 (file)
@@ -49,7 +49,7 @@ public class ApexPolicyModelTest {
         Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
         connection = DriverManager.getConnection("jdbc:derby:memory:apex_test;create=true");
 
-        testApexModel = new TestApexModel<AxPolicyModel>(AxPolicyModel.class, new ApexPolicyModelCreatorTest());
+        testApexModel = new TestApexModel<AxPolicyModel>(AxPolicyModel.class, new SupportApexPolicyModelCreator());
     }
 
     @After
index 425509d..d4ab6bd 100644 (file)
@@ -31,7 +31,7 @@ import org.onap.policy.apex.model.policymodel.handling.PolicyAnalysisResult;
 public class PolicyAnalyserTest {
     @Test
     public void test() {
-        final AxPolicyModel apexModel = new ApexPolicyModelCreatorTest().getModel();
+        final AxPolicyModel apexModel = new SupportApexPolicyModelCreator().getModel();
 
         final PolicyAnalyser policyAnalyser = new PolicyAnalyser();
         final PolicyAnalysisResult analysisResult = policyAnalyser.analyse(apexModel);
index 08d00e6..8b0396b 100644 (file)
@@ -39,7 +39,7 @@ public class PolicyModelComparerTest {
 
     @Test
     public void testPolicyComparer() throws IOException {
-        final AxPolicyModel leftApexModel = new ApexPolicyModelCreatorTest().getModel();
+        final AxPolicyModel leftApexModel = new SupportApexPolicyModelCreator().getModel();
         final AxPolicyModel rightApexModel = new AxPolicyModel(leftApexModel);
 
         PolicyModelComparer policyModelComparer = new PolicyModelComparer(leftApexModel, rightApexModel);
index 7d5ba6a..b477c47 100644 (file)
@@ -39,8 +39,8 @@ public class PolicyModelMergerTest {
 
     @Test
     public void testPolicyModelMerger() {
-        final AxPolicyModel leftPolicyModel = new ApexPolicyModelCreatorTest().getModel();
-        AxPolicyModel rightPolicyModel = new ApexPolicyModelCreatorTest().getModel();
+        final AxPolicyModel leftPolicyModel = new SupportApexPolicyModelCreator().getModel();
+        AxPolicyModel rightPolicyModel = new SupportApexPolicyModelCreator().getModel();
 
         try {
             final AxPolicyModel mergedPolicyModel = PolicyModelMerger.getMergedPolicyModel(leftPolicyModel,
@@ -99,7 +99,7 @@ public class PolicyModelMergerTest {
             fail("test should not throw an exception");
         }
 
-        rightPolicyModel = new ApexPolicyModelCreatorTest().getAnotherModel();
+        rightPolicyModel = new SupportApexPolicyModelCreator().getAnotherModel();
         try {
             final AxPolicyModel mergedPolicyModel = PolicyModelMerger.getMergedPolicyModel(leftPolicyModel,
                             rightPolicyModel, true);
index 29e7307..c20a407 100644 (file)
@@ -37,7 +37,7 @@ import org.onap.policy.apex.model.policymodel.handling.PolicyModelSplitter;
 public class PolicyModelSplitterTest {
     @Test
     public void test() {
-        final AxPolicyModel apexModel = new ApexPolicyModelCreatorTest().getModel();
+        final AxPolicyModel apexModel = new SupportApexPolicyModelCreator().getModel();
 
         final Set<AxArtifactKey> requiredPolicySet = new TreeSet<AxArtifactKey>();
         requiredPolicySet.add(new AxArtifactKey("policy", "0.0.1"));
@@ -56,7 +56,7 @@ import org.onap.policy.apex.model.policymodel.concepts.AxTasks;
  * 
  * @author Liam Fallon (liam.fallon@ericsson.com)
  */
-public class ApexPolicyModelCreatorTest implements TestApexModelCreator<AxPolicyModel> {
+public class SupportApexPolicyModelCreator implements TestApexModelCreator<AxPolicyModel> {
 
     @Override
     public AxPolicyModel getModel() {
index 6c7af80..59d3637 100644 (file)
@@ -98,7 +98,7 @@ public class TestFile2FileFiltered {
 
         // Wait for the file to be filled
         long outFile0Size = 0;
-        for (int i = 0; i < 4; i++) {
+        for (int i = 0; i < 20; i++) {
             final String fileString = stripVariableLengthText(outFilePaths[0]);
             outFile0Size = fileString.length();
             if (outFile0Size > 0 && outFile0Size >= expectedFileSizes[0]) {
index 94bd6b2..216b566 100644 (file)
@@ -20,7 +20,6 @@
 
 package org.onap.policy.apex.testsuites.integration.uservice.adapt.restclient;
 
-import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
 import java.io.ByteArrayOutputStream;
@@ -113,17 +112,14 @@ public class TestRest2File {
 
         final ApexMain apexMain = new ApexMain(args);
 
-        ThreadUtilities.sleep(1000);
+        ThreadUtilities.sleep(5000);
         apexMain.shutdown();
 
         final String outputEventText = TextFileUtils
             .getTextFileAsString("target/examples/events/SampleDomain/EventsOut.json");
 
-        if (!outputEventText.contains(
-            "04\",\n" + "  \"version\": \"0.0.1\",\n" + "  \"nameSpace\": \"org.onap.policy.apex.sample.events\"")) {
-            LOGGER.error(outputEventText);
-            fail("test output did not contain required string");
-        }
+        checkRequiredString(outputEventText,
+            "04\",\n" + "  \"version\": \"0.0.1\",\n" + "  \"nameSpace\": \"org.onap.policy.apex.sample.events\"");
     }
 
     /**
@@ -141,7 +137,7 @@ public class TestRest2File {
         final String[] args = { "src/test/resources/prodcons/REST2FileJsonEmptyEvents.json" };
         final ApexMain apexMain = new ApexMain(args);
 
-        ThreadUtilities.sleep(1000);
+        ThreadUtilities.sleep(5000);
         apexMain.shutdown();
 
         final String outString = outContent.toString();
@@ -149,11 +145,8 @@ public class TestRest2File {
         System.setOut(stdout);
         System.setErr(stderr);
 
-        if (!outString.contains(
-            "received an empty event from URL \"http://localhost:32801/TestRest2File/apex/event/GetEmptyEvent\"")) {
-            LOGGER.error(outString);
-            fail("test output did not contain required string");
-        }
+        checkRequiredString(outString,
+            "received an empty event from URL " + "\"http://localhost:32801/TestRest2File/apex/event/GetEmptyEvent\"");
     }
 
     /**
@@ -171,7 +164,7 @@ public class TestRest2File {
         final String[] args = { "src/test/resources/prodcons/REST2FileJsonEventNoURL.json" };
         final ApexMain apexMain = new ApexMain(args);
 
-        ThreadUtilities.sleep(1000);
+        ThreadUtilities.sleep(5000);
         apexMain.shutdown();
 
         final String outString = outContent.toString();
@@ -179,10 +172,7 @@ public class TestRest2File {
         System.setOut(stdout);
         System.setErr(stderr);
 
-        if (!outString.contains(" no URL has been set for event sending on REST client")) {
-            LOGGER.error(outString);
-            fail("test output did not contain required string");
-        }
+        checkRequiredString(outString, " no URL has been set for event sending on REST client");
     }
 
     /**
@@ -200,7 +190,7 @@ public class TestRest2File {
         final String[] args = { "src/test/resources/prodcons/REST2FileJsonEventBadURL.json" };
         final ApexMain apexMain = new ApexMain(args);
 
-        ThreadUtilities.sleep(1000);
+        ThreadUtilities.sleep(5000);
         apexMain.shutdown();
 
         final String outString = outContent.toString();
@@ -208,11 +198,8 @@ public class TestRest2File {
         System.setOut(stdout);
         System.setErr(stderr);
 
-        if (!outString.contains(
-            "reception of event from URL \"http://localhost:32801/TestRest2File/apex/event/Bad\" failed with status code 404")) {
-            LOGGER.error(outString);
-            fail("test output did not contain required string");
-        }
+        checkRequiredString(outString, "reception of event from URL "
+            + "\"http://localhost:32801/TestRest2File/apex/event/Bad\" failed with status code 404");
     }
 
     /**
@@ -230,7 +217,7 @@ public class TestRest2File {
         final String[] args = { "src/test/resources/prodcons/REST2FileJsonEventBadHTTPMethod.json" };
         final ApexMain apexMain = new ApexMain(args);
 
-        ThreadUtilities.sleep(1000);
+        ThreadUtilities.sleep(5000);
         apexMain.shutdown();
 
         final String outString = outContent.toString();
@@ -238,11 +225,8 @@ public class TestRest2File {
         System.setOut(stdout);
         System.setErr(stderr);
 
-        if (!outString.contains("specified HTTP method of \"POST\" is invalid, "
-            + "only HTTP method \"GET\" is supported for event reception on REST client consumer")) {
-            LOGGER.error(outString);
-            fail("test output did not contain required string");
-        }
+        checkRequiredString(outString, "specified HTTP method of \"POST\" is invalid, "
+            + "only HTTP method \"GET\" is supported for event reception on REST client consumer");
     }
 
     /**
@@ -260,7 +244,7 @@ public class TestRest2File {
         final String[] args = { "src/test/resources/prodcons/REST2FileJsonEventBadResponse.json" };
         final ApexMain apexMain = new ApexMain(args);
 
-        ThreadUtilities.sleep(1000);
+        ThreadUtilities.sleep(5000);
         apexMain.shutdown();
 
         final String outString = outContent.toString();
@@ -268,10 +252,21 @@ public class TestRest2File {
         System.setOut(stdout);
         System.setErr(stderr);
 
-        if (!outString.contains(
-            "reception of event from URL \"http://localhost:32801/TestRest2File/apex/event/GetEventBadResponse\" failed with status code 400 and message \"\"")) {
-            LOGGER.error(outString);
-            fail("test output did not contain required string");
+        checkRequiredString(outString,
+            "reception of event from URL " + "\"http://localhost:32801/TestRest2File/apex/event/GetEventBadResponse\" "
+                + "failed with status code 400 and message \"\"");
+    }
+
+    /**
+     * Check if a required string exists in the output.
+     * 
+     * @param outputEventText the text to examine
+     * @param requiredString the string to search for
+     */
+    private void checkRequiredString(String outputText, String requiredString) {
+        if (!outputText.contains(requiredString)) {
+            LOGGER.error("\n***output text:\n" + outputText + "\n***");
+            fail("\n***test output did not contain required string:\n" + requiredString + "\n***");
         }
     }
 }