aboutsummaryrefslogtreecommitdiffstats
path: root/integrity-audit/src/test/java/org/onap/policy/common/ia/DbAuditTest.java
blob: 27cd168f4e32fc87382d3abd840de801a774dbf5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
/*
 * ============LICENSE_START=======================================================
 * Integrity Audit
 * ================================================================================
 * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.common.ia;

import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;

import java.util.List;
import java.util.Properties;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.policy.common.ia.jpa.IntegrityAuditEntity;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
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.
 *
 * If any have been ignored (@Ignore) they will not run at the same time
 * as others. You should run them as JUnits by themselves.
 */
public class DbAuditTest extends IntegrityAuditTestBase {

    private static Logger logger = FlexLogger.getLogger(DbAuditTest.class);

    private static final String RESOURCE_NAME = "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();

        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(RESOURCE_NAME, A_SEQ_PU, properties);
        dbDao.deleteAllIntegrityAuditEntities();

        assertThatThrownBy(() -> {
            DbAudit dbAudit = new DbAudit(dbDao);
            dbAudit.dbAudit(RESOURCE_NAME, A_SEQ_PU, nodeType);
        }).isInstanceOf(DbAuditException.class);

        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(RESOURCE_NAME, A_SEQ_PU, properties);
        DbAudit dbAudit = new DbAudit(dbDao);
        dbAudit.dbAudit(RESOURCE_NAME, A_SEQ_PU, nodeType);

        List<IntegrityAuditEntity> 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);

        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(RESOURCE_NAME, A_SEQ_PU, properties);

        new DbDao(RESOURCE_NAME, 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(RESOURCE_NAME, 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(RESOURCE_NAME, 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 the properties
     */
    private void recreateDb1(Properties properties) {
        em.close();
        emf.close();

        createDb(properties);

        em = em2;
        emf = emf2;

        em2 = null;
        emf2 = null;
    }

}