Test Failed
Push — master ( 30a59f...a26a13 )
by Andreas
01:27
created

test_provide_unlock_reason()   A

Complexity

Conditions 2

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
c 1
b 0
f 0
dl 0
loc 16
rs 9.4285
1
import requests
2
import requests_mock
3
import unittest
4
import os.path
5
import tpm
6
import json
7
import logging
8
import hmac
9
import hashlib
10
import time
11
import random
12
13
log = logging.getLogger(__name__)
14
15
api_url = 'https://tpm.example.com/index.php/api/v4/'
16
local_path = 'tests/resources/'
17
18
item_limit = 20
19
20
def fake_data(url, m, altpath=False):
21
    """
22
    A stub urlopen() implementation that load json responses from
23
    the filesystem.
24
    """
25
26
    # Map path from url to a file
27
    path_parts = url.split('/')[6:]
28
    if altpath == False:
29
        path = '/'.join(path_parts)
30
    else:
31
        path = altpath
32
    resource_file = os.path.normpath('tests/resources/{}'.format(path))
33
    data_file = open(resource_file)
34
    data = json.load(data_file)
35
36
    # Must return a json-like object
37
    count = 0
38
    header = {}
39
    while True:
40
        count += 1
41
        if len(data) > item_limit and isinstance(data,list):
42
            returndata = data[:item_limit]
43
            data = data[item_limit:]
44
            pageingurl = url.replace('.json', '/page/{}.json'.format(count))
45
            log.debug("Registering URL: {}".format(pageingurl))
46
            log.debug("Registering data: {}".format(returndata))
47
            log.debug("Data length: {}".format(len(returndata)))
48
            log.debug("Registering header: {}".format(header))
49
            m.get(pageingurl, json=returndata, headers=header.copy())
50
            header = { 'link': '{}; rel="next"'.format(pageingurl)}
51
        else:
52
            log.debug("Registering URL: {}".format(url))
53
            log.debug("Registering data: {}".format(data))
54
            log.debug("Registering header: {}".format(header))
55
            log.debug("Data length: {}".format(len(data)))
56
            m.get(url, json=data, headers=header.copy())
57
            header.clear()
58
            break
59
60
class ClientProjectTestCase(unittest.TestCase):
61
    """Test cases for all project related queries."""
62
    client = tpm.TpmApiv4('https://tpm.example.com', username='USER', password='PASS')
63
    # get all retrievable sample data
64
    path_to_mock = 'projects.json'
65
    request_url = api_url + path_to_mock
66
    with requests_mock.Mocker() as m:
67
        fake_data(request_url, m)
68
        global Projects
69
        Projects = client.list_projects()
70
71
    def setUp(self):
72
        self.client = tpm.TpmApiv4('https://tpm.example.com', username='USER', password='PASS')
73
74
    def test_function_list_projects(self):
75
        """Test function list_projects."""
76
        path_to_mock = 'projects.json'
77
        request_url = api_url + path_to_mock
78
        request_path = local_path + path_to_mock
79
        resource_file = os.path.normpath(request_path)
80
        data_file = open(resource_file)
81
        data = json.load(data_file)
82
        with requests_mock.Mocker() as m:
83
            fake_data(request_url, m)
84
            response = self.client.list_projects()
85
        # number of passwords as from original json file.
86
        self.assertEqual(data, response)
87
88
    def test_function_list_projects_archived(self):
89
        """Test function list_projects_archived."""
90
        path_to_mock = 'projects/archived.json'
91
        request_url = api_url + path_to_mock
92
        request_path = local_path + path_to_mock
93
        resource_file = os.path.normpath(request_path)
94
        data_file = open(resource_file)
95
        data = json.load(data_file)
96
        with requests_mock.Mocker() as m:
97
            fake_data(request_url, m)
98
            response = self.client.list_projects_archived()
99
        # number of passwords as from original json file.
100
        self.assertEqual(data, response)
101
102
    def test_function_list_projects_favorite(self):
103
        """Test function list_projects_favorite."""
104
        path_to_mock = 'projects/favorite.json'
105
        request_url = api_url + path_to_mock
106
        request_path = local_path + path_to_mock
107
        resource_file = os.path.normpath(request_path)
108
        data_file = open(resource_file)
109
        data = json.load(data_file)
110
        with requests_mock.Mocker() as m:
111
            fake_data(request_url, m)
112
            response = self.client.list_projects_favorite()
113
        # number of passwords as from original json file.
114
        self.assertEqual(data, response)
115
116 View Code Duplication
    def test_function_list_projects_search(self):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
117
        """Test function list_projects_search."""
118
        searches = ['company', 'internal', 'website']
119
        for search in searches:
120
            path_to_mock = 'projects/search/{}.json'.format(search)
121
            request_url = api_url + path_to_mock
122
            request_path = local_path + path_to_mock
123
            resource_file = os.path.normpath(request_path)
124
            data_file = open(resource_file)
125
            data = json.load(data_file)
126
            with requests_mock.Mocker() as m:
127
                fake_data(request_url, m)
128
                response = self.client.list_projects_search(search)
129
            # number of passwords as from original json file.
130
            self.assertEqual(data, response)
131
132 View Code Duplication
    def test_function_show_project(self):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
133
        """Test function show_project."""
134
        for project in Projects:
135
            project_id = project.get('id')
136
            log.debug("Testing with Project ID: {}".format(project_id))
137
            path_to_mock = 'projects/{}.json'.format(project_id)
138
            request_url = api_url + path_to_mock
139
            request_path = local_path + path_to_mock
140
            resource_file = os.path.normpath(request_path)
141
            data_file = open(resource_file)
142
            data = json.load(data_file)
143
            with requests_mock.Mocker() as m:
144
                fake_data(request_url, m)
145
                response = self.client.show_project(project_id)
146
            # number of passwords as from original json file.
147
            self.assertEqual(data, response)
148
149 View Code Duplication
    def test_function_list_passwords_of_project(self):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
150
        """Test function list_passwords_of_project."""
151
        for project in Projects:
152
            project_id = project.get('id')
153
            log.debug("Testing with Project ID: {}".format(project_id))
154
            path_to_mock = 'projects/{}/passwords.json'.format(project_id)
155
            request_url = api_url + path_to_mock
156
            request_path = local_path + path_to_mock
157
            resource_file = os.path.normpath(request_path)
158
            data_file = open(resource_file)
159
            data = json.load(data_file)
160
            with requests_mock.Mocker() as m:
161
                fake_data(request_url, m)
162
                response = self.client.list_passwords_of_project(project_id)
163
            # number of passwords as from original json file.
164
            self.assertEqual(data, response)
165
166 View Code Duplication
    def test_function_list_user_access_on_project(self):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
167
        """Test function list_user_access_on_project."""
168
        for project in Projects:
169
            project_id = project.get('id')
170
            log.debug("Testing with Project ID: {}".format(project_id))
171
            path_to_mock = 'projects/{}/security.json'.format(project_id)
172
            request_url = api_url + path_to_mock
173
            request_path = local_path + path_to_mock
174
            resource_file = os.path.normpath(request_path)
175
            data_file = open(resource_file)
176
            data = json.load(data_file)
177
            with requests_mock.Mocker() as m:
178
                fake_data(request_url, m)
179
                response = self.client.list_user_access_on_project(project_id)
180
            # number of passwords as from original json file.
181
            self.assertEqual(data, response)
182
183
    def test_function_create_project(self):
184
        """Test function create_project."""
185
        path_to_mock = 'projects.json'
186
        request_url = api_url + path_to_mock
187
        return_data = { "id": 4 }
188
        create_data = { "name": "someproject"}
189
        with requests_mock.Mocker() as m:
190
            m.post(request_url, json=return_data, status_code=200)
191
            response = self.client.create_project(create_data)
192
        self.assertEqual(response, return_data.get('id'))
193
194
    def test_function_update_project(self):
195
        """Test function update_project."""
196
        path_to_mock = 'projects/4.json'
197
        request_url = api_url + path_to_mock
198
        update_data = { "name": "someproject"}
199
        with requests_mock.Mocker() as m:
200
            m.put(request_url, status_code=204)
201
            response = self.client.update_project('4', update_data)
202
        self.assertEqual(response, None)
203
204
    def test_function_change_parent_of_project(self):
205
        """Test function change_parent_of_project."""
206
        path_to_mock = 'projects/4/change_parent.json'
207
        request_url = api_url + path_to_mock
208
        with requests_mock.Mocker() as m:
209
            m.put(request_url, status_code=204)
210
            response = self.client.change_parent_of_project('4', '5')
211
        self.assertEqual(response, None)
212
213
    def test_function_update_security_of_project(self):
214
        """Test function update_security_of_project."""
215
        path_to_mock = 'projects/4/security.json'
216
        request_url = api_url + path_to_mock
217
        with requests_mock.Mocker() as m:
218
            m.put(request_url, status_code=204)
219
            response = self.client.update_security_of_project('4', {'name': 'setdata'})
220
        self.assertEqual(response, None)
221
222
    def test_function_archive_project(self):
223
        """Test function archive_project."""
224
        path_to_mock = 'projects/4/archive.json'
225
        request_url = api_url + path_to_mock
226
        with requests_mock.Mocker() as m:
227
            m.put(request_url, status_code=204)
228
            response = self.client.archive_project('4')
229
        self.assertEqual(response, None)
230
231
    def test_function_delete_project(self):
232
        """Test function delete_project."""
233
        path_to_mock = 'projects/4.json'
234
        request_url = api_url + path_to_mock
235
        with requests_mock.Mocker() as m:
236
            m.delete(request_url, status_code=204)
237
            response = self.client.delete_project('4')
238
        self.assertEqual(response, None)
239
240
    def test_function_unarchive_project(self):
241
        """Test function unarchive_project."""
242
        path_to_mock = 'projects/4/unarchive.json'
243
        request_url = api_url + path_to_mock
244
        with requests_mock.Mocker() as m:
245
            m.put(request_url, status_code=204)
246
            response = self.client.unarchive_project('4')
247
        self.assertEqual(response, None)
248
249 View Code Duplication
    def test_function_list_subprojects(self):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
250
        """Test function list_subprojects."""
251
        for project in Projects:
252
            project_id = project.get('id')
253
            log.debug("Testing with Project ID: {}".format(project_id))
254
            path_to_mock = 'projects/{}/subprojects.json'.format(project_id)
255
            request_url = api_url + path_to_mock
256
            request_path = local_path + path_to_mock
257
            resource_file = os.path.normpath(request_path)
258
            data_file = open(resource_file)
259
            data = json.load(data_file)
260
            with requests_mock.Mocker() as m:
261
                fake_data(request_url, m)
262
                response = self.client.list_subprojects(project_id)
263
            # number of passwords as from original json file.
264
            self.assertEqual(data, response)
265
266 View Code Duplication
    def test_function_list_subprojects_action_new_pwd(self):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
267
        """Test function list_subprojects_action_new_pwd."""
268
        action = 'new_pwd'
269
        for project in Projects:
270
            project_id = project.get('id')
271
            log.debug("Testing with Project ID: {}".format(project_id))
272
            path_to_mock = 'projects/{}/subprojects/{}.json'.format(project_id, action)
273
            request_url = api_url + path_to_mock
274
            request_path = local_path + path_to_mock
275
            resource_file = os.path.normpath(request_path)
276
            data_file = open(resource_file)
277
            data = json.load(data_file)
278
            with requests_mock.Mocker() as m:
279
                fake_data(request_url, m)
280
                response = self.client.list_subprojects_action(project_id, action)
281
            # number of passwords as from original json file.
282
            self.assertEqual(data, response)
283
284
class ClientPasswordTestCase(unittest.TestCase):
285
    """Test cases for all password related queries."""
286
    client = tpm.TpmApiv4('https://tpm.example.com', username='USER', password='PASS')
287
    path_to_mock = 'passwords.json'
288
    request_url = api_url + path_to_mock
289
    with requests_mock.Mocker() as m:
290
        fake_data(request_url, m)
291
        global Passwords
292
        Passwords = client.list_passwords()
293
294
    def setUp(self):
295
        self.client = tpm.TpmApiv4('https://tpm.example.com', username='USER', password='PASS')
296
297 View Code Duplication
    def test_function_list_passwords(self):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
298
        """Test function list_passwords."""
299
        path_to_mock = 'passwords.json'
300
        request_url = api_url + path_to_mock
301
        request_path = local_path + path_to_mock
302
        resource_file = os.path.normpath(request_path)
303
        data_file = open(resource_file)
304
        data = sorted(json.load(data_file), key=lambda k: k['id'])
305
        with requests_mock.Mocker() as m:
306
            fake_data(request_url, m)
307
            response = sorted(self.client.list_passwords(), key=lambda k: k['id'])
308
        self.assertEqual(data, response)
309
310 View Code Duplication
    def test_function_list_passwords_archived(self):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
311
        """Test function list_passwords_archived."""
312
        path_to_mock = 'passwords/archived.json'
313
        request_url = api_url + path_to_mock
314
        request_path = local_path + path_to_mock
315
        resource_file = os.path.normpath(request_path)
316
        data_file = open(resource_file)
317
        data = sorted(json.load(data_file), key=lambda k: k['id'])
318
        with requests_mock.Mocker() as m:
319
            fake_data(request_url, m)
320
            response = sorted(self.client.list_passwords_archived(), key=lambda k: k['id'])
321
        self.assertEqual(data, response)
322
323 View Code Duplication
    def test_function_list_passwords_favorite(self):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
324
        """Test function list_passwords_favorite."""
325
        path_to_mock = 'passwords/favorite.json'
326
        request_url = api_url + path_to_mock
327
        request_path = local_path + path_to_mock
328
        resource_file = os.path.normpath(request_path)
329
        data_file = open(resource_file)
330
        data = sorted(json.load(data_file), key=lambda k: k['id'])
331
        with requests_mock.Mocker() as m:
332
            fake_data(request_url, m)
333
            response = sorted(self.client.list_passwords_favorite(), key=lambda k: k['id'])
334
        self.assertEqual(data, response)
335
336 View Code Duplication
    def test_function_list_passwords_search(self):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
337
        """Test function list_passwords_search."""
338
        searches = ['backup', 'dns', 'facebook', 'firewall', 'reddit', 'test']
339
        for search in searches:
340
            path_to_mock = 'passwords/search/{}.json'.format(search)
341
            request_url = api_url + path_to_mock
342
            request_path = local_path + path_to_mock
343
            resource_file = os.path.normpath(request_path)
344
            data_file = open(resource_file)
345
            data = json.load(data_file)
346
            with requests_mock.Mocker() as m:
347
                fake_data(request_url, m)
348
                response = self.client.list_passwords_search(search)
349
            # number of passwords as from original json file.
350
            self.assertEqual(data, response)
351
352 View Code Duplication
    def test_function_show_password(self):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
353
        """Test function show_password."""
354
        for password in Passwords:
355
            password_id = password.get('id')
356
            log.debug("Testing with Password ID: {}".format(password_id))
357
            path_to_mock = 'passwords/{}.json'.format(password_id)
358
            request_url = api_url + path_to_mock
359
            request_path = local_path + path_to_mock
360
            resource_file = os.path.normpath(request_path)
361
            data_file = open(resource_file)
362
            data = json.load(data_file)
363
            with requests_mock.Mocker() as m:
364
                fake_data(request_url, m)
365
                response = self.client.show_password(password_id)
366
            # number of passwords as from original json file.
367
            self.assertEqual(data, response)
368
369 View Code Duplication
    def test_function_list_user_access_on_password(self):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
370
        """Test function list_user_access_on_password."""
371
        for password in Passwords:
372
            password_id = password.get('id')
373
            log.debug("Testing with Password ID: {}".format(password_id))
374
            path_to_mock = 'passwords/{}/security.json'.format(password_id)
375
            request_url = api_url + path_to_mock
376
            request_path = local_path + path_to_mock
377
            resource_file = os.path.normpath(request_path)
378
            data_file = open(resource_file)
379
            data = json.load(data_file)
380
            with requests_mock.Mocker() as m:
381
                fake_data(request_url, m)
382
                response = self.client.list_user_access_on_password(password_id)
383
            # number of passwords as from original json file.
384
            self.assertEqual(data, response)
385
386
    def test_function_create_password(self):
387
        """Test function create_password."""
388
        path_to_mock = 'passwords.json'
389
        request_url = api_url + path_to_mock
390
        return_data = { "id": 4 }
391
        create_data = { "name": "someproject"}
392
        with requests_mock.Mocker() as m:
393
            m.post(request_url, json=return_data, status_code=200)
394
            response = self.client.create_password(create_data)
395
        self.assertEqual(response, return_data.get('id'))
396
397
    def test_function_update_password(self):
398
        """Test function update_password."""
399
        path_to_mock = 'passwords/4.json'
400
        request_url = api_url + path_to_mock
401
        update_data = { "name": "someproject"}
402
        with requests_mock.Mocker() as m:
403
            m.put(request_url, status_code=204)
404
            response = self.client.update_password('4', update_data)
405
        self.assertEqual(response, None)
406
407
    def test_function_update_security_of_password(self):
408
        """Test function update_security_of_password."""
409
        path_to_mock = 'passwords/4/security.json'
410
        request_url = api_url + path_to_mock
411
        with requests_mock.Mocker() as m:
412
            m.put(request_url, status_code=204)
413
            response = self.client.update_security_of_password('4', {'name': 'setdata'})
414
        self.assertEqual(response, None)
415
416
    def test_function_update_custom_fields_of_password(self):
417
        """Test function update_custom_fields_of_password."""
418
        path_to_mock = 'passwords/4/custom_fields.json'
419
        request_url = api_url + path_to_mock
420
        with requests_mock.Mocker() as m:
421
            m.put(request_url, status_code=204)
422
            response = self.client.update_custom_fields_of_password('4', {'name': 'setdata'})
423
        self.assertEqual(response, None)
424
425
    def test_function_delete_password(self):
426
        """Test function delete_password."""
427
        path_to_mock = 'passwords/4.json'
428
        request_url = api_url + path_to_mock
429
        with requests_mock.Mocker() as m:
430
            m.delete(request_url, status_code=204)
431
            response = self.client.delete_password('4')
432
        self.assertEqual(response, None)
433
434
    def test_function_lock_password(self):
435
        """Test function lock_password."""
436
        path_to_mock = 'passwords/4/lock.json'
437
        request_url = api_url + path_to_mock
438
        with requests_mock.Mocker() as m:
439
            m.put(request_url, status_code=204)
440
            response = self.client.lock_password('4')
441
        self.assertEqual(response, None)
442
443
    def test_function_unlock_password(self):
444
        """Test function unlock_password."""
445
        path_to_mock = 'passwords/4/unlock.json'
446
        request_url = api_url + path_to_mock
447
        unlock_reason = 'because I can'
448
        with requests_mock.Mocker() as m:
449
            m.put(request_url, status_code=204, request_headers={'X-Unlock-Reason': unlock_reason})
450
            response = self.client.unlock_password('4', unlock_reason)
451
        self.assertEqual(response, None)
452
453
class ClientMyPasswordTestCase(unittest.TestCase):
454
    """Test cases for all mypassword related queries."""
455
    client = tpm.TpmApiv4('https://tpm.example.com', username='USER', password='PASS')
456
    path_to_mock = 'my_passwords.json'
457
    request_url = api_url + path_to_mock
458
    with requests_mock.Mocker() as m:
459
        fake_data(request_url, m)
460
        global MyPasswords
461
        MyPasswords = client.list_mypasswords()
462
463
    def setUp(self):
464
        self.client = tpm.TpmApiv4('https://tpm.example.com', username='USER', password='PASS')
465
466
    def test_function_list_mypasswords(self):
467
        """Test function list_mypasswords."""
468
        path_to_mock = 'my_passwords.json'
469
        request_url = api_url + path_to_mock
470
        request_path = local_path + path_to_mock
471
        resource_file = os.path.normpath(request_path)
472
        data_file = open(resource_file)
473
        data = json.load(data_file)
474
        with requests_mock.Mocker() as m:
475
            fake_data(request_url, m)
476
            response = self.client.list_mypasswords()
477
        # number of passwords as from original json file.
478
        self.assertEqual(data, response)
479
480 View Code Duplication
    def test_function_list_mypasswords_search(self):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
481
        """Test function list_mypasswords_search."""
482
        searches = ['amazon', 'backup', 'facebook', 'john', 'jonny']
483
        for search in searches:
484
            path_to_mock = 'my_passwords/search/{}.json'.format(search)
485
            request_url = api_url + path_to_mock
486
            request_path = local_path + path_to_mock
487
            resource_file = os.path.normpath(request_path)
488
            data_file = open(resource_file)
489
            data = json.load(data_file)
490
            with requests_mock.Mocker() as m:
491
                fake_data(request_url, m)
492
                response = self.client.list_mypasswords_search(search)
493
            # number of passwords as from original json file.
494
            self.assertEqual(data, response)
495
496 View Code Duplication
    def test_function_show_mypassword(self):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
497
        """Test function show_mypassword."""
498
        for password in MyPasswords:
499
            password_id = password.get('id')
500
            log.debug("Testing with Password ID: {}".format(password_id))
501
            path_to_mock = 'my_passwords/{}.json'.format(password_id)
502
            request_url = api_url + path_to_mock
503
            request_path = local_path + path_to_mock
504
            resource_file = os.path.normpath(request_path)
505
            data_file = open(resource_file)
506
            data = json.load(data_file)
507
            with requests_mock.Mocker() as m:
508
                fake_data(request_url, m)
509
                response = self.client.show_mypassword(password_id)
510
            # number of passwords as from original json file.
511
            self.assertEqual(data, response)
512
513
    def test_function_create_mypassword(self):
514
        """Test function create_mypassword."""
515
        path_to_mock = 'my_passwords.json'
516
        request_url = api_url + path_to_mock
517
        return_data = { "id": 4 }
518
        create_data = { "name": "someproject"}
519
        with requests_mock.Mocker() as m:
520
            m.post(request_url, json=return_data, status_code=200)
521
            response = self.client.create_mypassword(create_data)
522
        self.assertEqual(response, return_data.get('id'))
523
524
525
    def test_function_update_mypassword(self):
526
        """Test function update_mypassword."""
527
        path_to_mock = 'my_passwords/4.json'
528
        request_url = api_url + path_to_mock
529
        update_data = { "name": "someproject"}
530
        with requests_mock.Mocker() as m:
531
            m.put(request_url, status_code=204)
532
            response = self.client.update_mypassword('4', update_data)
533
        self.assertEqual(response, None)
534
535
    def test_function_delete_mypassword(self):
536
        """Test function delete_mypassword."""
537
        path_to_mock = 'my_passwords/4.json'
538
        request_url = api_url + path_to_mock
539
        with requests_mock.Mocker() as m:
540
            m.delete(request_url, status_code=204)
541
            response = self.client.delete_mypassword('4')
542
        self.assertEqual(response, None)
543
544
    def test_function_set_favorite_password(self):
545
        """Test function set_favorite_password."""
546
        path_to_mock = 'favorite_passwords/4.json'
547
        request_url = api_url + path_to_mock
548
        with requests_mock.Mocker() as m:
549
            m.post(request_url, status_code=204)
550
            response = self.client.set_favorite_password('4')
551
        self.assertEqual(response, None)
552
553
    def test_function_unset_favorite_password(self):
554
        """Test function unset_favorite_password."""
555
        path_to_mock = 'favorite_passwords/4.json'
556
        request_url = api_url + path_to_mock
557
        with requests_mock.Mocker() as m:
558
            m.delete(request_url, status_code=204)
559
            response = self.client.unset_favorite_password('4')
560
        self.assertEqual(response, None)
561
562
    def test_function_set_favorite_project(self):
563
        """Test function set_favorite_project."""
564
        path_to_mock = 'favorite_project/4.json'
565
        request_url = api_url + path_to_mock
566
        with requests_mock.Mocker() as m:
567
            m.post(request_url, status_code=204)
568
            response = self.client.set_favorite_project('4')
569
        self.assertEqual(response, None)
570
571
    def test_function_unset_favorite_project(self):
572
        """Test function unset_favorite_project."""
573
        path_to_mock = 'favorite_project/4.json'
574
        request_url = api_url + path_to_mock
575
        with requests_mock.Mocker() as m:
576
            m.delete(request_url, status_code=204)
577
            response = self.client.unset_favorite_project('4')
578
        self.assertEqual(response, None)
579
580
class ClientUsersTestCase(unittest.TestCase):
581
    """Test cases for all user related queries."""
582
    client = tpm.TpmApiv4('https://tpm.example.com', username='USER', password='PASS')
583
    path_to_mock = 'users.json'
584
    request_url = api_url + path_to_mock
585
    with requests_mock.Mocker() as m:
586
        fake_data(request_url, m)
587
        global Users
588
        Users = client.list_users()
589
590
    def setUp(self):
591
        self.client = tpm.TpmApiv4('https://tpm.example.com', username='USER', password='PASS')
592
593
    def test_function_list_users(self):
594
        """Test function list_users."""
595
        path_to_mock = 'users.json'
596
        request_url = api_url + path_to_mock
597
        request_path = local_path + path_to_mock
598
        resource_file = os.path.normpath(request_path)
599
        data_file = open(resource_file)
600
        data = json.load(data_file)
601
        with requests_mock.Mocker() as m:
602
            fake_data(request_url, m)
603
            response = self.client.list_users()
604
        self.assertEqual(data, response)
605
606 View Code Duplication
    def test_function_show_user(self):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
607
        """Test function show_user."""
608
        for user in Users:
609
            user_id = user.get('id')
610
            log.debug("Testing with Project ID: {}".format(user_id))
611
            path_to_mock = 'users/{}.json'.format(user_id)
612
            request_url = api_url + path_to_mock
613
            request_path = local_path + path_to_mock
614
            resource_file = os.path.normpath(request_path)
615
            data_file = open(resource_file)
616
            data = json.load(data_file)
617
            with requests_mock.Mocker() as m:
618
                fake_data(request_url, m)
619
                response = self.client.show_user(user_id)
620
            self.assertEqual(data, response)
621
622 View Code Duplication
    def test_function_show_me(self):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
623
        """Test function show_me."""
624
        path_to_mock = 'users/me.json'
625
        request_url = api_url + path_to_mock
626
        request_path = local_path + path_to_mock
627
        resource_file = os.path.normpath(request_path)
628
        data_file = open(resource_file)
629
        data = json.load(data_file)
630
        with requests_mock.Mocker() as m:
631
            fake_data(request_url, m)
632
            response = self.client.show_me()
633
            response2 = self.client.who_am_i()
634
        self.assertEqual(data, response)
635
        self.assertEqual(response2, response)
636
637
    def test_function_create_user(self):
638
        """Test function create_user."""
639
        path_to_mock = 'users.json'
640
        request_url = api_url + path_to_mock
641
        return_data = { "id": 4 }
642
        create_data = { "name": "someuser"}
643
        with requests_mock.Mocker() as m:
644
            m.post(request_url, json=return_data, status_code=200)
645
            response = self.client.create_user(create_data)
646
        self.assertEqual(response, return_data.get('id'))
647
648
    def test_function_update_user(self):
649
        """Test function update_user."""
650
        path_to_mock = 'users/4.json'
651
        request_url = api_url + path_to_mock
652
        update_data = { "name": "someuser"}
653
        with requests_mock.Mocker() as m:
654
            m.put(request_url, status_code=204)
655
            response = self.client.update_user('4', update_data)
656
        self.assertEqual(response, None)
657
658
    def test_function_change_user_password(self):
659
        """Test function change_user_password."""
660
        path_to_mock = 'users/4/change_password.json'
661
        request_url = api_url + path_to_mock
662
        update_data = { "password": "NewSecret"}
663
        with requests_mock.Mocker() as m:
664
            m.put(request_url, status_code=204)
665
            response = self.client.change_user_password('4', update_data)
666
        self.assertEqual(response, None)
667
668
    def test_function_activate_user(self):
669
        """Test function activate_user."""
670
        path_to_mock = 'users/4/activate.json'
671
        request_url = api_url + path_to_mock
672
        with requests_mock.Mocker() as m:
673
            m.put(request_url, status_code=204)
674
            response = self.client.activate_user('4')
675
        self.assertEqual(response, None)
676
677
    def test_function_deactivate_user(self):
678
        """Test function deactivate_user."""
679
        path_to_mock = 'users/4/deactivate.json'
680
        request_url = api_url + path_to_mock
681
        with requests_mock.Mocker() as m:
682
            m.put(request_url, status_code=204)
683
            response = self.client.deactivate_user('4')
684
        self.assertEqual(response, None)
685
686
    def test_function_convert_user_to_ldap(self):
687
        """Test function convert_user_to_ldap."""
688
        path_to_mock = 'users/4/convert_to_ldap.json'
689
        request_url = api_url + path_to_mock
690
        login_dn = 'CN=Jane,CN=Users,DC=tpm,DC=local'
691
        def match_request_text(request):
692
            return {"login_dn": login_dn}
693
        with requests_mock.Mocker() as m:
694
            m.put(request_url, status_code=204, additional_matcher=match_request_text)
695
            response = self.client.convert_user_to_ldap('4', login_dn)
696
        self.assertEqual(response, None)
697
698
    def test_function_convert_ldap_user_to_normal(self):
699
        """Test function convert_ldap_user_to_normal."""
700
        path_to_mock = 'users/4/convert_to_normal.json'
701
        request_url = api_url + path_to_mock
702
        with requests_mock.Mocker() as m:
703
            m.put(request_url, status_code=204)
704
            response = self.client.convert_ldap_user_to_normal('4')
705
        self.assertEqual(response, None)
706
707
    def test_function_delete_user(self):
708
        """Test function delete_user."""
709
        path_to_mock = 'users/4.json'
710
        request_url = api_url + path_to_mock
711
        with requests_mock.Mocker() as m:
712
            m.delete(request_url, status_code=204)
713
            response = self.client.delete_user('4')
714
        self.assertEqual(response, None)
715
716
class ClientGroupsTestCase(unittest.TestCase):
717
    """Test cases for all group related queries."""
718
    client = tpm.TpmApiv4('https://tpm.example.com', username='USER', password='PASS')
719
    path_to_mock = 'groups.json'
720
    request_url = api_url + path_to_mock
721
    with requests_mock.Mocker() as m:
722
        fake_data(request_url, m)
723
        global Groups
724
        Groups = client.list_groups()
725
726
    def setUp(self):
727
        self.client = tpm.TpmApiv4('https://tpm.example.com', username='USER', password='PASS')
728
729
    def test_function_list_groups(self):
730
        """Test function list_groups."""
731
        path_to_mock = 'groups.json'
732
        request_url = api_url + path_to_mock
733
        request_path = local_path + path_to_mock
734
        resource_file = os.path.normpath(request_path)
735
        data_file = open(resource_file)
736
        data = json.load(data_file)
737
        with requests_mock.Mocker() as m:
738
            fake_data(request_url, m)
739
            response = self.client.list_groups()
740
        self.assertEqual(data, response)
741
742 View Code Duplication
    def test_function_show_group(self):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
743
        """Test function show_group."""
744
        for group in Groups:
745
            group_id = group.get('id')
746
            log.debug("Testing with Project ID: {}".format(group_id))
747
            path_to_mock = 'groups/{}.json'.format(group_id)
748
            request_url = api_url + path_to_mock
749
            request_path = local_path + path_to_mock
750
            resource_file = os.path.normpath(request_path)
751
            data_file = open(resource_file)
752
            data = json.load(data_file)
753
            with requests_mock.Mocker() as m:
754
                fake_data(request_url, m)
755
                response = self.client.show_group(group_id)
756
            self.assertEqual(data, response)
757
758
    def test_function_create_group(self):
759
        """Test function create_group."""
760
        path_to_mock = 'groups.json'
761
        request_url = api_url + path_to_mock
762
        return_data = { "id": 4 }
763
        create_data = { "name": "somegroup"}
764
        with requests_mock.Mocker() as m:
765
            m.post(request_url, json=return_data, status_code=200)
766
            response = self.client.create_group(create_data)
767
        self.assertEqual(response, return_data.get('id'))
768
769
    def test_function_update_group(self):
770
        """Test function update_group."""
771
        path_to_mock = 'groups/4.json'
772
        request_url = api_url + path_to_mock
773
        update_data = { "name": "somegroup"}
774
        with requests_mock.Mocker() as m:
775
            m.put(request_url, status_code=204)
776
            response = self.client.update_group('4', update_data)
777
        self.assertEqual(response, None)
778
779
    def test_function_add_user_to_group(self):
780
        """Test function add_user_to_group."""
781
        group_id = '3'
782
        user_id = '4'
783
        path_to_mock = 'groups/{}/add_user/{}.json'.format(group_id, user_id)
784
        request_url = api_url + path_to_mock
785
        with requests_mock.Mocker() as m:
786
            m.put(request_url, status_code=204)
787
            response = self.client.add_user_to_group(group_id, user_id)
788
        self.assertEqual(response, None)
789
790
    def test_function_delete_user_from_group(self):
791
        """Test function delete_user_from_group."""
792
        group_id = '3'
793
        user_id = '4'
794
        path_to_mock = 'groups/{}/delete_user/{}.json'.format(group_id, user_id)
795
        request_url = api_url + path_to_mock
796
        with requests_mock.Mocker() as m:
797
            m.put(request_url, status_code=204)
798
            response = self.client.delete_user_from_group(group_id, user_id)
799
        self.assertEqual(response, None)
800
801
    def test_function_delete_group(self):
802
        """Test function delete_group."""
803
        path_to_mock = 'groups/4.json'
804
        request_url = api_url + path_to_mock
805
        with requests_mock.Mocker() as m:
806
            m.delete(request_url, status_code=204)
807
            response = self.client.delete_group('4')
808
        self.assertEqual(response, None)
809
810
class GeneralClientTestCases(unittest.TestCase):
811
    """general test cases for client queries."""
812
    def setUp(self):
813
        self.client = tpm.TpmApiv4('https://tpm.example.com', username='USER', password='PASS')
814
815 View Code Duplication
    def test_paging(self):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
816
        """Test paging, if number of items is same as from original data source."""
817
        path_to_mock = 'passwords.json'
818
        request_url = api_url + path_to_mock
819
        request_path = local_path + path_to_mock
820
        resource_file = os.path.normpath(request_path)
821
        data_file = open(resource_file)
822
        data = json.load(data_file)
823
        with requests_mock.Mocker() as m:
824
            fake_data(request_url, m)
825
            response = self.client.list_passwords()
826
        # number of passwords as from original json file.
827
        source_items = len(data)
828
        response_items = len(response)
829
        log.debug("Source Items: {}; Response Items: {}".format(source_items, response_items))
830
        self.assertEqual(source_items, response_items)
831
832
    def test_provide_unlock_reason(self):
833
        """Test providing an unlock reason."""
834
        path_to_mock = 'passwords/14.json'
835
        request_url = api_url + path_to_mock
836
        request_path = local_path + path_to_mock
837
        resource_file = os.path.normpath(request_path)
838
        data_file = open(resource_file)
839
        data = json.load(data_file)
840
        unlock_reason = 'because I can'
841
        client = tpm.TpmApiv4('https://tpm.example.com', username='USER', password='PASS', unlock_reason=unlock_reason)
842
        with requests_mock.Mocker() as m:
843
            m.get(request_url, request_headers={'X-Unlock-Reason': unlock_reason})
844
            response = client.show_password('14')
845
            history = m.request_history
846
            request_unlock_reason = history[0].headers.get('X-Unlock-Reason')
847
        self.assertEqual(request_unlock_reason, unlock_reason)
848
849
    def test_key_authentciation(self):
850
        """Test Key authentication header."""
851
        private_key='private_secret'
852
        public_key='public_secret'
853
        client = tpm.TpmApiv4('https://tpm.example.com', private_key=private_key, public_key=public_key)
854
        path_to_mock = 'version.json'
855
        request_url = api_url + path_to_mock
856
        with requests_mock.Mocker() as m:
857
            fake_data(request_url, m)
858
            response = client.get_version()
859
            history = m.request_history
860
        request_hash = history[0].headers.get('X-Request-Hash')
861
        request_pubkey = history[0].headers.get('X-Public-Key')
862
        request_timestamp = history[0].headers.get('X-Request-Timestamp')
863
        timestamp = str(int(time.time()))
864
        unhashed = 'api/v4/' + path_to_mock + request_timestamp
865
        hashed = hmac.new(str.encode(private_key),
866
                             msg=unhashed.encode('utf-8'),
867
                             digestmod=hashlib.sha256).hexdigest()
868
        self.assertEqual(request_hash, hashed)
869
870
    def test_function_generate_password(self):
871
        """Test function generate_password."""
872
        path_to_mock = 'generate_password.json'
873
        request_url = api_url + path_to_mock
874
        request_path = local_path + path_to_mock
875
        resource_file = os.path.normpath(request_path)
876
        data_file = open(resource_file)
877
        data = json.load(data_file)
878
        with requests_mock.Mocker() as m:
879
            fake_data(request_url, m)
880
            response = self.client.generate_password()
881
        self.assertEqual(data, response)
882
883
    def test_get_version(self):
884
        """Test function get_version."""
885
        path_to_mock = 'version.json'
886
        request_url = api_url + path_to_mock
887
        request_path = local_path + path_to_mock
888
        resource_file = os.path.normpath(request_path)
889
        data_file = open(resource_file)
890
        data = json.load(data_file)
891
        with requests_mock.Mocker() as m:
892
            fake_data(request_url, m)
893
            response = self.client.get_version()
894
        self.assertEqual(data, response)
895
896
    def test_a_call_with_v3(self):
897
        """Test function get_version with v3 API."""
898
        path_to_mock = 'version.json'
899
        request_url = 'https://tpm.example.com/index.php/api/v3/' + path_to_mock
900
        request_path = local_path + path_to_mock
901
        resource_file = os.path.normpath(request_path)
902
        data_file = open(resource_file)
903
        data = json.load(data_file)
904
        client = tpm.TpmApiv3('https://tpm.example.com', username='USER', password='PASS')
905
        with requests_mock.Mocker() as m:
906
            fake_data(request_url, m)
907
            response = client.get_version()
908
        self.assertEqual(data, response)
909
910
    def test_function_check_latest(self):
911
        """Test function generate_password."""
912
        path_to_mock = 'version/check_latest.json'
913
        request_url = api_url + path_to_mock
914
        request_path = local_path + path_to_mock
915
        resource_file = os.path.normpath(request_path)
916
        data_file = open(resource_file)
917
        data = json.load(data_file)
918
        with requests_mock.Mocker() as m:
919
            fake_data(request_url, m)
920
            response = self.client.get_latest_version()
921
        self.assertEqual(data, response)
922
923
    def test_function_up_to_date_true(self):
924
        """Test function up_to_date is true."""
925
        path_to_mock = 'version/check_latest.json'
926
        request_url = api_url + path_to_mock
927
        request_path = local_path + path_to_mock
928
        resource_file = os.path.normpath(request_path)
929
        data_file = open(resource_file)
930
        data = json.load(data_file)
931
        with requests_mock.Mocker() as m:
932
            fake_data(request_url, m)
933
            response_up_to_date_true = self.client.up_to_date()
934
            self.assertTrue(response_up_to_date_true)
935
936
    def test_function_up_to_date_false(self):
937
        """Test function up_to_date is false."""
938
        path_to_mock = 'version/check_latest.json'
939
        request_url = api_url + path_to_mock
940
        with requests_mock.Mocker() as m:
941
            fake_data(request_url, m, 'version/check_outdated.json')
942
            response_up_to_date_false = self.client.up_to_date()
943
            self.assertFalse(response_up_to_date_false)
944
945
946
class ExceptionTestCases(unittest.TestCase):
947
    """Test case for Config Exceptions."""
948
    def test_wrong_auth_exception1(self):
949
        """Exception if wrong authentication mehtod with username but private_key."""
950
        with self.assertRaises(tpm.TpmApi.ConfigError) as context:
951
            tpm.TpmApiv4('https://tpm.example.com', username='USER', private_key='PASS')
952
        log.debug("context exception: {}".format(context.exception))
953
        self.assertEqual("'No authentication specified (user/password or private/public key)'", str(context.exception))
954
955
    def test_wrong_auth_exception2(self):
956
        """Exception if wrong authentication mehtod with public key but password."""
957
        with self.assertRaises(tpm.TpmApi.ConfigError) as context:
958
            tpm.TpmApiv4('https://tpm.example.com', public_key='USER', password='PASS')
959
        log.debug("context exception: {}".format(context.exception))
960
        self.assertEqual("'No authentication specified (user/password or private/public key)'", str(context.exception))
961
962
    def test_wrong_auth_exception3(self):
963
        """Exception if wrong authentication mehtod with username but public_key."""
964
        with self.assertRaises(tpm.TpmApi.ConfigError) as context:
965
            tpm.TpmApiv4('https://tpm.example.com', username='USER', public_key='PASS')
966
        log.debug("context exception: {}".format(context.exception))
967
        self.assertEqual("'No authentication specified (user/password or private/public key)'", str(context.exception))
968
969
    def test_wrong_auth_exception4(self):
970
        """Exception if wrong authentication mehtod with private key but password."""
971
        with self.assertRaises(tpm.TpmApi.ConfigError) as context:
972
            tpm.TpmApiv4('https://tpm.example.com', private_key='USER', password='PASS')
973
        log.debug("context exception: {}".format(context.exception))
974
        self.assertEqual("'No authentication specified (user/password or private/public key)'", str(context.exception))
975
976
    def test_wrong_url_exception(self):
977
        """Exception if URL does not match REGEXurl."""
978
        wrong_url = 'ftp://tpm.example.com'
979
        with self.assertRaises(tpm.TpmApiv4.ConfigError) as context:
980
            tpm.TpmApiv4(wrong_url, username='USER', password='PASS')
981
        log.debug("context exception: {}".format(context.exception))
982
        self.assertEqual("'Invalid URL: {}'".format(wrong_url), str(context.exception))
983
984
class ExceptionOnRequestsTestCases(unittest.TestCase):
985
    """Test case for Request based Exceptions."""
986
    def setUp(self):
987 View Code Duplication
        self.client = tpm.TpmApiv4('https://tpm.example.com', username='USER', password='PASS')
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
988
989
    def test_connection_exception(self):
990
        """Exception if connection fails."""
991
        exception_error = "Connection error for "
992
        with self.assertRaises(tpm.TPMException) as context:
993
            self.client.list_passwords()
994
        log.debug("context exception: {}".format(context.exception))
995
        self.assertTrue(exception_error in str(context.exception))
996
997
    def test_value_error_exception(self):
998
        """Exception if value is not json format."""
999
        path_to_mock = 'passwords/value_error.json'
1000
        request_url = api_url + path_to_mock
1001
        exception_error = "No JSON object could be decoded: "
1002
        exception_error3 = "Expecting value: line 1 column 1 (char 0): "
1003
        resource_file = os.path.normpath('tests/resources/{}'.format(path_to_mock))
1004
        data = open(resource_file)
1005
        with self.assertRaises(ValueError) as context:
1006
            with requests_mock.Mocker() as m:
1007
                m.get(request_url, text=str(data))
1008
                response = self.client.show_password('value_error')
1009
        log.debug("context exception: {}".format(context.exception))
1010
        self.assertTrue(str(context.exception).startswith(exception_error) or str(context.exception).startswith(exception_error3))
1011
1012
    def test_exception_on_error_in_result(self):
1013
        """Exception if "error" found in result."""
1014
        exception_error = 'something bad happened'
1015
        error_json={'error': 'not good', 'message': exception_error}
1016
        path_to_mock = 'passwords/json_error.json'
1017
        request_url = api_url + path_to_mock
1018 View Code Duplication
        with self.assertRaises(tpm.TPMException) as context:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1019
            with requests_mock.Mocker() as m:
1020
                m.get(request_url, json=error_json)
1021
                response = self.client.show_password('json_error')
1022
        log.debug("context exception: {}".format(context.exception))
1023
        self.assertTrue(exception_error in str(context.exception))
1024
1025
    def test_exception_on_403(self):
1026
        """Exception if 403 forbidden."""
1027
        path_to_mock = 'passwords.json'
1028
        request_url = api_url + path_to_mock
1029
        exception_error = "{} forbidden".format(request_url)
1030
        with self.assertRaises(tpm.TPMException) as context:
1031
            with requests_mock.Mocker() as m:
1032
                m.get(request_url, text='forbidden', status_code=403)
1033
                response = self.client.list_passwords()
1034
        log.debug("context exception: {}".format(context.exception))
1035
        self.assertTrue(exception_error in str(context.exception))
1036
1037
    def test_exception_on_404(self):
1038
        """Exception if 404 not found."""
1039
        path_to_mock = 'passwords.json'
1040
        request_url = api_url + path_to_mock
1041
        exception_error = "{} not found".format(request_url)
1042
        with self.assertRaises(tpm.TPMException) as context:
1043 View Code Duplication
            with requests_mock.Mocker() as m:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1044
                m.get(request_url, text='not found', status_code=404)
1045
                response = self.client.list_passwords()
1046
        log.debug("context exception: {}".format(context.exception))
1047
        self.assertTrue(exception_error in str(context.exception))
1048
1049
    def test_exception_on_405(self):
1050
        """Exception if 405 Method Not Allowed."""
1051
        path_to_mock = 'passwords.json'
1052
        request_url = api_url + path_to_mock
1053
        exception_error = "{} Method Not Allowed".format(request_url)
1054
        with self.assertRaises(ValueError) as context:
1055 View Code Duplication
            with requests_mock.Mocker() as m:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1056
                m.get(request_url, text='Method Not Allowed', status_code=405)
1057
                response = self.client.list_passwords()
1058
        log.debug("context exception: {}".format(context.exception))
1059
        self.assertTrue(str(context.exception).endswith(exception_error))
1060