diff options
author | Michael Lando <ml636r@att.com> | 2017-02-19 10:28:42 +0200 |
---|---|---|
committer | Michael Lando <ml636r@att.com> | 2017-02-19 10:51:01 +0200 |
commit | 451a3400b76511393c62a444f588a4ed15f4a549 (patch) | |
tree | e4f5873a863d1d3e55618eab48b83262f874719d /common-app-api/src/test | |
parent | 5abfe4e1fb5fae4bbd5fbc340519f52075aff3ff (diff) |
Initial OpenECOMP SDC commit
Change-Id: I0924d5a6ae9cdc161ae17c68d3689a30d10f407b
Signed-off-by: Michael Lando <ml636r@att.com>
Diffstat (limited to 'common-app-api/src/test')
11 files changed, 1464 insertions, 0 deletions
diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/data_structure/CapListTest.java b/common-app-api/src/test/java/org/openecomp/sdc/common/data_structure/CapListTest.java new file mode 100644 index 0000000000..7aeb2ac70d --- /dev/null +++ b/common-app-api/src/test/java/org/openecomp/sdc/common/data_structure/CapListTest.java @@ -0,0 +1,126 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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========================================================= + */ + +package org.openecomp.sdc.common.data_structure; + +import static org.junit.Assert.assertTrue; + +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import org.junit.Test; +import org.openecomp.sdc.common.datastructure.CapList; + +public class CapListTest { + public enum LIST_ACTION { + Add, Remove, Size, Get + } + + @Test + public void testCap() { + List<Integer> testList = new CapList<>(10); + for (int i = 0; i < 100; i++) { + testList.add(i); + } + assertTrue(testList.size() == 10); + for (int i = 0; i < testList.size(); i++) { + assertTrue(testList.get(i) == (i + 90)); + } + } + + @Test + public void testThreadSafe() { + List<Integer> testList = new CapList<>(1000); + + ExecutorService executor = Executors.newFixedThreadPool(4); + for (int i = 0; i < 10; i++) { + Runnable worker; + // 0 - 4 + if (i < 5) { + worker = new ThreadWorker(i, LIST_ACTION.Add, testList); + } + // 5, 8 + else if (i == 5 || i == 8) { + worker = new ThreadWorker(i, LIST_ACTION.Remove, testList); + } + // 6 + else if (i == 6) { + worker = new ThreadWorker(i, LIST_ACTION.Size, testList); + } + // 7, 9 + else { + worker = new ThreadWorker(i, LIST_ACTION.Get, testList); + } + executor.execute(worker); + } + executor.shutdown(); + while (!executor.isTerminated()) { + } + assertTrue(testList.size() == 60); + } + + public static class ThreadWorker implements Runnable { + private LIST_ACTION action; + private List<Integer> list; + private Integer id; + + ThreadWorker(Integer id, LIST_ACTION action, List<Integer> list) { + this.action = action; + this.list = list; + this.id = id; + } + + @Override + public void run() { + for (int i = 0; i < 20; i++) { + threadNap(); + switch (action) { + case Add: + list.add(id * 100 + i); + break; + case Remove: { + int index = (int) (Math.random() * 10); + list.remove(index); + break; + } + case Get: + int index = (int) (Math.random() * 10); + Integer integer = list.get(index); + + break; + case Size: + int size = list.size(); + break; + } + } + + } + + private void threadNap() { + long napTime = (long) (Math.random() * 100); + try { + Thread.sleep(napTime); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } +} diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/test/CommonUtilsTest.java b/common-app-api/src/test/java/org/openecomp/sdc/common/test/CommonUtilsTest.java new file mode 100644 index 0000000000..1a062576dc --- /dev/null +++ b/common-app-api/src/test/java/org/openecomp/sdc/common/test/CommonUtilsTest.java @@ -0,0 +1,549 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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========================================================= + */ + +package org.openecomp.sdc.common.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang3.StringEscapeUtils; +import org.jsoup.Jsoup; +import org.jsoup.safety.Whitelist; +import org.junit.Test; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.util.GeneralUtility; +import org.openecomp.sdc.common.util.HtmlCleaner; +import org.openecomp.sdc.common.util.ValidationUtils; +import org.openecomp.sdc.common.util.YamlToObjectConverter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.html.HTMLStyleElement; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.Yaml; + +public class CommonUtilsTest { + private static Logger log = LoggerFactory.getLogger(CommonUtilsTest.class.getName()); + + /* + * Validation utils start + */ + @Test + public void testValidateServiceName() { + + assertTrue(ValidationUtils.validateComponentNamePattern("1111222")); + assertTrue(ValidationUtils.validateComponentNamePattern("sfE4444")); + assertTrue(ValidationUtils.validateComponentNamePattern("1111sfd222")); + assertTrue(ValidationUtils.validateComponentNamePattern("11sdf 1124_22")); + assertTrue(ValidationUtils.validateComponentNamePattern("111----1222")); + assertTrue(ValidationUtils.validateComponentNamePattern("1111f .222")); + assertTrue(ValidationUtils.validateComponentNamePattern("1111222")); + assertFalse(ValidationUtils.validateComponentNamePattern("11!11222")); + assertFalse(ValidationUtils.validateComponentNamePattern("111|`1222")); + + } + + @Test + public void validateServiceNameLengthTest() { + assertTrue(ValidationUtils.validateComponentNameLength("fsdlfsdlksdsd;")); + // assertFalse(ValidationUtils.validateComponentNameLength("ddddddddddddddddddddddsdfsddddddddddddddddddddddsdfs")); + } + + @Test + public void testValidateIcon() { + + assertTrue(ValidationUtils.validateIcon("something")); + assertTrue(ValidationUtils.validateIcon("sfE4444")); + assertTrue(ValidationUtils.validateIcon("1111sfd222")); + assertTrue(ValidationUtils.validateIcon("11sdf1124_22")); + assertTrue(ValidationUtils.validateIcon("111----1222")); + assertFalse(ValidationUtils.validateIcon("1111f.222")); + assertTrue(ValidationUtils.validateIcon("1111222")); + assertFalse(ValidationUtils.validateIcon("1111 222")); + assertFalse(ValidationUtils.validateIcon("11!11222")); + assertFalse(ValidationUtils.validateIcon("111|`1222")); + + } + + @Test + public void testFloatParsing() { + assertTrue(ValidationUtils.isFloatNumber("15555.45")); + assertTrue(ValidationUtils.isFloatNumber("0.5")); + assertFalse(ValidationUtils.isFloatNumber("15555")); + assertFalse(ValidationUtils.isFloatNumber("1")); + assertFalse(ValidationUtils.isFloatNumber("jk532")); + assertFalse(ValidationUtils.isFloatNumber("12..6")); + + } + + @Test + public void testValidateIconLength() { + assertTrue(ValidationUtils.validateIconLength("fsdlfsdlksdsd")); + assertFalse(ValidationUtils.validateIconLength("ddddddddddddddddddddddsdfsddddddddddddddddddddddsdfs")); + } + + // 1610OS Support - Because of changes in the validation in the ui this test needs to be fixed +// @Test +// public void testValidateProjectCode() { +// +// assertTrue(ValidationUtils.validateProjectCode("15555")); +// assertTrue(ValidationUtils.validateProjectCode("12434501")); +// assertTrue(ValidationUtils.validateProjectCode("00000")); +// assertFalse(ValidationUtils.validateProjectCode("something")); +// assertFalse(ValidationUtils.validateProjectCode("som ething")); +// assertFalse(ValidationUtils.validateProjectCode("3255 656")); +// assertFalse(ValidationUtils.validateProjectCode("43535t636")); +// assertFalse(ValidationUtils.validateProjectCode("098&656")); +// } + + @Test + public void testValidateProjectCodeLength() { + assertTrue(ValidationUtils.validateProjectCodeLegth("00000")); + assertFalse(ValidationUtils.validateProjectCodeLegth("ddddddddddddddddddddddsdfsddddddddddddddddddddddsdfs")); + } + + // 1610OS Support - Because of changes in the validation in the ui this test needs to be fixed +// @Test +// public void testValidateContactId() { +// +// assertTrue(ValidationUtils.validateContactId("ml7889")); +// assertTrue(ValidationUtils.validateContactId("Ml7889")); +// assertTrue(ValidationUtils.validateContactId("ml788r")); +// assertFalse(ValidationUtils.validateContactId("something")); +// assertFalse(ValidationUtils.validateContactId("mlk111")); +// assertFalse(ValidationUtils.validateContactId("12ml89")); +// assertFalse(ValidationUtils.validateContactId("!!78900")); +// } + + @Test + public void testRemoveHtml() { + + assertTrue("gooboo".equals(ValidationUtils.removeHtmlTags("<b>goo<b></b></b><b>boo</b>"))); + assertTrue("goo<boo".equals(ValidationUtils.removeHtmlTags("<b>goo<b></b><</b><b>boo</b>"))); + assertTrue("goo boo".equals(ValidationUtils.removeHtmlTags("goo boo"))); + assertTrue("goo# . boo12".equals(ValidationUtils.removeHtmlTags("goo# . boo12"))); + } + + @Test + public void testnormaliseWhitespace() { + + assertTrue("goo boo".equals(ValidationUtils.normaliseWhitespace("goo boo"))); + assertTrue("goo boo ".equals(ValidationUtils.normaliseWhitespace("goo boo "))); + assertTrue("goo boo".equals(ValidationUtils.normaliseWhitespace("goo boo"))); + } + + @Test + public void teststripOctets() { + assertTrue("goo boo".equals(ValidationUtils.stripOctets("goo%1F boo"))); + assertTrue("goo boo ".equals(ValidationUtils.stripOctets("goo boo %1F"))); + assertTrue("goo boo".equals(ValidationUtils.stripOctets("%1Fgoo boo"))); + } + + @Test + public void testRemoveNoneUtf8Chars() { + assertTrue("goo boo".equals(ValidationUtils.removeNoneUtf8Chars("goo boo"))); + assertTrue("goo boo!!._".equals(ValidationUtils.removeNoneUtf8Chars("goo boo!!._"))); + assertTrue("goo boo".equals(ValidationUtils.removeNoneUtf8Chars("goo boo"))); + assertTrue("goo bo123o".equals(ValidationUtils.removeNoneUtf8Chars("goo bo123o"))); + assertTrue("goo bo123o".equals(ValidationUtils.removeNoneUtf8Chars("goo קקbo123oגכקק"))); + assertTrue("goo bo123o".equals(ValidationUtils.removeNoneUtf8Chars("goo bo1������23o"))); + } + + @Test + public void validateEnglishTest() { + assertTrue(ValidationUtils.validateIsEnglish("ml7889")); + assertFalse(ValidationUtils.validateIsEnglish("ml7889קר")); + assertFalse(ValidationUtils.validateIsEnglish("ml7889文")); + } + + @Test + public void removeDuplicateFromListTest() { + List<String> tagsBefore = new ArrayList<>(); + tagsBefore.add("tag1"); + tagsBefore.add("tag7"); + tagsBefore.add("tag3"); + tagsBefore.add("tag4"); + tagsBefore.add("tag1"); + + List<String> tagsAfter = new ArrayList<>(); + tagsAfter.add("tag1"); + tagsAfter.add("tag7"); + tagsAfter.add("tag3"); + tagsAfter.add("tag4"); + assertTrue(tagsAfter.containsAll(ValidationUtils.removeDuplicateFromList(tagsBefore))); + tagsBefore = new ArrayList<>(); + tagsBefore.add("tag1"); + tagsBefore.add("tag7"); + tagsBefore.add("tag3"); + tagsBefore.add("tag4"); + tagsBefore.add("Tag1"); + + tagsAfter = new ArrayList<>(); + tagsAfter.add("tag1"); + tagsAfter.add("tag7"); + tagsAfter.add("tag3"); + tagsAfter.add("tag4"); + tagsAfter.add("Tag1"); + assertTrue(tagsAfter.containsAll(ValidationUtils.removeDuplicateFromList(tagsBefore))); + } + + @Test + public void validateTagLengthTest() { + assertTrue(ValidationUtils.validateTagLength("fsdlfsdlkfjkljsdf")); + // assertFalse(ValidationUtils.validateTagLength("ddddddddddddddddddddddsdfsddddddddddddddddddddddsdfs")); + + } + + @Test + public void validateTagListLengthTest() { + assertTrue(ValidationUtils.validateTagListLength("fsdlfsdlkfjkljsdf,dsfsdfsdf".length())); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i <= 1024; i++) { + sb.append("a"); + } + assertFalse(ValidationUtils.validateTagListLength(sb.toString().length())); + + } + + @Test + public void validateDescriptionLengthTest() { + assertTrue(ValidationUtils.validateDescriptionLength("fsdlfsdlkfjkljsddgfgdfgdfgdfgff")); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i <= 1024; i++) { + sb.append("a"); + } + assertFalse(ValidationUtils.validateDescriptionLength(sb.toString())); + + } + + @Test + public void validateStringNotEmptyTest() { + assertTrue(ValidationUtils.validateStringNotEmpty("fsdlfsdlk")); + assertFalse(ValidationUtils.validateStringNotEmpty("")); + assertFalse(ValidationUtils.validateStringNotEmpty(" ")); + assertFalse(ValidationUtils.validateStringNotEmpty(" ")); + } + + @Test + public void validateVendorNameTest() { + assertTrue(ValidationUtils.validateVendorName("fsdlfsdlk")); + assertTrue(ValidationUtils.validateVendorName("fsdlfsdlk.sdsd;")); + assertFalse(ValidationUtils.validateVendorName("sadf:")); + assertFalse(ValidationUtils.validateVendorName("sadf/")); + assertFalse(ValidationUtils.validateVendorName("sadf?")); + } + + @Test + public void validateVendorNameLengthTest() { + assertTrue(ValidationUtils.validateVendorNameLength("fsdlfsdlk.sdsd;")); + assertFalse(ValidationUtils.validateVendorNameLength("ddddddddddddddddddddddsdfs")); + } + + @Test + public void validateVendorReleaseTest() { + assertTrue(ValidationUtils.validateVendorRelease("fsdlfsdlk")); + assertTrue(ValidationUtils.validateVendorRelease("fsdlfsdlk.sdsd;")); + assertFalse(ValidationUtils.validateVendorRelease("sadf:")); + assertFalse(ValidationUtils.validateVendorRelease("sadf/")); + assertFalse(ValidationUtils.validateVendorRelease("sadf?")); + } + + @Test + public void validateVendorReleaseLengthTest() { + assertTrue(ValidationUtils.validateVendorNameLength("fsdlfsdlk.sdsd;")); + assertFalse(ValidationUtils.validateVendorNameLength("ddddddddddddddddddddddsdfs")); + } + + @Test + public void hasBeenCertifiedTest() { + assertTrue(ValidationUtils.hasBeenCertified("1.2")); + assertTrue(ValidationUtils.hasBeenCertified("2.2")); + assertTrue(ValidationUtils.hasBeenCertified("1.0")); + assertFalse(ValidationUtils.hasBeenCertified("0.1")); + + } + + @Test + public void normalizedNameTest() { + String input = "MyNewSysName"; + String outputNorm = ValidationUtils.normaliseComponentName(input); + String outputSys = ValidationUtils.convertToSystemName(input); + log.debug("{} <> {} <> {}", input, outputNorm, outputSys); + + input = "My New Sys Name"; + outputNorm = ValidationUtils.normaliseComponentName(input); + outputSys = ValidationUtils.convertToSystemName(input); + log.debug("{} <> {} <> {}", input, outputNorm, outputSys); + + input = "My.New-Sys_Name"; + outputNorm = ValidationUtils.normaliseComponentName(input); + outputSys = ValidationUtils.convertToSystemName(input); + log.debug("{} <> {} <> {}", input, outputNorm, outputSys); + + input = "My..New-Sys_Name"; + outputNorm = ValidationUtils.normaliseComponentName(input); + outputSys = ValidationUtils.convertToSystemName(input); + log.debug("{} <> {} <> {}", input, outputNorm, outputSys); + + input = "My.New--sys_NAme"; + outputNorm = ValidationUtils.normaliseComponentName(input); + outputSys = ValidationUtils.convertToSystemName(input); + log.debug("{} <> {} <> {}", input, outputNorm, outputSys); + + input = "Layer 3 Connectivity"; + outputNorm = ValidationUtils.normaliseComponentName(input); + outputSys = ValidationUtils.convertToSystemName(input); + log.debug("{} <> {} <> {}", input, outputNorm, outputSys); + + input = "Layer 3 VPN"; + outputNorm = ValidationUtils.normaliseComponentName(input); + outputSys = ValidationUtils.convertToSystemName(input); + log.debug("{} <> {} <> {}", input, outputNorm, outputSys); + + input = "Layer-3 Connectivity"; + outputNorm = ValidationUtils.normaliseComponentName(input); + outputSys = ValidationUtils.convertToSystemName(input); + log.debug("{} <> {} <> {}", input, outputNorm, outputSys); + + input = "IP-connectivity"; + outputNorm = ValidationUtils.normaliseComponentName(input); + outputSys = ValidationUtils.convertToSystemName(input); + log.debug("{} <> {} <> {}", input, outputNorm, outputSys); + + } + + @Test + public void normalizeFileNameTest() { + assertTrue("too.jpeg".equals(ValidationUtils.normalizeFileName("too.jpeg"))); + assertTrue("too..jpeg".equals(ValidationUtils.normalizeFileName("too..jpeg"))); + assertTrue("too..jpeg".equals(ValidationUtils.normalizeFileName("t*o:o..jpe<>g"))); + assertTrue("goo.too..jpeg".equals(ValidationUtils.normalizeFileName("goo.t*o:o..jpe<>g"))); + assertTrue("goo.too..jpeg".equals(ValidationUtils.normalizeFileName(" goo.t*o:o..jpe<>g "))); + assertTrue("goo-too-mo.jpeg".equals(ValidationUtils.normalizeFileName("goo too----mo.jpeg"))); + assertTrue("goo-too-mo.jpeg".equals(ValidationUtils.normalizeFileName(".\\..\\goo too----mo.jpeg"))); + assertTrue("goo-too-mo.jpeg".equals(ValidationUtils.normalizeFileName("__--goo too----mo.jpeg--__"))); + assertTrue("goo-too-mo.jpeg".equals(ValidationUtils.normalizeFileName("_ -goo too----mo.jpeg _-- _-"))); + + } + + @Test + public void validateUrlTest() { + assertTrue(ValidationUtils.validateUrl("http://google.co.il/")); + assertTrue(ValidationUtils.validateUrl("https://google.co.il/")); + assertTrue(ValidationUtils.validateUrl("https://google.co.il/go/go")); + assertTrue(ValidationUtils.validateUrl("https://google.co.il/go/go")); + assertTrue(ValidationUtils.validateUrl("http://google.co.il/go/go")); + assertFalse(ValidationUtils.validateUrl("google.co.il/go/go")); + assertFalse(ValidationUtils.validateUrl("https://google.co.il/go/go!")); + assertFalse(ValidationUtils.validateUrl("https://g;oogle.co.il/go/go")); + + } + + @Test + public void normalizeArtifactLabel() { + assertEquals(ValidationUtils.normalizeArtifactLabel("Test--3 134++"), "test3134"); + } + + @Test + public void cleanArtifactLabel() { + assertEquals(ValidationUtils.cleanArtifactDisplayName("Test--3 134++"), "Test-3 134+"); + } + + @Test + public void validateArtifactLabel() { + assertTrue(ValidationUtils.validateArtifactLabel("dsflkjsdf345JKL")); + assertTrue(ValidationUtils.validateArtifactLabel("dsfsd lkj ")); + assertTrue(ValidationUtils.validateArtifactLabel("sdfdsf---+")); + assertTrue(ValidationUtils.validateArtifactLabel(" - +")); + assertFalse(ValidationUtils.validateArtifactLabel("sfsdfhkj111=")); + assertFalse(ValidationUtils.validateArtifactLabel("sfsdfhkj111=dfsf%")); + assertFalse(ValidationUtils.validateArtifactLabel("sdfsdfljghgklsdg908*")); + + } + + @Test + public void validateConsumerNameTest() { + assertTrue(ValidationUtils.validateConsumerName("ab037cd")); + assertFalse(ValidationUtils.validateConsumerName(" ")); + assertTrue(ValidationUtils.validateConsumerName("_dD.d9")); + assertTrue(ValidationUtils.validateConsumerName("_dd.G9-")); + assertFalse(ValidationUtils.validateConsumerName(".dA.d9-")); + assertFalse(ValidationUtils.validateConsumerName("-d")); + assertFalse(ValidationUtils.validateConsumerName("d?")); + assertTrue(ValidationUtils.validateConsumerName("9")); + } + + @Test + public void validateConsumerPassSaltTest() { + assertTrue(ValidationUtils.validateConsumerPassSalt("ad35fg2")); + assertTrue(ValidationUtils.validateConsumerPassSalt("12s")); + assertTrue(ValidationUtils.validateConsumerPassSalt("9")); + assertFalse(ValidationUtils.validateConsumerPassSalt("dA.d9-")); + assertFalse(ValidationUtils.validateConsumerPassSalt("dASQe")); + assertFalse(ValidationUtils.validateConsumerPassSalt("_d")); + assertFalse(ValidationUtils.validateConsumerPassSalt("?")); + assertFalse(ValidationUtils.validateConsumerPassSalt("")); + assertFalse(ValidationUtils.validateConsumerPassSalt(" ")); + } + + @Test + public void validateCategoryNameFormatTest() { + assertTrue(ValidationUtils.validateCategoryDisplayNameFormat("Net ele-2_3#456&+.'=:@@@@@#####")); + // this will fail at length + assertTrue(ValidationUtils.validateCategoryDisplayNameFormat(null)); + // * is not allowed + assertFalse(ValidationUtils.validateCategoryDisplayNameFormat("Net ele-2_3#456&*+.'=:@")); + assertFalse(ValidationUtils.validateCategoryDisplayNameFormat("")); + // should start with alphanumeric + assertFalse(ValidationUtils.validateCategoryDisplayNameFormat("#abcdef")); + } + + @Test + public void validateCategoryNameLengthTest() { + assertTrue(ValidationUtils.validateCategoryDisplayNameLength("Netele-2_3#456&+.'=:@@@@@")); + assertTrue(ValidationUtils.validateCategoryDisplayNameLength("Nete")); + assertFalse(ValidationUtils.validateCategoryDisplayNameLength("Netele-2_3#456&+.'=:@@@@@1")); + assertFalse(ValidationUtils.validateCategoryDisplayNameLength("Net")); + assertFalse(ValidationUtils.validateCategoryDisplayNameLength(null)); + } + + @Test + public void normalizeCategoryNameTest() { + assertEquals("NeteLE-2_3 of #456&+. & Goal a Abc'=:@ AT & T", ValidationUtils.normalizeCategoryName4Display( + " neteLE---2___3 OF ###456&&&+++... aNd goal A abc'''==::@@@@@ AT and T ")); + assertEquals("The Bank of America", ValidationUtils.normalizeCategoryName4Display("The Bank OF America")); + } + + @Test + public void normalizeCategoryLabelTest() { + assertEquals("netele-2_3 of #456&+.&goal a abc'=:@ at&t", + ValidationUtils.normalizeCategoryName4Uniqueness("NeteLE-2_3 of #456&+.&Goal a Abc'=:@ AT&T")); + } + + /* + * Validation utils end + */ + + /* + * General utility start + */ + + @Test + public void validateFileExtension() { + assertEquals(Constants.EMPTY_STRING, GeneralUtility.getFilenameExtension("lalatru")); + assertEquals(Constants.EMPTY_STRING, GeneralUtility.getFilenameExtension("aa.")); + assertEquals(Constants.EMPTY_STRING, GeneralUtility.getFilenameExtension(null)); + assertEquals("yaml", GeneralUtility.getFilenameExtension("lala.tru.yaml")); + assertEquals("txt", GeneralUtility.getFilenameExtension("kuku.txt")); + } + + @Test + public void yamlTest() { + + log.debug("\"kuku\""); + DumperOptions options = new DumperOptions(); + // options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + options.setDefaultScalarStyle(DumperOptions.ScalarStyle.FOLDED); + Yaml yaml = new Yaml(options); + + Map<String, Object> parameters = new HashMap<String, Object>(); + parameters.put("k1", "val"); + parameters.put("k2", "\"val\""); + + String str = yaml.dump(parameters); + log.debug(str); + } + + @Test + public void yamlValidTest() { + + StringBuffer sb = new StringBuffer(); + sb.append("key: \"!@;/?:&=+$,_.~*'()[]\""); + byte[] payload = sb.toString().getBytes();// Base64.decodeBase64(sb.toString()); + + YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter(); + + assertTrue(yamlToObjectConverter.isValidYaml(payload)); + } + + @Test + public void testRemoveOnlyHtmlTags() { + + assertEquals("gooboo", HtmlCleaner.stripHtml("<b>goo<b></b></b><b>boo</b>")); + String str = HtmlCleaner.stripHtml("<esofer><b>goo<b></b><</b><b>boo</b>"); + + String stripHtmlAndEscape = HtmlCleaner.stripHtml("<esofer><b>goo<b></b><</b><b>boo</b>"); + assertEquals("<esofer>goo<boo", stripHtmlAndEscape); + + stripHtmlAndEscape = HtmlCleaner.stripHtml("<esofer><b>goo<b></b><</b><b>boo</b>", true); + assertEquals("<esofer>goo<boo", stripHtmlAndEscape); + + stripHtmlAndEscape = HtmlCleaner.stripHtml("<esofer><b>goo<b></b><&</b><b>boo</b>dvc&", true); + assertEquals("<esofer>goo<&boodvc&", stripHtmlAndEscape); + + assertEquals("esofer>><<", HtmlCleaner.stripHtml("esofer>><<", true)); + assertEquals("esofer>><<", HtmlCleaner.stripHtml("esofer>><<", false)); + + assertEquals("<esofer1>><<esofer2>", HtmlCleaner.stripHtml("<esofer1>><<esofer2>")); + + assertEquals("<esofer1 a= b>><<esofer2>", HtmlCleaner.stripHtml("<esofer1 a= b><h1>><<esofer2><br>")); + + assertEquals("<esofer1 a= 'b'>><<esofer2>", + HtmlCleaner.stripHtml("<esofer1 a= 'b'>><<esofer2>", true)); + assertEquals("<esofer1 a= 'b'>><<esofer2>", HtmlCleaner.stripHtml("<esofer1 a= 'b'>><H6><<esofer2>")); + + assertEquals("<esofer1 a= b>><<esofer2>", HtmlCleaner.stripHtml("<esofer1 a= b>><<esofer2>")); + + assertEquals("<esofer1 sd sa= b>><<esofer2>", HtmlCleaner.stripHtml("<esofer1 sd sa= b>><<esofer2>")); + + assertEquals("<esofer1 sd sa= b>><<esofer2>", + HtmlCleaner.stripHtml("<esofer1 sd sa= b>><<esofer2>", true)); + assertEquals("<esofer1 sd sa= b>><<esofer2>", HtmlCleaner.stripHtml("<esofer1 sd sa= b>><<esofer2>", false)); + assertEquals("<esofer1 sd sa= b>><<esofer2>", + HtmlCleaner.stripHtml("<esofer1 sd sa= b>><<esofer2>", true)); + assertEquals("<esofer1 sd sa= b>><<esofer2>", + HtmlCleaner.stripHtml("<esofer1 sd sa= b>><br><H1><<esofer2>", false)); + assertEquals("<esofer>goo<&boodvc&", + HtmlCleaner.stripHtml("<esofer><b>goo<b></b><&</b><b>boo</b>dvc&", true)); + assertEquals("<esofer>goo<&boodvc&", HtmlCleaner.stripHtml("<esofer><b>goo<b></b><&</b><b>boo</b>dvc&", false)); + assertEquals("<<<>>>;\"", HtmlCleaner.stripHtml("<<<>>>;\"", false)); + assertEquals("<<<>>>;"", HtmlCleaner.stripHtml("<<<>>>;\"", true)); + assertEquals("<<<>>>;\"", HtmlCleaner.stripHtml("<<<>>>;\"", false)); + assertEquals("abc ab a", HtmlCleaner.stripHtml("abc ab a", true)); + assertEquals("abc ab a", HtmlCleaner.stripHtml("abc ab a", false)); + assertEquals("< esofer1 sd &<>sa= b>><<esofer2>", + HtmlCleaner.stripHtml("< esofer1 sd &<>sa= b>><br><H1><<esofer2>", false)); + assertEquals("sa= b>><<esofer2>", HtmlCleaner.stripHtml("<br sd &<>sa= b>><br><H1><<esofer2>", false)); + assertEquals("< br sd &<>sa= b>><<esofer2>", + HtmlCleaner.stripHtml("< br sd &<>sa= b>><br><H1><<esofer2>", false)); + assertEquals("sa= b>><<esofer2>", HtmlCleaner.stripHtml("</br sd &<>sa= b>><br><H1><<esofer2>", false)); + assertEquals("sa= b>><<esofer2>", HtmlCleaner.stripHtml("<br sd &</>sa= b>><br><H1><<esofer2>", false)); + + } + + /* + * General utility end + */ +} diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/test/TestExternalConfiguration.java b/common-app-api/src/test/java/org/openecomp/sdc/common/test/TestExternalConfiguration.java new file mode 100644 index 0000000000..aa3b2e4083 --- /dev/null +++ b/common-app-api/src/test/java/org/openecomp/sdc/common/test/TestExternalConfiguration.java @@ -0,0 +1,258 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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========================================================= + */ + +package org.openecomp.sdc.common.test; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import static org.mockito.Matchers.anyList; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import org.openecomp.sdc.be.config.DistributionEngineConfiguration; +import org.openecomp.sdc.common.api.BasicConfiguration; +import org.openecomp.sdc.common.api.ConfigurationListener; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.api.FileChangeCallback; +import org.openecomp.sdc.common.impl.ConfigFileChangeListener; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.openecomp.sdc.common.test.config.TestConfiguration; +import org.openecomp.sdc.common.test.config.TestNotExistConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class TestExternalConfiguration { + + private static Logger log = LoggerFactory.getLogger(TestExternalConfiguration.class.getName()); + private static final String NEW_LINE = System.getProperty("line.separator"); + ConfigurationSource configurationSource = null; + + @Before + public void setup() { + + ExternalConfiguration.setAppName("common"); + ExternalConfiguration.setConfigDir("src/test/resources/config"); + ExternalConfiguration.listenForChanges(); + + configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName()); + + } + + @Test + public void testReadConfigurationFile() { + + ConfigurationListener configurationListener = new ConfigurationListener(TestConfiguration.class, new FileChangeCallback() { + + public void reconfigure(BasicConfiguration obj) { + // TODO Auto-generated method stub + log.debug("In reconfigure of {}", obj); + } + + }); + + TestConfiguration testConfiguration = configurationSource.getAndWatchConfiguration(TestConfiguration.class, configurationListener); + + assertTrue(testConfiguration != null); + log.debug("{}", testConfiguration); + assertEquals(testConfiguration.getBeHost(), "172.20.37.245"); + assertEquals(testConfiguration.getBeProtocol(), "http"); + assertEquals(testConfiguration.getBeContext(), "/sdc/rest/config/get"); + + } + + @Test + public void testNotExistConfigurationFile() { + + ConfigurationListener configurationListener = new ConfigurationListener(TestConfiguration.class, new FileChangeCallback() { + + public void reconfigure(BasicConfiguration obj) { + // TODO Auto-generated method stub + log.debug("In reconfigure of {}", obj); + } + + }); + + TestNotExistConfiguration testConfiguration = configurationSource.getAndWatchConfiguration(TestNotExistConfiguration.class, configurationListener); + + assertTrue(testConfiguration == null); + + } + + @Test + public void testUpdateConfigurationFile() { + + ConfigurationListener configurationListener = new ConfigurationListener(TestConfiguration.class, new FileChangeCallback() { + + public void reconfigure(BasicConfiguration obj) { + // TODO Auto-generated method stub + log.debug("In reconfigure of {}", obj); + // assertEquals(((TestConfiguration)obj).getBeSslPort(), + // 8444); + + // assertTrue(((TestConfiguration)obj).getBeSslPort() == + // 8444); + } + + }); + + TestConfiguration testConfiguration = configurationSource.getAndWatchConfiguration(TestConfiguration.class, configurationListener); + + assertTrue(testConfiguration != null); + log.debug("{}", testConfiguration); + assertEquals(testConfiguration.getBeHost(), "172.20.37.245"); + assertEquals(testConfiguration.getBeProtocol(), "http"); + assertEquals(testConfiguration.getBeContext(), "/sdc/rest/config/get"); + + // updateFileContent(); + + } + + private void updateFileContent() { + File file = new File(ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName() + File.separator + "test-configuration.yaml"); + replaceFile(file); + + try { + Thread.sleep(5000); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public void replaceFile(File f1) { + FileReader fr = null; + BufferedReader br = null; + FileWriter fw = null; + BufferedWriter out = null; + try { + List<String> lines = new ArrayList<String>(); + String line = null; + fr = new FileReader(f1); + br = new BufferedReader(fr); + while ((line = br.readLine()) != null) { + if (line.contains("beSslPort: 8443")) + line = line.replace("8443", "8444"); + lines.add(line); + } + + fw = new FileWriter(f1); + out = new BufferedWriter(fw); + for (String s : lines) + out.write(s + NEW_LINE); + out.flush(); + } catch (Exception ex) { + ex.printStackTrace(); + } finally { + + if (br != null) { + try { + br.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + if (fr != null) { + try { + fr.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + if (out != null) { + try { + out.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + if (fw != null) { + try { + fw.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + } + + @Test + public void testReadDistributionEngineConfigurationFile() { + + ConfigurationListener configurationListener = new ConfigurationListener(TestConfiguration.class, new FileChangeCallback() { + + public void reconfigure(BasicConfiguration obj) { + // TODO Auto-generated method stub + log.debug("In reconfigure of ", obj); + } + + }); + + DistributionEngineConfiguration deConfiguration = configurationSource.getAndWatchConfiguration(DistributionEngineConfiguration.class, configurationListener); + + assertTrue(deConfiguration != null); + log.debug("{}", deConfiguration); + assertEquals(deConfiguration.getDistributionNotifTopicName(), "ASDC-DISTR-NOTIF-TOPIC"); + assertEquals(deConfiguration.getDistributionStatusTopicName(), "ASDC-DISTR-STATUS-TOPIC"); + + assertEquals(deConfiguration.getDistributionStatusTopic().getConsumerGroup(), "asdc"); + assertEquals(deConfiguration.getDistributionStatusTopic().getConsumerGroup(), "asdc"); + assertEquals(deConfiguration.getDistributionStatusTopic().getFetchTimeSec().intValue(), 15); + assertEquals(deConfiguration.getDistributionStatusTopic().getPollingIntervalSec().intValue(), 60); + + assertEquals(deConfiguration.getEnvironments().size(), 1); + assertEquals(deConfiguration.getEnvironments().iterator().next(), "PROD"); + + assertEquals(deConfiguration.getDistribNotifResourceArtifactTypes().getInfo(), null); + assertEquals(deConfiguration.getDistribNotifResourceArtifactTypes().getLifecycle().size(), 2); + assertTrue(deConfiguration.getDistribNotifResourceArtifactTypes().getLifecycle().contains("HEAT")); + assertTrue(deConfiguration.getDistribNotifResourceArtifactTypes().getLifecycle().contains("DG_XML")); + + assertEquals(deConfiguration.getDistribNotifServiceArtifactTypes().getLifecycle(), null); + assertEquals(deConfiguration.getDistribNotifServiceArtifactTypes().getInfo().size(), 1); + assertTrue(deConfiguration.getDistribNotifServiceArtifactTypes().getInfo().contains("MURANO-PKG")); + + assertEquals(deConfiguration.getUebPublicKey(), "fff"); + assertEquals(deConfiguration.getUebSecretKey(), "ffff"); + assertEquals(deConfiguration.getUebServers().size(), 3); + assertEquals(deConfiguration.getInitRetryIntervalSec().intValue(), 5); + + } + +} diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/test/YamlTest.java b/common-app-api/src/test/java/org/openecomp/sdc/common/test/YamlTest.java new file mode 100644 index 0000000000..340bca9f1d --- /dev/null +++ b/common-app-api/src/test/java/org/openecomp/sdc/common/test/YamlTest.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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========================================================= + */ + +package org.openecomp.sdc.common.test; + +import static org.junit.Assert.*; + +import org.apache.commons.codec.binary.Base64; +import org.junit.BeforeClass; +import org.junit.Test; +import org.openecomp.sdc.common.util.YamlToObjectConverter; + +public class YamlTest { + + private static YamlToObjectConverter yamlToObjectConverter; + private static String validYaml = "heat_template_version: 2013-05-23\r\ndescription: A load-balancer server\r\nparameters:\r\n image:\r\n type: string\r\n description: Image used for servers\r\n key_name:\r\n type: string\r\n description: SSH key to connect to the servers\r\n flavor:\r\n type: string\r\n description: flavor used by the servers\r\n pool_id:\r\n type: string\r\n description: Pool to contact\r\n user_data:\r\n type: string\r\n description: Server user_data\r\n metadata:\r\n type: json\r\n network:\r\n type: string\r\n description: Network used by the server\r\n\r\nresources:\r\n server:\r\n type: OS::Nova::Server\r\n properties:\r\n flavor: {get_param: flavor}\r\n image: {get_param: image}\r\n key_name: {get_param: key_name}\r\n metadata: {get_param: metadata}\r\n user_data: {get_param: user_data}\r\n user_data_format: RAW\r\n networks: [{network: {get_param: network} }]\r\n member:\r\n type: OS::Neutron::PoolMember\r\n properties:\r\n pool_id: {get_param: pool_id}\r\n address: {get_attr: [server, first_address]}\r\n protocol_port: 80\r\n\r\noutputs:\r\n server_ip:\r\n description: IP Address of the load-balanced server.\r\n value: { get_attr: [server, first_address] }\r\n lb_member:\r\n description: LB member details.\r\n value: { get_attr: [member, show] }"; + // Missing square brackets at the end of string + private static String invalidYaml = "heat_template_version: 2013-05-23\r\ndescription: A load-balancer server\r\nparameters:\r\n image:\r\n type: string\r\n description: Image used for servers\r\n key_name:\r\n type: string\r\n description: SSH key to connect to the servers\r\n flavor:\r\n type: string\r\n description: flavor used by the servers\r\n pool_id:\r\n type: string\r\n description: Pool to contact\r\n user_data:\r\n type: string\r\n description: Server user_data\r\n metadata:\r\n type: json\r\n network:\r\n type: string\r\n description: Network used by the server\r\n\r\nresources:\r\n server:\r\n type: OS::Nova::Server\r\n properties:\r\n flavor: {get_param: flavor}\r\n image: {get_param: image}\r\n key_name: {get_param: key_name}\r\n metadata: {get_param: metadata}\r\n user_data: {get_param: user_data}\r\n user_data_format: RAW\r\n networks: [{network: {get_param: network} }]\r\n member:\r\n type: OS::Neutron::PoolMember\r\n properties:\r\n pool_id: {get_param: pool_id}\r\n address: {get_attr: [server, first_address]}\r\n protocol_port: 80\r\n\r\noutputs:\r\n server_ip:\r\n description: IP Address of the load-balanced server.\r\n value: { get_attr: [server, first_address] }\r\n lb_member:\r\n description: LB member details.\r\n value: { get_attr: [member, show}"; + + @BeforeClass + public static void setup() { + yamlToObjectConverter = new YamlToObjectConverter(); + } + + @Test + public void testValidYaml() { + assertTrue(yamlToObjectConverter.isValidYaml(validYaml.getBytes())); + } + + @Test + public void testInvalidYaml() { + assertFalse(yamlToObjectConverter.isValidYaml(invalidYaml.getBytes())); + } + + @Test + public void testValidYamlBase64() { + assertTrue(yamlToObjectConverter.isValidYaml(Base64.encodeBase64(validYaml.getBytes()))); + } + + @Test + public void testInvalidYamlBase64() { + assertFalse(yamlToObjectConverter.isValidYaml(Base64.encodeBase64(invalidYaml.getBytes()))); + } +} diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/test/config/TestConfiguration.java b/common-app-api/src/test/java/org/openecomp/sdc/common/test/config/TestConfiguration.java new file mode 100644 index 0000000000..b8bf394fd7 --- /dev/null +++ b/common-app-api/src/test/java/org/openecomp/sdc/common/test/config/TestConfiguration.java @@ -0,0 +1,149 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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========================================================= + */ + +package org.openecomp.sdc.common.test.config; + +import java.util.Date; +import java.util.List; +import java.util.Map; + +import org.openecomp.sdc.common.api.BasicConfiguration; + +import static java.lang.String.format; + +public class TestConfiguration extends BasicConfiguration { + + /** + * backend host + */ + private String beHost; + /** + * backend http port + */ + private Integer beHttpPort; + /** + * backend http secured port + */ + private Integer beSslPort; + /** + * be http context + */ + private String beContext; + /** + * backend protocol. http | https + */ + private String beProtocol = "http"; + + private Date released; + private String version = "1111"; + private TestConnection connection; + private List<String> protocols; + private Map<String, String> users; + + public Date getReleased() { + return released; + } + + public String getVersion() { + return version; + } + + public void setReleased(Date released) { + this.released = released; + } + + public void setVersion(String version) { + this.version = version; + } + + public TestConnection getConnection() { + return connection; + } + + public void setConnection(TestConnection connection) { + this.connection = connection; + } + + public List<String> getProtocols() { + return protocols; + } + + public void setProtocols(List<String> protocols) { + this.protocols = protocols; + } + + public Map<String, String> getUsers() { + return users; + } + + public void setUsers(Map<String, String> users) { + this.users = users; + } + + public String getBeHost() { + return beHost; + } + + public void setBeHost(String beHost) { + this.beHost = beHost; + } + + public Integer getBeHttpPort() { + return beHttpPort; + } + + public void setBeHttpPort(Integer beHttpPort) { + this.beHttpPort = beHttpPort; + } + + public Integer getBeSslPort() { + return beSslPort; + } + + public void setBeSslPort(Integer beSslPort) { + this.beSslPort = beSslPort; + } + + public String getBeContext() { + return beContext; + } + + public void setBeContext(String beContext) { + this.beContext = beContext; + } + + public String getBeProtocol() { + return beProtocol; + } + + public void setBeProtocol(String beProtocol) { + this.beProtocol = beProtocol; + } + + @Override + public String toString() { + return new StringBuilder().append(format("backend host: %s\n", beHost)) + .append(format("backend http port: %s\n", beHttpPort)) + .append(format("backend ssl port: %s\n", beSslPort)).append(format("backend context: %s\n", beContext)) + .append(format("backend protocol: %s\n", beProtocol)).append(format("Version: %s\n", version)) + .append(format("Released: %s\n", released)).append(format("Connecting to database: %s\n", connection)) + .append(format("Supported protocols: %s\n", protocols)).append(format("Users: %s\n", users)).toString(); + } +} diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/test/config/TestConnection.java b/common-app-api/src/test/java/org/openecomp/sdc/common/test/config/TestConnection.java new file mode 100644 index 0000000000..ad546f7f97 --- /dev/null +++ b/common-app-api/src/test/java/org/openecomp/sdc/common/test/config/TestConnection.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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========================================================= + */ + +package org.openecomp.sdc.common.test.config; + +public class TestConnection { + + private String url; + private int poolSize; + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public int getPoolSize() { + return poolSize; + } + + public void setPoolSize(int poolSize) { + this.poolSize = poolSize; + } + + @Override + public String toString() { + return String.format("'%s' with pool of %d", getUrl(), getPoolSize()); + } +} diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/test/config/TestNotExistConfiguration.java b/common-app-api/src/test/java/org/openecomp/sdc/common/test/config/TestNotExistConfiguration.java new file mode 100644 index 0000000000..76f694f5b8 --- /dev/null +++ b/common-app-api/src/test/java/org/openecomp/sdc/common/test/config/TestNotExistConfiguration.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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========================================================= + */ + +package org.openecomp.sdc.common.test.config; + +import static java.lang.String.format; + +import org.openecomp.sdc.common.api.BasicConfiguration; + +public class TestNotExistConfiguration extends BasicConfiguration { + + /** + * backend host + */ + private String beHost; + /** + * backend http port + */ + private Integer beHttpPort; + + /** + * backend http secured port + */ + + @Override + public String toString() { + return new StringBuilder().append(format("backend host: %s\n", beHost)) + .append(format("backend http port: %s\n", beHttpPort)).toString(); + } +} diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/util/StreamUtilsTests.java b/common-app-api/src/test/java/org/openecomp/sdc/common/util/StreamUtilsTests.java new file mode 100644 index 0000000000..31dc5f5f47 --- /dev/null +++ b/common-app-api/src/test/java/org/openecomp/sdc/common/util/StreamUtilsTests.java @@ -0,0 +1,143 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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========================================================= + */ + +package org.openecomp.sdc.common.util; + +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.junit.Test; +import org.openecomp.sdc.common.util.StreamUtils; + +import fj.data.Either; + +public class StreamUtilsTests { + @Test + public void testTakeWhilePredicateNotMet() { + List<Either<Integer, Boolean>> list = buildListWith10Integers(); + + assertTrue(StreamUtils.takeWhile(list.stream(), p -> p.isLeft()).count() == 10); + } + + @Test + public void testTakeWhilePredicateIsMet() { + List<Either<Integer, Boolean>> list = buildListWith10Integers(); + addToBooleansToList(list); + + final Stream<Either<Integer, Boolean>> takeWhileStream = StreamUtils.takeWhile(list.stream(), p -> p.isLeft()); + assertTrue(takeWhileStream.filter(p -> p.isRight()).count() == 0); + } + + @Test + public <T> void testTakeErrorEvalOnlyOnce() { + List<Integer> bucket = new ArrayList<>(); + // API + Function<Integer, Either<Integer, Boolean>> cons = num -> { + Either<Integer, Boolean> ret; + bucket.add(num); + if (num > 5) { + ret = Either.right(false); + } else { + ret = Either.left(num); + } + ; + return ret; + }; + + List<Integer> num1to10 = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + Stream<Either<Integer, Boolean>> streamEithers = num1to10.stream().map(e -> cons.apply(e)); + List<Either<Integer, Boolean>> collect = StreamUtils.takeWhilePlusOneNoEval(streamEithers, e -> e.isLeft()) + .collect(Collectors.toList()); + assertTrue(bucket.size() <= 6); + assertTrue(collect.size() <= 6); + assertTrue(collect.stream().filter(e -> e.isRight()).count() == 1); + + } + + @Test + public void testTakeWhilePlusOnePredicateNotMet() { + List<Either<Integer, Boolean>> list = buildListWith10Integers(); + + assertTrue(StreamUtils.takeWhilePlusOne(list.stream(), p -> p.isLeft()).count() == 10); + } + + @Test + public void testTakeWhilePlusOnePredicateIsMet() { + List<Either<Integer, Boolean>> list = buildListWith10Integers(); + addToBooleansToList(list); + + final Stream<Either<Integer, Boolean>> takeWhilePlusOneStream = StreamUtils.takeWhilePlusOne(list.stream(), + p -> p.isLeft()); + assertTrue(takeWhilePlusOneStream.filter(p -> p.isRight()).count() == 1); + } + + private void addToBooleansToList(List<Either<Integer, Boolean>> list) { + list.add(Either.right(false)); + list.add(Either.right(false)); + } + + private List<Either<Integer, Boolean>> buildListWith10Integers() { + List<Either<Integer, Boolean>> list = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + list.add(Either.left(i)); + } + return list; + } + + @Test + public void myTest() { + List<Integer> list = new ArrayList<Integer>(); + for (int i = 0; i < 10; i++) { + list.add(i); + } + + List<Either<Integer, Boolean>> container = new ArrayList<Either<Integer, Boolean>>(); + list.stream().map(e -> myBusinessLogic(e, container)).filter(p -> p.isRight()).findAny(); + // Actual Results are in container + assertTrue(container.size() == 6); + + } + + private Either<Integer, Boolean> myBusinessLogic(int e, List<Either<Integer, Boolean>> cobtainerList) { + Either<Integer, Boolean> eitherElement = similuteDBAccess(e); + // Keep The results in external List + cobtainerList.add(eitherElement); + + return eitherElement; + } + + private Either<Integer, Boolean> similuteDBAccess(int e) { + Either<Integer, Boolean> eitherElement; + if (e < 5) { + // DB Success + eitherElement = Either.left(e); + } else { + // DB Fail + eitherElement = Either.right(true); + } + return eitherElement; + } +} diff --git a/common-app-api/src/test/resources/config/common/distribution-engine-configuration.yaml b/common-app-api/src/test/resources/config/common/distribution-engine-configuration.yaml new file mode 100644 index 0000000000..a4ce7cc08c --- /dev/null +++ b/common-app-api/src/test/resources/config/common/distribution-engine-configuration.yaml @@ -0,0 +1,35 @@ +uebServers: + - ueb.fqdn.1:8888 + - ueb.fqdn.2:8888 + - ueb.fqdn.3:8888 + +uebPublicKey: fff + +uebSecretKey: ffff + +distributionNotifTopicName: ASDC-DISTR-NOTIF-TOPIC +distributionStatusTopicName: ASDC-DISTR-STATUS-TOPIC + +initRetryIntervalSec: 5 +initMaxIntervalSec: 60 + +distribNotifServiceArtifactTypes: + info: + - MURANO-PKG + +distribNotifResourceArtifactTypes: + lifecycle: + - HEAT + - DG_XML + +environments: + - PROD + +distributionStatusTopic: + pollingIntervalSec: 60 + fetchTimeSec: 15 + consumerGroup: asdc + +createTopic: + partitionCount: 1 + replicationCount: 1 diff --git a/common-app-api/src/test/resources/config/common/test-configuration.yaml b/common-app-api/src/test/resources/config/common/test-configuration.yaml new file mode 100644 index 0000000000..38912c06ff --- /dev/null +++ b/common-app-api/src/test/resources/config/common/test-configuration.yaml @@ -0,0 +1,35 @@ +# catalog backend hostname +beHost: 172.20.37.245 + +# catalog backend http port +beHttpPort: 8080 + +# catalog backend http context +beContext: /sdc/rest/config/get + +# catalog backend protocol +beProtocol: http + +# catalog backend ssl port +beSslPort: 8444 + +version: 1.0 +released: 2012-11-30 + +# Connection parameters +connection: + url: jdbc:mysql://localhost:3306/db + poolSize: 17 + +# Protocols +protocols: + - http + - https + +# Users +users: + tom: passwd + bob: passwd + + + diff --git a/common-app-api/src/test/resources/logback-test.xml b/common-app-api/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..d2b9bff23f --- /dev/null +++ b/common-app-api/src/test/resources/logback-test.xml @@ -0,0 +1,13 @@ +<!-- only one line, shut up logback ! --> +<configuration> + <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> + <encoder> + <Pattern> + %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n + </Pattern> + </encoder> + </appender> + <root level="OFF"> + <appender-ref ref="STDOUT" /> + </root> +</configuration>
\ No newline at end of file |