From b632bb134cf056640e7d5b3647875c41bfdc58da Mon Sep 17 00:00:00 2001 From: mmis Date: Tue, 20 Mar 2018 11:46:13 +0000 Subject: Removed checkstyle warnings Removed checkstyle warnings in policy/common/ia Issue-ID: POLICY-695 Change-Id: I25f589dff5ce1dba0681ba549a53087426593d71 Signed-off-by: mmis --- .../org/onap/policy/common/ia/AuditPeriodTest.java | 397 +++---- .../common/ia/DbAuditCompareEntriesTest.java | 1004 ++++++++--------- .../org/onap/policy/common/ia/DbAuditTest.java | 436 ++++---- .../java/org/onap/policy/common/ia/DbDAOTest.java | 785 ++++++------- .../org/onap/policy/common/ia/ExceptionsTest.java | 42 +- .../common/ia/IntegrityAuditDesignationTest.java | 1149 ++++++++++---------- .../onap/policy/common/ia/IntegrityAuditTest.java | 79 +- .../policy/common/ia/IntegrityAuditTestBase.java | 1134 ++++++++++--------- .../onap/policy/common/ia/jpa/IaTestEntity.java | 246 +++-- .../onap/policy/common/ia/jpa/PersonSample.java | 81 +- 10 files changed, 2676 insertions(+), 2677 deletions(-) (limited to 'integrity-audit/src/test/java/org/onap') diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/AuditPeriodTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/AuditPeriodTest.java index b627977b..232468d6 100644 --- a/integrity-audit/src/test/java/org/onap/policy/common/ia/AuditPeriodTest.java +++ b/integrity-audit/src/test/java/org/onap/policy/common/ia/AuditPeriodTest.java @@ -44,217 +44,222 @@ import org.onap.policy.common.utils.test.log.logback.ExtractAppender; */ public class AuditPeriodTest extends IntegrityAuditTestBase { - private static Logger logger = FlexLogger.getLogger(AuditPeriodTest.class); + private static Logger logger = FlexLogger.getLogger(AuditPeriodTest.class); - @BeforeClass - public static void setUpBeforeClass() throws Exception { - IntegrityAuditTestBase.setUpBeforeClass(DEFAULT_DB_URL_PREFIX + AuditPeriodTest.class.getSimpleName()); - } + @BeforeClass + public static void setUpBeforeClass() throws Exception { + IntegrityAuditTestBase.setUpBeforeClass(DEFAULT_DB_URL_PREFIX + AuditPeriodTest.class.getSimpleName()); + } - @AfterClass - public static void tearDownAfterClass() { - IntegrityAuditTestBase.tearDownAfterClass(); - } + @AfterClass + public static void tearDownAfterClass() { + IntegrityAuditTestBase.tearDownAfterClass(); + } - @Before - public void setUp() { - logger.info("setUp: Entering"); + /** + * Set up for test case. + */ + @Override + @Before + public void setUp() { + logger.info("setUp: Entering"); - super.setUp(); + super.setUp(); - logger.info("setUp: Exiting"); + logger.info("setUp: Exiting"); - } + } - @After - public void tearDown() { - logger.info("tearDown: Entering"); + /** + * Tear down after test cases. + */ + @Override + @After + public void tearDown() { + logger.info("tearDown: Entering"); - super.tearDown(); + super.tearDown(); - logger.info("tearDown: Exiting"); - } + logger.info("tearDown: Exiting"); + } - /* - * Verifies (via log parsing) that when a negative audit period is - * specified, the audit is suppressed. - */ - @Test - public void testNegativeAuditPeriod() throws Exception { + /* + * Verifies (via log parsing) that when a negative audit period is specified, the audit is + * suppressed. + */ + @Test + public void testNegativeAuditPeriod() throws Exception { - logger.info("testNegativeAuditPeriod: Entering"); + logger.info("testNegativeAuditPeriod: Entering"); - properties.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "-1"); + properties.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "-1"); - ExtractAppender logA = watch(debugLogger, "Suppressing integrity audit, integrityAuditPeriodSeconds=([^,]*)"); + ExtractAppender logA = watch(debugLogger, "Suppressing integrity audit, integrityAuditPeriodSeconds=([^,]*)"); - MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU); + MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU); - /* - * Sleep long enough to allow - * - * 1) audit to immediately terminate. - */ - waitThread(integrityAudit); + /* + * Sleep long enough to allow + * + * 1) audit to immediately terminate. + */ + waitThread(integrityAudit); - verifyItemsInLog(logA, "-1"); + verifyItemsInLog(logA, "-1"); - logger.info("testNegativeAuditPeriod: Exiting"); - - } - - /* - * Verifies (via log parsing) that when an audit period of zero is - * specified, the audit runs continuously, generating a number of sleep/wake - * sequences in a short period of time (e.g. 100ms). - */ - @Test - public void testZeroAuditPeriod() throws Exception { - - logger.info("testZeroAuditPeriod: Entering"); - - properties.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "0"); - - ExtractAppender logA = watch(debugLogger, "[Aa]waking from (0ms) sleep"); - - MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU); - - /* - * Wait for - * - * 1) audit to generate a bunch of sleep wake sequences. - */ - String[] awakings = new String[10]; - for (int x = 0; x < awakings.length; ++x) { - awakings[x] = "0ms"; - runAudit(integrityAudit); - } - - // run a couple more audits - runAudit(integrityAudit); - runAudit(integrityAudit); - - /* - * We should get at least 10 sleep/wake sequences. - */ - - verifyItemsInLog(logA, awakings); - - logger.info("testZeroAuditPeriod: Exiting"); - - } - - /** - * Verifies that when different audit periods are specified, there is an - * appropriate interval between the audits. - */ - @Test - public void testLongAuditPeriod() throws Exception { - - logger.info("testLongAuditPeriod: Entering"); - - testAuditPeriod(100); - testAuditPeriod(200); - - logger.info("testLongAuditPeriod: Exiting"); - } - - /** - * Verifies that audits actually take as long as expected, even with - * multiple auditors running simultaneously. - * - * @param periodms - * audit period, in milliseconds - * @throws Exception - * @throws InterruptedException - */ - private void testAuditPeriod(long periodms) throws Exception, InterruptedException { - - properties.put(IntegrityAuditProperties.AUDIT_PERIOD_MILLISECONDS, String.valueOf(periodms)); - - /* - * Start several auditors. - */ - MyIntegrityAudit[] ia = new MyIntegrityAudit[3]; - for (int x = 0; x < ia.length; ++x) { - ia[x] = makeAuditor("pdp" + x, A_SEQ_PU); - } - - /* - * Run an audit on all of them. - */ - runAudit(ia); - - /* - * Now run again and ensure it waited long enough between runs. - */ - long tmin = minAuditTime(ia); - assertTrue(tmin >= periodms + AUDIT_SIMULATION_MS); - - /* - * Now run again and ensure it waited long enough between runs. - */ - tmin = minAuditTime(ia); - assertTrue(tmin >= periodms + AUDIT_SIMULATION_MS); - } - - /** - * Runs simultaneous audits on several auditors. - * - * @param auditors - * @return the minimum time, in milliseconds, elapsed for any given auditor - * @throws InterruptedException - */ - private long minAuditTime(MyIntegrityAudit... auditors) throws InterruptedException { - List threads = new ArrayList<>(auditors.length); - AtomicLong tfirst = new AtomicLong(Long.MAX_VALUE); - long tbeg = System.currentTimeMillis(); - - // create the threads - for (MyIntegrityAudit p : auditors) { - Thread t = new Thread() { - - @Override - public void run() { - try { - runAudit(p); - setMinTime(tfirst); - - } catch (InterruptedException e) { - ; - } - } - }; - - t.setDaemon(true); - threads.add(t); - } - - // start the threads - for (Thread t : threads) { - t.start(); - } - - // wait for them to complete - for (Thread t : threads) { - t.join(); - } - - return (tfirst.get() - tbeg); - } - - /** - * Sets a value to the minimum between the current value and the current - * time. - * - * @param tmin - * current minimum value/value to be set - */ - private static void setMinTime(AtomicLong tmin) { - long tcur = System.currentTimeMillis(); - long t; - while ((t = tmin.get()) > tcur) { - tmin.compareAndSet(t, tcur); - } - } + logger.info("testNegativeAuditPeriod: Exiting"); + + } + + /* + * Verifies (via log parsing) that when an audit period of zero is specified, the audit runs + * continuously, generating a number of sleep/wake sequences in a short period of time (e.g. + * 100ms). + */ + @Test + public void testZeroAuditPeriod() throws Exception { + + logger.info("testZeroAuditPeriod: Entering"); + + properties.put(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS, "0"); + + final ExtractAppender logA = watch(debugLogger, "[Aa]waking from (0ms) sleep"); + + MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU); + + /* + * Wait for + * + * 1) audit to generate a bunch of sleep wake sequences. + */ + String[] awakings = new String[10]; + for (int x = 0; x < awakings.length; ++x) { + awakings[x] = "0ms"; + runAudit(integrityAudit); + } + + // run a couple more audits + runAudit(integrityAudit); + runAudit(integrityAudit); + + /* + * We should get at least 10 sleep/wake sequences. + */ + + verifyItemsInLog(logA, awakings); + + logger.info("testZeroAuditPeriod: Exiting"); + + } + + /** + * Verifies that when different audit periods are specified, there is an appropriate interval + * between the audits. + */ + @Test + public void testLongAuditPeriod() throws Exception { + + logger.info("testLongAuditPeriod: Entering"); + + testAuditPeriod(100); + testAuditPeriod(200); + + logger.info("testLongAuditPeriod: Exiting"); + } + + /** + * Verifies that audits actually take as long as expected, even with multiple auditors running + * simultaneously. + * + * @param periodms audit period, in milliseconds + * @throws Exception if an error occurs + * @throws InterruptedException if the thread is interrupted + */ + private void testAuditPeriod(long periodms) throws Exception, InterruptedException { + + properties.put(IntegrityAuditProperties.AUDIT_PERIOD_MILLISECONDS, String.valueOf(periodms)); + + /* + * Start several auditors. + */ + MyIntegrityAudit[] ia = new MyIntegrityAudit[3]; + for (int x = 0; x < ia.length; ++x) { + ia[x] = makeAuditor("pdp" + x, A_SEQ_PU); + } + + /* + * Run an audit on all of them. + */ + runAudit(ia); + + /* + * Now run again and ensure it waited long enough between runs. + */ + long tmin = minAuditTime(ia); + assertTrue(tmin >= periodms + AUDIT_SIMULATION_MS); + + /* + * Now run again and ensure it waited long enough between runs. + */ + tmin = minAuditTime(ia); + assertTrue(tmin >= periodms + AUDIT_SIMULATION_MS); + } + + /** + * Runs simultaneous audits on several auditors. + * + * @param auditors the auditors + * @return the minimum time, in milliseconds, elapsed for any given auditor + * @throws InterruptedException if the thread is interrupted + */ + private long minAuditTime(MyIntegrityAudit... auditors) throws InterruptedException { + List threads = new ArrayList<>(auditors.length); + AtomicLong tfirst = new AtomicLong(Long.MAX_VALUE); + final long tbeg = System.currentTimeMillis(); + + // create the threads + for (MyIntegrityAudit p : auditors) { + Thread auditThread = new Thread() { + + @Override + public void run() { + try { + runAudit(p); + setMinTime(tfirst); + + } catch (InterruptedException e) { + ; + } + } + }; + + auditThread.setDaemon(true); + threads.add(auditThread); + } + + // start the threads + for (Thread t : threads) { + t.start(); + } + + // wait for them to complete + for (Thread t : threads) { + t.join(); + } + + return (tfirst.get() - tbeg); + } + + /** + * Sets a value to the minimum between the current value and the current time. + * + * @param tmin current minimum value/value to be set + */ + private static void setMinTime(AtomicLong tmin) { + long tcur = System.currentTimeMillis(); + long time; + while ((time = tmin.get()) > tcur) { + tmin.compareAndSet(time, tcur); + } + } } diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/DbAuditCompareEntriesTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/DbAuditCompareEntriesTest.java index 3a48b20c..6335482a 100644 --- a/integrity-audit/src/test/java/org/onap/policy/common/ia/DbAuditCompareEntriesTest.java +++ b/integrity-audit/src/test/java/org/onap/policy/common/ia/DbAuditCompareEntriesTest.java @@ -50,505 +50,507 @@ import org.onap.policy.common.logging.flexlogger.Logger; */ public class DbAuditCompareEntriesTest extends IntegrityAuditTestBase { - private static Logger logger = FlexLogger.getLogger(DbAuditCompareEntriesTest.class); - - private DbDAO dbDAO; - private static String resourceName = "pdp1"; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - IntegrityAuditTestBase - .setUpBeforeClass(DEFAULT_DB_URL_PREFIX + DbAuditCompareEntriesTest.class.getSimpleName()); - } - - @AfterClass - public static void tearDownAfterClass() { - IntegrityAuditTestBase.tearDownAfterClass(); - } - - @Before - public void setUp() { - - logger.info("setUp: Entering"); - - super.setUp(); - - truncateTables(makeProperties()); - - logger.info("setUp: Exiting"); - } - - /* - * Clean up DB after each test. - */ - @After - public void tearDown() { - logger.info("tearDown: Entering"); - - dbDAO.destroy(); - - super.tearDown(); - - logger.info("tearDown: Exiting"); - } - - /* - * Tests that a comparison between hashsets is successful if the entries - * match - */ - // @Ignore - @Test - public void testSuccessfulComparison() throws Exception { - logger.info("testSuccessfulComparison: Entering"); - - dbDAO = new DbDAO(resourceName, A_SEQ_PU, makeProperties()); - DbAudit dbAudit = new DbAudit(dbDAO); - - String className = null; - // There is only one entry IntegrityAuditEntity, but we will check - // anyway - Set classNameSet = dbDAO.getPersistenceClassNames(); - for (String c : classNameSet) { - if (c.equals("org.onap.policy.common.ia.jpa.IntegrityAuditEntity")) { - className = c; - } - } - String resourceName1 = resourceName; - String resourceName2 = resourceName; - - IntegrityAuditEntity entry1 = new IntegrityAuditEntity(); - IntegrityAuditEntity entry2 = new IntegrityAuditEntity(); - Date date = new Date(); - - /* - * Two entries with the same field values - */ - entry1.setDesignated(false); - entry1.setJdbcDriver(dbDriver); - entry1.setJdbcPassword(dbPwd); - entry1.setJdbcUrl(dbUrl); - entry1.setJdbcUser(dbUser); - entry1.setLastUpdated(date); - entry1.setNodeType(nodeType); - entry1.setPersistenceUnit(A_SEQ_PU); - entry1.setResourceName(resourceName1); - entry1.setSite(siteName); - - entry2.setDesignated(false); - entry2.setJdbcDriver(dbDriver); - entry2.setJdbcPassword(dbPwd); - entry2.setJdbcUrl(dbUrl); - entry2.setJdbcUser(dbUser); - entry2.setLastUpdated(date); - entry2.setNodeType(nodeType); - entry2.setPersistenceUnit(A_SEQ_PU); - entry2.setResourceName(resourceName2); - entry2.setSite(siteName); - - dbAudit.writeAuditDebugLog(className, resourceName1, resourceName2, entry1, entry2); - - HashMap myEntries = new HashMap(); - HashMap theirEntries = new HashMap(); - - myEntries.put("pdp1", entry1); - theirEntries.put("pdp1", entry2); - - Set result = dbAudit.compareEntries(myEntries, theirEntries); - - /* - * Assert that there are no mismatches returned - */ - assertTrue(result.isEmpty()); - - logger.info("testSuccessfulComparison: Exit"); - } - - /* - * Tests that an error is detected if an entry in one hashset doesn't match - * the other - */ - // @Ignore - @Test - public void testComparisonError() throws Exception { - logger.info("testComparisonError: Entering"); - - dbDAO = new DbDAO(resourceName, A_SEQ_PU, makeProperties()); - DbAudit dbAudit = new DbAudit(dbDAO); - - String resourceName1 = resourceName; - String resourceName2 = resourceName; - - IntegrityAuditEntity entry1 = new IntegrityAuditEntity(); - IntegrityAuditEntity entry2 = new IntegrityAuditEntity(); - Date date = new Date(); - - /* - * Create two entries with different designated values - */ - entry1.setDesignated(false); - entry1.setJdbcDriver(dbDriver); - entry1.setJdbcPassword(dbPwd); - entry1.setJdbcUrl(dbUrl); - entry1.setJdbcUser(dbUser); - entry1.setLastUpdated(date); - entry1.setNodeType(nodeType); - entry1.setPersistenceUnit(A_SEQ_PU); - entry1.setResourceName(resourceName1); - entry1.setSite(siteName); - - entry2.setDesignated(true); - entry2.setJdbcDriver(dbDriver); - entry2.setJdbcPassword(dbPwd); - entry2.setJdbcUrl(dbUrl); - entry2.setJdbcUser(dbUser); - entry2.setLastUpdated(date); - entry2.setNodeType(nodeType); - entry2.setPersistenceUnit(A_SEQ_PU); - entry2.setResourceName(resourceName2); - entry2.setSite(siteName); - - HashMap myEntries = new HashMap(); - HashMap theirEntries = new HashMap(); - - myEntries.put("pdp1", entry1); - theirEntries.put("pdp1", entry2); - - Set result = dbAudit.compareEntries(myEntries, theirEntries); - - /* - * Assert that there was one mismatch - */ - assertEquals(1, result.size()); - - logger.info("testComparisonError: Exit"); - } - - /* - * Tests that a mismatch/miss entry is detected if there are missing entries - * in one or both of the hashsets - */ - // @Ignore - @Test - public void testCompareMissingEntries() throws Exception { - logger.info("testCompareMissingEntries: Entering"); - - dbDAO = new DbDAO(resourceName, A_SEQ_PU, makeProperties()); - DbAudit dbAudit = new DbAudit(dbDAO); - - String resourceName1 = resourceName; - String resourceName2 = resourceName; - - IntegrityAuditEntity entry1 = new IntegrityAuditEntity(); - IntegrityAuditEntity entry2 = new IntegrityAuditEntity(); - IntegrityAuditEntity entry3 = new IntegrityAuditEntity(); - IntegrityAuditEntity entry4 = new IntegrityAuditEntity(); - - Date date = new Date(); - - /* - * 4 entries, one mismatch, two miss entries - */ - entry1.setDesignated(false); - entry1.setJdbcDriver(dbDriver); - entry1.setJdbcPassword(dbPwd); - entry1.setJdbcUrl(dbUrl); - entry1.setJdbcUser(dbUser); - entry1.setLastUpdated(date); - entry1.setNodeType(nodeType); - entry1.setPersistenceUnit(A_SEQ_PU); - entry1.setResourceName(resourceName1); - entry1.setSite(siteName); - - entry2.setDesignated(true); - entry2.setJdbcDriver(dbDriver); - entry2.setJdbcPassword(dbPwd); - entry2.setJdbcUrl(dbUrl); - entry2.setJdbcUser(dbUser); - entry2.setLastUpdated(date); - entry2.setNodeType(nodeType); - entry2.setPersistenceUnit(A_SEQ_PU); - entry2.setResourceName(resourceName2); - entry2.setSite(siteName); - - entry3.setDesignated(false); - entry3.setJdbcDriver(dbDriver); - entry3.setJdbcPassword(dbPwd); - entry3.setJdbcUrl(dbUrl); - entry3.setJdbcUser(dbUser); - entry3.setLastUpdated(date); - entry3.setNodeType(nodeType); - entry3.setPersistenceUnit(A_SEQ_PU); - entry3.setResourceName(resourceName2); - entry3.setSite("SiteB"); - - entry4.setDesignated(false); - entry4.setJdbcDriver(dbDriver); - entry4.setJdbcPassword(dbPwd); - entry4.setJdbcUrl(dbUrl); - entry4.setJdbcUser(dbUser); - entry4.setLastUpdated(date); - entry4.setNodeType(nodeType); - entry4.setPersistenceUnit(A_SEQ_PU); - entry4.setResourceName(resourceName2); - entry4.setSite("SiteB"); - - HashMap myEntries = new HashMap(); - HashMap theirEntries = new HashMap(); - - myEntries.put("0", entry1); - myEntries.put("1", entry3); - theirEntries.put("0", entry2); - theirEntries.put("2", entry4); - - Set mismatchResult = dbAudit.compareEntries(myEntries, theirEntries); - - /* - * Assert 3 mismatches/missing entries were found - */ - assertEquals(3, mismatchResult.size()); - - logger.info("testCompareMissingEntries: Exit"); - } - - /* - * Tests that comparison algorithm works for each entity in the hashsets - */ - // @Ignore - @Test - public void testCompareAllHashEntities() throws Exception { - logger.info("testCompareAllHashEntities: Entering"); - - dbDAO = new DbDAO(resourceName, A_SEQ_PU, makeProperties()); - DbAudit dbAudit = new DbAudit(dbDAO); - - Set classNameSet = dbDAO.getPersistenceClassNames(); - Set mismatchResult = new HashSet(); - for (String c : classNameSet) { - if (c.equals("org.onap.policy.common.ia.jpa.IntegrityAuditEntity")) { - String resourceName1 = resourceName; - String resourceName2 = resourceName; - - IntegrityAuditEntity entry1 = new IntegrityAuditEntity(); - IntegrityAuditEntity entry2 = new IntegrityAuditEntity(); - Date date = new Date(); - - /* - * Two entries with the same field values - */ - entry1.setDesignated(false); - entry1.setJdbcDriver(dbDriver); - entry1.setJdbcPassword(dbPwd); - entry1.setJdbcUrl(dbUrl); - entry1.setJdbcUser(dbUser); - entry1.setLastUpdated(date); - entry1.setNodeType(nodeType); - entry1.setPersistenceUnit(A_SEQ_PU); - entry1.setResourceName(resourceName1); - entry1.setSite(siteName); - - entry2.setDesignated(false); - entry2.setJdbcDriver(dbDriver); - entry2.setJdbcPassword(dbPwd); - entry2.setJdbcUrl(dbUrl); - entry2.setJdbcUser(dbUser); - entry2.setLastUpdated(date); - entry2.setNodeType(nodeType); - entry2.setPersistenceUnit(A_SEQ_PU); - entry2.setResourceName(resourceName2); - entry2.setSite(siteName); - - HashMap myEntries = new HashMap(); - HashMap theirEntries = new HashMap(); - - myEntries.put("pdp1", entry1); - theirEntries.put("pdp1", entry2); - - mismatchResult = dbAudit.compareEntries(myEntries, theirEntries); - - /* - * Assert there was no mismatches - */ - assertTrue(mismatchResult.isEmpty()); - } else if (c.equals("org.onap.policy.common.ia.jpa.IaTestEntity")) { - IaTestEntity iate = new IaTestEntity(); - IaTestEntity iate2 = new IaTestEntity(); - IaTestEntity iate3 = new IaTestEntity(); - IaTestEntity iate4 = new IaTestEntity(); - - Date date = new Date(); - - /* - * Four entries, 2 mismatches - */ - iate.setCreatedBy("Ford"); - iate.setModifiedBy("Ford"); - iate.setModifiedDate(date); - - iate2.setCreatedBy("Ford"); - iate2.setModifiedBy("Zaphod"); - iate2.setModifiedDate(date); - - iate3.setCreatedBy("Zaphod"); - iate3.setModifiedBy("Ford"); - iate3.setModifiedDate(date); - - iate4.setCreatedBy("Ford"); - iate4.setModifiedBy("Ford"); - iate4.setModifiedDate(date); - - HashMap myEntries = new HashMap(); - HashMap theirEntries = new HashMap(); - - myEntries.put("0", iate); - myEntries.put("1", iate2); - theirEntries.put("0", iate3); - theirEntries.put("1", iate4); - - mismatchResult = dbAudit.compareEntries(myEntries, theirEntries); - - /* - * Assert that there is 2 mismatches - */ - assertEquals(2, mismatchResult.size()); - } - } - - logger.info("testCompareAllHashEntities: Exit"); - } - - /* - * Tests that comparison algorithm works for each entity in the database - */ - @Ignore - @Test - public void testCompareAllDbEntities() throws Exception { - logger.info("testCompareAllDbEntities: Entering"); - - logger.info("Setting up DB"); - - IntegrityAudit.setUnitTesting(true); - - Properties properties = makeProperties(); - - Properties properties2 = makeProperties(); - properties2.put(IntegrityAuditProperties.DB_URL, - "jdbc:h2:mem:" + DbAuditCompareEntriesTest.class.getSimpleName() + "2"); - - // Clean up the two DBs - truncateTables(properties); - truncateTables(properties2); - - // Add entries into DB1 - dbDAO = new DbDAO(resourceName, A_SEQ_PU, properties); - new DbDAO("pdp2", A_SEQ_PU, properties).destroy(); - DbAudit dbAudit = new DbAudit(dbDAO); - - // Add entries into DB2 - DbDAO dbDAO3 = new DbDAO(resourceName, A_SEQ_PU, properties2); - new DbDAO("pdp2", A_SEQ_PU, properties2).destroy(); - - // Pull all entries and compare - Set classNameSet = dbDAO.getPersistenceClassNames(); - Map myEntries; - Map theirEntries; - Set mismatchResult = new HashSet(); - String className; - for (String c : classNameSet) { - className = c; - logger.info("classNameSet entry = " + c); - myEntries = dbDAO.getAllEntries(A_SEQ_PU, properties, className); - theirEntries = dbDAO3.getAllEntries(A_SEQ_PU, properties2, className); - mismatchResult = dbAudit.compareEntries(myEntries, theirEntries); - if (className.contains("IntegrityAuditEntity")) { - break; - } - } - - dbDAO3.destroy(); - - // Assert that there is 2 mismatches between IntegrityAuditEntity tables - assertEquals(2, mismatchResult.size()); - - logger.info("testCompareAllDbEntities: Exit"); - } - - /** - * @param properties - */ - private void truncateTables(Properties properties) { - truncateTable(properties, A_SEQ_PU, "IntegrityAuditEntity"); - truncateTable(properties, A_SEQ_PU, "IaTestEntity"); - } - - /* - * Tests that differences in embedded classes are still caught - */ - // @Ignore - @Test - public void testEmbeddedClass() throws Exception { - logger.info("testEmbeddedClasses: Entering"); - - dbDAO = new DbDAO(resourceName, A_SEQ_PU, properties); - DbAudit dbAudit = new DbAudit(dbDAO); - - String className = null; - // There is only one entry IntegrityAuditEntity, but we will check - // anyway - Set classNameSet = dbDAO.getPersistenceClassNames(); - for (String c : classNameSet) { - if (c.equals("org.onap.policy.common.ia.jpa.IaTestEntity")) { - className = c; - } - } - - IaTestEntity iate = new IaTestEntity(); - IaTestEntity iate2 = new IaTestEntity(); - - Date date = new Date(); - - PersonSample person = new PersonSample("Ford", "Prefect", 21); - PersonSample person2 = new PersonSample("Zaphod", "Beeblebrox", 25); - - /* - * Silly tests to bump coverage stats, not sure why they are counting - * PersonSample to begin with. Will have to look into that at some - * point. - */ - assertNotEquals(person.getAge(), person2.getAge()); - assertNotEquals(person.getFirstName(), person2.getFirstName()); - assertNotEquals(person.getLasttName(), person2.getLasttName()); - PersonSample personTest = new PersonSample(null, null, 0); - personTest.setAge(person.getAge()); - personTest.setFirstName(person.getFirstName()); - personTest.setLastName(person.getLasttName()); - /* - * Two entries, 1 mismatch - */ - iate.setCreatedBy("Ford"); - iate.setModifiedBy("Zaphod"); - iate.setModifiedDate(date); - iate.setPersonTest(person); - - iate2.setCreatedBy("Ford"); - iate2.setModifiedBy("Zaphod"); - iate2.setModifiedDate(date); - iate2.setPersonTest(person2); - - dbAudit.writeAuditDebugLog(className, "resource1", "resource2", iate, iate2); - - HashMap myEntries = new HashMap(); - HashMap theirEntries = new HashMap(); - - myEntries.put("0", iate); - theirEntries.put("0", iate2); - - Set result = dbAudit.compareEntries(myEntries, theirEntries); - - /* - * Assert that there are no mismatches returned - */ - assertTrue(!result.isEmpty()); - - logger.info("testEmbeddedClasses: Exit"); - } + private static Logger logger = FlexLogger.getLogger(DbAuditCompareEntriesTest.class); + + private DbDAO dbDao; + private static String resourceName = "pdp1"; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + IntegrityAuditTestBase + .setUpBeforeClass(DEFAULT_DB_URL_PREFIX + DbAuditCompareEntriesTest.class.getSimpleName()); + } + + @AfterClass + public static void tearDownAfterClass() { + IntegrityAuditTestBase.tearDownAfterClass(); + } + + /** + * Set up for test cases. + */ + @Override + @Before + public void setUp() { + + logger.info("setUp: Entering"); + + super.setUp(); + + truncateTables(makeProperties()); + + logger.info("setUp: Exiting"); + } + + /** + * Clean up DB after each test. + */ + @Override + @After + public void tearDown() { + logger.info("tearDown: Entering"); + + dbDao.destroy(); + + super.tearDown(); + + logger.info("tearDown: Exiting"); + } + + /* + * Tests that a comparison between hashsets is successful if the entries match + */ + // @Ignore + @Test + public void testSuccessfulComparison() throws Exception { + logger.info("testSuccessfulComparison: Entering"); + + dbDao = new DbDAO(resourceName, A_SEQ_PU, makeProperties()); + final DbAudit dbAudit = new DbAudit(dbDao); + + String className = null; + // There is only one entry IntegrityAuditEntity, but we will check + // anyway + Set classNameSet = dbDao.getPersistenceClassNames(); + for (String c : classNameSet) { + if (c.equals("org.onap.policy.common.ia.jpa.IntegrityAuditEntity")) { + className = c; + } + } + final String resourceName1 = resourceName; + final String resourceName2 = resourceName; + + final IntegrityAuditEntity entry1 = new IntegrityAuditEntity(); + final IntegrityAuditEntity entry2 = new IntegrityAuditEntity(); + Date date = new Date(); + + /* + * Two entries with the same field values + */ + entry1.setDesignated(false); + entry1.setJdbcDriver(dbDriver); + entry1.setJdbcPassword(dbPwd); + entry1.setJdbcUrl(dbUrl); + entry1.setJdbcUser(dbUser); + entry1.setLastUpdated(date); + entry1.setNodeType(nodeType); + entry1.setPersistenceUnit(A_SEQ_PU); + entry1.setResourceName(resourceName1); + entry1.setSite(siteName); + + entry2.setDesignated(false); + entry2.setJdbcDriver(dbDriver); + entry2.setJdbcPassword(dbPwd); + entry2.setJdbcUrl(dbUrl); + entry2.setJdbcUser(dbUser); + entry2.setLastUpdated(date); + entry2.setNodeType(nodeType); + entry2.setPersistenceUnit(A_SEQ_PU); + entry2.setResourceName(resourceName2); + entry2.setSite(siteName); + + dbAudit.writeAuditDebugLog(className, resourceName1, resourceName2, entry1, entry2); + + HashMap myEntries = new HashMap(); + HashMap theirEntries = new HashMap(); + + myEntries.put("pdp1", entry1); + theirEntries.put("pdp1", entry2); + + Set result = dbAudit.compareEntries(myEntries, theirEntries); + + /* + * Assert that there are no mismatches returned + */ + assertTrue(result.isEmpty()); + + logger.info("testSuccessfulComparison: Exit"); + } + + /* + * Tests that an error is detected if an entry in one hashset doesn't match the other + */ + // @Ignore + @Test + public void testComparisonError() throws Exception { + logger.info("testComparisonError: Entering"); + + dbDao = new DbDAO(resourceName, A_SEQ_PU, makeProperties()); + final DbAudit dbAudit = new DbAudit(dbDao); + + final String resourceName1 = resourceName; + final String resourceName2 = resourceName; + + final IntegrityAuditEntity entry1 = new IntegrityAuditEntity(); + final IntegrityAuditEntity entry2 = new IntegrityAuditEntity(); + Date date = new Date(); + + /* + * Create two entries with different designated values + */ + entry1.setDesignated(false); + entry1.setJdbcDriver(dbDriver); + entry1.setJdbcPassword(dbPwd); + entry1.setJdbcUrl(dbUrl); + entry1.setJdbcUser(dbUser); + entry1.setLastUpdated(date); + entry1.setNodeType(nodeType); + entry1.setPersistenceUnit(A_SEQ_PU); + entry1.setResourceName(resourceName1); + entry1.setSite(siteName); + + entry2.setDesignated(true); + entry2.setJdbcDriver(dbDriver); + entry2.setJdbcPassword(dbPwd); + entry2.setJdbcUrl(dbUrl); + entry2.setJdbcUser(dbUser); + entry2.setLastUpdated(date); + entry2.setNodeType(nodeType); + entry2.setPersistenceUnit(A_SEQ_PU); + entry2.setResourceName(resourceName2); + entry2.setSite(siteName); + + HashMap myEntries = new HashMap(); + HashMap theirEntries = new HashMap(); + + myEntries.put("pdp1", entry1); + theirEntries.put("pdp1", entry2); + + Set result = dbAudit.compareEntries(myEntries, theirEntries); + + /* + * Assert that there was one mismatch + */ + assertEquals(1, result.size()); + + logger.info("testComparisonError: Exit"); + } + + /* + * Tests that a mismatch/miss entry is detected if there are missing entries in one or both of + * the hashsets + */ + // @Ignore + @Test + public void testCompareMissingEntries() throws Exception { + logger.info("testCompareMissingEntries: Entering"); + + dbDao = new DbDAO(resourceName, A_SEQ_PU, makeProperties()); + final DbAudit dbAudit = new DbAudit(dbDao); + + final String resourceName1 = resourceName; + final String resourceName2 = resourceName; + + final IntegrityAuditEntity entry1 = new IntegrityAuditEntity(); + final IntegrityAuditEntity entry2 = new IntegrityAuditEntity(); + final IntegrityAuditEntity entry3 = new IntegrityAuditEntity(); + final IntegrityAuditEntity entry4 = new IntegrityAuditEntity(); + + Date date = new Date(); + + /* + * 4 entries, one mismatch, two miss entries + */ + entry1.setDesignated(false); + entry1.setJdbcDriver(dbDriver); + entry1.setJdbcPassword(dbPwd); + entry1.setJdbcUrl(dbUrl); + entry1.setJdbcUser(dbUser); + entry1.setLastUpdated(date); + entry1.setNodeType(nodeType); + entry1.setPersistenceUnit(A_SEQ_PU); + entry1.setResourceName(resourceName1); + entry1.setSite(siteName); + + entry2.setDesignated(true); + entry2.setJdbcDriver(dbDriver); + entry2.setJdbcPassword(dbPwd); + entry2.setJdbcUrl(dbUrl); + entry2.setJdbcUser(dbUser); + entry2.setLastUpdated(date); + entry2.setNodeType(nodeType); + entry2.setPersistenceUnit(A_SEQ_PU); + entry2.setResourceName(resourceName2); + entry2.setSite(siteName); + + entry3.setDesignated(false); + entry3.setJdbcDriver(dbDriver); + entry3.setJdbcPassword(dbPwd); + entry3.setJdbcUrl(dbUrl); + entry3.setJdbcUser(dbUser); + entry3.setLastUpdated(date); + entry3.setNodeType(nodeType); + entry3.setPersistenceUnit(A_SEQ_PU); + entry3.setResourceName(resourceName2); + entry3.setSite("SiteB"); + + entry4.setDesignated(false); + entry4.setJdbcDriver(dbDriver); + entry4.setJdbcPassword(dbPwd); + entry4.setJdbcUrl(dbUrl); + entry4.setJdbcUser(dbUser); + entry4.setLastUpdated(date); + entry4.setNodeType(nodeType); + entry4.setPersistenceUnit(A_SEQ_PU); + entry4.setResourceName(resourceName2); + entry4.setSite("SiteB"); + + HashMap myEntries = new HashMap(); + HashMap theirEntries = new HashMap(); + + myEntries.put("0", entry1); + myEntries.put("1", entry3); + theirEntries.put("0", entry2); + theirEntries.put("2", entry4); + + Set mismatchResult = dbAudit.compareEntries(myEntries, theirEntries); + + /* + * Assert 3 mismatches/missing entries were found + */ + assertEquals(3, mismatchResult.size()); + + logger.info("testCompareMissingEntries: Exit"); + } + + /* + * Tests that comparison algorithm works for each entity in the hashsets + */ + // @Ignore + @Test + public void testCompareAllHashEntities() throws Exception { + logger.info("testCompareAllHashEntities: Entering"); + + dbDao = new DbDAO(resourceName, A_SEQ_PU, makeProperties()); + DbAudit dbAudit = new DbAudit(dbDao); + + Set classNameSet = dbDao.getPersistenceClassNames(); + Set mismatchResult = new HashSet(); + for (String className : classNameSet) { + if (className.equals("org.onap.policy.common.ia.jpa.IntegrityAuditEntity")) { + final String resourceName1 = resourceName; + final String resourceName2 = resourceName; + + final IntegrityAuditEntity entry1 = new IntegrityAuditEntity(); + final IntegrityAuditEntity entry2 = new IntegrityAuditEntity(); + Date date = new Date(); + + /* + * Two entries with the same field values + */ + entry1.setDesignated(false); + entry1.setJdbcDriver(dbDriver); + entry1.setJdbcPassword(dbPwd); + entry1.setJdbcUrl(dbUrl); + entry1.setJdbcUser(dbUser); + entry1.setLastUpdated(date); + entry1.setNodeType(nodeType); + entry1.setPersistenceUnit(A_SEQ_PU); + entry1.setResourceName(resourceName1); + entry1.setSite(siteName); + + entry2.setDesignated(false); + entry2.setJdbcDriver(dbDriver); + entry2.setJdbcPassword(dbPwd); + entry2.setJdbcUrl(dbUrl); + entry2.setJdbcUser(dbUser); + entry2.setLastUpdated(date); + entry2.setNodeType(nodeType); + entry2.setPersistenceUnit(A_SEQ_PU); + entry2.setResourceName(resourceName2); + entry2.setSite(siteName); + + HashMap myEntries = new HashMap(); + HashMap theirEntries = new HashMap(); + + myEntries.put("pdp1", entry1); + theirEntries.put("pdp1", entry2); + + mismatchResult = dbAudit.compareEntries(myEntries, theirEntries); + + /* + * Assert there was no mismatches + */ + assertTrue(mismatchResult.isEmpty()); + } else if (className.equals("org.onap.policy.common.ia.jpa.IaTestEntity")) { + final IaTestEntity iate = new IaTestEntity(); + final IaTestEntity iate2 = new IaTestEntity(); + final IaTestEntity iate3 = new IaTestEntity(); + final IaTestEntity iate4 = new IaTestEntity(); + + Date date = new Date(); + + /* + * Four entries, 2 mismatches + */ + iate.setCreatedBy("Ford"); + iate.setModifiedBy("Ford"); + iate.setModifiedDate(date); + + iate2.setCreatedBy("Ford"); + iate2.setModifiedBy("Zaphod"); + iate2.setModifiedDate(date); + + iate3.setCreatedBy("Zaphod"); + iate3.setModifiedBy("Ford"); + iate3.setModifiedDate(date); + + iate4.setCreatedBy("Ford"); + iate4.setModifiedBy("Ford"); + iate4.setModifiedDate(date); + + HashMap myEntries = new HashMap(); + HashMap theirEntries = new HashMap(); + + myEntries.put("0", iate); + myEntries.put("1", iate2); + theirEntries.put("0", iate3); + theirEntries.put("1", iate4); + + mismatchResult = dbAudit.compareEntries(myEntries, theirEntries); + + /* + * Assert that there is 2 mismatches + */ + assertEquals(2, mismatchResult.size()); + } + } + + logger.info("testCompareAllHashEntities: Exit"); + } + + /* + * Tests that comparison algorithm works for each entity in the database + */ + @Ignore + @Test + public void testCompareAllDbEntities() throws Exception { + logger.info("testCompareAllDbEntities: Entering"); + + logger.info("Setting up DB"); + + IntegrityAudit.setUnitTesting(true); + + Properties properties = makeProperties(); + + Properties properties2 = makeProperties(); + properties2.put(IntegrityAuditProperties.DB_URL, + "jdbc:h2:mem:" + DbAuditCompareEntriesTest.class.getSimpleName() + "2"); + + // Clean up the two DBs + truncateTables(properties); + truncateTables(properties2); + + // Add entries into DB1 + dbDao = new DbDAO(resourceName, A_SEQ_PU, properties); + new DbDAO("pdp2", A_SEQ_PU, properties).destroy(); + DbAudit dbAudit = new DbAudit(dbDao); + + // Add entries into DB2 + DbDAO dbDao3 = new DbDAO(resourceName, A_SEQ_PU, properties2); + new DbDAO("pdp2", A_SEQ_PU, properties2).destroy(); + + // Pull all entries and compare + Set classNameSet = dbDao.getPersistenceClassNames(); + Map myEntries; + Map theirEntries; + Set mismatchResult = new HashSet(); + for (String className : classNameSet) { + logger.info("classNameSet entry = " + className); + myEntries = dbDao.getAllEntries(A_SEQ_PU, properties, className); + theirEntries = dbDao3.getAllEntries(A_SEQ_PU, properties2, className); + mismatchResult = dbAudit.compareEntries(myEntries, theirEntries); + if (className.contains("IntegrityAuditEntity")) { + break; + } + } + + dbDao3.destroy(); + + // Assert that there is 2 mismatches between IntegrityAuditEntity tables + assertEquals(2, mismatchResult.size()); + + logger.info("testCompareAllDbEntities: Exit"); + } + + /** + * Truncate the tables. + * + * @param properties the properties + */ + private void truncateTables(Properties properties) { + truncateTable(properties, A_SEQ_PU, "IntegrityAuditEntity"); + truncateTable(properties, A_SEQ_PU, "IaTestEntity"); + } + + /* + * Tests that differences in embedded classes are still caught + */ + // @Ignore + @Test + public void testEmbeddedClass() throws Exception { + logger.info("testEmbeddedClasses: Entering"); + + dbDao = new DbDAO(resourceName, A_SEQ_PU, properties); + final DbAudit dbAudit = new DbAudit(dbDao); + + String className = null; + // There is only one entry IntegrityAuditEntity, but we will check + // anyway + Set classNameSet = dbDao.getPersistenceClassNames(); + for (String classNameInClassNameSet : classNameSet) { + if (classNameInClassNameSet.equals("org.onap.policy.common.ia.jpa.IaTestEntity")) { + className = classNameInClassNameSet; + } + } + + final IaTestEntity iate = new IaTestEntity(); + final IaTestEntity iate2 = new IaTestEntity(); + + final Date date = new Date(); + + PersonSample person = new PersonSample("Ford", "Prefect", 21); + PersonSample person2 = new PersonSample("Zaphod", "Beeblebrox", 25); + + /* + * Silly tests to bump coverage stats, not sure why they are counting PersonSample to begin + * with. Will have to look into that at some point. + */ + assertNotEquals(person.getAge(), person2.getAge()); + assertNotEquals(person.getFirstName(), person2.getFirstName()); + assertNotEquals(person.getLasttName(), person2.getLasttName()); + PersonSample personTest = new PersonSample(null, null, 0); + personTest.setAge(person.getAge()); + personTest.setFirstName(person.getFirstName()); + personTest.setLastName(person.getLasttName()); + /* + * Two entries, 1 mismatch + */ + iate.setCreatedBy("Ford"); + iate.setModifiedBy("Zaphod"); + iate.setModifiedDate(date); + iate.setPersonTest(person); + + iate2.setCreatedBy("Ford"); + iate2.setModifiedBy("Zaphod"); + iate2.setModifiedDate(date); + iate2.setPersonTest(person2); + + dbAudit.writeAuditDebugLog(className, "resource1", "resource2", iate, iate2); + + HashMap myEntries = new HashMap(); + HashMap theirEntries = new HashMap(); + + myEntries.put("0", iate); + theirEntries.put("0", iate2); + + Set result = dbAudit.compareEntries(myEntries, theirEntries); + + /* + * Assert that there are no mismatches returned + */ + assertTrue(!result.isEmpty()); + + logger.info("testEmbeddedClasses: Exit"); + } } diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/DbAuditTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/DbAuditTest.java index ad4041f5..cfbf90cb 100644 --- a/integrity-audit/src/test/java/org/onap/policy/common/ia/DbAuditTest.java +++ b/integrity-audit/src/test/java/org/onap/policy/common/ia/DbAuditTest.java @@ -53,230 +53,236 @@ import org.onap.policy.common.utils.test.log.logback.ExtractAppender; */ public class DbAuditTest extends IntegrityAuditTestBase { - private static Logger logger = FlexLogger.getLogger(DbAuditTest.class); + private static Logger logger = FlexLogger.getLogger(DbAuditTest.class); + + private static final String resourceName = "pdp1"; + + private EntityManagerFactory emf2; + private EntityManager em2; + private DbDAO dbDao; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + IntegrityAuditTestBase.setUpBeforeClass(DEFAULT_DB_URL_PREFIX + DbAuditTest.class.getSimpleName()); + IntegrityAuditEntity.setUnitTesting(true); + } + + @AfterClass + public static void tearDownAfterClass() { + IntegrityAuditTestBase.tearDownAfterClass(); + IntegrityAuditEntity.setUnitTesting(false); + } + + /** + * Set up for test cases. + */ + @Override + @Before + public void setUp() { + logger.info("setUp: Entering"); + + super.setUp(); + + dbDao = null; + emf2 = null; + em2 = null; + + logger.info("setUp: Exiting"); + } + + /** + * Tear down after test cases. + */ + @Override + @After + public void tearDown() { + logger.info("tearDown: Entering"); + + if (dbDao != null) { + dbDao.destroy(); + } + + if (em2 != null) { + em2.close(); + } + + if (emf2 != null) { + emf2.close(); + } + + super.tearDown(); - private static final String resourceName = "pdp1"; + logger.info("tearDown: Exiting"); + } + + private void createDb(Properties properties) { + if (emf2 != null) { + throw new IllegalStateException("DB2 has already been created"); + } + + // open the DB and ensure it stays open until the test completes + emf2 = Persistence.createEntityManagerFactory(A_SEQ_PU, properties); + em2 = emf2.createEntityManager(); + + truncateTable(properties, A_SEQ_PU, "IntegrityAuditEntity"); + } + + /* + * Tests printing an error to the log in the event where there are no entities saved in the + * database + */ + @Test + public void noEntitiesTest() throws Exception { + Properties properties = makeProperties(); + + logger.info("noEntitiesTest: Entering"); + + dbDao = new DbDAO(resourceName, A_SEQ_PU, properties); + dbDao.deleteAllIntegrityAuditEntities(); + try { + DbAudit dbAudit = new DbAudit(dbDao); + dbAudit.dbAudit(resourceName, A_SEQ_PU, nodeType); + fail("found unexpected entities"); + + } catch (DbAuditException e) { + // Ignore expected exception + } + + logger.info("noEntitiesTest: Exit"); + } + + /* + * Tests the detection of only one entry in the database + */ + @Test + public void oneEntityTest() throws Exception { + Properties properties = makeProperties(); + + logger.info("oneEntityTest: Entering"); + + final ExtractAppender log = watch(debugLogger, "DbAudit: Found only (one) IntegrityAuditEntity entry:"); + + // Add one entry in the database + dbDao = new DbDAO(resourceName, A_SEQ_PU, properties); + DbAudit dbAudit = new DbAudit(dbDao); + dbAudit.dbAudit(resourceName, A_SEQ_PU, nodeType); + + List iaeList = dbDao.getIntegrityAuditEntities(A_SEQ_PU, nodeType); + logger.info("List size: " + iaeList.size()); + + verifyItemsInLog(log, "one"); + + logger.info("oneEntityTest: Exit"); + } + + /* + * Tests reporting mismatches and missing entries using the error log + */ + @Test + public void mismatchTest() throws Exception { + logger.info("mismatchTest: Entering"); + + // use new URLs so we get a completely new DB + String dbUrl = DbAuditTest.dbUrl + "_mismatchTest"; + String dbUrl2 = dbUrl + "2"; + + Properties properties = makeProperties(); + properties.put(IntegrityAuditProperties.DB_URL, dbUrl); + + // Properties for DB2 + Properties properties2 = makeProperties(); + properties2.put(IntegrityAuditProperties.DB_URL, dbUrl2); + + /* + * We must drop and re-create DB1 so that it's sequence generator is in step with the + * sequence generator for DB2. + */ + recreateDb1(properties); + + // create/open DB2 + createDb(properties2); - private EntityManagerFactory emf2; - private EntityManager em2; - private DbDAO dbDAO; + final ExtractAppender dbglog = watch(debugLogger, "Mismatched entries [(]keys[)]:(.*)"); + final ExtractAppender errlog = watch(errorLogger, "DB Audit: ([0-9])"); + + /* + * Create entries in DB1 & DB2 for the resource of interest + */ + dbDao = new DbDAO(resourceName, A_SEQ_PU, properties); - @BeforeClass - public static void setUpBeforeClass() throws Exception { - IntegrityAuditTestBase.setUpBeforeClass(DEFAULT_DB_URL_PREFIX + DbAuditTest.class.getSimpleName()); - IntegrityAuditEntity.setUnitTesting(true); - } + new DbDAO(resourceName, A_SEQ_PU, properties2).destroy(); + + /* + * Entries in DB1, pointing to DB2, except for pdp3 + */ + new DbDAO("pdp2", A_SEQ_PU, properties, dbUrl2).destroy(); + new DbDAO("pdp1", A_SEQ_PU, properties, dbUrl2).destroy(); + new DbDAO("pdp3", A_SEQ_PU, properties).destroy(); // mismatched URL + new DbDAO("pdp4", A_SEQ_PU, properties, dbUrl2).destroy(); + + /* + * Identical entries in DB2, all pointing to DB2, including pdp3, but leaving out pdp4 + */ + new DbDAO("pdp2", A_SEQ_PU, properties2).destroy(); + new DbDAO("pdp1", A_SEQ_PU, properties2).destroy(); + new DbDAO("pdp3", A_SEQ_PU, properties2).destroy(); + + /* + * Run the DB Audit, once it finds a mismatch and sleeps, update DB1 to have the same entry + * as DB2 it can be confirmed that the mismatch is resolved + */ + DbAudit dbAudit = new DbAudit(dbDao); + dbAudit.dbAudit(resourceName, A_SEQ_PU, nodeType); - @AfterClass - public static void tearDownAfterClass() { - IntegrityAuditTestBase.tearDownAfterClass(); - IntegrityAuditEntity.setUnitTesting(false); - } + // update pdp3 entry in DB1 to point to DB2 + new DbDAO("pdp3", A_SEQ_PU, properties, dbUrl2).destroy(); + + /* + * Run the audit again and correct the mismatch, the result should be one entry in the + * mismatchKeySet because of the missing entry from the beginning of the test + */ + dbAudit.dbAudit(resourceName, A_SEQ_PU, nodeType); - @Before - public void setUp() { - logger.info("setUp: Entering"); + assertFalse(dbglog.getExtracted().isEmpty()); + + String mismatchIndex = dbglog.getExtracted().get(dbglog.getExtracted().size() - 1); + int mismatchEntries = mismatchIndex.trim().split(",").length; + logger.info("mismatchTest: mismatchIndex found: '" + mismatchIndex + "'" + " mismatachEntries = " + + mismatchEntries); - super.setUp(); + // Assert there is only one entry index + assertEquals(1, mismatchEntries); + + // Now check the entry in the error.log + assertFalse(errlog.getExtracted().isEmpty()); - dbDAO = null; - emf2 = null; - em2 = null; + String mismatchNum = errlog.getExtracted().get(errlog.getExtracted().size() - 1); - logger.info("setUp: Exiting"); - } + logger.info("mismatchTest: mismatchNum found: '" + mismatchNum + "'"); - @After - public void tearDown() { - logger.info("tearDown: Entering"); + // Assert that there are a total of 3 mismatches - 1 between each + // comparison node. + assertEquals("3", mismatchNum); + + logger.info("mismatchTest: Exit"); + } - if (dbDAO != null) { - dbDAO.destroy(); - } - - if (em2 != null) { - em2.close(); - } - - if (emf2 != null) { - emf2.close(); - } - - super.tearDown(); - - logger.info("tearDown: Exiting"); - } - - private void createDb(Properties properties) { - if (emf2 != null) { - throw new IllegalStateException("DB2 has already been created"); - } - - // open the DB and ensure it stays open until the test completes - emf2 = Persistence.createEntityManagerFactory(A_SEQ_PU, properties); - em2 = emf2.createEntityManager(); - - truncateTable(properties, A_SEQ_PU, "IntegrityAuditEntity"); - } - - /* - * Tests printing an error to the log in the event where there are no - * entities saved in the database - */ - @Test - public void noEntitiesTest() throws Exception { - Properties properties = makeProperties(); - - logger.info("noEntitiesTest: Entering"); - - dbDAO = new DbDAO(resourceName, A_SEQ_PU, properties); - dbDAO.deleteAllIntegrityAuditEntities(); - try { - DbAudit dbAudit = new DbAudit(dbDAO); - dbAudit.dbAudit(resourceName, A_SEQ_PU, nodeType); - fail("found unexpected entities"); - - } catch (DbAuditException e) { - - } - - logger.info("noEntitiesTest: Exit"); - } - - /* - * Tests the detection of only one entry in the database - */ - @Test - public void oneEntityTest() throws Exception { - Properties properties = makeProperties(); - - logger.info("oneEntityTest: Entering"); - - ExtractAppender log = watch(debugLogger, "DbAudit: Found only (one) IntegrityAuditEntity entry:"); - - // Add one entry in the database - dbDAO = new DbDAO(resourceName, A_SEQ_PU, properties); - DbAudit dbAudit = new DbAudit(dbDAO); - dbAudit.dbAudit(resourceName, A_SEQ_PU, nodeType); - - List iaeList = dbDAO.getIntegrityAuditEntities(A_SEQ_PU, nodeType); - logger.info("List size: " + iaeList.size()); - - verifyItemsInLog(log, "one"); - - logger.info("oneEntityTest: Exit"); - } - - /* - * Tests reporting mismatches and missing entries using the error log - */ - @Test - public void mismatchTest() throws Exception { - logger.info("mismatchTest: Entering"); - - // use new URLs so we get a completely new DB - String dbUrl = DbAuditTest.dbUrl + "_mismatchTest"; - String dbUrl2 = dbUrl + "2"; - - Properties properties = makeProperties(); - properties.put(IntegrityAuditProperties.DB_URL, dbUrl); - - // Properties for DB2 - Properties properties2 = makeProperties(); - properties2.put(IntegrityAuditProperties.DB_URL, dbUrl2); - - /* - * We must drop and re-create DB1 so that it's sequence generator is in - * step with the sequence generator for DB2. - */ - recreateDb1(properties); - - // create/open DB2 - createDb(properties2); - - ExtractAppender dbglog = watch(debugLogger, "Mismatched entries [(]keys[)]:(.*)"); - ExtractAppender errlog = watch(errorLogger, "DB Audit: ([0-9])"); - - /* - * Create entries in DB1 & DB2 for the resource of interest - */ - dbDAO = new DbDAO(resourceName, A_SEQ_PU, properties); - - new DbDAO(resourceName, A_SEQ_PU, properties2).destroy(); - - /* - * Entries in DB1, pointing to DB2, except for pdp3 - */ - new DbDAO("pdp2", A_SEQ_PU, properties, dbUrl2).destroy(); - new DbDAO("pdp1", A_SEQ_PU, properties, dbUrl2).destroy(); - new DbDAO("pdp3", A_SEQ_PU, properties).destroy(); // mismatched URL - new DbDAO("pdp4", A_SEQ_PU, properties, dbUrl2).destroy(); - - /* - * Identical entries in DB2, all pointing to DB2, including pdp3, but - * leaving out pdp4 - */ - new DbDAO("pdp2", A_SEQ_PU, properties2).destroy(); - new DbDAO("pdp1", A_SEQ_PU, properties2).destroy(); - new DbDAO("pdp3", A_SEQ_PU, properties2).destroy(); - - /* - * Run the DB Audit, once it finds a mismatch and sleeps, update DB1 to - * have the same entry as DB2 it can be confirmed that the mismatch is - * resolved - */ - DbAudit dbAudit = new DbAudit(dbDAO); - dbAudit.dbAudit(resourceName, A_SEQ_PU, nodeType); - - // update pdp3 entry in DB1 to point to DB2 - new DbDAO("pdp3", A_SEQ_PU, properties, dbUrl2).destroy(); - - /* - * Run the audit again and correct the mismatch, the result should be - * one entry in the mismatchKeySet because of the missing entry from the - * beginning of the test - */ - dbAudit.dbAudit(resourceName, A_SEQ_PU, nodeType); - - assertFalse(dbglog.getExtracted().isEmpty()); - - String mismatchIndex = dbglog.getExtracted().get(dbglog.getExtracted().size() - 1); - int mismatchEntries = mismatchIndex.trim().split(",").length; - logger.info("mismatchTest: mismatchIndex found: '" + mismatchIndex + "'" + " mismatachEntries = " - + mismatchEntries); - - // Assert there is only one entry index - assertEquals(1, mismatchEntries); - - // Now check the entry in the error.log - assertFalse(errlog.getExtracted().isEmpty()); - - String mismatchNum = errlog.getExtracted().get(errlog.getExtracted().size() - 1); - - logger.info("mismatchTest: mismatchNum found: '" + mismatchNum + "'"); - - // Assert that there are a total of 3 mismatches - 1 between each - // comparison node. - assertEquals("3", mismatchNum); - - logger.info("mismatchTest: Exit"); - } - - /** - * Re-creates DB1, using the specified properties. - * @param properties - */ - private void recreateDb1(Properties properties) { - em.close(); - emf.close(); - - createDb(properties); - - em = em2; - emf = emf2; - - em2 = null; - emf2 = null; - } + /** + * Re-creates DB1, using the specified properties. + * + * @param properties the properties + */ + private void recreateDb1(Properties properties) { + em.close(); + emf.close(); + + createDb(properties); + + em = em2; + emf = emf2; + + em2 = null; + emf2 = null; + } } diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/DbDAOTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/DbDAOTest.java index c4cba280..01e2f2b0 100644 --- a/integrity-audit/src/test/java/org/onap/policy/common/ia/DbDAOTest.java +++ b/integrity-audit/src/test/java/org/onap/policy/common/ia/DbDAOTest.java @@ -30,6 +30,7 @@ import static org.junit.Assert.assertTrue; * where they have write privileges and can execute time-sensitive * tasks. */ + import java.util.Date; import java.util.HashSet; import java.util.List; @@ -58,393 +59,399 @@ import org.onap.policy.common.utils.jpa.EntityTransCloser; * tasks. */ public class DbDAOTest extends IntegrityAuditTestBase { - private static String resourceName = "pdp0"; - - private DbDAO d; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - IntegrityAuditTestBase.setUpBeforeClass(DEFAULT_DB_URL_PREFIX + DbDAOTest.class.getSimpleName()); - } - - @AfterClass - public static void tearDownAfterClass() { - IntegrityAuditTestBase.tearDownAfterClass(); - } - - @Before - public void setUp() { - super.setUp(); - d = null; - } - - @After - public void tearDown() { - if(d != null) { - d.destroy(); - } - - super.tearDown(); - } - - /* Tests registering a new IntegrityAuditEntity object in the DB */ - @Test - public void testNewRegistration() throws Exception { - Properties properties = makeProperties(); - - try(EntityTransCloser et = new EntityTransCloser(em.getTransaction())) { - d = new DbDAO(resourceName, A_SEQ_PU, properties); - - // Find the proper entry in the database - Query iaequery = em - .createQuery("Select i from IntegrityAuditEntity i where i.resourceName=:rn and i.persistenceUnit=:pu"); - iaequery.setParameter("rn", DbDAOTest.resourceName); - iaequery.setParameter("pu", DbDAOTest.A_SEQ_PU); - - @SuppressWarnings("rawtypes") - List iaeList = iaequery.getResultList(); - - // Assert that the IntegrityAuditEntity object was found - assertNotNull(iaeList); - - // flush to the DB - em.flush(); - et.commit(); - } - } - - /* - * Tests updating an IntegrityAuditEntity if it has already been registered - */ - @Test - public void testUpdateRegistration() throws Exception { - Properties properties = makeProperties(); - - d = new DbDAO(resourceName, A_SEQ_PU, properties); - - // Change site_name in properties to test that an update was made to - // an existing entry in the table - properties.put(IntegrityAuditProperties.SITE_NAME, "SiteB"); - d = new DbDAO(resourceName, A_SEQ_PU, properties); - - try(EntityTransCloser et = new EntityTransCloser(em.getTransaction())) { - // Find the proper entry in the database - Query iaequery = em - .createQuery("Select i from IntegrityAuditEntity i where i.resourceName=:rn and i.persistenceUnit=:pu"); - iaequery.setParameter("rn", DbDAOTest.resourceName); - iaequery.setParameter("pu", DbDAOTest.A_SEQ_PU); - - @SuppressWarnings("rawtypes") - List iaeList = iaequery.getResultList(); - IntegrityAuditEntity iae = null; - if (!iaeList.isEmpty()) { - // ignores multiple results - iae = (IntegrityAuditEntity) iaeList.get(0); - - em.refresh(iae); - em.persist(iae); - - // flush to the DB - em.flush(); - - // commit transaction - et.commit(); - - // Assert that the site_name for the existing entry was updated - assertEquals("SiteB", iae.getSite()); - } - } - } - - /* Tests obtaining all Integrity Audit Entities from a table */ - @Test - public void testGetIntegrityAuditEntities() throws Exception { - Properties properties = makeProperties(); - - // Add some entries to the DB - d = new DbDAO(resourceName, A_SEQ_PU, properties); - new DbDAO("pdp1", A_SEQ_PU, properties).destroy(); - properties.put(IntegrityAuditProperties.NODE_TYPE, "pdp_drools"); - new DbDAO("pdp2", A_SEQ_PU, properties).destroy(); - - List entities; - // Obtain entries based on persistenceUnit and nodeType - entities = d.getIntegrityAuditEntities(A_SEQ_PU, "pdp_xacml"); - assertEquals(2, entities.size()); - } - - /* Tests retrieving a DbDAO instance's IntegrityAuditEntity */ - @Test - public void testGetMyIntegrityAuditEntity() throws Exception { - Properties properties = makeProperties(); - - d = new DbDAO(resourceName, A_SEQ_PU, properties); - IntegrityAuditEntity iae = d.getMyIntegrityAuditEntity(); - // assertEquals("integrityAuditPU", iae.getPersistenceUnit()); - assertEquals(A_SEQ_PU, iae.getPersistenceUnit()); - } - - /* Tests obtaining an IntegrityAuditEntity by ID */ - @Test - public void testGetIntegrityAuditEntity() throws Exception { - Properties properties = makeProperties(); - - // Obtain an entry from the database based on ID - d = new DbDAO(resourceName, A_SEQ_PU, properties); - - // Find the proper database entry - Query iaequery = em - .createQuery("Select i from IntegrityAuditEntity i where i.resourceName=:rn and i.persistenceUnit=:pu"); - iaequery.setParameter("rn", DbDAOTest.resourceName); - iaequery.setParameter("pu", DbDAOTest.A_SEQ_PU); - - @SuppressWarnings("rawtypes") - List iaeList = iaequery.getResultList(); - IntegrityAuditEntity iae = null; - if (!iaeList.isEmpty()) { - // ignores multiple results - iae = (IntegrityAuditEntity) iaeList.get(0); - - // refresh the object from DB in case cached data was returned - em.refresh(iae); - - // Obtain ID for an IntegrityAuditEntity - PersistenceUnitUtil util = emf.getPersistenceUnitUtil(); - Object iaeId = util.getIdentifier(iae); - - // Obtain the same IntegrityAuditEntity based on ID - IntegrityAuditEntity iaeDuplicate = d.getIntegrityAuditEntity((long) iaeId); - Object duplicateId = util.getIdentifier(iaeDuplicate); - - // Assert that the proper entry was retrieved based on ID - assertEquals((long) iaeId, (long) duplicateId); - } - } - - /* Tests setting an IntegrityAuditEntity as the designated node */ - @Test - public void testSetDesignated() throws Exception { - Properties properties = makeProperties(); - - try(EntityTransCloser et = new EntityTransCloser(em.getTransaction())) { - // Create an entry and set it's designated field to true - d = new DbDAO(resourceName, A_SEQ_PU, properties); - d.setDesignated(resourceName, A_SEQ_PU, true); - - // Find the proper entry in the database - Query iaequery = em - .createQuery("Select i from IntegrityAuditEntity i where i.resourceName=:rn and i.persistenceUnit=:pu"); - iaequery.setParameter("rn", resourceName); - iaequery.setParameter("pu", A_SEQ_PU); - - @SuppressWarnings("rawtypes") - List iaeList = iaequery.getResultList(); - IntegrityAuditEntity iae = null; - - if (!iaeList.isEmpty()) { - // ignores multiple results - iae = (IntegrityAuditEntity) iaeList.get(0); - em.refresh(iae); - - // Check if the node is designated - boolean result = iae.isDesignated(); - - // Assert that it is designated - assertTrue(result); - } - - // flush to the DB - em.flush(); - - // close the transaction - et.commit(); - } - } - - /* Tests that the lastUpdated column in the database is updated properly */ - @Test - public void testSetLastUpdated() throws Exception { - Properties properties = makeProperties(); - - try(EntityTransCloser et = new EntityTransCloser(em.getTransaction())) { - // Create an entry - d = new DbDAO(resourceName, A_SEQ_PU, properties); - - // Find the proper entry in the database - Query iaequery = em - .createQuery("Select i from IntegrityAuditEntity i where i.resourceName=:rn and i.persistenceUnit=:pu"); - iaequery.setParameter("rn", resourceName); - iaequery.setParameter("pu", A_SEQ_PU); - - @SuppressWarnings("rawtypes") - List iaeList = iaequery.getResultList(); - IntegrityAuditEntity iae = null; - - if (!iaeList.isEmpty()) { - // ignores multiple results - iae = (IntegrityAuditEntity) iaeList.get(0); - // refresh the object from DB in case cached data was returned - em.refresh(iae); - - // Obtain old update value and set new update value - Date oldDate = iae.getLastUpdated(); - - // ensure dates are different by sleeping for a bit - Thread.sleep(1); - - iae.setSite("SiteB"); - iae.setLastUpdated(new Date()); - Date newDate = iae.getLastUpdated(); - - em.persist(iae); - // flush to the DB - em.flush(); - // close the transaction - et.commit(); - - // Assert that the old and new update times are different - assertNotEquals(oldDate, newDate); - } - } - } - - /* Tests that all the entries from a class can be retrieved */ - @Test - public void testGetAllMyEntriesString() throws Exception { - Properties properties = makeProperties(); - - // create entries for the IntegrityAuditEntity table - d = new DbDAO(resourceName, A_SEQ_PU, properties); - new DbDAO("pdp1", A_SEQ_PU, properties).destroy(); - new DbDAO("pdp2", A_SEQ_PU, properties).destroy(); - - // Obtain a hash with the persisted objects - Map entries = d.getAllMyEntries("org.onap.policy.common.ia.jpa.IntegrityAuditEntity"); - - // Assert there were 3 entries for that class - assertEquals(3, entries.size()); - } - - /* - * Tests retrieving all entities in a Persistence Unit using the class name - * and a hashset of IDs - */ - @Test - public void testGetAllMyEntriesStringHashSet() throws Exception { - Properties properties = makeProperties(); - - // create entries for the IntegrityAuditEntity table - d = new DbDAO(resourceName, A_SEQ_PU, properties); - new DbDAO("pdp1", A_SEQ_PU, properties).destroy(); - new DbDAO("pdp2", A_SEQ_PU, properties).destroy(); - - // Obtain all entity keys - CriteriaBuilder cb = em.getCriteriaBuilder(); - CriteriaQuery cq = cb.createQuery(); - Root rootEntry = cq.from(Class.forName("org.onap.policy.common.ia.jpa.IntegrityAuditEntity")); - CriteriaQuery all = cq.select(rootEntry); - TypedQuery allQuery = em.createQuery(all); - List objectList = allQuery.getResultList(); - HashSet resultSet = new HashSet(); - PersistenceUnitUtil util = emf.getPersistenceUnitUtil(); - for (Object o : objectList) { - Object key = util.getIdentifier(o); - resultSet.add(key); - } - - // Obtain a hash with the persisted objects - Map entries = d.getAllMyEntries("org.onap.policy.common.ia.jpa.IntegrityAuditEntity", - resultSet); - - // Assert there were 3 entries for that class - assertEquals(3, entries.size()); - } - - /* - * Tests retrieving all entities in a Persistence Unit using the persistence - * unit, properties, and class name - */ - @Test - public void testGetAllEntriesStringPropertiesString() throws Exception { - Properties properties = makeProperties(); - - // create entries for the IntegrityAuditEntity table - d = new DbDAO(resourceName, A_SEQ_PU, properties); - new DbDAO("pdp1", A_SEQ_PU, properties).destroy(); - new DbDAO("pdp2", A_SEQ_PU, properties).destroy(); - - // Obtain a hash with the persisted objects - Map entries = d.getAllEntries("integrityAuditPU", properties, - "org.onap.policy.common.ia.jpa.IntegrityAuditEntity"); - - // Assert there were 3 entries for that class - assertEquals(3, entries.size()); - } - - /* - * Tests retrieving all entities in a Persistence Unit using the persistence - * unit, properties, class name, and a hashset of IDs - */ - @Test - public void testGetAllEntriesStringPropertiesStringHashSet() throws Exception { - Properties properties = makeProperties(); - - // create entries for the IntegrityAuditEntity table - d = new DbDAO(resourceName, A_SEQ_PU, properties); - new DbDAO("pdp1", A_SEQ_PU, properties).destroy(); - new DbDAO("pdp2", A_SEQ_PU, properties).destroy(); - - // Obtain all entity keys - CriteriaBuilder cb = em.getCriteriaBuilder(); - CriteriaQuery cq = cb.createQuery(); - Root rootEntry = cq.from(Class.forName("org.onap.policy.common.ia.jpa.IntegrityAuditEntity")); - CriteriaQuery all = cq.select(rootEntry); - TypedQuery allQuery = em.createQuery(all); - List objectList = allQuery.getResultList(); - HashSet resultSet = new HashSet(); - PersistenceUnitUtil util = emf.getPersistenceUnitUtil(); - for (Object o : objectList) { - Object key = util.getIdentifier(o); - resultSet.add(key); - } - - // Obtain a hash with the persisted objects - Map entries = d.getAllEntries("integrityAuditPU", properties, - "org.onap.policy.common.ia.jpa.IntegrityAuditEntity", resultSet); - - // Assert there were 3 entries for that class - assertEquals(3, entries.size()); - } - - /* - * Tests getting all the entries from a class based on persistenceUnit, - * properties, and className - */ - @Test - public void testGetAllEntries() throws Exception { - Properties properties = makeProperties(); - - // create entries for the IntegrityAuditEntity table - d = new DbDAO(resourceName, A_SEQ_PU, properties); - new DbDAO("pdp1", A_SEQ_PU, properties).destroy(); - new DbDAO("pdp2", A_SEQ_PU, properties).destroy(); - - // Obtain a hash with the persisted objects - Map entries = d.getAllEntries(A_SEQ_PU, properties, - "org.onap.policy.common.ia.jpa.IntegrityAuditEntity"); - - // Assert there were 3 entries for that class - assertEquals(3, entries.size()); - } - - /* Tests obtaining all class names of persisted classes */ - public void testGetPersistenceClassNames() throws Exception { - Properties properties = makeProperties(); - - d = new DbDAO(resourceName, A_SEQ_PU, properties); - - // Retrieve persistence class names - Set result = d.getPersistenceClassNames(); - assertEquals(1, result.size()); - } + private static String resourceName = "pdp0"; + + private DbDAO dbDao; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + IntegrityAuditTestBase.setUpBeforeClass(DEFAULT_DB_URL_PREFIX + DbDAOTest.class.getSimpleName()); + } + + @AfterClass + public static void tearDownAfterClass() { + IntegrityAuditTestBase.tearDownAfterClass(); + } + + @Override + @Before + public void setUp() { + super.setUp(); + dbDao = null; + } + + /** + * Tear down after test cases. + */ + @Override + @After + public void tearDown() { + if (dbDao != null) { + dbDao.destroy(); + } + + super.tearDown(); + } + + /* Tests registering a new IntegrityAuditEntity object in the DB */ + @Test + public void testNewRegistration() throws Exception { + Properties properties = makeProperties(); + + try (EntityTransCloser et = new EntityTransCloser(em.getTransaction())) { + dbDao = new DbDAO(resourceName, A_SEQ_PU, properties); + + // Find the proper entry in the database + Query iaequery = em.createQuery( + "Select i from IntegrityAuditEntity i where i.resourceName=:rn and i.persistenceUnit=:pu"); + iaequery.setParameter("rn", DbDAOTest.resourceName); + iaequery.setParameter("pu", DbDAOTest.A_SEQ_PU); + + @SuppressWarnings("rawtypes") + List iaeList = iaequery.getResultList(); + + // Assert that the IntegrityAuditEntity object was found + assertNotNull(iaeList); + + // flush to the DB + em.flush(); + et.commit(); + } + } + + /* + * Tests updating an IntegrityAuditEntity if it has already been registered + */ + @Test + public void testUpdateRegistration() throws Exception { + Properties properties = makeProperties(); + + dbDao = new DbDAO(resourceName, A_SEQ_PU, properties); + + // Change site_name in properties to test that an update was made to + // an existing entry in the table + properties.put(IntegrityAuditProperties.SITE_NAME, "SiteB"); + dbDao = new DbDAO(resourceName, A_SEQ_PU, properties); + + try (EntityTransCloser et = new EntityTransCloser(em.getTransaction())) { + // Find the proper entry in the database + Query iaequery = em.createQuery( + "Select i from IntegrityAuditEntity i where i.resourceName=:rn and i.persistenceUnit=:pu"); + iaequery.setParameter("rn", DbDAOTest.resourceName); + iaequery.setParameter("pu", DbDAOTest.A_SEQ_PU); + + @SuppressWarnings("rawtypes") + List iaeList = iaequery.getResultList(); + IntegrityAuditEntity iae = null; + if (!iaeList.isEmpty()) { + // ignores multiple results + iae = (IntegrityAuditEntity) iaeList.get(0); + + em.refresh(iae); + em.persist(iae); + + // flush to the DB + em.flush(); + + // commit transaction + et.commit(); + + // Assert that the site_name for the existing entry was updated + assertEquals("SiteB", iae.getSite()); + } + } + } + + /* Tests obtaining all Integrity Audit Entities from a table */ + @Test + public void testGetIntegrityAuditEntities() throws Exception { + Properties properties = makeProperties(); + + // Add some entries to the DB + dbDao = new DbDAO(resourceName, A_SEQ_PU, properties); + new DbDAO("pdp1", A_SEQ_PU, properties).destroy(); + properties.put(IntegrityAuditProperties.NODE_TYPE, "pdp_drools"); + new DbDAO("pdp2", A_SEQ_PU, properties).destroy(); + + List entities; + // Obtain entries based on persistenceUnit and nodeType + entities = dbDao.getIntegrityAuditEntities(A_SEQ_PU, "pdp_xacml"); + assertEquals(2, entities.size()); + } + + /* Tests retrieving a DbDAO instance's IntegrityAuditEntity */ + @Test + public void testGetMyIntegrityAuditEntity() throws Exception { + Properties properties = makeProperties(); + + dbDao = new DbDAO(resourceName, A_SEQ_PU, properties); + IntegrityAuditEntity iae = dbDao.getMyIntegrityAuditEntity(); + // assertEquals("integrityAuditPU", iae.getPersistenceUnit()); + assertEquals(A_SEQ_PU, iae.getPersistenceUnit()); + } + + /* Tests obtaining an IntegrityAuditEntity by ID */ + @Test + public void testGetIntegrityAuditEntity() throws Exception { + Properties properties = makeProperties(); + + // Obtain an entry from the database based on ID + dbDao = new DbDAO(resourceName, A_SEQ_PU, properties); + + // Find the proper database entry + Query iaequery = em + .createQuery("Select i from IntegrityAuditEntity i where i.resourceName=:rn and i.persistenceUnit=:pu"); + iaequery.setParameter("rn", DbDAOTest.resourceName); + iaequery.setParameter("pu", DbDAOTest.A_SEQ_PU); + + @SuppressWarnings("rawtypes") + List iaeList = iaequery.getResultList(); + IntegrityAuditEntity iae = null; + if (!iaeList.isEmpty()) { + // ignores multiple results + iae = (IntegrityAuditEntity) iaeList.get(0); + + // refresh the object from DB in case cached data was returned + em.refresh(iae); + + // Obtain ID for an IntegrityAuditEntity + PersistenceUnitUtil util = emf.getPersistenceUnitUtil(); + Object iaeId = util.getIdentifier(iae); + + // Obtain the same IntegrityAuditEntity based on ID + IntegrityAuditEntity iaeDuplicate = dbDao.getIntegrityAuditEntity((long) iaeId); + Object duplicateId = util.getIdentifier(iaeDuplicate); + + // Assert that the proper entry was retrieved based on ID + assertEquals((long) iaeId, (long) duplicateId); + } + } + + /* Tests setting an IntegrityAuditEntity as the designated node */ + @Test + public void testSetDesignated() throws Exception { + Properties properties = makeProperties(); + + try (EntityTransCloser et = new EntityTransCloser(em.getTransaction())) { + // Create an entry and set it's designated field to true + dbDao = new DbDAO(resourceName, A_SEQ_PU, properties); + dbDao.setDesignated(resourceName, A_SEQ_PU, true); + + // Find the proper entry in the database + Query iaequery = em.createQuery( + "Select i from IntegrityAuditEntity i where i.resourceName=:rn and i.persistenceUnit=:pu"); + iaequery.setParameter("rn", resourceName); + iaequery.setParameter("pu", A_SEQ_PU); + + @SuppressWarnings("rawtypes") + List iaeList = iaequery.getResultList(); + IntegrityAuditEntity iae = null; + + if (!iaeList.isEmpty()) { + // ignores multiple results + iae = (IntegrityAuditEntity) iaeList.get(0); + em.refresh(iae); + + // Check if the node is designated + boolean result = iae.isDesignated(); + + // Assert that it is designated + assertTrue(result); + } + + // flush to the DB + em.flush(); + + // close the transaction + et.commit(); + } + } + + /* Tests that the lastUpdated column in the database is updated properly */ + @Test + public void testSetLastUpdated() throws Exception { + Properties properties = makeProperties(); + + try (EntityTransCloser et = new EntityTransCloser(em.getTransaction())) { + // Create an entry + dbDao = new DbDAO(resourceName, A_SEQ_PU, properties); + + // Find the proper entry in the database + Query iaequery = em.createQuery( + "Select i from IntegrityAuditEntity i where i.resourceName=:rn and i.persistenceUnit=:pu"); + iaequery.setParameter("rn", resourceName); + iaequery.setParameter("pu", A_SEQ_PU); + + @SuppressWarnings("rawtypes") + List iaeList = iaequery.getResultList(); + IntegrityAuditEntity iae = null; + + if (!iaeList.isEmpty()) { + // ignores multiple results + iae = (IntegrityAuditEntity) iaeList.get(0); + // refresh the object from DB in case cached data was returned + em.refresh(iae); + + // Obtain old update value and set new update value + final Date oldDate = iae.getLastUpdated(); + + // ensure dates are different by sleeping for a bit + Thread.sleep(1); + + iae.setSite("SiteB"); + iae.setLastUpdated(new Date()); + final Date newDate = iae.getLastUpdated(); + + em.persist(iae); + // flush to the DB + em.flush(); + // close the transaction + et.commit(); + + // Assert that the old and new update times are different + assertNotEquals(oldDate, newDate); + } + } + } + + /* Tests that all the entries from a class can be retrieved */ + @Test + public void testGetAllMyEntriesString() throws Exception { + Properties properties = makeProperties(); + + // create entries for the IntegrityAuditEntity table + dbDao = new DbDAO(resourceName, A_SEQ_PU, properties); + new DbDAO("pdp1", A_SEQ_PU, properties).destroy(); + new DbDAO("pdp2", A_SEQ_PU, properties).destroy(); + + // Obtain a hash with the persisted objects + Map entries = dbDao.getAllMyEntries("org.onap.policy.common.ia.jpa.IntegrityAuditEntity"); + + // Assert there were 3 entries for that class + assertEquals(3, entries.size()); + } + + /* + * Tests retrieving all entities in a Persistence Unit using the class name and a hashset of IDs + */ + @Test + public void testGetAllMyEntriesStringHashSet() throws Exception { + Properties properties = makeProperties(); + + // create entries for the IntegrityAuditEntity table + dbDao = new DbDAO(resourceName, A_SEQ_PU, properties); + new DbDAO("pdp1", A_SEQ_PU, properties).destroy(); + new DbDAO("pdp2", A_SEQ_PU, properties).destroy(); + + // Obtain all entity keys + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery cq = cb.createQuery(); + Root rootEntry = cq.from(Class.forName("org.onap.policy.common.ia.jpa.IntegrityAuditEntity")); + CriteriaQuery all = cq.select(rootEntry); + TypedQuery allQuery = em.createQuery(all); + List objectList = allQuery.getResultList(); + HashSet resultSet = new HashSet(); + PersistenceUnitUtil util = emf.getPersistenceUnitUtil(); + for (Object o : objectList) { + Object key = util.getIdentifier(o); + resultSet.add(key); + } + + // Obtain a hash with the persisted objects + Map entries = + dbDao.getAllMyEntries("org.onap.policy.common.ia.jpa.IntegrityAuditEntity", resultSet); + + // Assert there were 3 entries for that class + assertEquals(3, entries.size()); + } + + /* + * Tests retrieving all entities in a Persistence Unit using the persistence unit, properties, + * and class name + */ + @Test + public void testGetAllEntriesStringPropertiesString() throws Exception { + Properties properties = makeProperties(); + + // create entries for the IntegrityAuditEntity table + dbDao = new DbDAO(resourceName, A_SEQ_PU, properties); + new DbDAO("pdp1", A_SEQ_PU, properties).destroy(); + new DbDAO("pdp2", A_SEQ_PU, properties).destroy(); + + // Obtain a hash with the persisted objects + Map entries = dbDao.getAllEntries("integrityAuditPU", properties, + "org.onap.policy.common.ia.jpa.IntegrityAuditEntity"); + + // Assert there were 3 entries for that class + assertEquals(3, entries.size()); + } + + /* + * Tests retrieving all entities in a Persistence Unit using the persistence unit, properties, + * class name, and a hashset of IDs + */ + @Test + public void testGetAllEntriesStringPropertiesStringHashSet() throws Exception { + Properties properties = makeProperties(); + + // create entries for the IntegrityAuditEntity table + dbDao = new DbDAO(resourceName, A_SEQ_PU, properties); + new DbDAO("pdp1", A_SEQ_PU, properties).destroy(); + new DbDAO("pdp2", A_SEQ_PU, properties).destroy(); + + // Obtain all entity keys + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery cq = cb.createQuery(); + Root rootEntry = cq.from(Class.forName("org.onap.policy.common.ia.jpa.IntegrityAuditEntity")); + CriteriaQuery all = cq.select(rootEntry); + TypedQuery allQuery = em.createQuery(all); + List objectList = allQuery.getResultList(); + HashSet resultSet = new HashSet(); + PersistenceUnitUtil util = emf.getPersistenceUnitUtil(); + for (Object o : objectList) { + Object key = util.getIdentifier(o); + resultSet.add(key); + } + + // Obtain a hash with the persisted objects + Map entries = dbDao.getAllEntries("integrityAuditPU", properties, + "org.onap.policy.common.ia.jpa.IntegrityAuditEntity", resultSet); + + // Assert there were 3 entries for that class + assertEquals(3, entries.size()); + } + + /* + * Tests getting all the entries from a class based on persistenceUnit, properties, and + * className + */ + @Test + public void testGetAllEntries() throws Exception { + Properties properties = makeProperties(); + + // create entries for the IntegrityAuditEntity table + dbDao = new DbDAO(resourceName, A_SEQ_PU, properties); + new DbDAO("pdp1", A_SEQ_PU, properties).destroy(); + new DbDAO("pdp2", A_SEQ_PU, properties).destroy(); + + // Obtain a hash with the persisted objects + Map entries = + dbDao.getAllEntries(A_SEQ_PU, properties, "org.onap.policy.common.ia.jpa.IntegrityAuditEntity"); + + // Assert there were 3 entries for that class + assertEquals(3, entries.size()); + } + + /** + * Tests obtaining all class names of persisted classes. + */ + public void testGetPersistenceClassNames() throws Exception { + Properties properties = makeProperties(); + + dbDao = new DbDAO(resourceName, A_SEQ_PU, properties); + + // Retrieve persistence class names + Set result = dbDao.getPersistenceClassNames(); + assertEquals(1, result.size()); + } } diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/ExceptionsTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/ExceptionsTest.java index b02b0c7f..3c8ce528 100644 --- a/integrity-audit/src/test/java/org/onap/policy/common/ia/ExceptionsTest.java +++ b/integrity-audit/src/test/java/org/onap/policy/common/ia/ExceptionsTest.java @@ -23,10 +23,6 @@ package org.onap.policy.common.ia; import static org.junit.Assert.assertEquals; import org.junit.Test; -import org.onap.policy.common.ia.DbAuditException; -import org.onap.policy.common.ia.DbDaoTransactionException; -import org.onap.policy.common.ia.IntegrityAuditException; -import org.onap.policy.common.ia.IntegrityAuditPropertiesException; import org.onap.policy.common.utils.test.ExceptionsTester; /** @@ -34,23 +30,23 @@ import org.onap.policy.common.utils.test.ExceptionsTester; */ public class ExceptionsTest extends ExceptionsTester { - @Test - public void testDbAuditException() throws Exception { - assertEquals(4, test(DbAuditException.class)); - } - - @Test - public void testDbDaoTransactionException() throws Exception { - assertEquals(4, test(DbDaoTransactionException.class)); - } - - @Test - public void testIntegrityAuditException() throws Exception { - assertEquals(4, test(IntegrityAuditException.class)); - } - - @Test - public void testIntegrityAuditPropertiesException() throws Exception { - assertEquals(4, test(IntegrityAuditPropertiesException.class)); - } + @Test + public void testDbAuditException() throws Exception { + assertEquals(4, test(DbAuditException.class)); + } + + @Test + public void testDbDaoTransactionException() throws Exception { + assertEquals(4, test(DbDaoTransactionException.class)); + } + + @Test + public void testIntegrityAuditException() throws Exception { + assertEquals(4, test(IntegrityAuditException.class)); + } + + @Test + public void testIntegrityAuditPropertiesException() throws Exception { + assertEquals(4, test(IntegrityAuditPropertiesException.class)); + } } diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditDesignationTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditDesignationTest.java index 1861787a..69f37da5 100644 --- a/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditDesignationTest.java +++ b/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditDesignationTest.java @@ -30,590 +30,573 @@ import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.common.utils.test.log.logback.ExtractAppender; /** - * All JUnits are designed to run in the local development environment where - * they have write privileges and can execute time-sensitive tasks. - *

- * Many of the test verification steps are performed by scanning for items - * written to the log file. Rather than actually scan the log file, an - * {@link ExtractAppender} is used to monitor events that are logged and extract - * relevant items. In order to attach the appender to the debug log, it assumes - * that the debug log is a logback Logger configured per EELF. - *

- * These tests use a temporary, in-memory DB, which is dropped once the tests - * complete. + * All JUnits are designed to run in the local development environment where they have write + * privileges and can execute time-sensitive tasks. + * + *

Many of the test verification steps are performed by scanning for items written to the log + * file. Rather than actually scan the log file, an {@link ExtractAppender} is used to monitor + * events that are logged and extract relevant items. In order to attach the appender to the debug + * log, it assumes that the debug log is a logback Logger configured per EELF. + * + *

These tests use a temporary, in-memory DB, which is dropped once the tests complete. */ public class IntegrityAuditDesignationTest extends IntegrityAuditTestBase { - private static Logger logger = FlexLogger.getLogger(IntegrityAuditDesignationTest.class); - - /** - * Matches specified PDPs in the debug log. A regular expression matching - * the desired PDPs should be appended, followed by a right parenthesis. For - * example: - * - *

-	 * new ExtractAppender(START_AUDIT_RE_PREFIX + "pdp[124])")
-	 * 
-	 * 
- */ - private static final String START_AUDIT_RE_PREFIX = "Starting audit simulation for resourceName=("; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - IntegrityAuditTestBase - .setUpBeforeClass(DEFAULT_DB_URL_PREFIX + IntegrityAuditDesignationTest.class.getSimpleName()); - } - - @AfterClass - public static void tearDownAfterClass() { - IntegrityAuditTestBase.tearDownAfterClass(); - } - - @Before - public void setUp() { - logger.info("setUp: Entering"); - - super.setUp(); - - logger.info("setUp: Exiting"); - } - - @After - public void tearDown() { - logger.info("tearDown: Entering"); - - super.tearDown(); - - logger.info("tearDown: Exiting"); - - } - - /* - * Tests designation logic when only one functioning resource is in play. - * Designation should stay with single resource. - * - * Note: console.log must be examined to ascertain whether or not this test - * was successful. - */ - @Test - public void testOneResource() throws Exception { - - logger.info("testOneResource: Entering"); - - ExtractAppender logA = watch(debugLogger, START_AUDIT_RE); - - MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU); - - /* - * Wait for - * - * 1) pdp1 to run audit - * - * 2) Logic to detect that no other node is available for designation - * - * 3) pdp1 to run audit again - */ - runAudit(integrityAudit); - waitStaleAndRun(integrityAudit); - - logger.info("testOneResource: Stopping audit thread"); - integrityAudit.stopAuditThread(); - - verifyItemsInLog(logA, "pdp1"); - - /* - * Test fix for ONAPD2TD-783: Audit fails to run when application is - * restarted. - */ - integrityAudit.startAuditThread(); - - /* - * Sleep long enough to allow - * - * 1) pdp1 to run audit - * - * 2) Logic to detect that no other node is available for designation - * - * 3) pdp1 to run audit again - */ - runAudit(integrityAudit); - waitStaleAndRun(integrityAudit); - - verifyItemsInLog(logA, "pdp1"); - - logger.info("testOneResource: Exiting"); - - } - - /* - * Tests designation logic when two functioning resources are in play. - * Designation should alternate between resources. - * - * Note: console.log must be examined to ascertain whether or not this test - * was successful. A quick way of examining the log is to search for the - * string "audit simulation": - * - * As you can see from the "dbAuditSimulate" method, when it executes, it - * logs the "Starting audit simulation..." message and when it finishes, it - * logs the "Finished audit simulation..." message. By looking for these - * messages, you can verify that the audits are run by the proper resource. - * For example, when testFourResourcesOneDead is run, you should see a - * Starting.../Finished... sequence for "pdp1", followed by a - * Starting.../Finished... sequence for pdp2, followed by a - * Starting.../Finished... sequence for pdp4 (pdp3 is skipped as it's - * dead/hung), followed by a Starting.../Finished... sequence for "pdp1", - * etc. - */ - @Test - public void testTwoResources() throws Exception { - - logger.info("testTwoResources: Entering"); - - ExtractAppender logA = watch(debugLogger, START_AUDIT_RE); - - /* - * Start audit for pdp1. - */ - MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU); - - /* - * Start audit for pdp2. - */ - MyIntegrityAudit integrityAudit2 = makeAuditor("pdp2", A_SEQ_PU); - - /* - * Sleep long enough to allow - * - * 1) pdp1 to run audit - * - * 2) Logic to detect that pdp1 is stale and designate pdp2 - * - * 3) pdp2 to run audit - * - * 4) Logic to detect that pdp2 is stale and designate pdp1 - * - * 5) pdp1 to run audit - */ - runAudit(integrityAudit); - waitStaleAndRun(integrityAudit2); - waitStaleAndRun(integrityAudit); - - verifyItemsInLog(logA, "pdp1", "pdp2", "pdp1"); - - logger.info("testTwoResources: Exiting"); - - } - - /* - * Tests designation logic when two functioning resources are in play, each - * with different PUs. Audits for persistenceUnit and PU_B should run - * simultaneously. Designation should not alternate. - * - * Note: console.log must be examined to ascertain whether or not this test - * was successful. - */ - @Test - public void testTwoResourcesDifferentPus() throws Exception { - - logger.info("testTwoResourcesDifferentPus: Entering"); - - ExtractAppender logA = watch(debugLogger, START_AUDIT_RE_PREFIX + "pdp1)"); - ExtractAppender logB = watch(debugLogger, START_AUDIT_RE_PREFIX + "pdp2)"); - - /* - * Start audit for pdp1. - */ - MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU); - - /* - * Start audit for pdp2. - */ - MyIntegrityAudit integrityAudit2 = makeAuditor("pdp2", B_SEQ_PU); - - /* - * Sleep long enough to allow - * - * 1) pdp1 and pdp2 to run audit simultaneously - * - * 2) Logic to detect that no other node is available for designation - * for either pdp1 or pdp2 - * - * 3) pdp1 and pdp2 to again run audit simultaneously - */ - runAudit(integrityAudit, integrityAudit2); - waitStaleAndRun(integrityAudit, integrityAudit2); - - verifyItemsInLog(logA, "pdp1", "pdp1"); - verifyItemsInLog(logB, "pdp2", "pdp2"); - - logger.info("testTwoResourcesDifferentPus: Exiting"); - - } - - /* - * Tests designation logic when two resources are in play but one of them is - * dead/hung. Designation should move to second resource but then get - * restored back to original resource when it's discovered that second - * resource is dead. - * - * Note: console.log must be examined to ascertain whether or not this test - * was successful. - */ - @Test - public void testTwoResourcesOneDead() throws Exception { - - logger.info("testTwoResourcesOneDead: Entering"); - - ExtractAppender logA = watch(debugLogger, START_AUDIT_RE); - - /* - * Start audit for pdp1. - */ - MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU); - - /* - * Populate DB for pdp2, which will simulate it having registered but - * then having died. - */ - new DbDAO("pdp2", A_SEQ_PU, makeProperties()).destroy(); - - /* - * Sleep long enough to allow - * - * 1) pdp1 to run audit - * - * 2) Logic to detect that other node, pdp2, is not available for - * designation - * - * 3) pdp1 to run audit again - */ - runAudit(integrityAudit); - waitStaleAndRun(integrityAudit); - - verifyItemsInLog(logA, "pdp1", "pdp1"); - - logger.info("testTwoResourcesOneDead: Exiting"); - - } - - /* - * Tests designation logic when three functioning resources are in play. - * Designation should round robin among resources. - * - * Note: console.log must be examined to ascertain whether or not this test - * was successful. - */ - @Test - public void testThreeResources() throws Exception { - - logger.info("testThreeResources: Entering"); - - ExtractAppender logA = watch(debugLogger, START_AUDIT_RE); - - /* - * Start audit for pdp1. - */ - MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU); - - /* - * Start audit for pdp2. - */ - MyIntegrityAudit integrityAudit2 = makeAuditor("pdp2", A_SEQ_PU); - - /* - * Start audit for pdp3. - */ - MyIntegrityAudit integrityAudit3 = makeAuditor("pdp3", A_SEQ_PU); - - /* - * Sleep long enough to allow - * - * 1) pdp1 to run audit - * - * 2) Logic to detect that pdp1 is stale and designate pdp2 - * - * 3) pdp2 to run audit - * - * 4) Logic to detect that pdp2 is stale and designate pdp3 - * - * 5) pdp3 to run audit - * - * 6) Logic to detect that pdp3 is stale and designate pdp1 - * - * 7) pdp1 to run audit - */ - runAudit(integrityAudit); - waitStaleAndRun(integrityAudit2); - waitStaleAndRun(integrityAudit3); - waitStaleAndRun(integrityAudit); - - verifyItemsInLog(logA, "pdp1", "pdp2", "pdp3", "pdp1"); - - logger.info("testThreeResources: Exiting"); - - } - - /* - * Tests designation logic when four functioning resources are in play, two - * with one PU, two with another. Audits for persistenceUnit and PU_B should - * run simultaneously. Designation should alternate between resources for - * each of the two persistence units. - * - * Note: console.log must be examined to ascertain whether or not this test - * was successful. - */ - @Test - public void testFourResourcesDifferentPus() throws Exception { - - logger.info("testFourResourcesDifferentPus: Entering"); - - ExtractAppender logA = watch(debugLogger, START_AUDIT_RE_PREFIX + "pdp1|pdp3)"); - ExtractAppender logB = watch(debugLogger, START_AUDIT_RE_PREFIX + "pdp2|pdp4)"); - - /* - * Start audit for "pdp1", testPU. - */ - MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU); - - /* - * Start audit for pdp2, integrityAuditPU. - */ - MyIntegrityAudit integrityAudit2 = makeAuditor("pdp2", B_SEQ_PU); - - /* - * Start audit for pdp3, testPU. - */ - MyIntegrityAudit integrityAudit3 = makeAuditor("pdp3", A_SEQ_PU); - - /* - * Start audit for pdp4, integrityAuditPU. - */ - MyIntegrityAudit integrityAudit4 = makeAuditor("pdp4", B_SEQ_PU); - - /* - * Sleep long enough to allow - * - * 1) pdp1 and pdp2 to run audit simultaneously - * - * 2) Logic to detect that pdp1 and pdp2 are stale and designate pdp3 - * (one's counterpart) and pdp4 (two's counterpart) - * - * 3) pdp3 and pdp4 to run audit simultaneously - * - * 4) Logic to detect that pdp3 and pdp4 are stale and designate pdp1 - * (three's counterpart) and pdp2 (four's counterpart) - * - * 5) pdp1 and pdp2 to run audit simultaneously - */ - runAudit(integrityAudit, integrityAudit2); - waitStaleAndRun(integrityAudit3, integrityAudit4); - waitStaleAndRun(integrityAudit, integrityAudit2); - - /* - * These sequences may be intermingled, so we extract and compare one - * sequence at a time. - */ - - // only care about pdp1 & pdp3 in this sequence - verifyItemsInLog(logA, "pdp1", "pdp3", "pdp1"); - - // only care about pdp2 & pdp4 in this sequence - verifyItemsInLog(logB, "pdp2", "pdp4", "pdp2"); - - logger.info("testFourResourcesDifferentPus: Exiting"); - - } - - /* - * Tests designation logic when four resources are in play but one is not - * functioning. Designation should round robin among functioning resources - * only. - * - * Note: console.log must be examined to ascertain whether or not this test - * was successful. - */ - @Test - public void testFourResourcesOneDead() throws Exception { - - logger.info("testFourResourcesOneDead: Entering"); - - ExtractAppender logA = watch(debugLogger, START_AUDIT_RE); - - /* - * Start audit for pdp1. - */ - MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU); - - /* - * Start audit for pdp2. - */ - MyIntegrityAudit integrityAudit2 = makeAuditor("pdp2", A_SEQ_PU); - - /* - * Populate DB for pdp3, which will simulate it having registered but - * then having died. - */ - new DbDAO("pdp3", A_SEQ_PU, makeProperties()).destroy(); - - /* - * Start audit for pdp4. - */ - MyIntegrityAudit integrityAudit4 = makeAuditor("pdp4", A_SEQ_PU); - - /* - * Sleep long enough to allow - * - * 1) pdp1 to run audit - * - * 2) Logic to detect that pdp1 is stale and designate pdp2 - * - * 3) pdp2 to run audit - * - * 4) Logic to detect that pdp2 is stale and designate pdp4 - * - * 5) pdp4 to run audit - * - * 6) Logic to detect that pdp4 is stale and designate pdp1 - * - * 7) pdp1 to run audit - * - * 8) Logic to detect that pdp1 is stale and designate pdp2 - * - * 7) pdp2 to run audit - */ - runAudit(integrityAudit); - waitStaleAndRun(integrityAudit2); - waitStaleAndRun(integrityAudit4); - waitStaleAndRun(integrityAudit); - waitStaleAndRun(integrityAudit2); - waitStaleAndRun(integrityAudit4); - - verifyItemsInLog(logA, "pdp1", "pdp2", "pdp4", "pdp1", "pdp2", "pdp4"); - - logger.info("testFourResourcesOneDead: Exiting"); - - } - - /* - * Tests designation logic when four resources are in play but only one is - * functioning. Designation should remain with sole functioning resource. - * - * Note: console.log must be examined to ascertain whether or not this test - * was successful. - */ - @Test - public void testFourResourcesThreeDead() throws Exception { - - logger.info("testFourResourcesThreeDead: Entering"); - - ExtractAppender logA = watch(debugLogger, START_AUDIT_RE); - - /* - * Populate DB for "pdp1", which will simulate it having registered but - * then having died. - */ - new DbDAO("pdp1", A_SEQ_PU, makeProperties()).destroy(); - - /* - * Populate DB for pdp2, which will simulate it having registered but - * then having died. - */ - new DbDAO("pdp2", A_SEQ_PU, makeProperties()).destroy(); - - /* - * Start audit for pdp3. - */ - MyIntegrityAudit integrityAudit3 = makeAuditor("pdp3", A_SEQ_PU); - - /* - * Populate DB for pdp4, which will simulate it having registered but - * then having died. - */ - new DbDAO("pdp4", A_SEQ_PU, makeProperties()).destroy(); - - /* - * Sleep long enough to allow - * - * 1) pdp3 to discover that all other designation candidates are stale - * - * 1) pdp3 to run audit - * - * 2) Logic to detect that no other nodes are available for designation - * - * 3) pdp3 to run audit again - */ - runAudit(integrityAudit3); - waitStaleAndRun(integrityAudit3); - - verifyItemsInLog(logA, "pdp3", "pdp3"); - - logger.info("testFourResourcesThreeDead: Exiting"); - - } - - /* - * Tests designation logic when the designated node dies and is no longer - * current - * - * Note: console.log must be examined to ascertain whether or not this test - * was successful. - */ - @Test - public void testDesignatedNodeDead() throws Exception { - logger.info("testDesignatedNodeDead: Entering"); - - ExtractAppender logA = watch(debugLogger, START_AUDIT_RE); - - /* - * Instantiate audit object for pdp1. - */ - MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU); - - /* - * Start audit for pdp2. - */ - MyIntegrityAudit integrityAudit2 = makeAuditor("pdp2", A_SEQ_PU); - - /* - * Instantiate audit object for pdp3. - */ - MyIntegrityAudit integrityAudit3 = makeAuditor("pdp3", A_SEQ_PU); - - // Start audit on pdp1 - logger.info("testDesignatedNodeDead: Start audit on pdp1"); - runAudit(integrityAudit); - - // Start the auditing threads on other nodes. - logger.info("testDesignatedNodeDead: Start audit on pdp2"); - runAudit(integrityAudit2); - - // Kill audit on pdp1 - logger.info("testDesignatedNodeDead: Kill audit on pdp1"); - integrityAudit.stopAuditThread(); - - // Wait long enough for pdp1 to get stale and pdp2 to take over - waitStaleAndRun(integrityAudit2); - - // Start audit thread on pdp1 again. - logger.info("testDesignatedNodeDead: Start audit thread on pdp1 again."); - integrityAudit.startAuditThread(); - - // Wait long enough for pdp2 to complete its audit and get stale, at - // which point pdp3 should take over - logger.info( - "testDesignatedNodeDead: Wait long enough for pdp2 to complete its audit and get stale, at which point pdp3 should take over"); - waitStaleAndRun(integrityAudit3); - - // Kill audit on pdp3 - logger.info("testDesignatedNodeDead: Killing audit on pdp3"); - integrityAudit3.stopAuditThread(); - - // Wait long enough for pdp3 to get stale and pdp1 to take over - logger.info("testDesignatedNodeDead: Wait long enough for pdp3 to get stale and pdp1 to take over"); - waitStaleAndRun(integrityAudit); - - verifyItemsInLog(logA, "pdp1", "pdp2", "pdp3", "pdp1"); - - logger.info("testDesignatedNodeDead: Exiting"); - } + private static Logger logger = FlexLogger.getLogger(IntegrityAuditDesignationTest.class); + + /** + * Matches specified PDPs in the debug log. A regular expression matching the desired PDPs + * should be appended, followed by a right parenthesis. For example: + * + *
+     * new ExtractAppender(START_AUDIT_RE_PREFIX + "pdp[124])")
+     * 
+     * 
+ */ + private static final String START_AUDIT_RE_PREFIX = "Starting audit simulation for resourceName=("; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + IntegrityAuditTestBase + .setUpBeforeClass(DEFAULT_DB_URL_PREFIX + IntegrityAuditDesignationTest.class.getSimpleName()); + } + + @AfterClass + public static void tearDownAfterClass() { + IntegrityAuditTestBase.tearDownAfterClass(); + } + + /** + * Set up before test cases. + */ + @Override + @Before + public void setUp() { + logger.info("setUp: Entering"); + + super.setUp(); + + logger.info("setUp: Exiting"); + } + + /** + * Tear down after test cases. + */ + @Override + @After + public void tearDown() { + logger.info("tearDown: Entering"); + + super.tearDown(); + + logger.info("tearDown: Exiting"); + + } + + /* + * Tests designation logic when only one functioning resource is in play. Designation should + * stay with single resource. + * + * Note: console.log must be examined to ascertain whether or not this test was successful. + */ + @Test + public void testOneResource() throws Exception { + + logger.info("testOneResource: Entering"); + + final ExtractAppender logA = watch(debugLogger, START_AUDIT_RE); + + MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU); + + /* + * Wait for + * + * 1) pdp1 to run audit + * + * 2) Logic to detect that no other node is available for designation + * + * 3) pdp1 to run audit again + */ + runAudit(integrityAudit); + waitStaleAndRun(integrityAudit); + + logger.info("testOneResource: Stopping audit thread"); + integrityAudit.stopAuditThread(); + + verifyItemsInLog(logA, "pdp1"); + + /* + * Test fix for ONAPD2TD-783: Audit fails to run when application is restarted. + */ + integrityAudit.startAuditThread(); + + /* + * Sleep long enough to allow + * + * 1) pdp1 to run audit + * + * 2) Logic to detect that no other node is available for designation + * + * 3) pdp1 to run audit again + */ + runAudit(integrityAudit); + waitStaleAndRun(integrityAudit); + + verifyItemsInLog(logA, "pdp1"); + + logger.info("testOneResource: Exiting"); + + } + + /* + * Tests designation logic when two functioning resources are in play. Designation should + * alternate between resources. + * + * Note: console.log must be examined to ascertain whether or not this test was successful. A + * quick way of examining the log is to search for the string "audit simulation": + * + * As you can see from the "dbAuditSimulate" method, when it executes, it logs the + * "Starting audit simulation..." message and when it finishes, it logs the + * "Finished audit simulation..." message. By looking for these messages, you can verify that + * the audits are run by the proper resource. For example, when testFourResourcesOneDead is run, + * you should see a Starting.../Finished... sequence for "pdp1", followed by a + * Starting.../Finished... sequence for pdp2, followed by a Starting.../Finished... sequence for + * pdp4 (pdp3 is skipped as it's dead/hung), followed by a Starting.../Finished... sequence for + * "pdp1", etc. + */ + @Test + public void testTwoResources() throws Exception { + + logger.info("testTwoResources: Entering"); + + final ExtractAppender logA = watch(debugLogger, START_AUDIT_RE); + + /* + * Start audit for pdp1. + */ + MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU); + + /* + * Start audit for pdp2. + */ + MyIntegrityAudit integrityAudit2 = makeAuditor("pdp2", A_SEQ_PU); + + /* + * Sleep long enough to allow + * + * 1) pdp1 to run audit + * + * 2) Logic to detect that pdp1 is stale and designate pdp2 + * + * 3) pdp2 to run audit + * + * 4) Logic to detect that pdp2 is stale and designate pdp1 + * + * 5) pdp1 to run audit + */ + runAudit(integrityAudit); + waitStaleAndRun(integrityAudit2); + waitStaleAndRun(integrityAudit); + + verifyItemsInLog(logA, "pdp1", "pdp2", "pdp1"); + + logger.info("testTwoResources: Exiting"); + + } + + /* + * Tests designation logic when two functioning resources are in play, each with different PUs. + * Audits for persistenceUnit and PU_B should run simultaneously. Designation should not + * alternate. + * + * Note: console.log must be examined to ascertain whether or not this test was successful. + */ + @Test + public void testTwoResourcesDifferentPus() throws Exception { + + logger.info("testTwoResourcesDifferentPus: Entering"); + + final ExtractAppender logA = watch(debugLogger, START_AUDIT_RE_PREFIX + "pdp1)"); + final ExtractAppender logB = watch(debugLogger, START_AUDIT_RE_PREFIX + "pdp2)"); + + /* + * Start audit for pdp1. + */ + MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU); + + /* + * Start audit for pdp2. + */ + MyIntegrityAudit integrityAudit2 = makeAuditor("pdp2", B_SEQ_PU); + + /* + * Sleep long enough to allow + * + * 1) pdp1 and pdp2 to run audit simultaneously + * + * 2) Logic to detect that no other node is available for designation for either pdp1 or + * pdp2 + * + * 3) pdp1 and pdp2 to again run audit simultaneously + */ + runAudit(integrityAudit, integrityAudit2); + waitStaleAndRun(integrityAudit, integrityAudit2); + + verifyItemsInLog(logA, "pdp1", "pdp1"); + verifyItemsInLog(logB, "pdp2", "pdp2"); + + logger.info("testTwoResourcesDifferentPus: Exiting"); + + } + + /* + * Tests designation logic when two resources are in play but one of them is dead/hung. + * Designation should move to second resource but then get restored back to original resource + * when it's discovered that second resource is dead. + * + * Note: console.log must be examined to ascertain whether or not this test was successful. + */ + @Test + public void testTwoResourcesOneDead() throws Exception { + + logger.info("testTwoResourcesOneDead: Entering"); + + final ExtractAppender logA = watch(debugLogger, START_AUDIT_RE); + + /* + * Start audit for pdp1. + */ + MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU); + + /* + * Populate DB for pdp2, which will simulate it having registered but then having died. + */ + new DbDAO("pdp2", A_SEQ_PU, makeProperties()).destroy(); + + /* + * Sleep long enough to allow + * + * 1) pdp1 to run audit + * + * 2) Logic to detect that other node, pdp2, is not available for designation + * + * 3) pdp1 to run audit again + */ + runAudit(integrityAudit); + waitStaleAndRun(integrityAudit); + + verifyItemsInLog(logA, "pdp1", "pdp1"); + + logger.info("testTwoResourcesOneDead: Exiting"); + + } + + /* + * Tests designation logic when three functioning resources are in play. Designation should + * round robin among resources. + * + * Note: console.log must be examined to ascertain whether or not this test was successful. + */ + @Test + public void testThreeResources() throws Exception { + + logger.info("testThreeResources: Entering"); + + final ExtractAppender logA = watch(debugLogger, START_AUDIT_RE); + + /* + * Start audit for pdp1. + */ + MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU); + + /* + * Start audit for pdp2. + */ + MyIntegrityAudit integrityAudit2 = makeAuditor("pdp2", A_SEQ_PU); + + /* + * Start audit for pdp3. + */ + MyIntegrityAudit integrityAudit3 = makeAuditor("pdp3", A_SEQ_PU); + + /* + * Sleep long enough to allow + * + * 1) pdp1 to run audit + * + * 2) Logic to detect that pdp1 is stale and designate pdp2 + * + * 3) pdp2 to run audit + * + * 4) Logic to detect that pdp2 is stale and designate pdp3 + * + * 5) pdp3 to run audit + * + * 6) Logic to detect that pdp3 is stale and designate pdp1 + * + * 7) pdp1 to run audit + */ + runAudit(integrityAudit); + waitStaleAndRun(integrityAudit2); + waitStaleAndRun(integrityAudit3); + waitStaleAndRun(integrityAudit); + + verifyItemsInLog(logA, "pdp1", "pdp2", "pdp3", "pdp1"); + + logger.info("testThreeResources: Exiting"); + + } + + /* + * Tests designation logic when four functioning resources are in play, two with one PU, two + * with another. Audits for persistenceUnit and PU_B should run simultaneously. Designation + * should alternate between resources for each of the two persistence units. + * + * Note: console.log must be examined to ascertain whether or not this test was successful. + */ + @Test + public void testFourResourcesDifferentPus() throws Exception { + + logger.info("testFourResourcesDifferentPus: Entering"); + + final ExtractAppender logA = watch(debugLogger, START_AUDIT_RE_PREFIX + "pdp1|pdp3)"); + final ExtractAppender logB = watch(debugLogger, START_AUDIT_RE_PREFIX + "pdp2|pdp4)"); + + /* + * Start audit for "pdp1", testPU. + */ + MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU); + + /* + * Start audit for pdp2, integrityAuditPU. + */ + MyIntegrityAudit integrityAudit2 = makeAuditor("pdp2", B_SEQ_PU); + + /* + * Start audit for pdp3, testPU. + */ + MyIntegrityAudit integrityAudit3 = makeAuditor("pdp3", A_SEQ_PU); + + /* + * Start audit for pdp4, integrityAuditPU. + */ + MyIntegrityAudit integrityAudit4 = makeAuditor("pdp4", B_SEQ_PU); + + /* + * Sleep long enough to allow + * + * 1) pdp1 and pdp2 to run audit simultaneously + * + * 2) Logic to detect that pdp1 and pdp2 are stale and designate pdp3 (one's counterpart) + * and pdp4 (two's counterpart) + * + * 3) pdp3 and pdp4 to run audit simultaneously + * + * 4) Logic to detect that pdp3 and pdp4 are stale and designate pdp1 (three's counterpart) + * and pdp2 (four's counterpart) + * + * 5) pdp1 and pdp2 to run audit simultaneously + */ + runAudit(integrityAudit, integrityAudit2); + waitStaleAndRun(integrityAudit3, integrityAudit4); + waitStaleAndRun(integrityAudit, integrityAudit2); + + /* + * These sequences may be intermingled, so we extract and compare one sequence at a time. + */ + + // only care about pdp1 & pdp3 in this sequence + verifyItemsInLog(logA, "pdp1", "pdp3", "pdp1"); + + // only care about pdp2 & pdp4 in this sequence + verifyItemsInLog(logB, "pdp2", "pdp4", "pdp2"); + + logger.info("testFourResourcesDifferentPus: Exiting"); + + } + + /* + * Tests designation logic when four resources are in play but one is not functioning. + * Designation should round robin among functioning resources only. + * + * Note: console.log must be examined to ascertain whether or not this test was successful. + */ + @Test + public void testFourResourcesOneDead() throws Exception { + + logger.info("testFourResourcesOneDead: Entering"); + + final ExtractAppender logA = watch(debugLogger, START_AUDIT_RE); + + /* + * Start audit for pdp1. + */ + MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU); + + /* + * Start audit for pdp2. + */ + MyIntegrityAudit integrityAudit2 = makeAuditor("pdp2", A_SEQ_PU); + + /* + * Populate DB for pdp3, which will simulate it having registered but then having died. + */ + new DbDAO("pdp3", A_SEQ_PU, makeProperties()).destroy(); + + /* + * Start audit for pdp4. + */ + MyIntegrityAudit integrityAudit4 = makeAuditor("pdp4", A_SEQ_PU); + + /* + * Sleep long enough to allow + * + * 1) pdp1 to run audit + * + * 2) Logic to detect that pdp1 is stale and designate pdp2 + * + * 3) pdp2 to run audit + * + * 4) Logic to detect that pdp2 is stale and designate pdp4 + * + * 5) pdp4 to run audit + * + * 6) Logic to detect that pdp4 is stale and designate pdp1 + * + * 7) pdp1 to run audit + * + * 8) Logic to detect that pdp1 is stale and designate pdp2 + * + * 7) pdp2 to run audit + */ + runAudit(integrityAudit); + waitStaleAndRun(integrityAudit2); + waitStaleAndRun(integrityAudit4); + waitStaleAndRun(integrityAudit); + waitStaleAndRun(integrityAudit2); + waitStaleAndRun(integrityAudit4); + + verifyItemsInLog(logA, "pdp1", "pdp2", "pdp4", "pdp1", "pdp2", "pdp4"); + + logger.info("testFourResourcesOneDead: Exiting"); + + } + + /* + * Tests designation logic when four resources are in play but only one is functioning. + * Designation should remain with sole functioning resource. + * + * Note: console.log must be examined to ascertain whether or not this test was successful. + */ + @Test + public void testFourResourcesThreeDead() throws Exception { + + logger.info("testFourResourcesThreeDead: Entering"); + + final ExtractAppender logA = watch(debugLogger, START_AUDIT_RE); + + /* + * Populate DB for "pdp1", which will simulate it having registered but then having died. + */ + new DbDAO("pdp1", A_SEQ_PU, makeProperties()).destroy(); + + /* + * Populate DB for pdp2, which will simulate it having registered but then having died. + */ + new DbDAO("pdp2", A_SEQ_PU, makeProperties()).destroy(); + + /* + * Start audit for pdp3. + */ + MyIntegrityAudit integrityAudit3 = makeAuditor("pdp3", A_SEQ_PU); + + /* + * Populate DB for pdp4, which will simulate it having registered but then having died. + */ + new DbDAO("pdp4", A_SEQ_PU, makeProperties()).destroy(); + + /* + * Sleep long enough to allow + * + * 1) pdp3 to discover that all other designation candidates are stale + * + * 1) pdp3 to run audit + * + * 2) Logic to detect that no other nodes are available for designation + * + * 3) pdp3 to run audit again + */ + runAudit(integrityAudit3); + waitStaleAndRun(integrityAudit3); + + verifyItemsInLog(logA, "pdp3", "pdp3"); + + logger.info("testFourResourcesThreeDead: Exiting"); + + } + + /* + * Tests designation logic when the designated node dies and is no longer current + * + * Note: console.log must be examined to ascertain whether or not this test was successful. + */ + @Test + public void testDesignatedNodeDead() throws Exception { + logger.info("testDesignatedNodeDead: Entering"); + + final ExtractAppender logA = watch(debugLogger, START_AUDIT_RE); + + /* + * Instantiate audit object for pdp1. + */ + final MyIntegrityAudit integrityAudit = makeAuditor("pdp1", A_SEQ_PU); + + /* + * Start audit for pdp2. + */ + final MyIntegrityAudit integrityAudit2 = makeAuditor("pdp2", A_SEQ_PU); + + /* + * Instantiate audit object for pdp3. + */ + final MyIntegrityAudit integrityAudit3 = makeAuditor("pdp3", A_SEQ_PU); + + // Start audit on pdp1 + logger.info("testDesignatedNodeDead: Start audit on pdp1"); + runAudit(integrityAudit); + + // Start the auditing threads on other nodes. + logger.info("testDesignatedNodeDead: Start audit on pdp2"); + runAudit(integrityAudit2); + + // Kill audit on pdp1 + logger.info("testDesignatedNodeDead: Kill audit on pdp1"); + integrityAudit.stopAuditThread(); + + // Wait long enough for pdp1 to get stale and pdp2 to take over + waitStaleAndRun(integrityAudit2); + + // Start audit thread on pdp1 again. + logger.info("testDesignatedNodeDead: Start audit thread on pdp1 again."); + integrityAudit.startAuditThread(); + + // Wait long enough for pdp2 to complete its audit and get stale, at + // which point pdp3 should take over + logger.info( + "testDesignatedNodeDead: Wait long enough for pdp2 to complete its audit and get stale, at which point" + + " pdp3 should take over"); + waitStaleAndRun(integrityAudit3); + + // Kill audit on pdp3 + logger.info("testDesignatedNodeDead: Killing audit on pdp3"); + integrityAudit3.stopAuditThread(); + + // Wait long enough for pdp3 to get stale and pdp1 to take over + logger.info("testDesignatedNodeDead: Wait long enough for pdp3 to get stale and pdp1 to take over"); + waitStaleAndRun(integrityAudit); + + verifyItemsInLog(logA, "pdp1", "pdp2", "pdp3", "pdp1"); + + logger.info("testDesignatedNodeDead: Exiting"); + } } diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditTest.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditTest.java index 344ac34e..5adbb561 100644 --- a/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditTest.java +++ b/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditTest.java @@ -20,53 +20,52 @@ package org.onap.policy.common.ia; -import static org.junit.Assert.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import java.util.Properties; import org.junit.Test; -import org.onap.policy.common.ia.IntegrityAudit; -import org.onap.policy.common.ia.IntegrityAuditProperties; public class IntegrityAuditTest { - @Test - /** - * Test if we can access the updated bad params outside of the parmsAreBad method - */ - public void parmsAreBadTest() { - // Try with 2 null params - StringBuilder badParams = new StringBuilder(); - IntegrityAudit.parmsAreBad(null, "something", null, badParams); - - assertFalse("".equals(badParams.toString())); - assertTrue(badParams.toString().contains("resourceName")); - assertTrue(badParams.toString().contains("properties")); - - // Try with 1 null params - badParams = new StringBuilder(); - Properties props = new Properties(); - props.put(IntegrityAuditProperties.DB_DRIVER, "test_db_driver"); - IntegrityAudit.parmsAreBad(null, "something", props, badParams); - - assertFalse("".equals(badParams.toString())); - assertTrue(badParams.toString().contains("resourceName")); - assertFalse(badParams.toString().contains("properties")); - - // Try with 0 null params - badParams = new StringBuilder(); - IntegrityAudit.parmsAreBad("someting", "something", props, badParams); - assertFalse("".equals(badParams.toString())); - assertFalse(badParams.toString().contains("resourceName")); - assertFalse(badParams.toString().contains("properties")); - - // Try with invalid node type - props.put(IntegrityAuditProperties.NODE_TYPE, "bogus"); - badParams = new StringBuilder(); - IntegrityAudit.parmsAreBad("someting", "something", props, badParams); - assertFalse("".equals(badParams.toString())); - assertTrue(badParams.toString().contains("nodeType")); + @Test + /** + * Test if we can access the updated bad params outside of the parmsAreBad method. + */ + public void parmsAreBadTest() { + // Try with 2 null params + StringBuilder badParams = new StringBuilder(); + IntegrityAudit.parmsAreBad(null, "something", null, badParams); - } + assertFalse("".equals(badParams.toString())); + assertTrue(badParams.toString().contains("resourceName")); + assertTrue(badParams.toString().contains("properties")); + + // Try with 1 null params + badParams = new StringBuilder(); + Properties props = new Properties(); + props.put(IntegrityAuditProperties.DB_DRIVER, "test_db_driver"); + IntegrityAudit.parmsAreBad(null, "something", props, badParams); + + assertFalse("".equals(badParams.toString())); + assertTrue(badParams.toString().contains("resourceName")); + assertFalse(badParams.toString().contains("properties")); + + // Try with 0 null params + badParams = new StringBuilder(); + IntegrityAudit.parmsAreBad("someting", "something", props, badParams); + assertFalse("".equals(badParams.toString())); + assertFalse(badParams.toString().contains("resourceName")); + assertFalse(badParams.toString().contains("properties")); + + // Try with invalid node type + props.put(IntegrityAuditProperties.NODE_TYPE, "bogus"); + badParams = new StringBuilder(); + IntegrityAudit.parmsAreBad("someting", "something", props, badParams); + assertFalse("".equals(badParams.toString())); + assertTrue(badParams.toString().contains("nodeType")); + + } } diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditTestBase.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditTestBase.java index e30c5631..afbcc452 100644 --- a/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditTestBase.java +++ b/integrity-audit/src/test/java/org/onap/policy/common/ia/IntegrityAuditTestBase.java @@ -23,6 +23,9 @@ package org.onap.policy.common.ia; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; + import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; @@ -47,587 +50,560 @@ import org.onap.policy.common.utils.jpa.EntityTransCloser; import org.onap.policy.common.utils.test.log.logback.ExtractAppender; import org.slf4j.LoggerFactory; -import ch.qos.logback.classic.Level; -import ch.qos.logback.classic.Logger; - /** - * All JUnits are designed to run in the local development environment where - * they have write privileges and can execute time-sensitive tasks. - *

- * Many of the test verification steps are performed by scanning for items - * written to the log file. Rather than actually scan the log file, an - * {@link ExtractAppender} is used to monitor events that are logged and extract - * relevant items. In order to attach the appender to the debug log, it assumes - * that the debug log is a logback Logger configured per EELF. - *

- * These tests use a temporary, in-memory DB, which is dropped once the tests - * complete. + * All JUnits are designed to run in the local development environment where they have write + * privileges and can execute time-sensitive tasks. + * + *

Many of the test verification steps are performed by scanning for items written to the log + * file. Rather than actually scan the log file, an {@link ExtractAppender} is used to monitor + * events that are logged and extract relevant items. In order to attach the appender to the debug + * log, it assumes that the debug log is a logback Logger configured per EELF. + * + *

These tests use a temporary, in-memory DB, which is dropped once the tests complete. */ public class IntegrityAuditTestBase { - /** - * Root of the debug logger, as defined in the logback-test.xml. - */ - protected static final Logger debugLogger = (Logger) LoggerFactory.getLogger("com.att.eelf.debug"); - - /** - * Root of the error logger, as defined in the logback-test.xml. - */ - protected static final Logger errorLogger = (Logger) LoggerFactory.getLogger("com.att.eelf.error"); - - /** - * Directory containing the log files. - */ - private static final String LOG_DIR = "testingLogs/common-modules/integrity-audit"; - - /** - * Max time, in milliseconds, to wait for a latch to be triggered. - */ - protected static final long WAIT_MS = 5000l; - - /** - * Milliseconds that auditor should sleep between audit steps. - */ - protected static final long SLEEP_INTERVAL_MS = 2l; - - /** - * Milliseconds that auditor should sleep when an audit completes. - */ - protected static final long COMPLETION_INTERVAL_MS = 5l; - - /** - * Milliseconds that an entire audit-simulation cycles takes. - */ - protected static final long AUDIT_SIMULATION_MS = SLEEP_INTERVAL_MS * AuditThread.AUDIT_SIMULATION_ITERATIONS; - - /** - * Milliseconds that it takes for an auditor's last update to become stale. - * Includes a 1ms fudge factor. - */ - protected static final long STALE_MS = 1 + 2 * Math.max(COMPLETION_INTERVAL_MS, AUDIT_SIMULATION_MS); - - /** - * Milliseconds that the db-audit should wait between makings updates. - */ - private static final long DB_AUDIT_UPDATE_MS = 10l; - - /** - * Milliseconds that the db-audit should sleep between cycles. - */ - private static final long DB_AUDIT_SLEEP_MS = 3l; - - public static final String DEFAULT_DB_URL_PREFIX = "jdbc:h2:mem:"; - - protected static final String dbDriver = "org.h2.Driver"; - protected static final String dbUser = "testu"; - protected static final String dbPwd = "testp"; - protected static final String siteName = "SiteA"; - protected static final String nodeType = "pdp_xacml"; - - // will be defined by the test *Classes* - protected static String dbUrl; - - /** - * Persistence unit for PDP sequence A. - */ - protected static final String A_SEQ_PU = "testPU"; - - /** - * Persistence unit for PDP sequence B. - */ - protected static final String B_SEQ_PU = "integrityAuditPU"; - - /** - * Matches the start of an audit for arbitrary PDPs in the debug log. - */ - protected static final String START_AUDIT_RE = "Starting audit simulation for resourceName=([^,]*)"; - - /** - * Properties to be used in all tests. - */ - protected static Properties properties; - - /** - * Entity manager factory pointing to the in-memory DB for A_SEQ_PU. - */ - protected static EntityManagerFactory emf; - - /** - * Entity manager factory pointing to the in-memory DB associated with emf. - */ - protected static EntityManager em; - - /** - * Saved debug logger level, to be restored once all tests complete. - */ - private static Level savedDebugLevel; - - /** - * Saved error logger level, to be restored once all tests complete. - */ - private static Level savedErrorLevel; - - /** - * Saved audit sleep interval, to be restored once all tests complete. - */ - private static long savedSleepIntervalMs; - - /** - * Saved audit completion interval, to be restored once all tests complete. - */ - private static long savedCompletionIntervalMs; - - /** - * Saved db audit update time, to be restored once all tests complete. - */ - private static long savedDbAuditUpdateMs; - - /** - * Saved db audit sleep time, to be restored once all tests complete. - */ - private static long savedDbAuditSleepMs; - - /** - * List of auditors whose threads must be stopped when a given test case - * ends. - */ - private List auditors; - - /** - * List of appenders that must be removed from loggers when a given test - * case ends. - */ - private List appenders; - - /** - * Saves current configuration information and then sets new values. - * - * @param dbDriver - * the name of the DB Driver class - * @param dbUrl - * the URL to the DB - * @throws IOException - * @throws Exception - */ - protected static void setUpBeforeClass(String dbUrl) throws IOException { - - // truncate the logs - new FileOutputStream(LOG_DIR + "/audit.log").close(); - new FileOutputStream(LOG_DIR + "/debug.log").close(); - new FileOutputStream(LOG_DIR + "/error.log").close(); - new FileOutputStream(LOG_DIR + "/metrics.log").close(); - - IntegrityAuditTestBase.dbUrl = dbUrl; - - // save data that we have to restore at the end of the test - savedDebugLevel = debugLogger.getLevel(); - savedErrorLevel = errorLogger.getLevel(); - savedSleepIntervalMs = AuditThread.getAuditThreadSleepIntervalMillis(); - savedCompletionIntervalMs = AuditThread.getAuditCompletionIntervalMillis(); - savedDbAuditUpdateMs = DbAudit.getDbAuditUpdateMillis(); - savedDbAuditSleepMs = DbAudit.getDbAuditSleepMillis(); - - AuditThread.setAuditThreadSleepIntervalMillis(SLEEP_INTERVAL_MS); - AuditThread.setAuditCompletionIntervalMillis(COMPLETION_INTERVAL_MS); - - DbAudit.setDbAuditUpdateMillis(DB_AUDIT_UPDATE_MS); - DbAudit.setDbAuditSleepMillis(DB_AUDIT_SLEEP_MS); - - IntegrityAudit.setUnitTesting(true); - - properties = new Properties(); - properties.put(IntegrityAuditProperties.DB_DRIVER, dbDriver); - properties.put(IntegrityAuditProperties.DB_URL, dbUrl); - properties.put(IntegrityAuditProperties.DB_USER, dbUser); - properties.put(IntegrityAuditProperties.DB_PWD, dbPwd); - properties.put(IntegrityAuditProperties.SITE_NAME, siteName); - properties.put(IntegrityAuditProperties.NODE_TYPE, nodeType); - - emf = Persistence.createEntityManagerFactory(A_SEQ_PU, makeProperties()); - - // keep this open so the in-memory DB stays around until all tests are - // done - em = emf.createEntityManager(); - - debugLogger.setLevel(Level.DEBUG); - errorLogger.setLevel(Level.ERROR); - } - - /** - * Restores the configuration to what it was before the test. - */ - protected static void tearDownAfterClass() { - AuditThread.setAuditThreadSleepIntervalMillis(savedSleepIntervalMs); - AuditThread.setAuditCompletionIntervalMillis(savedCompletionIntervalMs); - - DbAudit.setDbAuditUpdateMillis(savedDbAuditUpdateMs); - DbAudit.setDbAuditSleepMillis(savedDbAuditSleepMs); - - IntegrityAudit.setUnitTesting(false); - - debugLogger.setLevel(savedDebugLevel); - errorLogger.setLevel(savedErrorLevel); - - // this should result in the in-memory DB being deleted - em.close(); - emf.close(); - } - - /** - * Sets up for a test, which includes deleting all records from the - * IntegrityAuditEntity table. - */ - protected void setUp() { - auditors = new LinkedList<>(); - appenders = new LinkedList<>(); - - properties.put(IntegrityAuditProperties.AUDIT_PERIOD_MILLISECONDS, String.valueOf(SLEEP_INTERVAL_MS)); - - // Clean up the DB - try (EntityTransCloser etc = new EntityTransCloser(em.getTransaction())) { - EntityTransaction et = etc.getTransation(); - - em.createQuery("Delete from IntegrityAuditEntity").executeUpdate(); - - // commit transaction - et.commit(); - } - } - - /** - * Cleans up after a test, removing any ExtractAppenders from the logger and - * stopping any AuditThreads. - */ - protected void tearDown() { - for (LogApp p : appenders) { - p.detach(); - } - - for (MyIntegrityAudit p : auditors) { - p.stopAuditThread(); - } - } - - /** - * - * @param properties - * @param persistenceUnit - * @param tableName - */ - public void truncateTable(Properties properties, String persistenceUnit, String tableName) { - - try (EntityMgrFactoryCloser emfc = new EntityMgrFactoryCloser( - Persistence.createEntityManagerFactory(persistenceUnit, properties)); - EntityMgrCloser emc = new EntityMgrCloser(emfc.getFactory().createEntityManager()); - EntityTransCloser etc = new EntityTransCloser(emc.getManager().getTransaction())) { - - EntityManager em = emc.getManager(); - EntityTransaction et = etc.getTransation(); - - // Clean up the DB - em.createQuery("Delete from " + tableName).executeUpdate(); - - // commit transaction - et.commit(); - } - } - - /** - * Verifies that items appear within the log, in order. A given item may - * appear more than once. In addition, the log may contain extra items; - * those are ignored. - * - * @param textre - * regular expression used to extract an item from a line in the - * log. The first "capture" group of the regular expression is - * assumed to contain the extracted item - * @param items - * items that should be matched by the items extracted from the - * log, in order - * @throws IOException - * @throws AssertionError - * if the desired items were not all found - */ - protected void verifyItemsInLog(ExtractAppender app, String... items) throws IOException { - - Iterator it = new ArrayList<>(Arrays.asList(items)).iterator(); - if (!it.hasNext()) { - return; - } - - String expected = it.next(); - String last = null; - - for (String rName : app.getExtracted()) { - if (rName.equals(expected)) { - if (!it.hasNext()) { - // matched all of the items - return; - } - - last = expected; - expected = it.next(); - - } else if (!rName.equals(last)) { - List remaining = getRemaining(expected, it); - fail("missing items " + remaining + ", but was: " + rName); - } - } - - List remaining = getRemaining(expected, it); - assertTrue("missing items " + remaining, remaining.isEmpty()); - } - - /** - * Gets the remaining items from an iterator - * - * @param current - * the current item, to be included within the list - * @param it - * iterator from which to get the remaining items - * @return a list of the remaining items - */ - private LinkedList getRemaining(String current, Iterator it) { - LinkedList remaining = new LinkedList<>(); - remaining.add(current); - - while (it.hasNext()) { - remaining.add(it.next()); - } - return remaining; - } - - /** - * Waits for a thread to stop. If the thread doesn't complete in the - * allotted time, then it interrupts it and waits again. - * - * @param auditor - * the thread for which to wait - * @return {@code true} if the thread stopped, {@code false} otherwise - */ - public boolean waitThread(MyIntegrityAudit auditor) { - if (auditor != null) { - try { - auditor.interrupt(); - - if (!auditor.joinAuditThread(WAIT_MS)) { - System.out.println("failed to stop audit thread"); - return false; - } - - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - } - - return true; - } - - /** - * Makes a new auditor. - * - * @param resourceName2 - * @param persistenceUnit2 - * @return a new auditor - * @throws Exception - */ - protected MyIntegrityAudit makeAuditor(String resourceName2, String persistenceUnit2) throws Exception { - return new MyIntegrityAudit(resourceName2, persistenceUnit2, makeProperties()); - } - - /** - * Watches for patterns in a logger by attaching a ExtractAppender to it. - * - * @param logger - * the logger to watch - * @param regex - * regular expression used to extract relevant text - * @return a new appender - */ - protected ExtractAppender watch(Logger logger, String regex) { - ExtractAppender app = new ExtractAppender(regex); - appenders.add(new LogApp(logger, app)); - - return app; - } - - /** - * Makes a new Property set that's a clone of {@link #properties}. - * - * @return a new Property set containing all of a copy of all of the - * {@link #properties} - */ - protected static Properties makeProperties() { - Properties props = new Properties(); - props.putAll(properties); - return props; - } - - /** - * Waits for data to become stale and then runs an audit on several auditors - * in parallel. - * - * @param auditors - * @throws InterruptedException - */ - protected void waitStaleAndRun(MyIntegrityAudit... auditors) throws InterruptedException { - waitStale(); - runAudit(auditors); - } - - /** - * Runs an audit on several auditors in parallel. - * - * @param auditors - * @throws InterruptedException - */ - protected void runAudit(MyIntegrityAudit... auditors) throws InterruptedException { - - // start an audit cycle on each auditor - List latches = new ArrayList<>(auditors.length); - for (MyIntegrityAudit p : auditors) { - latches.add(p.startAudit()); - } - - // wait for each auditor to complete its cycle - for (CountDownLatch latch : latches) { - waitLatch(latch); - } - } - - /** - * Waits for a latch to reach zero. - * - * @param latch - * @throws InterruptedException - * @throws AssertionError - * if the latch did not reach zero in the allotted time - */ - protected void waitLatch(CountDownLatch latch) throws InterruptedException { - assertTrue(latch.await(WAIT_MS, TimeUnit.SECONDS)); - } - - /** - * Sleep a bit so that the currently designated pdp becomes stale. - * - * @throws InterruptedException - */ - protected void waitStale() throws InterruptedException { - Thread.sleep(STALE_MS); - } - - /** - * Tracks which appender has been added to a logger. - */ - private static class LogApp { - private final Logger logger; - private final ExtractAppender appender; - - public LogApp(Logger logger, ExtractAppender appender) { - this.logger = logger; - this.appender = appender; - - logger.addAppender(appender); - - appender.start(); - } - - public void detach() { - logger.detachAppender(appender); - } - } - - /** - * Manages audits by inserting latches into a queue for the AuditThread to - * count. - */ - protected class MyIntegrityAudit extends IntegrityAudit { - - /** - * Queue from which the AuditThread will take latches. - */ - private BlockingQueue queue = null; - - /** - * Constructs an auditor and starts the AuditThread. - * - * @param resourceName - * @param persistenceUnit - * @param properties - * @throws Exception - */ - public MyIntegrityAudit(String resourceName, String persistenceUnit, Properties properties) throws Exception { - super(resourceName, persistenceUnit, properties); - - auditors.add(this); - - startAuditThread(); - } - - /** - * Interrupts the AuditThread. - */ - public void interrupt() { - super.stopAuditThread(); - } - - /** - * Triggers an audit by adding a latch to the queue. - * - * @return the latch that was added - * @throws InterruptedException - */ - public CountDownLatch startAudit() throws InterruptedException { - CountDownLatch latch = new CountDownLatch(1); - queue.add(latch); - - return latch; - } - - /** - * Starts a new AuditThread. Creates a new latch queue and associates it - * with the thread. - */ - @Override - public final void startAuditThread() throws IntegrityAuditException { - if (queue != null) { - // queue up a bogus latch, in case a thread is still running - queue.add(new CountDownLatch(1) { - @Override - public void countDown() { - throw new RuntimeException("auditor has multiple threads"); - } - }); - } - - queue = new LinkedBlockingQueue<>(); - - if (super.startAuditThread(queue)) { - // wait for the thread to start - CountDownLatch latch = new CountDownLatch(1); - queue.add(latch); - - try { - waitLatch(latch); - - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new IntegrityAuditException(e); - } - } - } - - /** - * Stops the AuditThread and waits for it to stop. - * - * @throws AssertionError - * if the thread is still running - */ - @Override - public void stopAuditThread() { - super.stopAuditThread(); - - assertTrue(waitThread(this)); - } - } + /** + * Root of the debug logger, as defined in the logback-test.xml. + */ + protected static final Logger debugLogger = (Logger) LoggerFactory.getLogger("com.att.eelf.debug"); + + /** + * Root of the error logger, as defined in the logback-test.xml. + */ + protected static final Logger errorLogger = (Logger) LoggerFactory.getLogger("com.att.eelf.error"); + + /** + * Directory containing the log files. + */ + private static final String LOG_DIR = "testingLogs/common-modules/integrity-audit"; + + /** + * Max time, in milliseconds, to wait for a latch to be triggered. + */ + protected static final long WAIT_MS = 5000L; + + /** + * Milliseconds that auditor should sleep between audit steps. + */ + protected static final long SLEEP_INTERVAL_MS = 2L; + + /** + * Milliseconds that auditor should sleep when an audit completes. + */ + protected static final long COMPLETION_INTERVAL_MS = 5L; + + /** + * Milliseconds that an entire audit-simulation cycles takes. + */ + protected static final long AUDIT_SIMULATION_MS = SLEEP_INTERVAL_MS * AuditThread.AUDIT_SIMULATION_ITERATIONS; + + /** + * Milliseconds that it takes for an auditor's last update to become stale. Includes a 1ms fudge + * factor. + */ + protected static final long STALE_MS = 1 + 2 * Math.max(COMPLETION_INTERVAL_MS, AUDIT_SIMULATION_MS); + + /** + * Milliseconds that the db-audit should wait between makings updates. + */ + private static final long DB_AUDIT_UPDATE_MS = 10L; + + /** + * Milliseconds that the db-audit should sleep between cycles. + */ + private static final long DB_AUDIT_SLEEP_MS = 3L; + + public static final String DEFAULT_DB_URL_PREFIX = "jdbc:h2:mem:"; + + protected static final String dbDriver = "org.h2.Driver"; + protected static final String dbUser = "testu"; + protected static final String dbPwd = "testp"; + protected static final String siteName = "SiteA"; + protected static final String nodeType = "pdp_xacml"; + + // will be defined by the test *Classes* + protected static String dbUrl; + + /** + * Persistence unit for PDP sequence A. + */ + protected static final String A_SEQ_PU = "testPU"; + + /** + * Persistence unit for PDP sequence B. + */ + protected static final String B_SEQ_PU = "integrityAuditPU"; + + /** + * Matches the start of an audit for arbitrary PDPs in the debug log. + */ + protected static final String START_AUDIT_RE = "Starting audit simulation for resourceName=([^,]*)"; + + /** + * Properties to be used in all tests. + */ + protected static Properties properties; + + /** + * Entity manager factory pointing to the in-memory DB for A_SEQ_PU. + */ + protected static EntityManagerFactory emf; + + /** + * Entity manager factory pointing to the in-memory DB associated with emf. + */ + protected static EntityManager em; + + /** + * Saved debug logger level, to be restored once all tests complete. + */ + private static Level savedDebugLevel; + + /** + * Saved error logger level, to be restored once all tests complete. + */ + private static Level savedErrorLevel; + + /** + * Saved audit sleep interval, to be restored once all tests complete. + */ + private static long savedSleepIntervalMs; + + /** + * Saved audit completion interval, to be restored once all tests complete. + */ + private static long savedCompletionIntervalMs; + + /** + * Saved db audit update time, to be restored once all tests complete. + */ + private static long savedDbAuditUpdateMs; + + /** + * Saved db audit sleep time, to be restored once all tests complete. + */ + private static long savedDbAuditSleepMs; + + /** + * List of auditors whose threads must be stopped when a given test case ends. + */ + private List auditors; + + /** + * List of appenders that must be removed from loggers when a given test case ends. + */ + private List appenders; + + /** + * Saves current configuration information and then sets new values. + * + * @param dbDriver the name of the DB Driver class + * @param dbUrl the URL to the DB + * @throws IOException if an IO error occurs + */ + protected static void setUpBeforeClass(String dbUrl) throws IOException { + + // truncate the logs + new FileOutputStream(LOG_DIR + "/audit.log").close(); + new FileOutputStream(LOG_DIR + "/debug.log").close(); + new FileOutputStream(LOG_DIR + "/error.log").close(); + new FileOutputStream(LOG_DIR + "/metrics.log").close(); + + IntegrityAuditTestBase.dbUrl = dbUrl; + + // save data that we have to restore at the end of the test + savedDebugLevel = debugLogger.getLevel(); + savedErrorLevel = errorLogger.getLevel(); + savedSleepIntervalMs = AuditThread.getAuditThreadSleepIntervalMillis(); + savedCompletionIntervalMs = AuditThread.getAuditCompletionIntervalMillis(); + savedDbAuditUpdateMs = DbAudit.getDbAuditUpdateMillis(); + savedDbAuditSleepMs = DbAudit.getDbAuditSleepMillis(); + + AuditThread.setAuditThreadSleepIntervalMillis(SLEEP_INTERVAL_MS); + AuditThread.setAuditCompletionIntervalMillis(COMPLETION_INTERVAL_MS); + + DbAudit.setDbAuditUpdateMillis(DB_AUDIT_UPDATE_MS); + DbAudit.setDbAuditSleepMillis(DB_AUDIT_SLEEP_MS); + + IntegrityAudit.setUnitTesting(true); + + properties = new Properties(); + properties.put(IntegrityAuditProperties.DB_DRIVER, dbDriver); + properties.put(IntegrityAuditProperties.DB_URL, dbUrl); + properties.put(IntegrityAuditProperties.DB_USER, dbUser); + properties.put(IntegrityAuditProperties.DB_PWD, dbPwd); + properties.put(IntegrityAuditProperties.SITE_NAME, siteName); + properties.put(IntegrityAuditProperties.NODE_TYPE, nodeType); + + emf = Persistence.createEntityManagerFactory(A_SEQ_PU, makeProperties()); + + // keep this open so the in-memory DB stays around until all tests are + // done + em = emf.createEntityManager(); + + debugLogger.setLevel(Level.DEBUG); + errorLogger.setLevel(Level.ERROR); + } + + /** + * Restores the configuration to what it was before the test. + */ + protected static void tearDownAfterClass() { + AuditThread.setAuditThreadSleepIntervalMillis(savedSleepIntervalMs); + AuditThread.setAuditCompletionIntervalMillis(savedCompletionIntervalMs); + + DbAudit.setDbAuditUpdateMillis(savedDbAuditUpdateMs); + DbAudit.setDbAuditSleepMillis(savedDbAuditSleepMs); + + IntegrityAudit.setUnitTesting(false); + + debugLogger.setLevel(savedDebugLevel); + errorLogger.setLevel(savedErrorLevel); + + // this should result in the in-memory DB being deleted + em.close(); + emf.close(); + } + + /** + * Sets up for a test, which includes deleting all records from the IntegrityAuditEntity table. + */ + protected void setUp() { + auditors = new LinkedList<>(); + appenders = new LinkedList<>(); + + properties.put(IntegrityAuditProperties.AUDIT_PERIOD_MILLISECONDS, String.valueOf(SLEEP_INTERVAL_MS)); + + // Clean up the DB + try (EntityTransCloser etc = new EntityTransCloser(em.getTransaction())) { + EntityTransaction et = etc.getTransation(); + + em.createQuery("Delete from IntegrityAuditEntity").executeUpdate(); + + // commit transaction + et.commit(); + } + } + + /** + * Cleans up after a test, removing any ExtractAppenders from the logger and stopping any + * AuditThreads. + */ + protected void tearDown() { + for (LogApp p : appenders) { + p.detach(); + } + + for (MyIntegrityAudit p : auditors) { + p.stopAuditThread(); + } + } + + /** + * Truncate the table. + * + * @param properties the properties + * @param persistenceUnit the persistence unit + * @param tableName the name of the table + */ + public void truncateTable(Properties properties, String persistenceUnit, String tableName) { + + try (EntityMgrFactoryCloser emfc = + new EntityMgrFactoryCloser(Persistence.createEntityManagerFactory(persistenceUnit, properties)); + EntityMgrCloser emc = new EntityMgrCloser(emfc.getFactory().createEntityManager()); + EntityTransCloser etc = new EntityTransCloser(emc.getManager().getTransaction())) { + + EntityManager em = emc.getManager(); + EntityTransaction et = etc.getTransation(); + + // Clean up the DB + em.createQuery("Delete from " + tableName).executeUpdate(); + + // commit transaction + et.commit(); + } + } + + /** + * Verifies that items appear within the log, in order. A given item may appear more than once. + * In addition, the log may contain extra items; those are ignored. + * + * @param textre regular expression used to extract an item from a line in the log. The first + * "capture" group of the regular expression is assumed to contain the extracted item + * @param items items that should be matched by the items extracted from the log, in order + * @throws IOException if an IO error occurs + * @throws AssertionError if the desired items were not all found + */ + protected void verifyItemsInLog(ExtractAppender app, String... items) throws IOException { + + Iterator it = new ArrayList<>(Arrays.asList(items)).iterator(); + if (!it.hasNext()) { + return; + } + + String expected = it.next(); + String last = null; + + for (String extractedText : app.getExtracted()) { + if (extractedText.equals(expected)) { + if (!it.hasNext()) { + // matched all of the items + return; + } + + last = expected; + expected = it.next(); + + } else if (!extractedText.equals(last)) { + List remaining = getRemaining(expected, it); + fail("missing items " + remaining + ", but was: " + extractedText); + } + } + + List remaining = getRemaining(expected, it); + assertTrue("missing items " + remaining, remaining.isEmpty()); + } + + /** + * Gets the remaining items from an iterator. + * + * @param current the current item, to be included within the list + * @param it iterator from which to get the remaining items + * @return a list of the remaining items + */ + private LinkedList getRemaining(String current, Iterator it) { + LinkedList remaining = new LinkedList<>(); + remaining.add(current); + + while (it.hasNext()) { + remaining.add(it.next()); + } + return remaining; + } + + /** + * Waits for a thread to stop. If the thread doesn't complete in the allotted time, then it + * interrupts it and waits again. + * + * @param auditor the thread for which to wait + * @return {@code true} if the thread stopped, {@code false} otherwise + */ + public boolean waitThread(MyIntegrityAudit auditor) { + if (auditor != null) { + try { + auditor.interrupt(); + + if (!auditor.joinAuditThread(WAIT_MS)) { + System.out.println("failed to stop audit thread"); + return false; + } + + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + return true; + } + + /** + * Makes a new auditor. + * + * @param resourceName2 the name of the resource + * @param persistenceUnit2 the persistence unit + * @return a new auditor + * @throws Exception if an error occurs + */ + protected MyIntegrityAudit makeAuditor(String resourceName2, String persistenceUnit2) throws Exception { + return new MyIntegrityAudit(resourceName2, persistenceUnit2, makeProperties()); + } + + /** + * Watches for patterns in a logger by attaching a ExtractAppender to it. + * + * @param logger the logger to watch + * @param regex regular expression used to extract relevant text + * @return a new appender + */ + protected ExtractAppender watch(Logger logger, String regex) { + ExtractAppender app = new ExtractAppender(regex); + appenders.add(new LogApp(logger, app)); + + return app; + } + + /** + * Makes a new Property set that's a clone of {@link #properties}. + * + * @return a new Property set containing all of a copy of all of the {@link #properties} + */ + protected static Properties makeProperties() { + Properties props = new Properties(); + props.putAll(properties); + return props; + } + + /** + * Waits for data to become stale and then runs an audit on several auditors in parallel. + * + * @param auditors the auditors + * @throws InterruptedException if a thread is interrupted + */ + protected void waitStaleAndRun(MyIntegrityAudit... auditors) throws InterruptedException { + waitStale(); + runAudit(auditors); + } + + /** + * Runs an audit on several auditors in parallel. + * + * @param auditors the auditors + * @throws InterruptedException if a thread is interrupted + */ + protected void runAudit(MyIntegrityAudit... auditors) throws InterruptedException { + + // start an audit cycle on each auditor + List latches = new ArrayList<>(auditors.length); + for (MyIntegrityAudit p : auditors) { + latches.add(p.startAudit()); + } + + // wait for each auditor to complete its cycle + for (CountDownLatch latch : latches) { + waitLatch(latch); + } + } + + /** + * Waits for a latch to reach zero. + * + * @param latch the latch to wait for + * @throws InterruptedException if the thread is interrupted + * @throws AssertionError if the latch did not reach zero in the allotted time + */ + protected void waitLatch(CountDownLatch latch) throws InterruptedException { + assertTrue(latch.await(WAIT_MS, TimeUnit.SECONDS)); + } + + /** + * Sleep a bit so that the currently designated pdp becomes stale. + * + * @throws InterruptedException if the thread is interrupted + */ + protected void waitStale() throws InterruptedException { + Thread.sleep(STALE_MS); + } + + /** + * Tracks which appender has been added to a logger. + */ + private static class LogApp { + private final Logger logger; + private final ExtractAppender appender; + + public LogApp(Logger logger, ExtractAppender appender) { + this.logger = logger; + this.appender = appender; + + logger.addAppender(appender); + + appender.start(); + } + + public void detach() { + logger.detachAppender(appender); + } + } + + /** + * Manages audits by inserting latches into a queue for the AuditThread to count. + */ + protected class MyIntegrityAudit extends IntegrityAudit { + + /** + * Queue from which the AuditThread will take latches. + */ + private BlockingQueue queue = null; + + /** + * Constructs an auditor and starts the AuditThread. + * + * @param resourceName the resource name + * @param persistenceUnit the persistence unit + * @param properties the properties + * @throws Exception if an error occurs + */ + public MyIntegrityAudit(String resourceName, String persistenceUnit, Properties properties) throws Exception { + super(resourceName, persistenceUnit, properties); + + auditors.add(this); + + startAuditThread(); + } + + /** + * Interrupts the AuditThread. + */ + public void interrupt() { + super.stopAuditThread(); + } + + /** + * Triggers an audit by adding a latch to the queue. + * + * @return the latch that was added + * @throws InterruptedException if the thread is interrupted + */ + public CountDownLatch startAudit() throws InterruptedException { + CountDownLatch latch = new CountDownLatch(1); + queue.add(latch); + + return latch; + } + + /** + * Starts a new AuditThread. Creates a new latch queue and associates it with the thread. + */ + @Override + public final void startAuditThread() throws IntegrityAuditException { + if (queue != null) { + // queue up a bogus latch, in case a thread is still running + queue.add(new CountDownLatch(1) { + @Override + public void countDown() { + throw new RuntimeException("auditor has multiple threads"); + } + }); + } + + queue = new LinkedBlockingQueue<>(); + + if (super.startAuditThread(queue)) { + // wait for the thread to start + CountDownLatch latch = new CountDownLatch(1); + queue.add(latch); + + try { + waitLatch(latch); + + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IntegrityAuditException(e); + } + } + } + + /** + * Stops the AuditThread and waits for it to stop. + * + * @throws AssertionError if the thread is still running + */ + @Override + public void stopAuditThread() { + super.stopAuditThread(); + + assertTrue(waitThread(this)); + } + } } diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/jpa/IaTestEntity.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/jpa/IaTestEntity.java index 43277a71..36b9ef66 100644 --- a/integrity-audit/src/test/java/org/onap/policy/common/ia/jpa/IaTestEntity.java +++ b/integrity-audit/src/test/java/org/onap/policy/common/ia/jpa/IaTestEntity.java @@ -37,119 +37,139 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; @Entity -@Table(name="IaTestEntity") -@NamedQueries({ - @NamedQuery(name=" IaTestEntity.findAll", query="SELECT e FROM IaTestEntity e "), - @NamedQuery(name="IaTestEntity.deleteAll", query="DELETE FROM IaTestEntity WHERE 1=1") -}) +@Table(name = "IaTestEntity") +@NamedQueries({@NamedQuery(name = " IaTestEntity.findAll", query = "SELECT e FROM IaTestEntity e "), + @NamedQuery(name = "IaTestEntity.deleteAll", query = "DELETE FROM IaTestEntity WHERE 1=1")}) public class IaTestEntity implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="ImTestId") - private long imTestId; - - @Column(name="created_by", nullable=false, length=255) - private String createdBy = "guest"; - - @Column(name="person", nullable=false, length=255) - private PersonSample person; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="created_date", updatable=false) - private Date createdDate; - - @Column(name="modified_by", nullable=false, length=255) - private String modifiedBy = "guest"; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate; - - public IaTestEntity() { - } - - @PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - this.modifiedDate = date; - } - - @PreUpdate - public void preUpdate() { - this.modifiedDate = new Date(); - } - - /** - * @return the Id - */ - public long getImTestId() { - return imTestId; - } - - /** - * @return the createdBy - */ - public String getCreatedBy() { - return createdBy; - } - - /** - * @param createdBy the createdBy to set - */ - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } - - /** - * @return the modifiedBy - */ - public String getModifiedBy() { - return modifiedBy; - } - - /** - * @param modifiedBy the modifiedBy to set - */ - public void setModifiedBy(String modifiedBy) { - this.modifiedBy = modifiedBy; - } - - /** - * @return the modifiedDate - */ - public Date getModifiedDate() { - return modifiedDate; - } - - /** - * @param modifiedDate the modifiedDate to set - */ - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } - - /** - * @return the createdDate - */ - public Date getCreatedDate() { - return createdDate; - } - - /** - * @param the person to set - */ - public void setPersonTest(PersonSample p) { - this.person = p; - } - - /** - * @return the person - */ - public PersonSample getPersonTest() { - return person; - } + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "ImTestId") + private long imTestId; + + @Column(name = "created_by", nullable = false, length = 255) + private String createdBy = "guest"; + + @Column(name = "person", nullable = false, length = 255) + private PersonSample person; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "created_date", updatable = false) + private Date createdDate; + + @Column(name = "modified_by", nullable = false, length = 255) + private String modifiedBy = "guest"; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "modified_date", nullable = false) + private Date modifiedDate; + + public IaTestEntity() {} + + /** + * PrePersist call back method. + */ + @PrePersist + public void prePersist() { + Date date = new Date(); + this.createdDate = date; + this.modifiedDate = date; + } + + @PreUpdate + public void preUpdate() { + this.modifiedDate = new Date(); + } + + /** + * The the Im test Id. + * + * @return the Id + */ + public long getImTestId() { + return imTestId; + } + + /** + * Get the createdBy. + * + * @return the createdBy + */ + public String getCreatedBy() { + return createdBy; + } + + /** + * Set the createdBy. + * + * @param createdBy the createdBy to set + */ + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } + + /** + * Get the modifiedBy. + * + * @return the modifiedBy + */ + public String getModifiedBy() { + return modifiedBy; + } + + /** + * Set the ModifiedBy. + * + * @param modifiedBy the modifiedBy to set + */ + public void setModifiedBy(String modifiedBy) { + this.modifiedBy = modifiedBy; + } + + /** + * Get the ModifiedDate. + * + * @return the modifiedDate + */ + public Date getModifiedDate() { + return modifiedDate; + } + + /** + * Set the ModifiedDate. + * + * @param modifiedDate the modifiedDate to set + */ + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } + + /** + * Get the CreatedDate. + * + * @return the createdDate + */ + public Date getCreatedDate() { + return createdDate; + } + + /** + * Set the person. + * + * @param person the person to set + */ + public void setPersonTest(PersonSample person) { + this.person = person; + } + + /** + * Get the person. + * + * @return the person + */ + public PersonSample getPersonTest() { + return person; + } } diff --git a/integrity-audit/src/test/java/org/onap/policy/common/ia/jpa/PersonSample.java b/integrity-audit/src/test/java/org/onap/policy/common/ia/jpa/PersonSample.java index d7fcf330..47fa843b 100644 --- a/integrity-audit/src/test/java/org/onap/policy/common/ia/jpa/PersonSample.java +++ b/integrity-audit/src/test/java/org/onap/policy/common/ia/jpa/PersonSample.java @@ -23,42 +23,47 @@ package org.onap.policy.common.ia.jpa; import java.io.Serializable; public class PersonSample implements Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; - private String firstName; - private String lastName; - private int age; - - public PersonSample(String first, String last, int age) { - this.firstName = first; - this.lastName = last; - this.age = age; - } - - public String getFirstName() { - return this.firstName; - } - - public void setFirstName(String name) { - this.firstName = name; - } - - public String getLasttName() { - return this.lastName; - } - - public void setLastName(String name) { - this.lastName = name; - } - - public int getAge() { - return this.age; - } - - public void setAge(int age) { - this.age = age; - } - + + private static final long serialVersionUID = 1L; + private String firstName; + private String lastName; + private int age; + + /** + * Create an instance. + * + * @param first first name + * @param last last name + * @param age age + */ + public PersonSample(String first, String last, int age) { + this.firstName = first; + this.lastName = last; + this.age = age; + } + + public String getFirstName() { + return this.firstName; + } + + public void setFirstName(String name) { + this.firstName = name; + } + + public String getLasttName() { + return this.lastName; + } + + public void setLastName(String name) { + this.lastName = name; + } + + public int getAge() { + return this.age; + } + + public void setAge(int age) { + this.age = age; + } + } -- cgit 1.2.3-korg