-
Notifications
You must be signed in to change notification settings - Fork 89
/
tests.py
6160 lines (5570 loc) · 245 KB
/
tests.py
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import base64
import io
import os
import re
import sys
import time
import shutil
import logging
import threading
from unittest import skipIf
from http.server import BaseHTTPRequestHandler, HTTPServer
from django.forms import ValidationError
from django.test import override_settings
from django_test_migrations.contrib.unittest_case import MigratorTestCase
from django.core.exceptions import FieldDoesNotExist
from rest_framework import fields as drffields
from django.conf import settings
import git
import yaml
from uuid import uuid1
from tempfile import mkdtemp
from pathlib import Path
from requests import Response
from django.core.management import call_command
from django.utils import timezone
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import ContentType
from vstutils.tests import BaseTestCase as VSTBaseTestCase
from vstutils.api import fields as vstfields
try:
from polemarch.main.openapi import PROJECT_MENU
from polemarch.main.tasks import ScheduledTask
from polemarch.main.constants import CYPHER
from polemarch.main.executions import PLUGIN_HANDLERS
from polemarch.main.models.utils import ProjectProxy
from polemarch.plugins.execution.ansible import BaseAnsiblePlugin, BasePlugin, AnsibleModule, AnsiblePlaybook
from polemarch.plugins.inventory.base import BasePlugin as BaseInventoryPlugin
from polemarch.main.exceptions import NotApplicable
except ImportError:
from pmlib.main.tasks import ScheduledTask
from pmlib.main.constants import CYPHER
from pmlib.main.executions import PLUGIN_HANDLERS
from pmlib.main.models.utils import ProjectProxy
from pmlib.plugins.execution.ansible import BaseAnsiblePlugin, BasePlugin, AnsibleModule, AnsiblePlaybook
from pmlib.plugins.inventory.base import BasePlugin as BaseInventoryPlugin
from pmlib.main.exceptions import NotApplicable
logger = logging.getLogger('polemarch')
TEST_DATA_DIR = Path(__file__).parent.absolute()
ORIGINAL_PROJECTS_DIR = settings.PROJECTS_DIR
if settings.VST_PROJECT_LIB_NAME == 'polemarch':
TEST_DATA_DIR /= 'test_data'
TESTS_MODULE = 'tests'
else:
TEST_DATA_DIR /= 'test_data_ce'
TESTS_MODULE = 'tests_ce'
User = get_user_model()
example_key = """
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIH1LLUytCpUG6FMH06Wnuk+p4ZewjyDPJKcQwsaGZ5y3oAoGCCqGSM49
AwEHoUQDQgAET5LtltdvCIaMd4ZzXBP3JkZp/F2EMxPUiNVSe/HMdNIEnzy7WdH9
HD1a8+068eoT+KV/ESsjDxwo2NUPZAo0pQ==
-----END EC PRIVATE KEY-----
""".strip()
def use_temp_dir(func):
"""
Decorator which makes temp directory and removes
it after successful execution or error.
"""
def wrapper(*args, **kwargs):
temp_dir = mkdtemp()
try:
result = func(*args, temp_dir=temp_dir, **kwargs)
shutil.rmtree(temp_dir)
return result
except:
shutil.rmtree(temp_dir)
raise
return wrapper
def own_projects_dir(cls):
"""
Decorator which overrides PROJECTS_DIR setting based
on current app name (CE/EE) and class name.
"""
return override_settings(PROJECTS_DIR=Path(settings.PROJECTS_DIR) / cls.__module__ / cls.__name__)(cls)
class MockServer:
"""
Context manager which creates, serves and returns an
instance of HTTPServer with given handler in separate
thread. You can then make request to the `http://localhost:<PORT>`,
where `<PORT>` in `.server_port` attribute of return value.
Stops server after leaving context.
"""
__slots__ = ('handler', 'httpd',)
def __init__(self, handler: BaseHTTPRequestHandler):
self.handler = handler
def __enter__(self) -> HTTPServer:
self.httpd = HTTPServer(('', 0), self.handler)
threading.Thread(target=self.httpd.serve_forever).start()
return self.httpd
def __exit__(self, exc_cls, exc_object, traceback):
self.httpd.shutdown()
if exc_cls is not None:
exc_cls(exc_object, traceback)
class TestException(Exception):
def __init__(self, msg='Test exception.', *args, **kwargs):
super().__init__(msg, *args, **kwargs)
class DummyProject:
def __init__(self):
self.env_vars = {
'env1': 'env1_value',
'env2': 'env2_value',
}
def __getattr__(self, name):
return name
class TestAnsibleDoc(BaseAnsiblePlugin):
reference = {
'module-path': {'type': 'string'},
'verbose': {'type': 'int', 'help': 'verbose level'},
'json': {'type': None},
}
serializer_fields = {'target': vstfields.VSTCharField()}
arg_shown_on_history_as_mode = 'target'
@property
def base_command(self):
return super().base_command + ['ansible-doc']
def post_execute_hook(self, *args, **kwargs):
self.verbose_output('Test log from test plugin', level=2)
def _process_arg(self, key, value):
if key == 'target':
return value
return super()._process_arg(key, value)
class TestEcho(BasePlugin):
serializer_fields = {
'string': vstfields.VSTCharField(),
'n': drffields.BooleanField(default=drffields.empty, required=False, label='No trailing newlines'),
'e': drffields.BooleanField(default=drffields.empty, required=False, label='Interpret backslash escapes'),
}
arg_shown_on_history_as_mode = 'string'
@property
def base_command(self):
return ['echo']
def _process_arg(self, key, value):
if key == 'string':
return value
if key in ('n', 'e') and value:
return f'-{key}'
class TestModule(AnsibleModule):
def post_execute_hook(self, cmd, raw_args):
if not self.inventory.plugin_object.state_managed:
return
state = self.inventory.inventory_state
if 'counter' not in state.data:
state.data['counter'] = 1
else:
state.data['counter'] += 1
state.save(update_fields=('data',))
def get_pre_commands(self, *args, **kwargs):
return [['echo', 'echo_first'], ['echo', 'echo_second']]
class TestInventoryPlugin(BaseInventoryPlugin):
supports_import = True
serializer_fields = {
'body': vstfields.TextareaField(allow_blank=True, default=''),
}
defaults = {
'body': 'localhost ansible_connection=local',
}
serializer_import_fields = {
'body': vstfields.FileInStringField(),
}
def render_inventory(self, instance, execution_dir):
state_data = instance.inventory_state.data
filename = str(uuid1())
filepath = Path(execution_dir) / filename
filepath.write_text(state_data['body'])
return filepath, []
def get_raw_inventory(self, inventory_string):
return f'File contents:\n{inventory_string}'
@classmethod
def import_inventory(cls, instance, data):
instance.update_inventory_state(data=data)
return instance
class BaseTestCase(VSTBaseTestCase):
def setUp(self):
self.host = self.get_model_class('main.Host').objects.create(name='localhost')
self.group = self.get_model_class('main.Group').objects.create(name='default_group')
self.group.hosts.add(self.host)
self.inventory = self.get_model_class('main.Inventory').objects.create(name='default_inventory')
self.inventory.hosts.add(self.host)
self.inventory.groups.add(self.group)
host_type = ContentType.objects.get(model='host')
self.get_model_class('main.Variable').objects.create(
key='ansible_connection',
value='local',
object_id=self.inventory.id,
content_type=host_type
)
super().setUp()
class BaseProjectTestCase(BaseTestCase):
@classmethod
def setUpTestData(cls):
assert ORIGINAL_PROJECTS_DIR != settings.PROJECTS_DIR, (
f'You should decorate {cls.__name__} using "@own_projects_dir". '
'This needs to avoid race conditions in parallel executions.'
)
super().setUpTestData()
def setUp(self):
super().setUp()
self.project = self.get_model_filter('main.Project').create(name='default_project')
os.makedirs(f'{settings.PROJECTS_DIR}/{self.project.id}', exist_ok=True)
self.project.hosts.add(self.host)
self.project.groups.add(self.group)
self.project.inventories.add(self.inventory)
shutil.copy(f'{TEST_DATA_DIR}/playbook.yml', f'{settings.PROJECTS_DIR}/{self.project.id}/playbook.yml')
shutil.copy(
f'{TEST_DATA_DIR}/localhost-inventory.yml',
f'{settings.PROJECTS_DIR}/{self.project.id}/localhost-inventory.yml'
)
self.project.start_repo_task('sync')
self.inventory_path = 'localhost-inventory.yml'
self.template = self.get_model_filter('main.ExecutionTemplate').create(
name='default_template',
project=self.project,
plugin='ANSIBLE_MODULE',
)
self.template_option = self.get_model_filter('main.ExecutionTemplateOption').create(
name='default_option',
template=self.template,
arguments={
'module': 'system.ping',
'connection': 'local',
'inventory': 'localhost,',
'group': 'all',
}
)
def tearDown(self):
if Path(settings.PROJECTS_DIR).exists():
shutil.rmtree(settings.PROJECTS_DIR)
super().tearDown()
def create_inventory_bulk_data(self, plugin='POLEMARCH_DB', project_id=None, **kwargs):
return {
'method': 'post',
'path': 'inventory' if project_id is None else ['project', project_id, 'inventory'],
'data': {
'name': 'test-inventory',
'plugin': plugin,
**kwargs,
}
}
def update_inventory_state_bulk_data(self, inventory_id, project_id=None, **kwargs):
path = ['inventory', inventory_id, 'state']
if project_id is not None:
path = ['project', project_id] + path
return {
'method': 'put',
'path': path,
'data': kwargs,
}
def import_inventory_bulk_data(self, plugin, data, project_id=None, name='test_imported_inventory'):
project_prefix = [] if project_id is None else ['project', project_id]
path = project_prefix + ['inventory', 'import_inventory']
return {
'method': 'post',
'path': path,
'data': {
'name': name,
'plugin': plugin,
'data': data,
}
}
def get_inventory_state_bulk_data(self, inventory_id, project_id=None):
path = ['inventory', inventory_id, 'state']
if project_id is not None:
path = ['project', project_id] + path
return {
'method': 'get',
'path': path,
}
def get_inventory_bulk_data(self, inventory_id, project_id=None):
path = ['inventory', inventory_id]
if project_id is not None:
path = ['project', project_id] + path
return {
'method': 'get',
'path': path,
}
def create_project_bulk_data(self, type='MANUAL', **kwargs):
return {
'method': 'post',
'path': 'project',
'data': {
'name': str(uuid1()),
'type': type,
**kwargs
}
}
def sync_project_bulk_data(self, project_id=None):
return {
'method': 'patch',
'path': ['project', project_id or self.project.id, 'sync'],
}
def create_project_variable_bulk_data(self, key, value, project_id=None):
return {
'method': 'post',
'path': ['project', project_id or self.project.id, 'variables'],
'data': {'key': key, 'value': value}
}
def get_project_bulk_data(self, project_id=None):
return {
'method': 'get',
'path': ['project', project_id or self.project.id]
}
def get_history_bulk_data(self, history_id, path_prefix=None):
path_prefix = path_prefix or []
return {
'method': 'get',
'path': [*path_prefix, 'history', history_id]
}
def get_raw_history_bulk_data(self, history_id, path_prefix=None):
path_prefix = path_prefix or []
return {
'method': 'get',
'path': [*path_prefix, 'history', history_id, 'raw']
}
def execute_plugin_bulk_data(self, plugin, project_id=None, **arguments):
return {
'method': 'post',
'path': ['project', project_id or self.project.id, f'execute_{plugin.lower()}'],
'data': arguments,
}
def create_template_periodic_task_bulk_data(
self,
template_id=None,
option_id=None,
project_id=None,
**kwargs
):
option_id = option_id or self.template_option.id
return {
'method': 'post',
'path': [
'project',
project_id or self.project.id,
'execution_templates',
template_id or self.template.id,
'options',
str(option_id),
'periodic_tasks',
],
'data': {
'name': str(uuid1()),
'type': 'INTERVAL',
'schedule': 5,
'enabled': False,
'save_result': True,
'notes': 'some notes',
**kwargs,
}
}
def get_default_template_option(self, template_id):
template = self.get_model_filter('main.ExecutionTemplate').get(id=template_id)
return template.options.filter(name='default').first()
def create_template_bulk_data(
self,
project_id=None,
plugin='ANSIBLE_MODULE',
arguments=None,
**kwargs
):
return {
'method': 'post',
'path': ['project', project_id or self.project.id, 'execution_templates'],
'data': {
'name': 'template',
'notes': 'some notes',
'plugin': plugin,
'arguments': arguments or {
'module': 'system.ping',
'inventory': 'localhost,',
'connection': 'local',
'verbose': 2,
},
**kwargs,
}
}
def create_template_option_bulk_data(
self,
arguments,
template_id=None,
project_id=None,
**kwargs,
):
return {
'method': 'post',
'path': [
'project',
project_id or self.project.id,
'execution_templates',
template_id or self.template.id,
'options',
],
'data': {
'name': 'custom_option',
'notes': 'some notes',
'arguments': arguments,
**kwargs,
}
}
def execute_template_bulk_data(
self,
project_id=None,
template_id=None,
option_id=None,
via_option=False,
**kwargs,
):
option_id = option_id or self.template_option.id
if via_option:
return {
'method': 'post',
'path': [
'project',
project_id or self.project.id,
'execution_templates',
template_id or self.template.id,
'options',
str(option_id),
'execute',
],
'data': kwargs,
}
return {
'method': 'post',
'path': [
'project',
project_id or self.project.id,
'execution_templates',
template_id or self.template.id,
'execute',
],
'data': {'option': str(option_id), **kwargs},
}
@own_projects_dir
class ProjectTestCase(BaseProjectTestCase):
def test_project_files_deletion(self):
project_path = Path(self.project.path)
self.assertTrue(project_path.is_dir())
self.bulk_transactional(
{'method': 'delete', 'path': ['project', self.project.id]},
)
self.assertFalse(project_path.is_dir())
def test_copy_project(self):
results = self.bulk_transactional([
# [0] add variable to project
{
'method': 'post',
'path': ['project', self.project.id, 'variables'],
'data': {'key': 'repo_sync_on_run_timeout', 'value': 12}
},
# [1] copy project
{'method': 'post', 'path': ['project', self.project.id, 'copy'], 'data': {'name': 'copy'}},
# [2]
self.get_project_bulk_data('<<1[data][id]>>'),
# [3] check variable list of copied project
{
'method': 'get',
'path': ['project', '<<1[data][id]>>', 'variables'],
},
])
self.assertEqual(results[1]['data']['name'], 'copy')
self.assertEqual(results[2]['data']['repository'], self.project.repository)
self.assertEqual(results[2]['data']['status'], 'NEW')
self.assertEqual(results[2]['data']['revision'], self.project.revision)
self.assertEqual(results[3]['data']['count'], 1)
self.assertEqual(results[3]['data']['results'][0]['key'], 'repo_sync_on_run_timeout')
self.assertEqual(results[3]['data']['results'][0]['value'], 12)
def test_create_project(self):
results = self.bulk_transactional([
# [0]
self.create_project_bulk_data(
type='GIT',
repository='example.repo',
repo_auth='KEY',
auth_data=example_key,
branch='main',
additional_playbook_path='./somepath',
),
# [1]
self.get_project_bulk_data('<<0[data][id]>>'),
# [2]
{'method': 'get', 'path': ['project', '<<0[data][id]>>', 'variables']},
])
self.assertEqual(results[1]['data']['repository'], 'example.repo')
self.assertEqual(results[1]['data']['status'], 'NEW')
self.assertEqual(results[1]['data']['revision'], 'NOT_SYNCED')
self.assertEqual(results[1]['data']['branch'], 'waiting... => main')
self.assertIsNone(results[1]['data']['readme_content'])
self.assertIsNone(results[1]['data']['execute_view_data'])
self.assertEqual(results[2]['data']['count'], 4)
self.assertEqual(results[2]['data']['results'][0]['key'], 'playbook_path')
self.assertEqual(results[2]['data']['results'][0]['value'], './somepath')
self.assertEqual(results[2]['data']['results'][1]['key'], 'repo_branch')
self.assertEqual(results[2]['data']['results'][1]['value'], 'main')
self.assertEqual(results[2]['data']['results'][2]['key'], 'repo_key')
self.assertEqual(results[2]['data']['results'][2]['value'], CYPHER)
self.assertEqual(results[2]['data']['results'][3]['key'], 'repo_type')
self.assertEqual(results[2]['data']['results'][3]['value'], 'GIT')
def test_project_owner(self):
user = self._create_user(is_super_user=False)
with self.user_as(self, user):
results = self.bulk([
{'method': 'post', 'path': 'project', 'data': {'name': 'test'}},
{'method': 'get', 'path': ['project', '<<0[data][id]>>']}
])
self.assertEqual(results[0]['status'], 201)
self.assertEqual(results[1]['status'], 200)
self.assertEqual(results[1]['data']['owner'], user.id)
def test_set_owner(self):
user = self._create_user(is_super_user=False, is_staff=True)
user2 = self._create_user(is_super_user=False, is_staff=True)
results = self.bulk([
{
'method': 'patch',
'path': ['project', self.project.id, 'set_owner'],
'data': {'owner': user.id}
},
{
'method': 'patch',
'path': ['project', self.project.id, 'set_owner'],
'data': {'owner': 146}
},
{'method': 'get', 'path': ['project', self.project.id]},
])
self.assertEqual(results[0]['status'], 200)
self.assertEqual(results[1]['status'], 400)
self.assertEqual(results[2]['status'], 200)
self.assertEqual(results[2]['data']['owner'], user.id)
with self.user_as(self, user2):
results = self.bulk([
{'method': 'patch', 'path': ['project', self.project.id, 'set_owner'], 'data': {'owner': user.id}},
])
self.assertEqual(results[0]['status'], 403)
self.assertEqual(results[0]['data']['detail'], 'Only owner can change owner.')
@own_projects_dir
class InventoryTestCase(BaseProjectTestCase):
def test_ansible_string_inventory(self):
inventory_string = (TEST_DATA_DIR / 'repo' / 'inventory.ini').read_text()
results = self.bulk_transactional([
# [0]
self.create_inventory_bulk_data('ANSIBLE_STRING', self.project.id),
# [1]
self.get_inventory_state_bulk_data(inventory_id='<<0[data][id]>>'),
])
self.assertEqual(results[0]['data']['plugin'], 'ANSIBLE_STRING')
self.assertDictEqual(results[1]['data']['data'], {
'body': '',
'filename': '',
'extension': 'yaml',
'executable': False,
})
inventory_id = results[0]['data']['id']
results = self.bulk_transactional([
# [0]
self.update_inventory_state_bulk_data(
inventory_id=inventory_id,
data={
'executable': True,
'extension': 'ini',
'body': inventory_string,
}
),
# [1]
self.execute_plugin_bulk_data(
'ANSIBLE_MODULE',
module='system.ping',
inventory=inventory_id,
),
# [2]
self.get_history_bulk_data('<<1[data][history_id]>>'),
])
self.assertEqual(results[0]['data']['data']['body'].strip(), inventory_string.strip())
self.assertEqual(results[0]['data']['data']['extension'], 'ini')
self.assertTrue(results[0]['data']['data']['executable'])
self.assertEqual(results[2]['data']['status'], 'OK')
self.assertEqual(results[2]['data']['inventory'], inventory_id)
self.assertEqual(results[2]['data']['raw_inventory'].strip(), inventory_string.strip())
# check hosts and groups path are unavailable
bulk_data = [
{
'method': 'get',
'path': ['inventory', inventory_id, endpoint],
}
for endpoint in ['variables', 'hosts', 'group', 'all_hosts', 'all_groups']
]
results = self.bulk(bulk_data)
for result in results:
self.assertEqual(result['status'], 404)
# check that state deletes with inventory
state_id = self.get_model_filter('main.Inventory').get(id=inventory_id)._inventory_state_id
self.assertIsNotNone(state_id)
self.bulk_transactional([
{
'method': 'delete',
'path': ['project', self.project.id, 'inventory', inventory_id],
'headers': {'X-Purge-Nested': 'true'}
},
])
self.assertFalse(self.get_model_filter('main.Inventory').filter(id=inventory_id).exists())
self.assertFalse(self.get_model_filter('main.InventoryState').filter(id=state_id).exists())
@use_temp_dir
def test_ansible_file_inventory(self, temp_dir):
repo_dir = f'{temp_dir}/repo'
shutil.copytree(TEST_DATA_DIR / 'repo', repo_dir)
repo = git.Repo.init(repo_dir)
repo.git.add(all=True)
repo.index.commit('Initial commit')
results = self.bulk_transactional([
# [0]
self.create_project_bulk_data(type='GIT', repository=repo_dir),
# [1]
self.sync_project_bulk_data('<<0[data][id]>>'),
# [2]
self.create_inventory_bulk_data('ANSIBLE_FILE', project_id='<<0[data][id]>>'),
# [3]
self.get_inventory_state_bulk_data('<<2[data][id]>>'),
])
self.assertDictEqual(results[3]['data']['data'], {'path': ''})
project_id = results[0]['data']['id']
inventory_id = results[2]['data']['id']
results = self.bulk_transactional([
# [0]
self.update_inventory_state_bulk_data(inventory_id, data={'path': './inventory.ini'}),
# [1]
self.execute_plugin_bulk_data(
'ANSIBLE_MODULE',
module='system.ping',
project_id=project_id,
inventory=inventory_id,
),
# [2]
self.get_history_bulk_data('<<1[data][history_id]>>'),
# [3] create new inventory and check that its state has defaults
self.create_inventory_bulk_data('ANSIBLE_FILE', project_id=project_id),
# [4]
self.get_inventory_state_bulk_data('<<3[data][id]>>'),
])
self.assertDictEqual(results[0]['data']['data'], {'path': './inventory.ini'})
self.assertEqual(results[2]['data']['status'], 'OK')
self.assertEqual(results[2]['data']['inventory'], inventory_id)
self.assertEqual(
results[2]['data']['raw_inventory'],
(TEST_DATA_DIR / 'repo' / 'inventory.ini').read_text()
)
self.assertDictEqual(results[4]['data']['data'], {'path': ''})
# check hosts and groups path are unavailable
bulk_data = [
{
'method': 'get',
'path': ['inventory', inventory_id, endpoint],
}
for endpoint in ['variables', 'hosts', 'group', 'all_hosts', 'all_groups']
]
results = self.bulk(bulk_data)
for result in results:
self.assertEqual(result['status'], 404)
# check copy
results = self.bulk_transactional([
{
'method': 'post',
'path': ['project', project_id, 'inventory', inventory_id, 'copy'],
'data': {'name': 'copied'},
},
self.get_inventory_state_bulk_data('<<0[data][id]>>'),
])
self.assertDictEqual(results[1]['data']['data'], {'path': './inventory.ini'})
# check that state deletes with inventory
state_id = self.get_model_filter('main.Inventory').get(id=inventory_id)._inventory_state_id
self.assertIsNotNone(state_id)
self.bulk_transactional([
{
'method': 'delete',
'path': ['project', project_id, 'inventory', inventory_id],
'headers': {'X-Purge-Nested': 'true'}
},
])
self.assertFalse(self.get_model_filter('main.Inventory').filter(id=inventory_id).exists())
self.assertFalse(self.get_model_filter('main.InventoryState').filter(id=state_id).exists())
def test_custom_inventory_plugin(self):
results = self.bulk_transactional([
# [0]
self.create_inventory_bulk_data('TEST_INVENTORY_PLUGIN', project_id=self.project.id),
# [1]
self.get_inventory_state_bulk_data('<<0[data][id]>>'),
])
self.assertDictEqual(results[1]['data']['data'], {'body': 'localhost ansible_connection=local'})
inventory = self.get_model_filter('main.Inventory').get(id=results[0]['data']['id'])
self.assertDictEqual(inventory.inventory_state.data, {'body': 'localhost ansible_connection=local'})
# check post_execute_hook and get_pre_commands
results = self.bulk_transactional([
self.execute_plugin_bulk_data(
'TEST_MODULE',
module='system.ping',
inventory=inventory.id,
),
self.get_history_bulk_data('<<0[data][history_id]>>'),
self.get_raw_history_bulk_data('<<0[data][history_id]>>'),
])
self.assertEqual(results[1]['data']['status'], 'OK')
self.assertEqual(results[1]['data']['inventory'], inventory.id)
self.assertEqual(results[1]['data']['raw_inventory'], 'File contents:\nlocalhost ansible_connection=local')
self.assertTrue(
results[1]['data']['raw_args'].startswith('echo echo_first && echo echo_second &&'),
)
self.assertTrue(
results[2]['data']['detail'].startswith('echo_first\necho_second')
)
inventory.inventory_state.refresh_from_db()
self.assertDictEqual(inventory.inventory_state.data, {
'body': 'localhost ansible_connection=local',
'counter': 1,
})
results = self.bulk([
# [0] try to execute incompatible execution plugin
self.execute_plugin_bulk_data(
'ANSIBLE_MODULE',
module='system.ping',
inventory=inventory.id,
),
# [1] try to create option with incompatible plugin
self.create_template_option_bulk_data(arguments={
'module': 'system.ping',
'inventory': inventory.id,
}),
])
for result in results:
self.assertEqual(result['status'], 400)
self.assertEqual(
result['data']['detail'],
'Field "inventory" is not compatible with TEST_INVENTORY_PLUGIN inventory plugin.',
)
# test import
results = self.bulk_transactional([
self.import_inventory_bulk_data(
plugin='TEST_INVENTORY_PLUGIN',
data={'body': 'some_data'},
),
self.get_inventory_state_bulk_data('<<0[data][inventory_id]>>'),
])
self.assertDictEqual(results[-1]['data']['data'], {'body': 'some_data'})
def test_fk_inventory_usage(self):
results = self.bulk_transactional([
self.create_inventory_bulk_data(name='unreachable'),
self.create_template_bulk_data(),
])
inventory_id = results[0]['data']['id']
template_id = results[1]['data']['id']
option_id = self.get_model_filter('main.ExecutionTemplateOption').filter(template__id=template_id).first().id
results = self.bulk([
# [0]
self.execute_plugin_bulk_data(plugin='ANSIBLE_MODULE', inventory=inventory_id, module='system.ping'),
# [1]
self.create_template_bulk_data(arguments={
'inventory': inventory_id,
'module': 'system.ping',
}),
# [2]
{
'method': 'patch',
'path': ['project', self.project.id, 'execution_templates', template_id, 'options', str(option_id)],
'data': {'arguments': {'inventory': inventory_id, 'module': 'system.setup'}},
},
])
self.assertEqual(results[0]['status'], 400, results[0])
self.assertEqual(results[0]['data'], ['No Inventory matches the given query.'])
for idx in range(1, 3):
self.assertEqual(results[idx]['status'], 400, f'Failed on {idx}')
self.assertEqual(results[idx]['data'], ['No Inventory matches the given query.'])
def test_import_ansible_string_inventory(self):
json_file = {
'content': base64.b64encode(b'{"json": true}').decode('utf-8'),
'mediaType': 'application/json',
'name': '1.json',
}
yml_file = {
'content': base64.b64encode(b'---\nyml:\n true').decode('utf-8'),
'mediaType': 'application/x-yaml',
'name': '2.yml',
}
ini_file = {
'content': base64.b64encode(b'[example]\nini = true').decode('utf-8'),
'mediaType': None,
'name': '3.ini',
}
sh_file = {
'content': base64.b64encode(b'#!/bin/sh\necho example').decode('utf-8'),
'mediaType': 'application/x-shellscript',
'name': '4.sh',
}
unknown_file = {
'content': '',
'mediaType': None,
'name': 'unknown',
}
results = self.bulk_transactional([
# [0]
self.import_inventory_bulk_data(plugin='ANSIBLE_STRING', data={'file': json_file}),
# [1]
self.get_inventory_state_bulk_data('<<0[data][inventory_id]>>'),
# [2]
self.import_inventory_bulk_data(plugin='ANSIBLE_STRING', data={'file': yml_file}),
# [3]
self.get_inventory_state_bulk_data('<<2[data][inventory_id]>>'),
# [4]
self.import_inventory_bulk_data(plugin='ANSIBLE_STRING', data={'file': ini_file}),
# [5]
self.get_inventory_state_bulk_data('<<4[data][inventory_id]>>'),
# [6]
self.import_inventory_bulk_data(plugin='ANSIBLE_STRING', data={'file': sh_file}),
# [7]
self.get_inventory_state_bulk_data('<<6[data][inventory_id]>>'),
# [8]
self.import_inventory_bulk_data(plugin='ANSIBLE_STRING', data={'file': unknown_file}),
# [9]
self.get_inventory_state_bulk_data('<<8[data][inventory_id]>>'),
])
self.assertDictEqual(results[1]['data']['data'], {
'extension': 'json',
'executable': False,
'filename': '1',
'body': '{"json": true}',
})
self.assertDictEqual(results[3]['data']['data'], {
'extension': 'yml',
'executable': False,
'filename': '2',
'body': '---\nyml:\n true',
})
self.assertDictEqual(results[5]['data']['data'], {
'extension': 'ini',
'executable': False,
'filename': '3',
'body': '[example]\nini = true',
})
self.assertDictEqual(results[7]['data']['data'], {
'extension': 'sh',
'executable': True,
'filename': '4',
'body': '#!/bin/sh\necho example',
})
self.assertDictEqual(results[9]['data']['data'], {
'extension': '',
'executable': False,
'filename': 'unknown',
'body': '',
})
def test_import_polemarch_db_inventory(self):
inventory = (TEST_DATA_DIR / 'inventory.yml').read_text()
shutil.copy(
TEST_DATA_DIR / 'inventory.yml',
Path(settings.PROJECTS_DIR) / str(self.project.id) / 'inventory.yml'
)
results = self.bulk_transactional([
# [0]
self.import_inventory_bulk_data(
plugin='POLEMARCH_DB',
project_id=self.project.id,
data={'body': inventory},
name='inventory',
),
# [1] check hosts added
{'method': 'get', 'path': ['inventory', '<<0[data][inventory_id]>>', 'all_hosts']},
# [2] check groups added
{'method': 'get', 'path': ['inventory', '<<0[data][inventory_id]>>', 'all_groups']},
# [3] check variables added
{'method': 'get', 'path': ['inventory', '<<0[data][inventory_id]>>', 'variables']},
# [4] check created inventory in project
self.get_inventory_bulk_data('<<0[data][inventory_id]>>', self.project.id),
])
self.assertEqual(results[1]['data']['count'], 3)
self.assertEqual(results[2]['data']['count'], 3)
self.assertEqual(results[3]['data']['count'], 1)
self.assertEqual(results[4]['data']['name'], 'inventory')
self.assertEqual(results[4]['data']['plugin'], 'POLEMARCH_DB')
inventory_id = results[0]['data']['inventory_id']
# check copy
results = self.bulk_transactional([
# [0]
{
'method': 'post',
'path': ['inventory', inventory_id, 'copy'],
'data': {'name': 'copied'},
},
# [1] check hosts added
{'method': 'get', 'path': ['inventory', '<<0[data][id]>>', 'all_hosts']},