Debian Codegraph @

ansible_collections/community/postgresql/tests/unit/plugins/module_utils/test_postgres.py

raw
1 # Copyright: (c) 2019, Andrew Klychkov (@Andersson007) <[email protected]>
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 from __future__ import absolute_import, division, print_function
5
6 __metaclass__ = type
7 from os import environ
8
9 import ansible_collections.community.postgresql.plugins.module_utils.postgres as pg
10 import pytest
11 from ansible_collections.community.postgresql.plugins.module_utils.version import \
12 LooseVersion
13
14 INPUT_DICT = dict(
15 session_role=dict(default=''),
16 login_user=dict(default='postgres'),
17 login_password=dict(default='test', no_log=True),
18 login_host=dict(default='test'),
19 login_unix_socket=dict(default=''),
20 login_port=dict(type='int', default=5432, aliases=['port']),
21 ssl_mode=dict(
22 default='prefer',
23 choices=['allow', 'disable', 'prefer', 'require', 'verify-ca', 'verify-full']
24 ),
25 ca_cert=dict(aliases=['ssl_rootcert']),
26 ssl_cert=dict(type='path'),
27 ssl_key=dict(type='path'),
28 )
29
30 EXPECTED_DICT = dict(
31 user=dict(default='postgres'),
32 password=dict(default='test', no_log=True),
33 host=dict(default='test'),
34 port=dict(type='int', aliases=['port'], default=5432),
35 sslmode=dict(
36 default='prefer',
37 choices=['allow', 'disable', 'prefer', 'require', 'verify-ca', 'verify-full']
38 ),
39 sslrootcert=dict(aliases=['ssl_rootcert']),
40 sslcert=dict(type='path'),
41 sslkey=dict(type='path'),
42 )
43
44
45 class TestPostgresCommonArgSpec():
46
47 """
48 Namespace for testing postgresql_common_arg_spec() function.
49 """
50
51 def test_postgres_common_argument_spec(self):
52 """
53 Test for postgresql_common_arg_spec() function.
54
55 The tested function just returns a dictionary with the default
56 parameters and their values for PostgreSQL modules.
57 The return and expected dictionaries must be compared.
58 """
59 expected_dict = dict(
60 login_user=dict(default='postgres', aliases=['login'], deprecated_aliases=[
61 {
62 'name': 'login',
63 'version': '5.0.0',
64 'collection_name': 'community.postgresql',
65 }
66 ]),
67 login_password=dict(default='', no_log=True),
68 login_host=dict(default='', aliases=['host'], deprecated_aliases=[
69 {
70 'name': 'host',
71 'version': '5.0.0',
72 'collection_name': 'community.postgresql',
73 }
74 ]),
75 login_unix_socket=dict(default='', aliases=['unix_socket'], deprecated_aliases=[
76 {
77 'name': 'unix_socket',
78 'version': '5.0.0',
79 'collection_name': 'community.postgresql',
80 }
81 ]),
82 login_port=dict(type='int', default=5432, aliases=['port'], deprecated_aliases=[
83 {
84 'collection_name': 'community.postgresql',
85 'name': 'port',
86 'version': '5.0.0'
87 }
88 ]),
89 ssl_mode=dict(
90 default='prefer',
91 choices=['allow', 'disable', 'prefer', 'require', 'verify-ca', 'verify-full']
92 ),
93 ca_cert=dict(aliases=['ssl_rootcert']),
94 ssl_cert=dict(type='path'),
95 ssl_key=dict(type='path'),
96 connect_params=dict(default={}, type='dict'),
97 )
98 assert pg.postgres_common_argument_spec() == expected_dict
99
100 # Setting new values for checking environment variables
101 expected_dict['login_port']['default'] = 5435
102 expected_dict['login_user']['default'] = 'test_user'
103
104 # Setting environment variables
105 environ['PGUSER'] = 'test_user'
106 environ['PGPORT'] = '5435'
107 assert pg.postgres_common_argument_spec() == expected_dict
108
109
110 @pytest.fixture
111 def m_psycopg2():
112 """Return mock object for psycopg2 emulation."""
113 global Cursor
114 Cursor = None
115
116 class Cursor():
117 def __init__(self):
118 self.passed_query = None
119
120 def execute(self, query):
121 self.passed_query = query
122
123 def close(self):
124 pass
125
126 global DbConnection
127 DbConnection = None
128
129 class DbConnection():
130 def __init__(self):
131 pass
132
133 def cursor(self, cursor_factory=None):
134 return Cursor()
135
136 def set_session(self, autocommit=None):
137 pass
138
139 def set_isolation_level(self, isolevel):
140 pass
141
142 class Extras():
143 def __init__(self):
144 self.DictCursor = True
145
146 class Extensions():
147 def __init__(self):
148 self.ISOLATION_LEVEL_AUTOCOMMIT = True
149
150 class DummyPsycopg2():
151 def __init__(self):
152 self.__version__ = "2.9.6"
153 self.extras = Extras()
154 self.extensions = Extensions()
155
156 def connect(self, host=None, port=None, user=None,
157 password=None, sslmode=None, sslrootcert=None, connect_params=None):
158 if user == 'Exception':
159 raise Exception()
160
161 return DbConnection()
162
163 return DummyPsycopg2()
164
165
166 class TestEnsureReqLibs():
167
168 """
169 Namespace for testing ensure_required_libs() function.
170
171 If there is something wrong with libs, the function invokes fail_json()
172 method of AnsibleModule object passed as an argument called 'module'.
173 Therefore we must check:
174 1. value of err_msg attribute of m_ansible_module mock object.
175 """
176
177 @pytest.fixture(scope='class')
178 def m_ansible_module(self):
179 """Return an object of dummy AnsibleModule class."""
180 class Dummym_ansible_module():
181 def __init__(self):
182 self.params = {'ca_cert': False}
183 self.warn_msg = ''
184 self.err_msg = ''
185
186 def warn(self, msg):
187 self.warn_msg = msg
188
189 def fail_json(self, msg):
190 self.err_msg = msg
191
192 return Dummym_ansible_module()
193
194 def test_ensure_req_libs_has_not_psycopg2(self, m_ansible_module):
195 """Test ensure_required_libs() with psycopg2 is None."""
196 # HAS_PSYCOPG is False by default
197 pg.ensure_required_libs(m_ansible_module)
198 assert 'Failed to import the required Python library (psycopg2)' in m_ansible_module.err_msg
199
200 def test_ensure_req_libs_has_psycopg2(self, m_ansible_module, monkeypatch):
201 """Test ensure_required_libs() with psycopg2 is not None."""
202 monkeypatch.setattr(pg, 'HAS_PSYCOPG', True)
203 monkeypatch.setattr(pg, 'PSYCOPG_VERSION', "2.9")
204
205 pg.ensure_required_libs(m_ansible_module)
206 assert m_ansible_module.err_msg == ''
207
208 def test_ensure_req_libs_ca_cert(self, m_ansible_module, m_psycopg2, monkeypatch):
209 """
210 Test with module.params['ca_cert'], psycopg2 version is suitable.
211 """
212 m_ansible_module.params['ca_cert'] = True
213 monkeypatch.setattr(pg, 'HAS_PSYCOPG', True)
214 monkeypatch.setattr(pg, 'PSYCOPG_VERSION', LooseVersion("2.9.6"))
215 monkeypatch.setattr(pg, 'psycopg', m_psycopg2)
216
217 pg.ensure_required_libs(m_ansible_module)
218 assert m_ansible_module.err_msg == ''
219
220 def test_ensure_req_libs_ca_cert_low_psycopg2_ver(self, m_ansible_module, m_psycopg2, monkeypatch):
221 """
222 Test with module.params['ca_cert'], psycopg2 version is wrong.
223 """
224 m_ansible_module.params['ca_cert'] = True
225 psycopg = m_psycopg2
226 monkeypatch.setattr(pg, 'psycopg', psycopg)
227 # Set wrong psycopg2 version number:
228 monkeypatch.setattr(pg, 'PSYCOPG_VERSION', LooseVersion("2.4.2"))
229
230 pg.ensure_required_libs(m_ansible_module)
231 assert 'psycopg2 must be at least 2.4.3' in m_ansible_module.err_msg
232
233
234 @pytest.fixture(scope='class')
235 def m_ansible_module():
236 """Return an object of dummy AnsibleModule class."""
237 class DummyAnsibleModule():
238 def __init__(self):
239
240 # take default params from argument spec
241 spec = pg.postgres_common_argument_spec()
242 params = dict()
243 for k in spec.keys():
244 params[k] = spec[k].get('default')
245
246 self.params = params
247 self.err_msg = ''
248 self.warn_msg = ''
249
250 def fail_json(self, msg):
251 self.err_msg = msg
252
253 def warn(self, msg):
254 self.warn_msg = msg
255
256 return DummyAnsibleModule()
257
258
259 class TestConnectToDb():
260
261 """
262 Namespace for testing connect_to_db() function.
263
264 When some connection errors occur connect_to_db() caught any of them
265 and invoke fail_json() or warn() methods of AnsibleModule object
266 depending on the passed parameters.
267 connect_to_db may return db_connection object or None if errors occurred.
268 Therefore we must check:
269 1. Values of err_msg and warn_msg attributes of m_ansible_module mock object.
270 2. Types of return objects (db_connection and cursor).
271 """
272
273 def test_connect_to_db(self, m_ansible_module, monkeypatch, m_psycopg2):
274 """Test connect_to_db(), common test."""
275 monkeypatch.setattr(pg, 'psycopg', m_psycopg2)
276 monkeypatch.setattr(pg, 'psycopg2', m_psycopg2)
277
278 conn_params = pg.get_conn_params(m_ansible_module, m_ansible_module.params)
279 db_connection, dummy = pg.connect_to_db(m_ansible_module, conn_params)
280 cursor = db_connection.cursor()
281 # if errors, db_connection returned as None:
282 assert type(db_connection) is DbConnection
283 assert type(cursor) is Cursor
284 assert m_ansible_module.err_msg == ''
285 # The default behaviour, normal in this case:
286 assert 'Database name has not been passed' in m_ansible_module.warn_msg
287
288 def test_session_role(self, m_ansible_module, monkeypatch, m_psycopg2):
289 """Test connect_to_db(), switch on session_role."""
290 monkeypatch.setattr(pg, 'psycopg', m_psycopg2)
291 monkeypatch.setattr(pg, 'psycopg2', m_psycopg2)
292
293 m_ansible_module.params['session_role'] = 'test_role'
294 conn_params = pg.get_conn_params(m_ansible_module, m_ansible_module.params)
295 db_connection, dummy = pg.connect_to_db(m_ansible_module, conn_params)
296 cursor = db_connection.cursor()
297 # if errors, db_connection returned as None:
298 assert type(db_connection) is DbConnection
299 assert type(cursor) is Cursor
300 assert m_ansible_module.err_msg == ''
301 # The default behaviour, normal in this case:
302 assert 'Database name has not been passed' in m_ansible_module.warn_msg
303
304 def test_fail_on_conn_true(self, m_ansible_module, monkeypatch, m_psycopg2):
305 """
306 Test connect_to_db(), fail_on_conn arg passed as True (the default behavior).
307 """
308 monkeypatch.setattr(pg, 'psycopg', m_psycopg2)
309
310 m_ansible_module.params['login_user'] = 'Exception' # causes Exception
311
312 conn_params = pg.get_conn_params(m_ansible_module, m_ansible_module.params)
313 db_connection, dummy = pg.connect_to_db(m_ansible_module, conn_params, fail_on_conn=True)
314
315 assert 'unable to connect to database' in m_ansible_module.err_msg
316 assert db_connection is None
317
318 def test_fail_on_conn_false(self, m_ansible_module, monkeypatch, m_psycopg2):
319 """
320 Test connect_to_db(), fail_on_conn arg passed as False.
321 """
322 monkeypatch.setattr(pg, 'psycopg', m_psycopg2)
323
324 m_ansible_module.params['login_user'] = 'Exception' # causes Exception
325
326 conn_params = pg.get_conn_params(m_ansible_module, m_ansible_module.params)
327 db_connection, dummy = pg.connect_to_db(m_ansible_module, conn_params, fail_on_conn=False)
328
329 assert m_ansible_module.err_msg == ''
330 assert 'PostgreSQL server is unavailable' in m_ansible_module.warn_msg
331 assert db_connection is None
332
333 def test_autocommit_true(self, m_ansible_module, monkeypatch, m_psycopg2):
334 """
335 Test connect_to_db(), autocommit arg passed as True (the default is False).
336 """
337
338 # case 1: psycopg2.__version >= 2.4.2 (the default in m_psycopg2)
339 monkeypatch.setattr(pg, 'psycopg', m_psycopg2)
340 monkeypatch.setattr(pg, 'psycopg2', m_psycopg2)
341
342 conn_params = pg.get_conn_params(m_ansible_module, m_ansible_module.params)
343 db_connection, dummy = pg.connect_to_db(m_ansible_module, conn_params, autocommit=True)
344 cursor = db_connection.cursor()
345
346 # if errors, db_connection returned as None:
347 assert type(db_connection) is DbConnection
348 assert type(cursor) is Cursor
349 assert m_ansible_module.err_msg == ''
350
351
352 class TestGetConnParams():
353
354 """Namespace for testing get_conn_params() function."""
355
356 def test_get_conn_params_def(self, m_ansible_module, m_psycopg2, monkeypatch):
357 """Test get_conn_params(), warn_db_default kwarg is default."""
358 monkeypatch.setattr(pg, 'psycopg', m_psycopg2)
359 assert pg.get_conn_params(m_ansible_module, INPUT_DICT) == EXPECTED_DICT
360 assert m_ansible_module.warn_msg == 'Database name has not been passed, used default database to connect to.'
361
362 def test_get_conn_params_warn_db_def_false(self, m_ansible_module, m_psycopg2, monkeypatch):
363 """Test get_conn_params(), warn_db_default kwarg is False."""
364 monkeypatch.setattr(pg, 'psycopg', m_psycopg2)
365 assert pg.get_conn_params(m_ansible_module, INPUT_DICT, warn_db_default=False) == EXPECTED_DICT
366 assert m_ansible_module.warn_msg == ''