diff options
author | Michael Dürre <michael.duerre@highstreet-technologies.com> | 2020-02-06 12:57:23 +0100 |
---|---|---|
committer | KAPIL SINGAL <ks220y@att.com> | 2020-02-07 16:41:48 +0000 |
commit | f6f3b57be8e57ffc6790d139b0b7f168b8cc69e6 (patch) | |
tree | d510d50c0f651e5b7f853ec6247f57a1a7f2b432 /sdnr/wt/common/src/test | |
parent | 561aa2a8ef7bd222d274aea065929920aedd0723 (diff) |
improve code coverage
more unit tests for common and data-provider
Issue-ID: SDNC-1063
Signed-off-by: Michael Dürre <michael.duerre@highstreet-technologies.com>
Change-Id: Id99cb3e300b9649b77e0900347fbefae8d55cd87
Signed-off-by: Michael Dürre <michael.duerre@highstreet-technologies.com>
Diffstat (limited to 'sdnr/wt/common/src/test')
6 files changed, 551 insertions, 2 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 index af3979c50..47fe9d4f6 100644 --- 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 @@ -19,6 +19,7 @@ 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.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; @@ -77,6 +78,8 @@ public class TestBaseHttpClient { fail(e.getMessage()); } assertNotNull(response); + assertTrue(response.isSuccess()); + System.out.println(response.toString()); assertEquals(RESPONSE_POST, response.body); try { response= httpClient.sendRequest(TESTURI, HTTPMETHOD_PUT, "{}", headers ); diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestBaseServlet.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestBaseServlet.java new file mode 100644 index 000000000..ee602ce28 --- /dev/null +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestBaseServlet.java @@ -0,0 +1,70 @@ +/******************************************************************************* + * ============LICENSE_START======================================================================== + * ONAP : ccsdk feature sdnr wt + * ================================================================================================= + * Copyright (C) 2020 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 java.io.IOException; + +import javax.servlet.ServletException; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.ccsdk.features.sdnr.wt.common.test.helper.HelpServlet; +import org.onap.ccsdk.features.sdnr.wt.common.test.helper.HelpServletBase; + +/** + * @author Michael Dürre + * + */ +public class TestBaseServlet extends HelpServletBase{ + + private static final int PORT = 40003; + public TestBaseServlet() { + super("/base",PORT); + } + + @Test + public void test() throws ServletException, IOException { + + String query = "{\"query\":{\"match_all\":{}}}"; + HelpServlet servlet = new HelpServlet(PORT); + this.setServlet(servlet); + // test disabled message + String expectedResponse = "offline"; + testrequest(HTTPMETHOD_GET, query, expectedResponse, false); + testrequest(HTTPMETHOD_POST, query, expectedResponse, false); + testrequest(HTTPMETHOD_PUT, query, expectedResponse, false); + testrequest(HTTPMETHOD_DELETE, query, expectedResponse, false); + servlet.setOffline(false); + // initEsTestWebserver(port); + testrequest(HTTPMETHOD_GET, query, HelpServletBase.RESPONSE_GET, true); + testrequest(HTTPMETHOD_POST, query, HelpServletBase.RESPONSE_POST, true); + testrequest(HTTPMETHOD_PUT, query, HelpServletBase.RESPONSE_PUT, true); + testrequest(HTTPMETHOD_DELETE, query, HelpServletBase.RESPONSE_DELETE, true); + testrequest(HTTPMETHOD_OPTIONS, query, "", false); + // stopTestWebserver(); + } + @Before + public void init() throws IOException{ + HelpServletBase.initEsTestWebserver(PORT); + } + @After + public void deinit() { + HelpServletBase.stopTestWebserver(); + } +} 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 index 0d46b4d20..e39998008 100644 --- 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 @@ -22,9 +22,11 @@ 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.IsEsObject; 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.QueryBuilder; import org.onap.ccsdk.features.sdnr.wt.common.database.queries.QueryBuilders; public class TestDbClient { @@ -56,16 +58,99 @@ public class TestDbClient { //Update esId= dbClient.doUpdateOrCreate(IDX, ID, JSON2); assertEquals("update response not successfull",ID,esId); - //Verify + //check that update with null fails + assertNull("update with id null should not be possible",dbClient.doUpdateOrCreate(IDX,null,JSON2)); + //Verify update 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()); + //test second read + String resStr = dbClient.doReadJsonData(IDX, new IsEsObject() { + + @Override + public void setEsId(String id) { + + } + + @Override + public String getEsId() { + return ID; + } + }); + //test all read + result = dbClient.doReadAllJsonData(IDX); + assertNotNull("all read not working",result); + + assertEquals("read works not as expected", JSON2,resStr); //Delete - boolean del=dbClient.doRemove(IDX, ID); + boolean del=dbClient.doRemove(IDX, new IsEsObject() { + + @Override + public void setEsId(String id) { + + } + @Override + public String getEsId() { + return ID; + } + }); assertTrue("item not deleted",del); //Verify result = dbClient.doReadByQueryJsonData(IDX, QueryBuilders.matchQuery("_id", ID)); assertEquals("amount of results is wrong",0,result.getTotal()); + + + + } + @Test + public void testCRUD2() { + 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()); + QueryBuilder matchQuery = QueryBuilders.matchQuery("_id", ID); + //Update + assertTrue("update response not successfull",dbClient.doUpdate(IDX, JSON2,matchQuery )); + //check that update with null fails + assertNull("update with id null should not be possible",dbClient.doUpdateOrCreate(IDX,null,JSON2)); + //Verify update + 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()); + //test second read + String resStr = dbClient.doReadJsonData(IDX, new IsEsObject() { + + @Override + public void setEsId(String id) { + + } + + @Override + public String getEsId() { + return ID; + } + }); + //test all read + result = dbClient.doReadAllJsonData(IDX); + assertNotNull("all read not working",result); + + assertEquals("read works not as expected", JSON2,resStr); + //Delete + int del=dbClient.doRemove(IDX, matchQuery); + assertTrue("item not deleted",del>0); + //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/helper/HelpServlet.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/HelpServlet.java new file mode 100644 index 000000000..2e8cda0ef --- /dev/null +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/HelpServlet.java @@ -0,0 +1,126 @@ +/* + * ============LICENSE_START======================================================= + * ONAP : CCSDK.apps.sdnr.wt.apigateway + * ================================================================================ + * Copyright (C) 2018 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.helper; + +import java.io.IOException; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.onap.ccsdk.features.sdnr.wt.common.http.BaseServlet; + +public class HelpServlet extends BaseServlet implements IPublicServlet{ + + /** + * + */ + private static final long serialVersionUID = 1L; + 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 HOST = "localhost"; + private int port; + private boolean isoff; + + /** + * @param port + */ + public HelpServlet(int port) { + this.port = port; + this.isoff=true; + } + @Override + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + super.doGet(req, resp); + } + @Override + public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + super.doPost(req, resp); + } + @Override + public void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + super.doPut(req, resp); + } + @Override + public void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + resp.setStatus(200); + } + @Override + public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + super.doDelete(req, resp); + } + @Override + protected String getOfflineResponse() { + return "offline"; + } + @Override + protected boolean isOff() { + return this.isoff; + } + @Override + protected boolean doTrustAll() { + // TODO Auto-generated method stub + return false; + } + @Override + protected void trustAll(boolean trust) { + // TODO Auto-generated method stub + + } + @Override + protected String getRemoteUrl(String uri) { + if (uri.startsWith("/")) { + uri = uri.substring(1); + } + if (uri.startsWith("base")) { + uri = uri.substring("base".length()); + } + if (uri.startsWith("/")) { + uri = uri.substring(1); + } + String base = "http://" + HOST + ":" + this.port; + if (!base.endsWith("/")) { + base += "/"; + } + + return base + uri; + } + @Override + protected boolean trustInsecure() { + // TODO Auto-generated method stub + return false; + } + @Override + protected boolean isCorsEnabled() { + // TODO Auto-generated method stub + return false; + } + /** + * @param b + */ + public void setOffline(boolean b) { + this.isoff = b; + + } +} diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/HelpServletBase.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/HelpServletBase.java new file mode 100644 index 000000000..b0db4f0e6 --- /dev/null +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/HelpServletBase.java @@ -0,0 +1,228 @@ +/* + * ============LICENSE_START======================================================= + * ONAP : CCSDK.apps.sdnr.wt.apigateway + * ================================================================================ + * Copyright (C) 2018 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.helper; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.StringWriter; +import java.net.InetSocketAddress; +import java.util.Enumeration; +import java.util.Map; +import java.util.Vector; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import javax.servlet.ServletInputStream; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.After; +import org.junit.Before; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; +import com.sun.net.httpserver.HttpServer; + +public class HelpServletBase { + + 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"; + + 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"; + private IPublicServlet servlet; + private static HttpServer server; + private static ExecutorService httpThreadPool; + + public final String HOST = "localhost"; + protected static int testPort; + private final String baseUri; + protected static final String LR = "\n"; + + public HelpServletBase(String baseuri, int port) { + this.baseUri=baseuri; + testPort = port; + } + + public void setServlet(IPublicServlet s) + { + this.servlet=s; + } + + protected void testrequest(String method, String data, String expectedResponse, boolean exact) { + this.testrequest("/mwtn/test",method, data, expectedResponse, exact, null); + } + protected void testrequest(String uri,String method, String data, String expectedResponse, boolean exact) { + this.testrequest(uri,method, data, expectedResponse, exact, null); + } + + protected void testrequest(String uri,String method, String data, String expectedResponse, boolean exact, + Map<String, String> headersToCheck) { + + HttpServletRequest mockRequest = mock(HttpServletRequest.class); + HttpServletResponse mockResponse = mock(HttpServletResponse.class); + + StringWriter out = new StringWriter(); + ServletOutputStream printOut = new ServletOutputStream() { + + @Override + public void write(int arg0) throws IOException { + out.write(arg0); + } + }; + ByteArrayInputStream bis = new ByteArrayInputStream(data.getBytes()); + ServletInputStream inputStream= new ServletInputStream() { + @Override + public int read() throws IOException { + return bis.read(); + } + }; + Vector<String> headers=new Vector<String>(); + headers.addElement("Accept"); + headers.add("User-Agent"); + Enumeration<String> headerNames = headers.elements(); + try { + when(mockRequest.getRequestURI()).thenReturn(this.baseUri+uri); + when(mockRequest.getHeaderNames()).thenReturn(headerNames); + when(mockRequest.getHeader("Accept")).thenReturn("application/json"); + when(mockRequest.getHeader("User-Agent")).thenReturn("Gecko abc"); + when(mockRequest.getInputStream()).thenReturn(inputStream); + when(mockResponse.getOutputStream()).thenReturn(printOut); + System.out.println("do a " + method + " request"); + if (method == HTTPMETHOD_GET) + this.servlet.doGet(mockRequest, mockResponse); + else if (method == HTTPMETHOD_POST) + this.servlet.doPost(mockRequest, mockResponse); + else if (method == HTTPMETHOD_PUT) + this.servlet.doPut(mockRequest, mockResponse); + else if (method == HTTPMETHOD_DELETE) + this.servlet.doDelete(mockRequest, mockResponse); + else if (method == HTTPMETHOD_OPTIONS) + this.servlet.doOptions(mockRequest, mockResponse); + else + fail("http request method " + method + " test not implemented"); + } catch (Exception e) { + System.err.println(e.getMessage()); + } + + verify(mockResponse).setStatus(200); + if (exact) + assertEquals(expectedResponse, out.toString()); + else + assertTrue("response not for method " + method + "correct", out.toString().contains(expectedResponse)); + // currently unable to check extra headers + if (headersToCheck != null) { + + } + } + @Before + private void init() throws IOException{ + + + initEsTestWebserver(testPort); + } + @After + private void deinit() { + stopTestWebserver(); + } + + public static void initEsTestWebserver(int port) throws IOException { + initEsTestWebserver(port, "/mwtn/test"); + } + public static void initEsTestWebserver(int port,String baseUri) throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", port), 0); + httpThreadPool = Executors.newFixedThreadPool(5); + server.setExecutor(httpThreadPool); + server.createContext(baseUri, new MyHandler()); + //server.createContext("/", new MyRootHandler()); + server.setExecutor(null); // creates a default executor + server.start(); + System.out.println("http server started"); + } + + public static void stopTestWebserver() { + if (server != null) { + server.stop(0); + httpThreadPool.shutdownNow(); + System.out.println("http server stopped" ); + } + } + + + + 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.close(); + } + } + } + } +} diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/IPublicServlet.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/IPublicServlet.java new file mode 100644 index 000000000..9d5ac4fc0 --- /dev/null +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/IPublicServlet.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : CCSDK + * ================================================================================ + * 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.onap.ccsdk.features.sdnr.wt.common.test.helper; + +import java.io.IOException; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +public interface IPublicServlet { + + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException; + public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException; + public void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException; + public void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException ; + public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException ; +} |