summaryrefslogtreecommitdiffstats
path: root/tests/test_config_notif.py
blob: 707717cb331cf9a5f2e1999005853d37d7f9f267 (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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
# ============LICENSE_START=======================================================
# Copyright (c) 2020 AT&T Intellectual Property. All rights reserved.
# Copyright 2020 Deutsche Telekom. 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=========================================================

import config_notif
# from miss_htbt_service.mod.trapd_get_cbs_config import get_cbs_config
import mod.trapd_get_cbs_config
import mod.trapd_settings

from . import monkey_psycopg2
import psycopg2
import tempfile, sys, json, os

def assert_default_values(ip_address, port_num, user_name, password, db_name, cbs_polling_required, cbs_polling_interval):
    """
    used in the test_read_hb_properties*() tests
    """
    assert(str(port_num) == "5432")
    assert(str(user_name) == "postgres")
    assert(str(db_name) == "postgres")
    assert(str(password) == "postgres")

def test_read_hb_properties_default():
    """
    run read_hb_properties_default()
    """
    ( ip_address, port_num, user_name, password, db_name, cbs_polling_required, cbs_polling_interval ) = config_notif.read_hb_properties_default()
    assert_default_values(ip_address, port_num, user_name, password, db_name, cbs_polling_required, cbs_polling_interval)

def test_read_hb_properties_success():
    """
    run read_hb_properties() to read properties from a file
    """
    tmp = tempfile.NamedTemporaryFile(mode="w+")
    testdata = {
        "pg_ipAddress": "10.0.0.99",
        "pg_portNum": 65432,
        "pg_dbName": "dbname",
        "pg_userName": "pguser",
        "pg_passwd": "pgpswd",
        "CBS_polling_allowed": True,
        "CBS_polling_interval": 30,
        "SERVICE_NAME": "service_name"
    }
    json.dump(testdata, tmp)
    tmp.flush()
    ( ip_address, port_num, user_name, password, db_name, cbs_polling_required, cbs_polling_interval ) = config_notif.read_hb_properties(tmp.name)
    assert(str(ip_address) == str(testdata["pg_ipAddress"]))
    assert(str(port_num) == str(testdata["pg_portNum"]))
    assert(str(user_name) == str(testdata["pg_userName"]))
    assert(str(password) == str(testdata["pg_passwd"]))
    assert(str(db_name) == str(testdata["pg_dbName"]))
    assert(str(cbs_polling_required) == str(testdata["CBS_polling_allowed"]))
    assert(str(cbs_polling_interval) == str(testdata["CBS_polling_interval"]))
    assert(str(os.environ['SERVICE_NAME']) == str(testdata["SERVICE_NAME"]))

def test_read_hb_properties_fail_bad_json():
    """
    failure case for read_hb_properties: bad json in the file
    """
    tmp = tempfile.NamedTemporaryFile(mode="w+")
    print("bad json", file=tmp)
    tmp.flush()
    ( ip_address, port_num, user_name, password, db_name, cbs_polling_required, cbs_polling_interval ) = config_notif.read_hb_properties(tmp.name)
    assert_default_values(ip_address, port_num, user_name, password, db_name, cbs_polling_required, cbs_polling_interval)

def test_read_hb_properties_fail_missing_parameter():
    """
    failure case for read_hb_properties: CBS_polling_allowed is missing
    """
    tmp = tempfile.NamedTemporaryFile(mode="w+")
    testdata = {
        "pg_ipAddress": "10.0.0.99",
        "pg_portNum": 65432,
        "pg_dbName": "dbname",
        "pg_userName": "pguser",
        "pg_passwd": "pgpswd",
        # "CBS_polling_allowed": True, # missing CBS_polling_allowed
        "CBS_polling_interval": 30,
        "SERVICE_NAME": "service_name"
    }
    json.dump(testdata, tmp)
    tmp.flush()
    ( ip_address, port_num, user_name, password, db_name, cbs_polling_required, cbs_polling_interval ) = config_notif.read_hb_properties(tmp.name)
    assert_default_values(ip_address, port_num, user_name, password, db_name, cbs_polling_required, cbs_polling_interval)

def test_postgres_db_open(monkeypatch):
    """
    test postgres_db_open()
    """
    monkeypatch.setattr(psycopg2, 'connect', monkey_psycopg2.monkey_connect)
    monkey_psycopg2.monkey_reset_forces()
    dbconn = config_notif.postgres_db_open("test", "testpswd", "testsite", 5432, "dbname")
    assert(type(dbconn) is monkey_psycopg2.MockConn)
    
def test_postgres_db_open_fail(monkeypatch):
    """
    failure ase for postgres_db_open()
    """
    monkeypatch.setattr(psycopg2, 'connect', monkey_psycopg2.monkey_connect)
    monkey_psycopg2.monkey_reset_forces(connect=True)
    dbconn = config_notif.postgres_db_open("test", "badpassword", "testsite", 5432, "dbname")
    assert(type(dbconn) is not monkey_psycopg2.MockConn)

def test_db_table_creation_check(monkeypatch):
    """
    test db_table_creation_check()
    """
    monkeypatch.setattr(psycopg2, 'connect', monkey_psycopg2.monkey_connect)
    monkey_psycopg2.monkey_reset_forces()
    dbconn = config_notif.postgres_db_open("test", "testpswd", "testsite", 5432, "dbname")
    dbconn.monkey_setDbInfo({ "select * from information_schema.tables": [ [ "testtable" ] ] })
    assert(type(dbconn) is monkey_psycopg2.MockConn)
    ret = config_notif.db_table_creation_check(dbconn, "testtable")
    assert(ret == True)
    ret2 = config_notif.db_table_creation_check(dbconn, "missingtable")
    monkey_psycopg2.monkey_reset_forces(cursor=True)
    ret3 = config_notif.db_table_creation_check(dbconn, "testtable")
    assert(ret3 is None)
    
def test_commit_and_close_db(monkeypatch):
    """
    test commit_and_close_db()
    """
    monkeypatch.setattr(psycopg2, 'connect', monkey_psycopg2.monkey_connect)
    monkey_psycopg2.monkey_reset_forces()
    dbconn = config_notif.postgres_db_open("test", "testpswd", "testsite", 5432, "dbname")
    assert(type(dbconn) is monkey_psycopg2.MockConn)
    print("commit_and_close_db(): no forced failures")
    ret = config_notif.commit_and_close_db(dbconn)
    assert(ret == True)

def test_commit_and_close_db_fail1(monkeypatch):
    """
    failure case for commit_and_close_db(): dbconn.close() fails
    """
    monkeypatch.setattr(psycopg2, 'connect', monkey_psycopg2.monkey_connect)
    monkey_psycopg2.monkey_reset_forces()
    dbconn = config_notif.postgres_db_open("test", "testpswd", "testsite", 5432, "dbname")
    assert(type(dbconn) is monkey_psycopg2.MockConn)
    print("commit_and_close_db() - close failure")
    monkey_psycopg2.monkey_reset_forces(close=True)
    ret = config_notif.commit_and_close_db(dbconn)
    assert(ret == False)

def test_commit_and_close_db_fail2(monkeypatch):
    """
    failure case for commit_and_close_db(): dbconn.commit() fails
    """
    monkeypatch.setattr(psycopg2, 'connect', monkey_psycopg2.monkey_connect)
    monkey_psycopg2.monkey_reset_forces()
    dbconn = config_notif.postgres_db_open("test", "testpswd", "testsite", 5432, "dbname")
    assert(type(dbconn) is monkey_psycopg2.MockConn)
    print("commit_and_close_db() - commit failure")
    monkey_psycopg2.monkey_reset_forces(commit=True)
    ret = config_notif.commit_and_close_db(dbconn)
    assert(ret == False)

def test_read_hb_properties_default(monkeypatch):
    """
    test read_hb_properties_default()
    """
    monkeypatch.setattr(psycopg2, 'connect', monkey_psycopg2.monkey_connect)
    monkey_psycopg2.monkey_reset_forces()
    monkey_psycopg2.monkey_set_defaults({
        "testdb1": {
            "hb_common": [
                [ 1, "sn1", 31, "st1" ],
                [ 2, "sn2", 32, "st2" ]
            ]
        }
    })

    output = config_notif.read_hb_common("test", "testpswd", "testsite", 5432, "testdb1")
    assert(output[0] == 1)
    assert(output[1] == "st1")
    assert(output[2] == "sn1")
    assert(output[3] == 31)
    
def test_update_hb_common(monkeypatch):
    """
    test update_hb_common()
    """
    monkeypatch.setattr(psycopg2, 'connect', monkey_psycopg2.monkey_connect)
    monkey_psycopg2.monkey_reset_forces()
    output = config_notif.update_hb_common(None, 1234, "st1234", "test", "testpswd", "testsite", 5432, "testdb1")
    assert(output == True)

def monkeypatch_get_cbs_config_False():
    """
    monkeypatch for get_cbs_config() to force it to return False
    Required side affect: c_config is set to a json value
    """
    print("monkeypatch_get_cbs_config_False()")
    mod.trapd_settings.c_config = { "patch": "false" }
    return False

def monkeypatch_get_cbs_config_True():
    """
    monkeypatch for get_cbs_config() to force it to return False
    Required side affect: c_config is set to a json value
    """
    print("monkeypatch_get_cbs_config_True()")
    mod.trapd_settings.c_config = { "patch": "true" }
    return True

def test_fetch_json_file_get_cbs_config_is_true(monkeypatch):
    """
    test fetch_json_file() with get_cbs_config() returning True
    """
    monkeypatch.setattr(mod.trapd_get_cbs_config, 'get_cbs_config', monkeypatch_get_cbs_config_True)
    tmp1 = tempfile.NamedTemporaryFile(mode="w+")
    tmp2 = tempfile.NamedTemporaryFile(mode="w+")
    output = config_notif.fetch_json_file(download_json = tmp1.name, config_json = tmp2.name)
    assert(output == tmp1.name)
    with open(tmp1.name, "r") as fp:
        j1 = json.load(fp)
    print(f"j1={j1}")
    assert("patch" in j1 and j1["patch"] == "true")

def test_fetch_json_file_get_cbs_config_is_false(monkeypatch):
    """
    test fetch_json_file() with get_cbs_config() returning False
    """
    monkeypatch.setattr(mod.trapd_get_cbs_config, 'get_cbs_config', monkeypatch_get_cbs_config_False)
    tmp1 = tempfile.NamedTemporaryFile(mode="w+")
    tmp2 = tempfile.NamedTemporaryFile(mode="w+")
    output = config_notif.fetch_json_file(download_json = tmp1.name, config_json = tmp2.name)
    assert(output == tmp2.name)

FETCH_JSON_FILE = None

def monkeypatch_fetch_json_file():
    """
    Monkeypatch for fetch_json_file() to test config_notif_run()
    """
    print("monkeypatch_fetch_json_file()")
    return FETCH_JSON_FILE

def monkeypatch_return_False(*args, **kwargs):
    """
    Monkeypatch that can be used to force a function to return False
    """
    print("monkeypatch_return_False()")
    return False


def test_config_notif_run_good(monkeypatch):
    """
    test config_notif_run()
    everything good: "dbname" found (from below JSON info), "hb_common" listed in tables
    and hb_common has data.
    """
    monkeypatch.setattr(config_notif, 'fetch_json_file', monkeypatch_fetch_json_file)

    tmp = tempfile.NamedTemporaryFile(mode="w+")
    global FETCH_JSON_FILE
    FETCH_JSON_FILE = tmp.name

    monkeypatch.setattr(psycopg2, 'connect', monkey_psycopg2.monkey_connect)
    monkey_psycopg2.monkey_reset_forces()

    monkey_psycopg2.monkey_set_defaults({
        "dbname": {
            "from information_schema.tables": [
                [ "hb_common" ]
            ],
            "from hb_common": [
                [ 1, "sn1", 31, "st1" ],
                [ 2, "sn2", 32, "st2" ]
            ]
        }
    })

    testdata = {
        "pg_ipAddress": "10.0.0.99",
        "pg_portNum": 65432,
        "pg_dbName": "dbname",
        "pg_userName": "pguser",
        "pg_passwd": "pgpswd",
        "CBS_polling_allowed": True,
        "CBS_polling_interval": 30,
        "SERVICE_NAME": "service_name"
    }
    json.dump(testdata, tmp)
    tmp.flush()
    
    output = config_notif.config_notif_run()
    print(f"output={output}")
    assert(output == True)

def test_config_notif_run_fail1(monkeypatch):
    """
    test config_notif_run()
    Failure case 1: "dbname" NOT found (from below JSON info), "hb_common" listed in tables
    and hb_common has data.
    """
    monkeypatch.setattr(config_notif, 'fetch_json_file', monkeypatch_fetch_json_file)

    tmp = tempfile.NamedTemporaryFile(mode="w+")
    global FETCH_JSON_FILE
    FETCH_JSON_FILE = tmp.name

    monkeypatch.setattr(psycopg2, 'connect', monkey_psycopg2.monkey_connect)
    monkey_psycopg2.monkey_reset_forces()

    monkey_psycopg2.monkey_set_defaults({
        "dbnameNOTHERE": {
            "from information_schema.tables": [
                [ "hb_common" ]
            ],
            "from hb_common": [
                [ 1, "sn1", 31, "st1" ],
                [ 2, "sn2", 32, "st2" ]
            ]
        }
    })

    testdata = {
        "pg_ipAddress": "10.0.0.99",
        "pg_portNum": 65432,
        "pg_dbName": "dbname",
        "pg_userName": "pguser",
        "pg_passwd": "pgpswd",
        "CBS_polling_allowed": True,
        "CBS_polling_interval": 30,
        "SERVICE_NAME": "service_name"
    }
    json.dump(testdata, tmp)
    tmp.flush()
    
    output = config_notif.config_notif_run()
    print(f"output={output}")
    assert(output is None)

def test_config_notif_run_fail2(monkeypatch):
    """
    test config_notif_run()
    Failure case 2: "dbname" found (from below JSON info), "hb_common" NOT listed in tables
    and hb_common has data.
    """
    monkeypatch.setattr(config_notif, 'fetch_json_file', monkeypatch_fetch_json_file)

    tmp = tempfile.NamedTemporaryFile(mode="w+")
    global FETCH_JSON_FILE
    FETCH_JSON_FILE = tmp.name

    monkeypatch.setattr(psycopg2, 'connect', monkey_psycopg2.monkey_connect)
    monkey_psycopg2.monkey_reset_forces()

    monkey_psycopg2.monkey_set_defaults({
        "dbname": {
            "from information_schema.tables": [
                [ "hb_commonNOTHERE" ]
            ],
            "from hb_common": [
                [ 1, "sn1", 31, "st1" ],
                [ 2, "sn2", 32, "st2" ]
            ]
        }
    })

    testdata = {
        "pg_ipAddress": "10.0.0.99",
        "pg_portNum": 65432,
        "pg_dbName": "dbname",
        "pg_userName": "pguser",
        "pg_passwd": "pgpswd",
        "CBS_polling_allowed": True,
        "CBS_polling_interval": 30,
        "SERVICE_NAME": "service_name"
    }
    json.dump(testdata, tmp)
    tmp.flush()
    
    output = config_notif.config_notif_run()
    print(f"output={output}")
    assert(output is None)

def test_config_notif_run_fail3(monkeypatch):
    """
    test config_notif_run()
    Failure case 3: "dbname" found (from below JSON info), "hb_common" listed in tables
    and update_hb_common() fails
    """
    monkeypatch.setattr(config_notif, 'fetch_json_file', monkeypatch_fetch_json_file)
    monkeypatch.setattr(config_notif, 'update_hb_common', monkeypatch_return_False)

    tmp = tempfile.NamedTemporaryFile(mode="w+")
    global FETCH_JSON_FILE
    FETCH_JSON_FILE = tmp.name

    monkeypatch.setattr(psycopg2, 'connect', monkey_psycopg2.monkey_connect)
    monkey_psycopg2.monkey_reset_forces()

    monkey_psycopg2.monkey_set_defaults({
        "dbname": {
            "from information_schema.tables": [
                [ "hb_common" ]
            ],
            "from hb_common": [
                [ 1, "sn1", 31, "st1" ],
                [ 2, "sn2", 32, "st2" ]
            ]
        }
    })

    testdata = {
        "pg_ipAddress": "10.0.0.99",
        "pg_portNum": 65432,
        "pg_dbName": "dbname",
        "pg_userName": "pguser",
        "pg_passwd": "pgpswd",
        "CBS_polling_allowed": True,
        "CBS_polling_interval": 30,
        "SERVICE_NAME": "service_name"
    }
    json.dump(testdata, tmp)
    tmp.flush()
    
    output = config_notif.config_notif_run()
    print(f"output={output}")
    assert(output == False)