From: Tomek Kaminski Date: Thu, 21 Mar 2019 11:34:02 +0000 (+0100) Subject: Fix Resources Jersey tests X-Git-Tag: 1.0.26~29^2 X-Git-Url: https://gerrit.onap.org/r/gitweb?p=dmaap%2Fdbcapi.git;a=commitdiff_plain;h=ed283717c1d63873fd93cb5c5446cf44ca93d018 Fix Resources Jersey tests -fix for tests: DR_SubResourceTest.DelTest DR_SubResourceTest.PutTest MR_ClusterResourceTest.DelTest TopicResourceTest.DelTest -DataBaseClass refactor -Rewriten tests for DR_SubResource Change-Id: I484ad1b18504e0eacc1aae4d8e3b6773e075fa63 Issue-ID: DMAAP-1117 Signed-off-by: Tomek Kaminski --- diff --git a/src/main/java/org/onap/dmaap/dbcapi/database/DatabaseClass.java b/src/main/java/org/onap/dmaap/dbcapi/database/DatabaseClass.java index e2004bd..c853782 100644 --- a/src/main/java/org/onap/dmaap/dbcapi/database/DatabaseClass.java +++ b/src/main/java/org/onap/dmaap/dbcapi/database/DatabaseClass.java @@ -32,201 +32,252 @@ import org.onap.dmaap.dbcapi.util.DmaapConfig; import org.onap.dmaap.dbcapi.util.Singleton; +public class DatabaseClass extends BaseLoggingClass { + private static Singleton dmaap; + private static Map dcaeLocations; + private static Map dr_nodes; + private static Map dr_pubs; + private static Map dr_subs; + private static Map mr_clients; + private static Map mr_clusters; + private static Map feeds; + private static Map topics; + private static Map mirrors; -public class DatabaseClass extends BaseLoggingClass { - - private static Singleton dmaap; - private static Map dcaeLocations; - private static Map dr_nodes; - private static Map dr_pubs; - private static Map dr_subs; - private static Map mr_clients; - private static Map mr_clusters; - private static Map feeds; - private static Map topics; - private static Map mirrors; - - private static long lastTime = 0L; - - - - private static class MirrorTopicsHandler implements DBFieldHandler.SqlOp { - public Object get(ResultSet rs, int index) throws Exception { - String val = rs.getString(index); - if (val == null) { - return(null); - } - List rv = new ArrayList<>(); - for (String s: val.split(",")) { - rv.add(new String(s)); - } - return(rv); - } - public void set(PreparedStatement ps, int index, Object val) throws Exception { - if (val == null) { - ps.setString(index, null); - return; - } - @SuppressWarnings("unchecked") - List xv = (List)val; - StringBuilder sb = new StringBuilder(); - String sep = ""; - for (Object o: xv) { - String rv = (String)o; - sb.append(sep).append(DBFieldHandler.fesc(rv)); - sep = ","; - } - ps.setString(index, sb.toString()); - } - } - private static class TopicReplicationTypeHandler implements DBFieldHandler.SqlOp { - public Object get(ResultSet rs, int index) throws Exception { - int val = rs.getInt(index); - - return (ReplicationType.valueOf(val)); - } - public void set(PreparedStatement ps, int index, Object val) throws Exception { - if (val == null) { - ps.setInt(index, 0); - return; - } - @SuppressWarnings("unchecked") - ReplicationType rep = (ReplicationType) val; - ps.setInt(index, rep.getValue()); - } - } - public static Singleton getDmaap() { - return dmaap; - } - - - - public static Map getDcaeLocations() { - return dcaeLocations; - } - - public static Map getDr_nodes() { - return dr_nodes; - } - - public static Map getDr_subs() { - return dr_subs; - } - public static Map getDr_pubs() { - return dr_pubs; - } - - public static Map getMr_clients() { - return mr_clients; - } - - - public static Map getMr_clusters() { - return mr_clusters; - } - - public static Map getFeeds() { - return feeds; - } - public static Map getTopics() { - return topics; - } - public static Map getMirrorMakers() { - return mirrors; - } - - static { - try { - appLogger.info( "begin static initialization"); - appLogger.info( "initializing dmaap" ); - DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig(); - if ("true".equalsIgnoreCase(p.getProperty("UsePGSQL", "false"))) { - appLogger.info("Data from database"); - try { - LoadSchema.upgrade(); - } catch (Exception e) { - appLogger.warn("Problem updating DB schema", e); - } - try { - dmaap = new DBSingleton<>(Dmaap.class, "dmaap"); - dcaeLocations = new DBMap<>(DcaeLocation.class, "dcae_location", "dcae_location_name"); - dr_nodes = new DBMap<>(DR_Node.class, "dr_node", "fqdn"); - dr_pubs = new DBMap<>(DR_Pub.class, "dr_pub", "pub_id"); - dr_subs = new DBMap<>(DR_Sub.class, "dr_sub", "sub_id"); - mr_clients = new DBMap<>(MR_Client.class, "mr_client", "mr_client_id"); - mr_clusters = new DBMap<>(MR_Cluster.class, "mr_cluster", "dcae_location_name"); - feeds = new DBMap<>(Feed.class, "feed", "feed_id"); - TableHandler.setSpecialCase("topic", "replication_case", new TopicReplicationTypeHandler()); - topics = new DBMap<>(Topic.class, "topic", "fqtn"); - TableHandler.setSpecialCase("mirror_maker", "topics", new MirrorTopicsHandler()); - mirrors = new DBMap<>(MirrorMaker.class, "mirror_maker", "mm_name"); - } catch (Exception e) { - errorLogger.error("Error initializing database access " + e, e); - System.exit(1); - } - } else { - appLogger.info("Data from memory"); - dmaap = new Singleton() { - private Dmaap dmaap; - public void remove() { - dmaap = null; - } - public void init(Dmaap val) { - if (dmaap == null) { - dmaap = val; - } - } - public Dmaap get() { - return(dmaap); - } - public void update(Dmaap nd) { - dmaap.setVersion(nd.getVersion()); - dmaap.setTopicNsRoot(nd.getTopicNsRoot()); - dmaap.setDmaapName(nd.getDmaapName()); - dmaap.setDrProvUrl(nd.getDrProvUrl()); - dmaap.setBridgeAdminTopic(nd.getBridgeAdminTopic()); - dmaap.setLoggingUrl(nd.getLoggingUrl()); - dmaap.setNodeKey(nd.getNodeKey()); - dmaap.setAccessKeyOwner(nd.getAccessKeyOwner()); - } - }; - dcaeLocations = new HashMap<>(); - dr_nodes = new HashMap<>(); - dr_pubs = new HashMap<>(); - dr_subs = new HashMap<>(); - mr_clients = new HashMap<>(); - mr_clusters = new HashMap<>(); - feeds = new HashMap<>(); - topics = new HashMap<>(); - mirrors = new HashMap<>(); - } - dmaap.init(new Dmaap("0", "", "", "", "", "", "", "")); - // force initial read from DB, if it exists - @SuppressWarnings("unused") - Dmaap dmx = dmaap.get(); - - // old code in this spot would read from properties file as part of init. - // but all those properties are now set via /dmaap API - - } catch (Exception e) { - errorLogger.error("Error", e); - errorLogger.error(DmaapbcLogMessageEnum.DB_UPDATE_ERROR, e.getMessage()); - } - - } - - public static synchronized String getNextClientId() { - - long id = System.currentTimeMillis(); - if ( id <= lastTime ) { - id = lastTime + 1; - } - lastTime = id; - return Long.toString(id); - } - - + private static long lastTime = 0L; + private static DBType databaseType; + + private enum DBType { + PGSQL, MEMORY + } + + public static Singleton getDmaap() { + return dmaap; + } + + + public static Map getDcaeLocations() { + return dcaeLocations; + } + + public static Map getDr_nodes() { + return dr_nodes; + } + + public static Map getDr_subs() { + return dr_subs; + } + + public static Map getDr_pubs() { + return dr_pubs; + } + + public static Map getMr_clients() { + return mr_clients; + } + + + public static Map getMr_clusters() { + return mr_clusters; + } + + public static Map getFeeds() { + return feeds; + } + + public static Map getTopics() { + return topics; + } + + public static Map getMirrorMakers() { + return mirrors; + } + + static { + try { + appLogger.info("begin static initialization"); + appLogger.info("initializing dmaap"); + determineDatabaseType(); + + switch (databaseType) { + case PGSQL: + databaseResourceInit(); + break; + case MEMORY: + inMemoryResourceInit(); + break; + } + + dmaap.init(new Dmaap("0", "", "", "", "", "", "", "")); + // force initial read from DB, if it exists + @SuppressWarnings("unused") + Dmaap dmx = dmaap.get(); + + // old code in this spot would read from properties file as part of init. + // but all those properties are now set via /dmaap API + + } catch (Exception e) { + errorLogger.error("Error", e); + errorLogger.error(DmaapbcLogMessageEnum.DB_UPDATE_ERROR, e.getMessage()); + } + + } + + public static synchronized String getNextClientId() { + + long id = System.currentTimeMillis(); + if (id <= lastTime) { + id = lastTime + 1; + } + lastTime = id; + return Long.toString(id); + } + + public static synchronized void clearDatabase() { + switch (databaseType) { + case PGSQL: + try { + initDatabase(); + } catch (Exception e) { + errorLogger.error("Error initializing database access " + e, e); + } + break; + case MEMORY: + initMemoryDatabase(); + break; + } + } + + private static void inMemoryResourceInit() { + appLogger.info("Data from memory"); + dmaap = new Singleton() { + private Dmaap dmaap; + + public void remove() { + dmaap = null; + } + + public void init(Dmaap val) { + if (dmaap == null) { + dmaap = val; + } + } + + public Dmaap get() { + return (dmaap); + } + + public void update(Dmaap nd) { + dmaap.setVersion(nd.getVersion()); + dmaap.setTopicNsRoot(nd.getTopicNsRoot()); + dmaap.setDmaapName(nd.getDmaapName()); + dmaap.setDrProvUrl(nd.getDrProvUrl()); + dmaap.setBridgeAdminTopic(nd.getBridgeAdminTopic()); + dmaap.setLoggingUrl(nd.getLoggingUrl()); + dmaap.setNodeKey(nd.getNodeKey()); + dmaap.setAccessKeyOwner(nd.getAccessKeyOwner()); + } + }; + initMemoryDatabase(); + } + + private static void databaseResourceInit() { + appLogger.info("Data from database"); + try { + LoadSchema.upgrade(); + } catch (Exception e) { + appLogger.warn("Problem updating DB schema", e); + } + try { + dmaap = new DBSingleton<>(Dmaap.class, "dmaap"); + TableHandler.setSpecialCase("topic", "replication_case", new TopicReplicationTypeHandler()); + TableHandler.setSpecialCase("mirror_maker", "topics", new MirrorTopicsHandler()); + initDatabase(); + } catch (Exception e) { + errorLogger.error("Error initializing database access " + e, e); + System.exit(1); + } + } + + private static class MirrorTopicsHandler implements DBFieldHandler.SqlOp { + + public Object get(ResultSet rs, int index) throws Exception { + String val = rs.getString(index); + if (val == null) { + return (null); + } + List rv = new ArrayList<>(); + for (String s : val.split(",")) { + rv.add(new String(s)); + } + return (rv); + } + + public void set(PreparedStatement ps, int index, Object val) throws Exception { + if (val == null) { + ps.setString(index, null); + return; + } + @SuppressWarnings("unchecked") + List xv = (List) val; + StringBuilder sb = new StringBuilder(); + String sep = ""; + for (Object o : xv) { + String rv = (String) o; + sb.append(sep).append(DBFieldHandler.fesc(rv)); + sep = ","; + } + ps.setString(index, sb.toString()); + } + } + + private static class TopicReplicationTypeHandler implements DBFieldHandler.SqlOp { + + public Object get(ResultSet rs, int index) throws Exception { + int val = rs.getInt(index); + + return (ReplicationType.valueOf(val)); + } + + public void set(PreparedStatement ps, int index, Object val) throws Exception { + if (val == null) { + ps.setInt(index, 0); + return; + } + @SuppressWarnings("unchecked") + ReplicationType rep = (ReplicationType) val; + ps.setInt(index, rep.getValue()); + } + } + + private static void initMemoryDatabase() { + dcaeLocations = new HashMap<>(); + dr_nodes = new HashMap<>(); + dr_pubs = new HashMap<>(); + dr_subs = new HashMap<>(); + mr_clients = new HashMap<>(); + mr_clusters = new HashMap<>(); + feeds = new HashMap<>(); + topics = new HashMap<>(); + mirrors = new HashMap<>(); + } + private static void initDatabase() throws Exception { + dcaeLocations = new DBMap<>(DcaeLocation.class, "dcae_location", "dcae_location_name"); + dr_nodes = new DBMap<>(DR_Node.class, "dr_node", "fqdn"); + dr_pubs = new DBMap<>(DR_Pub.class, "dr_pub", "pub_id"); + dr_subs = new DBMap<>(DR_Sub.class, "dr_sub", "sub_id"); + mr_clients = new DBMap<>(MR_Client.class, "mr_client", "mr_client_id"); + mr_clusters = new DBMap<>(MR_Cluster.class, "mr_cluster", "dcae_location_name"); + feeds = new DBMap<>(Feed.class, "feed", "feed_id"); + topics = new DBMap<>(Topic.class, "topic", "fqtn"); + mirrors = new DBMap<>(MirrorMaker.class, "mirror_maker", "mm_name"); + } + private static void determineDatabaseType() { + DmaapConfig dmaapConfig = (DmaapConfig) DmaapConfig.getConfig(); + String isPgSQLset = dmaapConfig.getProperty("UsePGSQL", "false"); + databaseType = isPgSQLset.equalsIgnoreCase("true") ? DBType.PGSQL : DBType.MEMORY; + } } diff --git a/src/main/java/org/onap/dmaap/dbcapi/model/DR_Sub.java b/src/main/java/org/onap/dmaap/dbcapi/model/DR_Sub.java index 9d30021..8ac0880 100644 --- a/src/main/java/org/onap/dmaap/dbcapi/model/DR_Sub.java +++ b/src/main/java/org/onap/dmaap/dbcapi/model/DR_Sub.java @@ -331,7 +331,7 @@ public class DR_Sub extends DmaapObject { @Override public String toString() { - String rc = String.format ( "DR_Sub: {dcaeLocationName=%s username=%s userpwd=%s feedId=%s deliveryURL=%s logURL=%s subid=%s use100=%s suspended=%s owner=%s}", + return String.format ( "DR_Sub: {dcaeLocationName=%s username=%s userpwd=%s feedId=%s deliveryURL=%s logURL=%s subid=%s use100=%s suspended=%s owner=%s}", dcaeLocationName, username, userpwd, @@ -343,6 +343,49 @@ public class DR_Sub extends DmaapObject { suspended, owner ); - return rc; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + DR_Sub drSub = (DR_Sub) o; + + if (use100 != drSub.use100) { + return false; + } + if (suspended != drSub.suspended) { + return false; + } + if (!dcaeLocationName.equals(drSub.dcaeLocationName)) { + return false; + } + if (!username.equals(drSub.username)) { + return false; + } + if (!userpwd.equals(drSub.userpwd)) { + return false; + } + if (!feedId.equals(drSub.feedId)) { + return false; + } + return subId.equals(drSub.subId); + } + + @Override + public int hashCode() { + int result = dcaeLocationName.hashCode(); + result = 31 * result + username.hashCode(); + result = 31 * result + userpwd.hashCode(); + result = 31 * result + feedId.hashCode(); + result = 31 * result + subId.hashCode(); + result = 31 * result + (use100 ? 1 : 0); + result = 31 * result + (suspended ? 1 : 0); + return result; } } diff --git a/src/main/java/org/onap/dmaap/dbcapi/resources/DR_SubResource.java b/src/main/java/org/onap/dmaap/dbcapi/resources/DR_SubResource.java index b74d5a1..d5a96de 100644 --- a/src/main/java/org/onap/dmaap/dbcapi/resources/DR_SubResource.java +++ b/src/main/java/org/onap/dmaap/dbcapi/resources/DR_SubResource.java @@ -22,7 +22,9 @@ package org.onap.dmaap.dbcapi.resources; +import com.google.common.collect.Iterables; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import javax.ws.rs.Consumes; @@ -107,11 +109,17 @@ public class DR_SubResource extends BaseLoggingClass { } // if we found a FeedName instead of a FeedId then try to look it up. List nfeeds = feeds.getAllFeeds( sub.getFeedName(), sub.getFeedVersion(), "equals"); - if ( nfeeds.size() != 1 ) { + if ( nfeeds.isEmpty() ) { + resp.setCode(Status.NOT_FOUND.getStatusCode()); + resp.setFields("feedName"); + return responseBuilder.error(resp.getErr()); + } else if (nfeeds.size() > 1) { logger.debug( "Attempt to match "+ sub.getFeedName() + " ver="+sub.getFeedVersion() + " matched " + nfeeds.size() ); + resp.setCode(Status.CONFLICT.getStatusCode()); + resp.setFields("feedName"); return responseBuilder.error(resp.getErr()); } - fnew = nfeeds.get(0); + fnew = Iterables.getOnlyElement(nfeeds); } try { diff --git a/src/main/java/org/onap/dmaap/dbcapi/service/DR_SubService.java b/src/main/java/org/onap/dmaap/dbcapi/service/DR_SubService.java index 9d233a5..c14b1fd 100644 --- a/src/main/java/org/onap/dmaap/dbcapi/service/DR_SubService.java +++ b/src/main/java/org/onap/dmaap/dbcapi/service/DR_SubService.java @@ -209,8 +209,8 @@ public class DR_SubService extends BaseLoggingClass { server, subid, sub.getUsername(), sub.getUserpwd()); String links = String.format( "\"links\": {\"feed\": \"https://dr-prov/feedlog/%s\", \"self\": \"https://dr-prov/sub/%s\", \"log\": \"https://dr-prov/sublog/%s\" }", sub.getFeedId(), - sub.getSubId(), - sub.getSubId() ); + subid, + subid ); ret += links + "}"; logger.info( "DR_SubService:simulateResp=" + ret); diff --git a/src/test/java/org/onap/dmaap/dbcapi/model/DmaapTest.java b/src/test/java/org/onap/dmaap/dbcapi/model/DmaapTest.java index fb83fe9..c0f3bef 100644 --- a/src/test/java/org/onap/dmaap/dbcapi/model/DmaapTest.java +++ b/src/test/java/org/onap/dmaap/dbcapi/model/DmaapTest.java @@ -19,17 +19,14 @@ */ package org.onap.dmaap.dbcapi.model; -import static org.junit.Assert.*; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; +import static org.junit.Assert.assertTrue; import org.junit.After; import org.junit.Before; import org.junit.Test; + public class DmaapTest { - String ver, tnr, dn, dpu, lu, bat, nk, ako; + private String ver, tnr, dn, dpu, lu, bat, nk, ako; @Before public void setUp() throws Exception { diff --git a/src/test/java/org/onap/dmaap/dbcapi/resources/DR_SubResourceTest.java b/src/test/java/org/onap/dmaap/dbcapi/resources/DR_SubResourceTest.java index 9ba5776..f9513a6 100644 --- a/src/test/java/org/onap/dmaap/dbcapi/resources/DR_SubResourceTest.java +++ b/src/test/java/org/onap/dmaap/dbcapi/resources/DR_SubResourceTest.java @@ -1,9 +1,8 @@ - /*- * ============LICENSE_START======================================================= * org.onap.dmaap * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019 Nokia 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. @@ -19,211 +18,446 @@ * ============LICENSE_END========================================================= */ package org.onap.dmaap.dbcapi.resources; -import org.onap.dmaap.dbcapi.model.*; -import org.onap.dmaap.dbcapi.service.*; -import org.onap.dmaap.dbcapi.testframework.DmaapObjectFactory; -import static org.junit.Assert.*; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import java.util.*; -import java.sql.*; +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 org.glassfish.jersey.test.JerseyTest; -import org.glassfish.jersey.server.ResourceConfig; import javax.ws.rs.client.Entity; import javax.ws.rs.core.Application; -import javax.ws.rs.core.Response; import javax.ws.rs.core.MediaType; -import javax.ws.rs.Path; -import javax.ws.rs.GET; - -public class DR_SubResourceTest extends JerseyTest{ - - static DmaapObjectFactory factory = new DmaapObjectFactory(); - - @Override - protected Application configure() { - return new ResourceConfig() - .register( DR_SubResource.class ) - .register( FeedResource.class ) - .register( DcaeLocationResource.class ) - .register( DmaapResource.class ); - } - - String d, un, up, f, p; - - @Before - public void preTest() throws Exception { - try { - - Dmaap dmaap = factory.genDmaap(); - Entity reqEntity = Entity.entity( dmaap, MediaType.APPLICATION_JSON ); - Response resp = target( "dmaap").request().post( reqEntity, Response.class ); - System.out.println( resp.getStatus() ); - assertTrue( resp.getStatus() == 200 ); - }catch (Exception e ) { - } - try { - DcaeLocation loc = factory.genDcaeLocation( "central" ); - Entity reqEntity = Entity.entity( loc, MediaType.APPLICATION_JSON ); - Response resp = target( "dcaeLocations").request().post( reqEntity, Response.class ); - System.out.println( "POST dcaeLocation resp=" + resp.getStatus() + " " + resp.readEntity( String.class )); - if ( resp.getStatus() != 409 ) { - assertTrue( resp.getStatus() == 201 ); - } - } catch (Exception e ) { - } - - - } -/* - @Before - public void setUp() throws Exception { - d = "central-onap"; - un = "user1"; - up = "secretW0rd"; - f = "234"; - p = "678"; - } - - @After - public void tearDown() throws Exception { - } -*/ - - - -/* may conflict with test framework! - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } -*/ - - private Feed addFeed( String name, String desc ) { - Feed feed = new Feed( name, "1.0", desc, "dgl", "unrestricted" ); - Entity reqEntity = Entity.entity( feed, MediaType.APPLICATION_JSON ); - Response resp = target( "feeds").request().post( reqEntity, Response.class ); - int rc = resp.getStatus(); - System.out.println( "POST feed resp=" + rc ); - assertTrue( rc == 200 || rc == 409 ); - feed = resp.readEntity( Feed.class ); - return feed; - } - - private DR_Sub addSub( String d, String un, String up, String feedId ) { - DR_Sub dr_sub = new DR_Sub( d, un, up, feedId, - "https://subscriber.onap.org/foo", "https://dr-prov/sublog", true ); - - Entity reqEntity2 = Entity.entity( dr_sub, MediaType.APPLICATION_JSON); - Response resp = target( "dr_subs").request().post( reqEntity2, Response.class); - System.out.println( "POST dr_subs resp=" + resp.getStatus() ); - assertTrue( resp.getStatus() == 201 ); - dr_sub = resp.readEntity( DR_Sub.class ); - - return dr_sub; - } - private DR_Sub addSubByName( String d, String un, String up, String feedName ) { - DR_Sub dr_sub = new DR_Sub( d, un, up, null, - "https://subscriber.onap.org/foo", "https://dr-prov/sublog", true ); - - dr_sub.setFeedName(feedName); - - Entity reqEntity2 = Entity.entity( dr_sub, MediaType.APPLICATION_JSON); - Response resp = target( "dr_subs").request().post( reqEntity2, Response.class); - System.out.println( "POST dr_subs resp=" + resp.getStatus() ); - assertTrue( resp.getStatus() == 201 ); - dr_sub = resp.readEntity( DR_Sub.class ); - - return dr_sub; - } - - @Test - public void GetTest() { - Response resp = target( "dr_subs").request().get( Response.class ); - System.out.println( "GET dr_subs resp=" + resp.getStatus() ); - - assertTrue( resp.getStatus() == 200 ); - } - - @Test - public void PostTest() { - - Feed feed = addFeed( "subPostTest", "post unit test" ); - System.out.println( "subPostTest: feedId=" + feed.getFeedId()); - - String d, un, up; - d = "central-onap"; - un = "user1"; - up = "secretW0rd"; - - DR_Sub dr_pub = addSub( d, un, up, feed.getFeedId() ); - } - - @Test - public void PostTestByName() { - - Feed feed = addFeed( "subPostTest2", "post unit test" ); - System.out.println( "subPostTest2: feedId=" + feed.getFeedId()); - - String d, un, up; - d = "central-onap"; - un = "user1"; - up = "secretW0rd"; - - DR_Sub dr_pub = addSubByName( d, un, up, feed.getFeedName() ); - } - - @Test - public void PutTest() { - - Feed feed = addFeed( "subPutTest", "put unit test"); - String d, un, up; - d = "central-onap"; - un = "user1"; - up = "secretW0rd"; - - DR_Sub dr_sub = addSub( d, un, up, feed.getFeedId() ); - - dr_sub.setUserpwd("newSecret"); - Entity reqEntity2 = Entity.entity( dr_sub, MediaType.APPLICATION_JSON); - Response resp = target( "dr_subs") - .path( dr_sub.getSubId() ) - .request() - .put( reqEntity2, Response.class); - System.out.println( "PUT dr_subs resp=" + resp.getStatus() ); - assertTrue( resp.getStatus() == 200 ); - } - - -// TODO: figure out how to check delete() response - @Test - public void DelTest() { - - Feed feed = addFeed( "subDelTest", "del unit test"); - String d, un, up; - d = "central-onap"; - un = "user1"; - up = "secretW0rd"; - - DR_Sub dr_sub = addSub( d, un, up, feed.getFeedId() ); - - Entity reqEntity2 = Entity.entity( dr_sub, MediaType.APPLICATION_JSON); - Response resp = target( "dr_subs") - .path( dr_sub.getSubId() ) - .request() - .delete(); - System.out.println( "DEL dr_subs resp=" + resp.getStatus() ); - assertTrue( resp.getStatus() == 204 ); - } - +import javax.ws.rs.core.Response; +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.test.JerseyTest; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.dmaap.dbcapi.database.DatabaseClass; +import org.onap.dmaap.dbcapi.model.ApiError; +import org.onap.dmaap.dbcapi.model.DR_Sub; +import org.onap.dmaap.dbcapi.model.Feed; +import org.onap.dmaap.dbcapi.testframework.DmaapObjectFactory; +public class DR_SubResourceTest { + + private static final DmaapObjectFactory DMAAP_OBJECT_FACTORY = new DmaapObjectFactory(); + + private static final String DCAE_LOCATION_NAME = "central-onap"; + private static final String USERNAME = "user1"; + private static final String USRPWD = "secretW0rd"; + private static final String DELIVERY_URL = "https://subscriber.onap.org/delivery/id"; + private static final String LOG_URL = "https://dr-prov/sublog/id"; + private static final String DELIVERY_URL_TEMPLATE = "https://subscriber.onap.org/delivery/"; + private static final String LOG_URL_TEMPLATE = "https://dr-prov/sublog/"; + private static FastJerseyTest testContainer; + + @BeforeClass + public static void setUpClass() throws Exception { + //TODO: init is still needed here to assure that dmaap is not null + DatabaseClass.getDmaap().init(DMAAP_OBJECT_FACTORY.genDmaap()); + DatabaseClass.getDmaap().update(DMAAP_OBJECT_FACTORY.genDmaap()); + + testContainer = new FastJerseyTest(new ResourceConfig() + .register(DR_SubResource.class) + .register(FeedResource.class) + .register(DmaapResource.class)); + testContainer.init(); + } + + @AfterClass + public static void tearDownClass() throws Exception { + testContainer.destroy(); + /*TODO: Cannot cleanup yet until still other Resources tests depends on the static DB content + + DatabaseClass.clearDatabase(); + DatabaseClass.getDmaap().remove();*/ + } + + @Before + public void cleanupDatabase() throws Exception { + DatabaseClass.clearDatabase(); + } + + //TODO: figure out generic entity list unmarshall to check the entity list + @Test + public void getDr_Subs_test() { + Response resp = testContainer.target("dr_subs").request().get(Response.class); + System.out.println("GET dr_subs resp=" + resp.getStatus()); + + assertTrue(resp.getStatus() == 200); + assertTrue(resp.hasEntity()); + } + + @Test + public void addDr_Sub_shallReturnError_whenNoFeedIdAndFeedNameInSubProvided() { + //given + DR_Sub drSub = new DR_Sub(DCAE_LOCATION_NAME, USERNAME, USRPWD, null, DELIVERY_URL, LOG_URL, true); + Entity requestedEntity = Entity.entity(drSub, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target("dr_subs") + .request() + .post(requestedEntity, Response.class); + + //then + assertEquals(400, resp.getStatus()); + ApiError responseError = resp.readEntity(ApiError.class); + assertNotNull(responseError); + assertEquals("feedName", responseError.getFields()); + } + + @Test + public void addDr_Sub_shallReturnError_whenFeedNameProvided_butFeedNotExist() { + //given + String notExistingFeedName = "notRealFead"; + DR_Sub drSub = new DR_Sub(DCAE_LOCATION_NAME, USERNAME, USRPWD, null, DELIVERY_URL, LOG_URL, true); + drSub.setFeedName(notExistingFeedName); + Entity requestedEntity = Entity.entity(drSub, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target("dr_subs") + .request() + .post(requestedEntity, Response.class); + + //then + assertEquals(404, resp.getStatus()); + ApiError responseError = resp.readEntity(ApiError.class); + assertNotNull(responseError); + assertEquals("feedName", responseError.getFields()); + } + + @Test + public void addDr_Sub_shallReturnError_whenFeedNameProvided_andManyFeedsWithTheSameNameInDB() { + //given + String notDistinctFeedName = "notDistinctFeedName"; + Feed feed1 = new Feed(notDistinctFeedName, "1.0", "description", "dgl", "unrestricted"); + Feed feed2 = new Feed(notDistinctFeedName, "2.0", "description", "dgl", "unrestricted"); + DatabaseClass.getFeeds().put("1", feed1); + DatabaseClass.getFeeds().put("2", feed2); + DR_Sub drSub = new DR_Sub(DCAE_LOCATION_NAME, USERNAME, USRPWD, null, DELIVERY_URL, LOG_URL, true); + drSub.setFeedName(notDistinctFeedName); + Entity requestedEntity = Entity.entity(drSub, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target("dr_subs") + .request() + .post(requestedEntity, Response.class); + + //then + assertEquals(409, resp.getStatus()); + ApiError responseError = resp.readEntity(ApiError.class); + assertNotNull(responseError); + assertEquals("feedName", responseError.getFields()); + } + + @Test + public void addDr_Sub_shallReturnError_whenFeedIdProvided_butFeedNotExist() { + //given + DR_Sub drSub = new DR_Sub(DCAE_LOCATION_NAME, USERNAME, USRPWD, "someFakeFeedId", DELIVERY_URL, LOG_URL, true); + Entity requestedEntity = Entity.entity(drSub, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target("dr_subs") + .request() + .post(requestedEntity, Response.class); + + //then + assertEquals(404, resp.getStatus()); + ApiError responseError = resp.readEntity(ApiError.class); + assertNotNull(responseError); + assertTrue(responseError.getFields().contains("feedId")); + } + + @Test + public void addDr_Sub_shallExecuteSuccessfully_whenValidFeedIdProvided() { + //given + String feedId = assureFeedIsInDB(); + DR_Sub drSub = new DR_Sub(DCAE_LOCATION_NAME, USERNAME, USRPWD, feedId, DELIVERY_URL, LOG_URL, true); + Entity requestedEntity = Entity.entity(drSub, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target("dr_subs") + .request() + .post(requestedEntity, Response.class); + + //then + assertEquals(201, resp.getStatus()); + assertTrue(resp.hasEntity()); + DR_Sub created = resp.readEntity(DR_Sub.class); + assertSubscriptionExistInDB(created); + } + + @Test + public void addDr_Sub_shallExecuteSuccessfully_whenValidFeedNameProvided() { + //given + String feedName = "testFeed"; + addFeed(feedName, "test feed"); + DR_Sub drSub = new DR_Sub(DCAE_LOCATION_NAME, USERNAME, USRPWD, null, DELIVERY_URL, LOG_URL, true); + drSub.setFeedName(feedName); + Entity requestedEntity = Entity.entity(drSub, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target("dr_subs") + .request() + .post(requestedEntity, Response.class); + + //then + assertEquals(201, resp.getStatus()); + assertTrue(resp.hasEntity()); + DR_Sub created = resp.readEntity(DR_Sub.class); + assertSubscriptionExistInDB(created); + } + + + @Test + public void updateDr_Sub_shallReturnError_whenNoFeedIdInSubProvided() { + //given + String subId = "1234"; + DR_Sub drSub = new DR_Sub(DCAE_LOCATION_NAME, USERNAME, USRPWD, null, DELIVERY_URL, LOG_URL, true); + Entity requestedEntity = Entity.entity(drSub, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target("dr_subs") + .path(subId) + .request() + .put(requestedEntity, Response.class); + + //then + assertEquals(400, resp.getStatus()); + ApiError responseError = resp.readEntity(ApiError.class); + assertNotNull(responseError); + assertEquals("feedId", responseError.getFields()); + } + + @Test + public void updateDr_Sub_shallReturnError_whenNoDCAELocationInSubProvided() { + //given + String subId = "1234"; + DR_Sub drSub = new DR_Sub(null, USERNAME, USRPWD, "someFeedId", DELIVERY_URL, LOG_URL, true); + Entity requestedEntity = Entity.entity(drSub, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target("dr_subs") + .path(subId) + .request() + .put(requestedEntity, Response.class); + + //then + assertEquals(400, resp.getStatus()); + ApiError responseError = resp.readEntity(ApiError.class); + assertNotNull(responseError); + assertEquals("dcaeLocationName", responseError.getFields()); + } + + @Test + public void updateDr_Sub_shallReturnError_whenFeedWithGivenIdInSubNotExists() { + //given + String subId = "1234"; + DR_Sub drSub = new DR_Sub(DCAE_LOCATION_NAME, USERNAME, USRPWD, "someFeedId", DELIVERY_URL, LOG_URL, true); + Entity requestedEntity = Entity.entity(drSub, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target("dr_subs") + .path(subId) + .request() + .put(requestedEntity, Response.class); + + //then + assertEquals(404, resp.getStatus()); + assertNotNull(resp.readEntity(ApiError.class)); + } + + @Test + public void updateDr_Sub_shallReturnSuccess_whenAddingNewSubscription() { + //given + String subId = "31"; + String feedId = assureFeedIsInDB(); + DR_Sub drSub = new DR_Sub(DCAE_LOCATION_NAME, USERNAME, USRPWD, feedId, null, null, true); + Entity requestedEntity = Entity.entity(drSub, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target("dr_subs") + .path(subId) + .request() + .put(requestedEntity, Response.class); + + //then + assertEquals(200, resp.getStatus()); + + DR_Sub createdDrSub = resp.readEntity(DR_Sub.class); + assertNotNull(createdDrSub.getLastMod()); + assertEquals(subId, createdDrSub.getSubId()); + assertEquals(DCAE_LOCATION_NAME, createdDrSub.getDcaeLocationName()); + assertEquals(USERNAME, createdDrSub.getUsername()); + assertEquals(USRPWD, createdDrSub.getUserpwd()); + assertEquals(DELIVERY_URL_TEMPLATE + subId, createdDrSub.getDeliveryURL()); + assertEquals(LOG_URL_TEMPLATE + subId, createdDrSub.getLogURL()); + + assertSubscriptionExistInDB(createdDrSub); + } + + @Test + public void updateDr_Sub_shallReturnSuccess_whenUpdatingExistingSubscription() { + //given + String feedId = assureFeedIsInDB(); + DR_Sub existingDrSub = addSub(DCAE_LOCATION_NAME, USERNAME, USRPWD, feedId); + DR_Sub drSubUpdate = new DR_Sub("newDcaeLocationName", "newUserName", "newUserPwd", feedId, null, null, false); + Entity requestedEntity = Entity.entity(drSubUpdate, MediaType.APPLICATION_JSON); + + //when + Response resp = testContainer.target("dr_subs") + .path(existingDrSub.getSubId()) + .request() + .put(requestedEntity, Response.class); + + //then + assertEquals(200, resp.getStatus()); + + DR_Sub updatedDrSub = resp.readEntity(DR_Sub.class); + assertNotNull(updatedDrSub.getLastMod()); + assertEquals(existingDrSub.getSubId(), updatedDrSub.getSubId()); + assertEquals(drSubUpdate.getDcaeLocationName(), updatedDrSub.getDcaeLocationName()); + assertEquals(drSubUpdate.getUsername(), updatedDrSub.getUsername()); + assertEquals(drSubUpdate.getUserpwd(), updatedDrSub.getUserpwd()); + assertEquals(DELIVERY_URL_TEMPLATE + existingDrSub.getSubId(), updatedDrSub.getDeliveryURL()); + assertEquals(LOG_URL_TEMPLATE + existingDrSub.getSubId(), updatedDrSub.getLogURL()); + + assertSubscriptionExistInDB(updatedDrSub); + } + + @Test + public void deleteDr_Sub_shouldDeleteSubscriptionWithSuccess() { + //given + String feedId = assureFeedIsInDB(); + DR_Sub dr_sub = addSub(DCAE_LOCATION_NAME, USERNAME, USRPWD, feedId); + + //when + Response resp = testContainer.target("dr_subs") + .path(dr_sub.getSubId()) + .request() + .delete(); + + //then + assertEquals("Shall delete subscription with success", 204, resp.getStatus()); + assertFalse("No entity object shall be returned",resp.hasEntity()); + assertSubscriptionNotExistInDB(dr_sub.getSubId()); + } + + @Test + public void deleteDr_Sub_shouldReturnErrorResponse_whenGivenSubIdNotFound() { + //given + String notExistingSubId = "6789"; + + //when + Response resp = testContainer.target("dr_subs") + .path(notExistingSubId) + .request() + .delete(); + + //then + assertEquals("Shall return error, when trying to delete not existing subscription", 404, resp.getStatus()); + assertNotNull(resp.readEntity(ApiError.class)); + } + + @Test + public void get_shallReturnExistingObject() { + //given + String feedId = assureFeedIsInDB(); + DR_Sub dr_sub = addSub(DCAE_LOCATION_NAME, USERNAME, USRPWD, feedId); + + //when + Response resp = testContainer.target("dr_subs") + .path(dr_sub.getSubId()) + .request() + .get(); + + //ten + assertEquals("Subscription shall be found",200, resp.getStatus()); + assertEquals("Retrieved object shall be equal to eh one put into DB", dr_sub, resp.readEntity(DR_Sub.class)); + } + + @Test + public void get_shouldReturnError_whenSubWithIdNotFound() { + //given + String notExistingSubId = "1234"; + + //when + Response resp = testContainer.target("dr_subs") + .path(notExistingSubId) + .request() + .get(); + + //then + assertEquals("Subscription shall not be found", 404, resp.getStatus()); + assertNotNull(resp.readEntity(ApiError.class)); + } + + private Feed addFeed(String name, String desc) { + Feed feed = new Feed(name, "1.0", desc, "dgl", "unrestricted"); + Entity reqEntity = Entity.entity(feed, MediaType.APPLICATION_JSON); + Response resp = testContainer.target("feeds").request().post(reqEntity, Response.class); + int rc = resp.getStatus(); + System.out.println("POST feed resp=" + rc); + assertTrue(rc == 200 || rc == 409); + feed = resp.readEntity(Feed.class); + return feed; + } + + private DR_Sub addSub(String d, String un, String up, String feedId) { + DR_Sub dr_sub = new DR_Sub(d, un, up, feedId, + "https://subscriber.onap.org/foo", "https://dr-prov/sublog", true); + + Entity reqEntity2 = Entity.entity(dr_sub, MediaType.APPLICATION_JSON); + Response resp = testContainer.target("dr_subs").request().post(reqEntity2, Response.class); + System.out.println("POST dr_subs resp=" + resp.getStatus()); + assertTrue(resp.getStatus() == 201); + dr_sub = resp.readEntity(DR_Sub.class); + + return dr_sub; + } + + private String assureFeedIsInDB() { + Feed feed = addFeed("SubscriberTestFeed", "feed for DR_Sub testing"); + assertNotNull("Feed shall be added into DB properly", feed); + return feed.getFeedId(); + } + + + private void assertSubscriptionNotExistInDB(String subId) { + assertEquals(404, testContainer.target("dr_subs") + .path(subId) + .request() + .get() + .getStatus()); + } + + private void assertSubscriptionExistInDB(DR_Sub sub) { + Response response = testContainer.target("dr_subs") + .path(sub.getSubId()) + .request() + .get(); + assertEquals(200, response.getStatus()); + assertTrue(response.hasEntity()); + assertEquals(sub, response.readEntity(DR_Sub.class)); + } + + //TODO: move it outside class and use in other Resource integration tests + private static class FastJerseyTest extends JerseyTest { + + FastJerseyTest(Application jaxrsApplication) { + super(jaxrsApplication); + } + + void init() throws Exception { + this.setUp(); + } + + void destroy() throws Exception { + this.tearDown(); + } + } } diff --git a/src/test/java/org/onap/dmaap/dbcapi/resources/MR_ClusterResourceTest.java b/src/test/java/org/onap/dmaap/dbcapi/resources/MR_ClusterResourceTest.java index 05bdeea..7367471 100644 --- a/src/test/java/org/onap/dmaap/dbcapi/resources/MR_ClusterResourceTest.java +++ b/src/test/java/org/onap/dmaap/dbcapi/resources/MR_ClusterResourceTest.java @@ -28,7 +28,9 @@ import javax.ws.rs.core.Response; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; +import org.junit.Before; import org.junit.Test; +import org.onap.dmaap.dbcapi.database.DatabaseClass; import org.onap.dmaap.dbcapi.model.DcaeLocation; import org.onap.dmaap.dbcapi.model.MR_Cluster; import org.onap.dmaap.dbcapi.testframework.DmaapObjectFactory; @@ -50,11 +52,12 @@ public class MR_ClusterResourceTest extends JerseyTest { -/* may conflict with test framework! + @Before - public void preTest() throws Exception { + public void init() throws Exception { + DatabaseClass.clearDatabase(); } - +/* @After public void tearDown() throws Exception { } diff --git a/src/test/java/org/onap/dmaap/dbcapi/resources/TopicResourceTest.java b/src/test/java/org/onap/dmaap/dbcapi/resources/TopicResourceTest.java index ac22e17..88840fe 100644 --- a/src/test/java/org/onap/dmaap/dbcapi/resources/TopicResourceTest.java +++ b/src/test/java/org/onap/dmaap/dbcapi/resources/TopicResourceTest.java @@ -30,6 +30,7 @@ import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.Before; import org.junit.Test; +import org.onap.dmaap.dbcapi.database.DatabaseClass; import org.onap.dmaap.dbcapi.model.DcaeLocation; import org.onap.dmaap.dbcapi.model.Dmaap; import org.onap.dmaap.dbcapi.model.MR_Cluster; @@ -54,15 +55,14 @@ public class TopicResourceTest extends JerseyTest { private static final String fmt = "%24s: %s%n"; - - @Before public void preTest() throws Exception { + DatabaseClass.clearDatabase(); try { Dmaap dmaap = factory.genDmaap(); Entity reqEntity = Entity.entity( dmaap, MediaType.APPLICATION_JSON ); - Response resp = target( "dmaap").request().post( reqEntity, Response.class ); + Response resp = target( "dmaap").request().put( reqEntity, Response.class ); System.out.println( resp.getStatus() ); assertTrue( resp.getStatus() == 200 ); }catch (Exception e ) { diff --git a/src/test/java/org/onap/dmaap/dbcapi/service/DmaapServiceTest.java b/src/test/java/org/onap/dmaap/dbcapi/service/DmaapServiceTest.java index 7029bd2..c1fa0fd 100644 --- a/src/test/java/org/onap/dmaap/dbcapi/service/DmaapServiceTest.java +++ b/src/test/java/org/onap/dmaap/dbcapi/service/DmaapServiceTest.java @@ -19,16 +19,11 @@ */ package org.onap.dmaap.dbcapi.service; -import org.onap.dmaap.dbcapi.model.*; -import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; -import org.onap.dmaap.dbcapi.aaf.*; - -import static org.junit.Assert.*; - import org.junit.After; import org.junit.Before; import org.junit.Test; -import java.util.List; +import org.onap.dmaap.dbcapi.model.Dmaap; +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; public class DmaapServiceTest {