diff options
Diffstat (limited to 'sdnr/wt/common/src/test')
12 files changed, 1507 insertions, 0 deletions
diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestBaseHttpClient.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestBaseHttpClient.java new file mode 100644 index 000000000..af3979c50 --- /dev/null +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestBaseHttpClient.java @@ -0,0 +1,180 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH 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.onap.ccsdk.features.sdnr.wt.common.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.ccsdk.features.sdnr.wt.common.http.BaseHTTPClient; +import org.onap.ccsdk.features.sdnr.wt.common.http.BaseHTTPResponse; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; +import com.sun.net.httpserver.HttpServer; + +@SuppressWarnings("restriction") +public class TestBaseHttpClient { + + public static final String HTTPMETHOD_GET = "GET"; + public static final String HTTPMETHOD_POST = "POST"; + public static final String HTTPMETHOD_PUT = "PUT"; + public static final String HTTPMETHOD_DELETE = "DELETE"; + public static final String HTTPMETHOD_OPTIONS = "OPTIONS"; + public static final String RESPONSE_GET = "This is the response get"; + public static final String RESPONSE_POST = "This is the response post"; + public static final String RESPONSE_PUT = "This is the response put"; + public static final String RESPONSE_DELETE = "This is the response delete"; + public static final String RESPONSE_OPTIONS = "This is the response options"; + private static final String TESTURI = "/mwtn/test"; + private static HttpServer server; + private static ExecutorService httpThreadPool; + private static final int testPort = 54440; + + @Test + public void test() { + MyHttpClient httpClient = new MyHttpClient("http://localhost:"+testPort, true); + Map<String, String> headers = new HashMap<String,String>(); + headers.put("Authorization", BaseHTTPClient.getAuthorizationHeaderValue("admin", "admin")); + headers.put("Content-Type","application/json"); + BaseHTTPResponse response=null; + try { + response= httpClient.sendRequest(TESTURI, HTTPMETHOD_GET, null, headers ); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response); + assertEquals(RESPONSE_GET, response.body); + try { + response= httpClient.sendRequest(TESTURI, HTTPMETHOD_POST, "{}", headers ); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response); + assertEquals(RESPONSE_POST, response.body); + try { + response= httpClient.sendRequest(TESTURI, HTTPMETHOD_PUT, "{}", headers ); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response); + assertEquals(RESPONSE_PUT, response.body); + try { + response= httpClient.sendRequest(TESTURI, HTTPMETHOD_DELETE, "{}", headers ); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response); + assertEquals(RESPONSE_DELETE, response.body); + + } + + + + + @BeforeClass + public static void initTestWebserver() throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", testPort), 0); + httpThreadPool = Executors.newFixedThreadPool(5); + server.setExecutor(httpThreadPool); + server.createContext(TESTURI, new MyHandler()); + //server.createContext("/", new MyRootHandler()); + server.setExecutor(null); // creates a default executor + server.start(); + System.out.println("http server started"); + } + @AfterClass + public static void stopTestWebserver() { + System.out.println("try to stop server"); + if (server != null) { + server.stop(0); + httpThreadPool.shutdownNow(); + System.out.println("http server stopped" ); + } + } + + private class MyHttpClient extends BaseHTTPClient{ + + public MyHttpClient(String base, boolean trustAllCerts) { + super(base, trustAllCerts); + } + + @Override + public BaseHTTPResponse sendRequest(String uri, String method, String body, Map<String, String> headers) + throws IOException { + return super.sendRequest(uri, method, body, headers); + } + } + + public static class MyHandler implements HttpHandler { + + @Override + public void handle(HttpExchange t) throws IOException { + String method = t.getRequestMethod(); + System.out.println(String.format("req received: %s %s" ,method,t.getRequestURI())); + OutputStream os = null; + try { + if (method.equals(HTTPMETHOD_GET)) { + t.sendResponseHeaders(200, RESPONSE_GET.length()); + os = t.getResponseBody(); + os.write(RESPONSE_GET.getBytes()); + } else if (method.equals(HTTPMETHOD_POST)) { + t.sendResponseHeaders(200, RESPONSE_POST.length()); + os = t.getResponseBody(); + os.write(RESPONSE_POST.getBytes()); + } else if (method.equals(HTTPMETHOD_PUT)) { + t.sendResponseHeaders(200, RESPONSE_PUT.length()); + os = t.getResponseBody(); + os.write(RESPONSE_PUT.getBytes()); + } else if (method.equals(HTTPMETHOD_DELETE)) { + t.sendResponseHeaders(200, RESPONSE_DELETE.length()); + os = t.getResponseBody(); + os.write(RESPONSE_DELETE.getBytes()); + } else if (method.equals(HTTPMETHOD_OPTIONS)) { + t.sendResponseHeaders(200, RESPONSE_OPTIONS.length()); + //os = t.getResponseBody(); + //os.write(RESPONSE_OPTIONS.getBytes()); + } else { + t.sendResponseHeaders(404, 0); + } + System.out.println("req handled successful"); + + } catch (Exception e) { + System.out.println(e.getMessage()); + } + finally { + if (os != null) + { + os.flush(); + os.close(); + } + } + } + } +} diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestConfig.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestConfig.java new file mode 100644 index 000000000..f6f741197 --- /dev/null +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestConfig.java @@ -0,0 +1,233 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH 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.onap.ccsdk.features.sdnr.wt.common.test; + +import static org.junit.Assert.*; + +import java.io.File; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.nio.file.Files; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.ccsdk.features.sdnr.wt.common.configuration.ConfigurationFileRepresentation; +import org.onap.ccsdk.features.sdnr.wt.common.configuration.exception.ConversionException; +import org.onap.ccsdk.features.sdnr.wt.common.configuration.filechange.IConfigChangedListener; +import org.onap.ccsdk.features.sdnr.wt.common.configuration.subtypes.Section; +import org.onap.ccsdk.features.sdnr.wt.common.database.config.HostInfo; +import org.onap.ccsdk.features.sdnr.wt.common.database.config.HostInfo.Protocol; + +public class TestConfig { + + private static final String TESTFILENAME = "test.properties"; + private static final String TESTKEY1 = "abc"; + private static final String TESTKEY2 = "def"; + private static final String TESTKEY3 = "hhh"; + private static final String TESTKEY4 = "hhv"; + + private static final int TESTVALUE1=123; + private static final int TESTVALUE1_2=1234; + private static final boolean TESTVALUE2 = true; + private static final String TESTVALUE3 = "http://localhost:2223"; + private static final String TESTVALUE4 = "httasdasdas"; + private static final String TESTCONTENT1 = " [test]\n" + + TESTKEY1+"="+TESTVALUE1+"\n" + + "#her a comment\n"+ + TESTKEY2+"="+TESTVALUE2+"\n" + + TESTKEY3+"="+TESTVALUE3; + + + + + @After + @Before + public void init() { + File f=new File(TESTFILENAME); + if(f.exists()) { + f.delete(); + } + } + + public void write(String filename,String lines) { + + try { + Files.write(new File(filename).toPath(), lines.getBytes()); + } catch (IOException e) { + fail("problem writing file "+filename); + } + } + @Test + public void testRead() { + this.write(TESTFILENAME, TESTCONTENT1); + ConfigurationFileRepresentation confiuration=new ConfigurationFileRepresentation(TESTFILENAME); + Section section = confiuration.getSection("test").get(); + assertNotNull(section); + try { + assertEquals(TESTVALUE1, section.getInt(TESTKEY1, 0)); + assertEquals(TESTVALUE2, section.getBoolean(TESTKEY2, !TESTVALUE2)); + assertEquals(TESTVALUE3, section.getString(TESTKEY3, "")); + } catch (ConversionException e) { + fail(e.getMessage()); + } + this.init(); + } + @Test + public void testWrite() { + final String SECTIONNAME = "test"; + //write values + ConfigurationFileRepresentation confiuration=new ConfigurationFileRepresentation(TESTFILENAME); + Section section=confiuration.addSection(SECTIONNAME); + + section.setProperty(TESTKEY1, String.valueOf(TESTVALUE1)); + section.setProperty(TESTKEY2, String.valueOf(TESTVALUE2)); + section.setProperty(TESTKEY3, String.valueOf(TESTVALUE3)); + confiuration.save(); + + //verify written + ConfigurationFileRepresentation confiuration2=new ConfigurationFileRepresentation(TESTFILENAME); + + section = confiuration2.getSection(SECTIONNAME).get(); + assertNotNull(section); + try { + assertEquals(TESTVALUE1, section.getInt(TESTKEY1, 0)); + assertEquals(TESTVALUE2, section.getBoolean(TESTKEY2, !TESTVALUE2)); + assertEquals(TESTVALUE3, section.getString(TESTKEY3, "")); + } catch (ConversionException e) { + fail(e.getMessage()); + } + this.init(); + + //write directly into base + confiuration=new ConfigurationFileRepresentation(TESTFILENAME); + section=confiuration.addSection(SECTIONNAME); + confiuration.setProperty(SECTIONNAME,TESTKEY1 , TESTVALUE1); + confiuration.setProperty(SECTIONNAME,TESTKEY2 , TESTVALUE2); + confiuration.setProperty(SECTIONNAME,TESTKEY3 , TESTVALUE3); + confiuration.save(); + + //verify + confiuration2=new ConfigurationFileRepresentation(TESTFILENAME); + section = confiuration2.getSection(SECTIONNAME).get(); + assertNotNull(section); + assertEquals(TESTVALUE1, confiuration.getPropertyLong(SECTIONNAME,TESTKEY1).get().intValue()); + assertEquals(TESTVALUE2, confiuration.getPropertyBoolean(SECTIONNAME,TESTKEY2)); + assertEquals(TESTVALUE3, confiuration.getProperty(SECTIONNAME,TESTKEY3)); + this.init(); + + + } + @Test + public void testOverwrite() { + final String SECTIONNAME = "test"; + //write values + ConfigurationFileRepresentation confiuration=new ConfigurationFileRepresentation(TESTFILENAME); + Section section=confiuration.addSection(SECTIONNAME); + + section.setProperty(TESTKEY1, String.valueOf(TESTVALUE1)); + section.setProperty(TESTKEY2, String.valueOf(TESTVALUE2)); + section.setProperty(TESTKEY3, String.valueOf(TESTVALUE3)); + confiuration.save(); + + //verify written + ConfigurationFileRepresentation confiuration2=new ConfigurationFileRepresentation(TESTFILENAME); + + section = confiuration2.getSection(SECTIONNAME).get(); + + assertNotNull(section); + try { + assertEquals(TESTVALUE1, section.getInt(TESTKEY1, 0)); + assertEquals(TESTVALUE2, section.getBoolean(TESTKEY2, !TESTVALUE2)); + assertEquals(TESTVALUE3, section.getString(TESTKEY3, "")); + } catch (ConversionException e) { + fail(e.getMessage()); + } + + //write directly into base + confiuration=new ConfigurationFileRepresentation(TESTFILENAME); + section=confiuration.addSection(SECTIONNAME); + confiuration.setPropertyIfNotAvailable(SECTIONNAME,TESTKEY1 , TESTVALUE1_2); + confiuration.setPropertyIfNotAvailable(SECTIONNAME,TESTKEY4 , TESTVALUE4); + + confiuration.save(); + + //verify + confiuration2=new ConfigurationFileRepresentation(TESTFILENAME); + section = confiuration2.getSection(SECTIONNAME).get(); + assertNotNull(section); + assertEquals(TESTVALUE1, confiuration.getPropertyLong(SECTIONNAME,TESTKEY1).get().intValue()); + assertEquals(TESTVALUE2, confiuration.getPropertyBoolean(SECTIONNAME,TESTKEY2)); + assertEquals(TESTVALUE3, confiuration.getProperty(SECTIONNAME,TESTKEY3)); + assertEquals(TESTVALUE4, confiuration.getProperty(SECTIONNAME,TESTKEY4)); + this.init(); + + + } + static boolean changeFlag=false; + @Test + public void testChangeListener() { + + changeFlag=false; + this.init(); + ConfigurationFileRepresentation confiuration=new ConfigurationFileRepresentation(TESTFILENAME); + IConfigChangedListener listener = new IConfigChangedListener() { + + @Override + public void onConfigChanged() { + changeFlag=true; + } + }; + confiuration.registerConfigChangedListener(listener ); + try { + Thread.sleep(2000); + } catch (InterruptedException e) { + Thread.interrupted(); + } + this.write(TESTFILENAME, TESTCONTENT1); + int i=10; + while(i-->0) { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + Thread.interrupted(); + } + if(changeFlag) { + break; + } + } + confiuration.unregisterConfigChangedListener(listener); + assertTrue("changelistener not called",changeFlag); + } + @Test + public void testHostInfo() { + HostInfo hi=HostInfo.getDefault(); + try { + new URL(hi.toUrl()); + } catch (MalformedURLException e) { + fail("url conversion failed: "+e.getMessage()); + } + hi = new HostInfo("localhost", 44444, Protocol.getValueOf("https")); + try { + new URL(hi.toUrl()); + } catch (MalformedURLException e) { + fail("url conversion failed: "+e.getMessage()); + } + + } +} diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDatabaseFilterConversion.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDatabaseFilterConversion.java new file mode 100644 index 000000000..2dd74bbec --- /dev/null +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDatabaseFilterConversion.java @@ -0,0 +1,81 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH 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.onap.ccsdk.features.sdnr.wt.common.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.json.JSONException; +import org.junit.Test; +import org.onap.ccsdk.features.sdnr.wt.common.database.data.DbFilter; + +public class TestDatabaseFilterConversion { + + @Test + public void testStartsWith() { + String re=DbFilter.createDatabaseRegex("abc*"); + assertEquals("abc.*", re); + } + @Test + public void testEndsWith() { + String re=DbFilter.createDatabaseRegex("*abc"); + assertEquals(".*abc", re); + } + @Test + public void testMultiple() { + String re=DbFilter.createDatabaseRegex("abc*ff*fa"); + assertEquals("abc.*ff.*fa", re); + } + + @Test + public void testPlaceholder() { + String re=DbFilter.createDatabaseRegex("abc?ef"); + assertEquals("abc.{1,1}ef", re); + } + @Test + public void testCombined() { + String re=DbFilter.createDatabaseRegex("abc?ff*fa"); + assertEquals("abc.{1,1}ff.*fa", re); + } + @Test + public void testFilterCheck() { + assertTrue(DbFilter.hasSearchParams("abc?")); + assertTrue(DbFilter.hasSearchParams("bac*")); + assertFalse(DbFilter.hasSearchParams("abc+")); + } + @Test + public void testRangeConversion() { + try { + JSONAssert.assertEquals("", "{\"query\":{\"range\":{\"port\":{\"gte\":2230,\"boost\":2}}}}", + DbFilter.getRangeQuery("port", ">=2230").toJSON(),true); + JSONAssert.assertEquals("", "{\"query\":{\"range\":{\"port\":{\"gt\":2230,\"boost\":2}}}}", + DbFilter.getRangeQuery("port", ">2230").toJSON(),true); + JSONAssert.assertEquals("", "{\"query\":{\"range\":{\"port\":{\"lte\":2230,\"boost\":2}}}}", + DbFilter.getRangeQuery("port", "<=2230").toJSON(),true); + JSONAssert.assertEquals("", "{\"query\":{\"range\":{\"port\":{\"lt\":2230,\"boost\":2}}}}", + DbFilter.getRangeQuery("port", "<2230").toJSON(),true); + JSONAssert.assertEquals("", "{\"query\":{\"range\":{\"timestamp\":{\"lt\":\"2018-01-01T23:59:59.0Z\",\"boost\":2}}}}", + DbFilter.getRangeQuery("timestamp", "<2018-01-01T23:59:59.0Z").toJSON(),true); + } catch (JSONException e) { + fail(e.getMessage()); + } + } + +} diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbClient.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbClient.java new file mode 100644 index 000000000..0d46b4d20 --- /dev/null +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbClient.java @@ -0,0 +1,71 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH 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.onap.ccsdk.features.sdnr.wt.common.test; + +import static org.junit.Assert.*; + +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.ccsdk.features.sdnr.wt.common.database.HtDatabaseClient; +import org.onap.ccsdk.features.sdnr.wt.common.database.SearchHit; +import org.onap.ccsdk.features.sdnr.wt.common.database.SearchResult; +import org.onap.ccsdk.features.sdnr.wt.common.database.config.HostInfo; +import org.onap.ccsdk.features.sdnr.wt.common.database.queries.QueryBuilders; + +public class TestDbClient { + + private static HtDatabaseClient dbClient; + private static HostInfo[] hosts = new HostInfo[] { new HostInfo("localhost", Integer + .valueOf(System.getProperty("databaseport") != null ? System.getProperty("databaseport") : "49200")) }; + + @BeforeClass + public static void init() { + + dbClient = new HtDatabaseClient(hosts); + dbClient.waitForYellowStatus(20000); + + } + @Test + public void testCRUD() { + final String IDX = "test23-knmoinsd"; + final String ID = "abcddd"; + final String JSON = "{\"data\":{\"inner\":\"more\"}}"; + final String JSON2 = "{\"data\":{\"inner\":\"more2\"}}"; + //Create + String esId=dbClient.doWriteRaw(IDX, ID, JSON); + assertEquals("inserted id is wrong",ID,esId); + //Read + SearchResult<SearchHit> result = dbClient.doReadByQueryJsonData(IDX, QueryBuilders.matchQuery("_id", ID)); + assertEquals("amount of results is wrong",1,result.getTotal()); + assertEquals("data not valid", JSON,result.getHits().get(0).getSourceAsString()); + //Update + esId= dbClient.doUpdateOrCreate(IDX, ID, JSON2); + assertEquals("update response not successfull",ID,esId); + //Verify + result = dbClient.doReadByQueryJsonData( IDX, QueryBuilders.matchQuery("_id", ID)); + assertEquals("amount of results is wrong",1,result.getTotal()); + assertEquals("data not valid", JSON2,result.getHits().get(0).getSourceAsString()); + //Delete + boolean del=dbClient.doRemove(IDX, ID); + assertTrue("item not deleted",del); + //Verify + result = dbClient.doReadByQueryJsonData(IDX, QueryBuilders.matchQuery("_id", ID)); + assertEquals("amount of results is wrong",0,result.getTotal()); + } + +} diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbQueries.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbQueries.java new file mode 100644 index 000000000..40c2cfe9a --- /dev/null +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbQueries.java @@ -0,0 +1,223 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH 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.onap.ccsdk.features.sdnr.wt.common.test; + +import static org.junit.Assert.fail; + +import org.json.JSONException; +import org.junit.Test; +import org.onap.ccsdk.features.sdnr.wt.common.database.data.DbFilter; +import org.onap.ccsdk.features.sdnr.wt.common.database.queries.BoolQueryBuilder; +import org.onap.ccsdk.features.sdnr.wt.common.database.queries.QueryBuilder; +import org.onap.ccsdk.features.sdnr.wt.common.database.queries.QueryBuilders; +import org.onap.ccsdk.features.sdnr.wt.common.database.queries.SortOrder; +import org.onap.ccsdk.features.sdnr.wt.common.test.JSONAssert; + + +public class TestDbQueries { + + private static final String MATCH_ALL_QUERY = "{\n" + + " \"query\": {\n" + + " \"match_all\" : {\n" + + " }\n" + + " }\n" + + "}"; + private static final String MATCH_QUERY_KEY = "is-required"; + private static final Object MATCH_QUERY_VALUE = true; + private static final String MATCH_QUERY = "{\n" + + " \"query\": {\n" + + " \"match\" : {\n" + + " \""+MATCH_QUERY_KEY+"\" : "+MATCH_QUERY_VALUE+"\n" + + " }\n" + + " }\n" + + "}"; + private static final String MATCH_QUERY_KEY2 = "node-id"; + private static final Object MATCH_QUERY_VALUE2 = "sim2"; + private static final String BOOL_QUERY = "{\n" + + " \"query\": {\n" + + " \"bool\": {\n" + + " \"must\": [\n" + + " {\n" + + " \"match\": {\n" + + " \""+MATCH_QUERY_KEY+"\": "+MATCH_QUERY_VALUE+"\n" + + " }\n" + + " },\n" + + " {\n" + + " \"match\": {\n" + + " \""+MATCH_QUERY_KEY2+"\":"+MATCH_QUERY_VALUE2+" \n" + + " }\n" + + " }\n" + + " ]\n" + + " }\n" + + " }\n" + + "}"; + private static final String RANGE_QUERY_KEY = "timestamp"; + private static final String RANGE_QUERY_LTEND = "2017-08-10T20:00:00.0Z"; + private static final String RANGE_QUERY = "{\n" + + " \"query\": {\n" + + " \"range\" : {\n" + + " \""+RANGE_QUERY_KEY+"\" : {\n" + + " \"lte\" : \""+RANGE_QUERY_LTEND+"\",\n" + + " \"boost\": 2.0\n" + + " }\n" + + " }\n" + + " }\n" + + "}"; + private static final String RANGEBOOL_QUERY="{\n" + + " \"query\": {\n" + + " \"bool\": {\n" + + " \"must\": [\n" + + " {\n" + + " \"match\": {\n" + + " \"is-required\": true\n" + + " }\n" + + " },\n" + + " {\n" + + " \"regexp\": {\n" + + " \"node-id\": {\n" + + " \"max_determinized_states\": 10000,\n" + + " \"flags\": \"ALL\",\n" + + " \"value\": \"sim.*\"\n" + + " }\n" + + " }\n" + + " }\n" + + " ]\n" + + " }\n" + + " }\n" + + "}"; + private static final String AGG_FIELD = "severity"; + private static final String AGG_QUERY = "{\n" + + " \"query\": {\n" + + " \"match_all\": {}\n" + + " },\n" + + " \"aggs\": {\n" + + " \"severity\": {\n" + + " \"terms\": {\n" + + " \"field\": \""+AGG_FIELD+"\"\n" + + " }\n" + + " }\n" + + " }\n" + + "}"; + private static final long FROMANDSIZE_QUERY_SIZE = 20; + private static final long FROMANDSIZE_QUERY_FROM = 120; + private static final String FROMANDSIZE_QUERY = "{\n" + + " \"size\": "+FROMANDSIZE_QUERY_SIZE+",\n" + + " \"query\": {\n" + + " \"match_all\": {}\n" + + " },\n" + + " \"from\":"+FROMANDSIZE_QUERY_FROM+"\n" + + "}"; + private static final String TERMQUERY_KEY = "node-id"; + private static final String TERMQUERY_VALUE = "abc"; + private static final String TERM_QUERY = "{\n" + + " \"query\": {\n" + + " \"term\": {\n" + + " \""+TERMQUERY_KEY+"\": \""+TERMQUERY_VALUE+"\"\n" + + " }\n" + + " }\n" + + "}"; + private static final String SORTING_PROPERTY = "node-id"; + private static final String SORTING_QUERY_ASC = "{\n" + + " \"query\": {\n" + + " \"match_all\": {}\n" + + " },\n" + + " \"sort\": [\n" + + " {\n" + + " \""+SORTING_PROPERTY+"\": {\n" + + " \"order\": \"asc\"\n" + + " }\n" + + " }\n" + + " ]\n" + + "}"; + private static final String SORTING_QUERY_DESC = "{\n" + + " \"query\": {\n" + + " \"match_all\": {}\n" + + " },\n" + + " \"sort\": [\n" + + " {\n" + + " \""+SORTING_PROPERTY+"\": {\n" + + " \"order\": \"desc\"\n" + + " }\n" + + " }\n" + + " ]\n" + + "}"; + + private void testEquals(String message,String json, QueryBuilder query) { + this.testEquals(message, json, query,true); + } + private void testEquals(String message,String json, QueryBuilder query,boolean strict) { + + try { + System.out.println("===test if "+message+"==================="); + System.out.println("orig : "+trim(json)); + System.out.println("totest: "+query.toJSON().trim()); + JSONAssert.assertEquals(json,query.toJSON(),strict); + } catch (JSONException e) { + fail(message); + } + } + + private String trim(String json) { + return json.trim().replaceAll("\n","").replaceAll(" ", ""); + } + + @Test + public void testMatchAll() { + testEquals("match all query is wrong", MATCH_ALL_QUERY, QueryBuilders.matchAllQuery()); + } + @Test + public void testMatch() { + testEquals("match query is wrong", MATCH_QUERY, QueryBuilders.matchQuery(MATCH_QUERY_KEY, MATCH_QUERY_VALUE)); + } + @Test + public void testBool() { + testEquals("bool query is wrong", BOOL_QUERY, + QueryBuilders.boolQuery(). + must(QueryBuilders.matchQuery(MATCH_QUERY_KEY, MATCH_QUERY_VALUE)). + must(QueryBuilders.matchQuery(MATCH_QUERY_KEY2, MATCH_QUERY_VALUE2))); + } + @Test + public void testRange() { + testEquals("range query is wrong", RANGE_QUERY, QueryBuilders.rangeQuery(RANGE_QUERY_KEY).lte(RANGE_QUERY_LTEND)); + + } + @Test + public void testAggregation() { + testEquals("aggregation query is wrong",AGG_QUERY, QueryBuilders.matchAllQuery().aggregations(AGG_FIELD)); + } + @Test + public void testSizeAndFrom() { + testEquals("aggregation query is wrong",FROMANDSIZE_QUERY, QueryBuilders.matchAllQuery().size(FROMANDSIZE_QUERY_SIZE).from(FROMANDSIZE_QUERY_FROM)); + } + @Test + public void testRegex() { + testEquals("range and bool query is wrong1",RANGEBOOL_QUERY,QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("is-required", true)).must(QueryBuilders.regex("node-id", DbFilter.createDatabaseRegex("sim*"))),false); + BoolQueryBuilder q = QueryBuilders.boolQuery().must(QueryBuilders.regex("node-id", DbFilter.createDatabaseRegex("sim*"))); + q.must(QueryBuilders.matchQuery("is-required", true)); + testEquals("range and bool query is wrong2",RANGEBOOL_QUERY,q,false); + } + @Test + public void testTerm() { + testEquals("term query is wrong", TERM_QUERY, QueryBuilders.termQuery(TERMQUERY_KEY, TERMQUERY_VALUE)); + } + @Test + public void testSorting() { + testEquals("sortorder is wrong",SORTING_QUERY_ASC, QueryBuilders.matchAllQuery().sort(SORTING_PROPERTY, SortOrder.ASCENDING)); + testEquals("sortorder is wrong",SORTING_QUERY_DESC, QueryBuilders.matchAllQuery().sort(SORTING_PROPERTY, SortOrder.DESCENDING)); + } +} diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbRequests.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbRequests.java new file mode 100644 index 000000000..36bbebefd --- /dev/null +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbRequests.java @@ -0,0 +1,412 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH 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.onap.ccsdk.features.sdnr.wt.common.test; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.ccsdk.features.sdnr.wt.common.database.HtDatabaseClient; +import org.onap.ccsdk.features.sdnr.wt.common.database.config.HostInfo; +import org.onap.ccsdk.features.sdnr.wt.common.database.queries.QueryBuilders; +import org.onap.ccsdk.features.sdnr.wt.common.database.requests.ClusterHealthRequest; +import org.onap.ccsdk.features.sdnr.wt.common.database.requests.CreateIndexRequest; +import org.onap.ccsdk.features.sdnr.wt.common.database.requests.DeleteByQueryRequest; +import org.onap.ccsdk.features.sdnr.wt.common.database.requests.DeleteIndexRequest; +import org.onap.ccsdk.features.sdnr.wt.common.database.requests.DeleteRequest; +import org.onap.ccsdk.features.sdnr.wt.common.database.requests.GetRequest; +import org.onap.ccsdk.features.sdnr.wt.common.database.requests.IndexRequest; +import org.onap.ccsdk.features.sdnr.wt.common.database.requests.NodeStatsRequest; +import org.onap.ccsdk.features.sdnr.wt.common.database.requests.RefreshIndexRequest; +import org.onap.ccsdk.features.sdnr.wt.common.database.requests.SearchRequest; +import org.onap.ccsdk.features.sdnr.wt.common.database.requests.UpdateByQueryRequest; +import org.onap.ccsdk.features.sdnr.wt.common.database.requests.UpdateRequest; +import org.onap.ccsdk.features.sdnr.wt.common.database.responses.ClusterHealthResponse; +import org.onap.ccsdk.features.sdnr.wt.common.database.responses.CreateIndexResponse; +import org.onap.ccsdk.features.sdnr.wt.common.database.responses.DeleteByQueryResponse; +import org.onap.ccsdk.features.sdnr.wt.common.database.responses.DeleteIndexResponse; +import org.onap.ccsdk.features.sdnr.wt.common.database.responses.DeleteResponse; +import org.onap.ccsdk.features.sdnr.wt.common.database.responses.GetResponse; +import org.onap.ccsdk.features.sdnr.wt.common.database.responses.IndexResponse; +import org.onap.ccsdk.features.sdnr.wt.common.database.responses.NodeStatsResponse; +import org.onap.ccsdk.features.sdnr.wt.common.database.responses.SearchResponse; +import org.onap.ccsdk.features.sdnr.wt.common.database.responses.UpdateByQueryResponse; +import org.onap.ccsdk.features.sdnr.wt.common.database.responses.UpdateResponse; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import java.io.IOException; +import java.util.Arrays; +import java.util.List; + +import org.json.JSONException; +import org.json.JSONObject; + +public class TestDbRequests { + + private static HtDatabaseClient dbClient; + private static HostInfo[] hosts = new HostInfo[] { new HostInfo("localhost", Integer + .valueOf(System.getProperty("databaseport") != null ? System.getProperty("databaseport") : "49200")) }; + + @BeforeClass + public static void init() { + + dbClient = new HtDatabaseClient(hosts); + + } + @AfterClass + public static void deinit() { + if(dbClient!=null) { + dbClient.close(); + } + } + @Test + public void testHealth() { + + ClusterHealthResponse response = null; + ClusterHealthRequest request = new ClusterHealthRequest(); + request.timeout(10); + try { + response = dbClient.health(request); + } catch (UnsupportedOperationException | IOException | JSONException e) { + fail(e.getMessage()); + } + assertNotNull("response is null", response); + assertTrue(response.isStatusMinimal(ClusterHealthResponse.HEALTHSTATUS_YELLOW)); + } + + @Test + public void testCount() { + + } + + @Test + public void testCreateAndDeleteIndex() { + final String IDX = "testcidx1"; + CreateIndexRequest request = new CreateIndexRequest(IDX); + CreateIndexResponse response = null; + try { + response = dbClient.createIndex(request); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response); + + assertTrue("index not existing", dbClient.isExistsIndex(IDX)); + + DeleteIndexRequest request2 = new DeleteIndexRequest(IDX); + + DeleteIndexResponse response2 = null; + try { + response2 = dbClient.deleteIndex(request2); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response2); + assertFalse("index still existing", dbClient.isExistsIndex(IDX)); + this.deleteIndex(IDX); + } + + @Test + public void testInsertAndDelete() { + final String IDX = "test23-knmoinsd"; + final String ID = "abcddd"; + final String JSON = "{\"data\":{\"inner\":\"more\"}}"; + this.insert(IDX, ID, JSON); + // delete data + DeleteRequest request2 = new DeleteRequest(IDX, IDX, ID); + DeleteResponse response2 = null; + try { + response2 = dbClient.delete(request2); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response2); + assertTrue(response2.isDeleted()); + try { + dbClient.refreshIndex(new RefreshIndexRequest(IDX)); + } catch (IOException e) { + fail(e.getMessage()); + } + // verify data deleted + GetRequest request4 = new GetRequest(IDX, IDX, ID); + GetResponse response4 = null; + try { + response4 = dbClient.get(request4); + } catch (IOException e1) { + fail(e1.getMessage()); + } + assertNotNull(response4); + assertFalse("data still existing", response4.isExists()); + this.deleteIndex(IDX); + } + + @Test + public void testInsertAndDeleteByQuery() { + final String IDX = "test34-knmoinsd"; + final String ID = "abcdddseae"; + final String JSON = "{\"data\":{\"inner\":\"more\"}}"; + this.insert(IDX, ID, JSON); + + // delete data + DeleteByQueryRequest request2 = new DeleteByQueryRequest(IDX); + request2.source(QueryBuilders.matchQuery("_id", ID)); + DeleteByQueryResponse response2 = null; + try { + response2 = dbClient.deleteByQuery(request2); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response2); + assertTrue(response2.isResponseSucceeded()); + try { + dbClient.refreshIndex(new RefreshIndexRequest(IDX)); + } catch (IOException e) { + fail(e.getMessage()); + } + // verify data deleted + GetRequest request4 = new GetRequest(IDX, IDX, ID); + GetResponse response4 = null; + try { + response4 = dbClient.get(request4); + } catch (IOException e1) { + fail(e1.getMessage()); + } + assertNotNull(response4); + assertFalse("data still existing", response4.isExists()); + this.deleteIndex(IDX); + } + + private void insert(String IDX, String ID, String JSON) { + + // create data + IndexRequest request = new IndexRequest(IDX, IDX, ID); + request.source(JSON); + IndexResponse response = null; + try { + response = dbClient.index(request); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response); + if (ID != null) { + assertEquals("id not correct", ID, response.getId()); + } else { + ID = response.getId(); + } + // do db refresh + try { + dbClient.refreshIndex(new RefreshIndexRequest(IDX)); + } catch (IOException e) { + fail(e.getMessage()); + } + // verify data exists + GetRequest request3 = new GetRequest(IDX, IDX, ID); + GetResponse response3 = null; + try { + response3 = dbClient.get(request3); + } catch (IOException e1) { + fail(e1.getMessage()); + } + assertNotNull(response3); + JSONAssert.assertEquals("could not verify update", JSON, response3.getSourceAsBytesRef(), true); + } + + @Test + public void testSearch() { + final String IDX = "test44-moinsd"; + final String ID = "abe"; + final String JSON = "{\"data\":{\"inner\":\"more\"}}"; + final String ID2 = "abe2"; + final String JSON2 = "{\"data\":{\"inner\":\"more2\"}}"; + final String ID3 = "abe3"; + final String JSON3 = "{\"data\":{\"inner\":\"more3\"}}"; + this.insert(IDX, ID, JSON); + this.insert(IDX, ID2, JSON2); + this.insert(IDX, ID3, JSON3); + SearchRequest request = new SearchRequest(IDX, IDX); + request.setQuery(QueryBuilders.matchAllQuery()); + SearchResponse response = null; + try { + response = dbClient.search(request); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response); + assertEquals("not all items found", 3, response.getHits().length); + assertEquals("incorrect index",IDX,response.getHits()[0].getIndex()); + assertEquals("incorrect type",IDX,response.getHits()[0].getType()); + this.deleteIndex(IDX); + } + + @Test + public void testUpdate() { + final String IDX = "test4534-moinsd"; + final String ID = "assbe"; + final String JSON = "{\"data\":{\"inner\":\"more\"}}"; + final String JSON2 = "{\"data\":{\"inner\":\"more2\"},\"data2\":\"value2\",\"data3\":true}"; + + this.insert(IDX, ID, JSON); + UpdateRequest request = new UpdateRequest(IDX, IDX, ID); + UpdateResponse response = null; + try { + request.source(new JSONObject(JSON2)); + response = dbClient.update(request); + } catch (JSONException | IOException e) { + fail(e.getMessage()); + } + assertNotNull(response); + assertTrue(response.succeeded()); + // refresh index + try { + dbClient.refreshIndex(new RefreshIndexRequest(IDX)); + } catch (IOException e) { + fail(e.getMessage()); + } + // verify update + GetRequest request3 = new GetRequest(IDX, IDX, ID); + GetResponse response3 = null; + try { + response3 = dbClient.get(request3); + } catch (IOException e1) { + fail(e1.getMessage()); + } + assertNotNull(response3); + JSONAssert.assertEquals("could not verify update", JSON2, response3.getSourceAsBytesRef(), true); + this.deleteIndex(IDX); + } + + @Test + public void testUpdateByQuery() { + final String IDX = "test224534-moinsd"; + final String ID = "asssabe"; + final String JSON = "{\"data\":{\"inner\":\"more\"}}"; + final String JSON2 = "{\"data\":{\"inner\":\"more2\"},\"data2\":\"value2\",\"data3\":true}"; + + this.insert(IDX, ID, JSON); + UpdateByQueryRequest request = new UpdateByQueryRequest(IDX, IDX); + UpdateByQueryResponse response = null; + try { + request.source(ID, new JSONObject(JSON2)); + response = dbClient.update(request); + } catch (JSONException | IOException e) { + fail(e.getMessage()); + } + assertNotNull(response); + assertTrue(response.isUpdated()); + // refresh index + try { + dbClient.refreshIndex(new RefreshIndexRequest(IDX)); + } catch (IOException e) { + fail(e.getMessage()); + } + // verify update + GetRequest request3 = new GetRequest(IDX, IDX, ID); + GetResponse response3 = null; + try { + response3 = dbClient.get(request3); + } catch (IOException e1) { + fail(e1.getMessage()); + } + assertNotNull(response3); + JSONAssert.assertEquals("could not verify update", JSON2, response3.getSourceAsBytesRef(), true); + this.deleteIndex(IDX); + } + + @Test + public void testAggregations() { + final String IDX = "test3227533677-moisnsd"; + final String JSON = "{ \"node-id\":\"sim1\",\"severity\":\"critical\"}"; + final String JSON2 = "{ \"node-id\":\"sim2\",\"severity\":\"critical\"}"; + final String JSON3 = "{ \"node-id\":\"sim3\",\"severity\":\"minor\"}"; + final String JSON4 = "{ \"node-id\":\"sim4\",\"severity\":\"warning\"}"; + final String JSON5 = "{ \"node-id\":\"sim5\",\"severity\":\"major\"}"; + final String MAPPINGS = "{\""+IDX+"\":{\"properties\":{\"node-id\": {\"type\": \"keyword\"},\"severity\": {\"type\": \"keyword\"}}}}"; + //create index with mapping keyword + CreateIndexRequest irequest = new CreateIndexRequest(IDX); + irequest.mappings(new JSONObject(MAPPINGS)); + CreateIndexResponse iresponse = null; + try { + iresponse = dbClient.createIndex(irequest); + } catch (IOException e1) { + fail("unable to create index: "+e1.getMessage()); + } + assertNotNull(iresponse); + assertTrue(iresponse.isAcknowledged()); + // fill index + this.insert(IDX, null, JSON); + this.insert(IDX, null, JSON2); + this.insert(IDX, null, JSON3); + this.insert(IDX, null, JSON4); + this.insert(IDX, null, JSON5); + // refresh index + try { + dbClient.refreshIndex(new RefreshIndexRequest(IDX)); + } catch (IOException e) { + fail(e.getMessage()); + } + + SearchRequest request = new SearchRequest(IDX, IDX); + request.setQuery(QueryBuilders.matchAllQuery().aggregations("severity").size(0)); + SearchResponse response = null; + try { + response = dbClient.search(request); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response); + assertTrue(response.hasAggregations()); + assertEquals("aggregation size not correct", 4, response.getAggregations("severity").size()); + + List<String> items1 = Arrays.asList(response.getAggregations("severity").getKeysAsPagedStringList(2, 0)); + List<String> items2 = Arrays.asList(response.getAggregations("severity").getKeysAsPagedStringList(2, 2)); + assertEquals("pagination does not work", 2,items1.size()); + assertEquals("pagination does not work", 2,items2.size()); + for(String s:items1) { + assertFalse("pagination overlap is not allowed",items2.contains(s)); + } + for(String s:items2) { + assertFalse("pagination overlap is not allowed",items1.contains(s)); + } + + this.deleteIndex(IDX); + } + + @Test + public void testStatistics() { + NodeStatsResponse stats=null; + try { + stats = dbClient.stats(new NodeStatsRequest()); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(stats); + System.out.println(stats.getNodesInfo()); + System.out.println(stats.getNodeStatistics()); + } + private void deleteIndex(String idx) { + try { + dbClient.deleteIndex( new DeleteIndexRequest(idx)); + } catch (IOException e) { + + } + } + +} diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestJsonAssert.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestJsonAssert.java new file mode 100644 index 000000000..e4e8f9477 --- /dev/null +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestJsonAssert.java @@ -0,0 +1,144 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH 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.onap.ccsdk.features.sdnr.wt.common.test; + +import static org.junit.Assert.*; + +import org.json.JSONException; +import org.junit.Test; +import org.onap.ccsdk.features.sdnr.wt.common.test.JSONAssert; + +public class TestJsonAssert { + + @Test + public void testGenericTypes() { + try { + JSONAssert.assertEquals("test boolean","{ \"test\":true}","{ \"test\":true}",true); + } catch (JSONException e) { + fail(e.getMessage()); + } + try { + JSONAssert.assertEquals("test int","{ \"test\":2}","{ \"test\":2}",true); + } catch (JSONException e) { + fail(e.getMessage()); + } + try { + JSONAssert.assertEquals("test string","{ \"test\":\"abc\"}","{ \"test\":\"abc\"}",true); + } catch (JSONException e) { + fail(e.getMessage()); + } + + } + @Test + public void testGenericTypesFails() { + try { + JSONAssert.assertEquals("test boolean","{ \"test\":true}","{ \"test\":false}",true); + fail("test boolean not failed, but has to"); + } catch (JSONException e) { + fail("problem with json"); + }catch(AssertionError e) { + + } + try { + JSONAssert.assertEquals("test int","{ \"test\":2}","{ \"test\":3}",true); + fail("test int not failed, but has to"); + } catch (JSONException e) { + fail("problem with json"); + } catch(AssertionError e) { + + } + try { + JSONAssert.assertEquals("test string","{ \"test\":\"abc\"}","{ \"test\":\"abcd\"}",true); + fail("test string not failed, but has to"); + } catch (JSONException e) { + fail("problem with json"); + }catch(AssertionError e) { + + } + + } + @Test + public void testObject() { + try { + JSONAssert.assertEquals("test object","{ \"test\":{\"more\":{\"x\":1,\"y\":\"2\",\"z\":{}}}}","{ \"test\":{\"more\":{\"x\":1,\"z\":{},\"y\":\"2\"}}}",true); + } catch (JSONException e) { + fail(e.getMessage()); + } + } + @Test + public void testObjectFails() { + try { + JSONAssert.assertEquals("test object","{ \"test\":{\"more\":{\"x\":1,\"y\":\"2\",\"z\":{}}}}","{ \"test\":{\"more\":{\"x\":1,\"z\":{}}}}",true); + fail("test object not failed, but has to"); + } catch (JSONException e) { + fail("problem with json"); + } + catch(AssertionError e) { + + } + } + @Test + public void testArrayStrict() { + try { + JSONAssert.assertEquals("test array strict","{ \"test\":[\"a\",\"b\",\"c\"]}","{ \"test\":[\"a\",\"b\",\"c\"]}",true); + } catch (JSONException e) { + fail(e.getMessage()); + } + } + @Test + public void testArrayStrictFails() { + try { + JSONAssert.assertEquals("test array strict","{ \"test\":[\"a\",\"b\",\"c\"]}","{ \"test\":[\"a\",\"c\",\"b\"]}",true); + fail("test object not failed, but has to"); + } catch (JSONException e) { + fail("problem with json"); + } + catch(AssertionError e) { + + } + } + @Test + public void testArrayNonStrict() { + try { + JSONAssert.assertEquals("test array strict","{ \"test\":[\"a\",\"b\",\"c\"]}","{ \"test\":[\"a\",\"c\",\"b\"]}",false); + } catch (JSONException e) { + fail(e.getMessage()); + } + } + @Test + public void testArrayNonStrictFails() { + try { + JSONAssert.assertEquals("test array strict","{ \"test\":[\"a\",\"b\",\"c\"]}","{ \"test\":[\"a\",\"c\",\"b\",\"d\"]}",false); + fail("test object not failed, but has to"); + } catch (JSONException e) { + fail("problem with json"); + } + catch(AssertionError e) { + + } + try { + JSONAssert.assertEquals("test array strict","{ \"test\":[\"a\",\"b\",\"c\"]}","{ \"test\":[\"a\",\"b\",\"d\"]}",false); + fail("test object not failed, but has to"); + } catch (JSONException e) { + fail("problem with json"); + } + catch(AssertionError e) { + + } + } +} diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestPageHashMap.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestPageHashMap.java new file mode 100644 index 000000000..9c2ade992 --- /dev/null +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestPageHashMap.java @@ -0,0 +1,58 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH 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.onap.ccsdk.features.sdnr.wt.common.test; + +import org.junit.Test; +import org.onap.ccsdk.features.sdnr.wt.common.database.responses.AggregationEntries; + +public class TestPageHashMap { + + @Test + public void testGenericTypes() { + AggregationEntries agg = new AggregationEntries(); + + for (int t=0; t < 100; t++) { + agg.put("Key"+t, Long.valueOf(t)); + } + + int x =0; + for (String k : agg.keySet()) { + if (x++ >= 10) + break; + System.out.println("Keys: "+k); + } + + String[] res; + + res = agg.getKeysAsPagedStringList(5, 10); + System.out.println("Entries: "+res.length); + for (int t=0; t < res.length; t++) { + System.out.println("Entry "+t+": "+res[t]); + } + + res = agg.getKeysAsPagedStringList(5, 10); + System.out.println("Entries: "+res.length); + for (int t=0; t < res.length; t++) { + System.out.println("Entry "+t+": "+res[t]); + } + + + } + + +} diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestPomfile.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestPomfile.java new file mode 100644 index 000000000..49e0445a1 --- /dev/null +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestPomfile.java @@ -0,0 +1,70 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2019 highstreet technologies GmbH 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.onap.ccsdk.features.sdnr.wt.common.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + +import java.io.ByteArrayInputStream; +import java.io.FileInputStream; +import java.io.IOException; +import javax.xml.parsers.ParserConfigurationException; + +import org.junit.Test; +import org.onap.ccsdk.features.sdnr.wt.common.file.PomFile; +import org.onap.ccsdk.features.sdnr.wt.common.file.PomPropertiesFile; +import org.xml.sax.SAXException; + +public class TestPomfile { + + private static final String TESTPROPERTY_KEY="elasticsearch.version"; + private static final String TESTPROPERTY_VALUE = "6.4.3"; + private static final String POMFILENAME = "pom.xml"; + private static final String POM_PROPERTY = "#Generated by org.apache.felix.bundleplugin\n" + + "#Tue Nov 19 11:20:33 CET 2019\n" + + "version=0.7.0-SNAPSHOT\n" + + "groupId=org.onap.ccsdk.features.sdnr.wt\n" + + "artifactId=sdnr-wt-data-provider-provider\n"; + //private static final Date DATE_EXPECTED = new Date(119, 10, 19, 11, 20, 33); + + @Test + public void test() { + PomFile pom=null; + try { + pom = new PomFile(new FileInputStream(POMFILENAME)); + } catch (ParserConfigurationException | SAXException | IOException e) { + fail(e.getMessage()); + } + assertNotNull(pom); + assertEquals(TESTPROPERTY_VALUE, pom.getProperty(TESTPROPERTY_KEY)); + + } + @Test + public void testProp() { + PomPropertiesFile file = null; + try { + file = new PomPropertiesFile(new ByteArrayInputStream(POM_PROPERTY.getBytes())); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertNotNull(file); + assertNotNull(file.getBuildDate()); + } +} diff --git a/sdnr/wt/common/src/test/resources/log4j.properties b/sdnr/wt/common/src/test/resources/log4j.properties new file mode 100644 index 000000000..142663bd2 --- /dev/null +++ b/sdnr/wt/common/src/test/resources/log4j.properties @@ -0,0 +1,12 @@ +log4j.rootLogger=INFO, out + +log4j.logger.org.apache.camel.impl.converter=WARN +log4j.logger.org.apache.camel.management=WARN +log4j.logger.org.apache.camel.impl.DefaultPackageScanClassResolver=WARN +log4j.logger.org.springframework=ERROR + +# CONSOLE appender not used by default +log4j.appender.out=org.apache.log4j.ConsoleAppender +log4j.appender.out.layout=org.apache.log4j.PatternLayout +log4j.appender.out.layout.ConversionPattern=%d [%-15.15t] %-5p %-30.30c{1} - %m%n + diff --git a/sdnr/wt/common/src/test/resources/log4j2.xml b/sdnr/wt/common/src/test/resources/log4j2.xml new file mode 100644 index 000000000..164e93f54 --- /dev/null +++ b/sdnr/wt/common/src/test/resources/log4j2.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<Configuration package="log4j.test" + status="WARN"> + <Appenders> + <Console name="Console" target="SYSTEM_OUT"> + <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/> + </Console> + </Appenders> + <Loggers> + <Logger name="log4j.test.Log4jTest" level="debug"> + <AppenderRef ref="Console"/> + </Logger> + <Root level="trace"> + <AppenderRef ref="Console"/> + </Root> + </Loggers> +</Configuration>
\ No newline at end of file diff --git a/sdnr/wt/common/src/test/resources/simplelogger.properties b/sdnr/wt/common/src/test/resources/simplelogger.properties new file mode 100644 index 000000000..a2f1e7e76 --- /dev/null +++ b/sdnr/wt/common/src/test/resources/simplelogger.properties @@ -0,0 +1,6 @@ +org.slf4j.simpleLogger.defaultLogLevel=debug +org.slf4j.simpleLogger.showDateTime=true +#org.slf4j.simpleLogger.dateTimeFormat=yyyy-MM-dd HH:mm:ss:SSS Z +#org.slf4j.simpleLogger.showThreadName=true +org.slf4j.simpleLogger.showLogName=true +org.slf4j.simpleLogger.showShortLogName=false
\ No newline at end of file |