/
test_zaza_model.py
1827 lines (1620 loc) · 70.9 KB
/
test_zaza_model.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
# Copyright 2018 Canonical Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import aiounittest
# Prior to Python 3.8 asyncio would raise a ``asyncio.futures.TimeoutError``
# exception on timeout, from Python 3.8 onwards it raises a exception from a
# new ``asyncio.exceptions`` module.
#
# Neither of these are inherited from a relevant built-in exception so we
# cannot catch them generally with the built-in TimeoutError or similar.
try:
import asyncio.exceptions
AsyncTimeoutError = asyncio.exceptions.TimeoutError
except ImportError:
import asyncio.futures
AsyncTimeoutError = asyncio.futures.TimeoutError
import copy
import concurrent
import mock
import unit_tests.utils as ut_utils
from juju import loop
import zaza.model as model
FAKE_STATUS = {
'can-upgrade-to': '',
'charm': 'local:trusty/app-136',
'subordinate-to': [],
'units': {'app/0': {'leader': True,
'machine': '0',
'agent-status': {
'status': 'idle'
},
'subordinates': {
'app-hacluster/0': {
'charm': 'local:trusty/hacluster-0',
'leader': True,
'agent-status': {
'status': 'idle'
}}}},
'app/1': {'machine': '1',
'agent-status': {
'status': 'idle'
},
'subordinates': {
'app-hacluster/1': {
'charm': 'local:trusty/hacluster-0',
'agent-status': {
'status': 'idle'
}}}},
'app/2': {'machine': '2',
'agent-status': {
'status': 'idle'
},
'subordinates': {
'app-hacluster/2': {
'charm': 'local:trusty/hacluster-0',
'agent-status': {
'status': 'idle'
}}}}}}
EXECUTING_STATUS = {
'can-upgrade-to': '',
'charm': 'local:trusty/app-136',
'subordinate-to': [],
'units': {'app/0': {'leader': True,
'machine': '0',
'agent-status': {
'status': 'executing'
},
'subordinates': {
'app-hacluster/0': {
'charm': 'local:trusty/hacluster-0',
'leader': True,
'agent-status': {
'status': 'executing'
}}}}}}
class TestModel(ut_utils.BaseTestCase):
def tearDown(self):
super(TestModel, self).tearDown()
# Clear cached model name
model.CURRENT_MODEL = None
model.MODEL_ALIASES = {}
def setUp(self):
super(TestModel, self).setUp()
async def _scp_to(source, destination, user=None, proxy=None,
scp_opts=None):
return
async def _scp_from(source, destination, user=None, proxy=None,
scp_opts=None):
return
async def _run(command, timeout=None):
return self.action
async def _run_action(command, **params):
return self.run_action
async def _wait():
return
async def _add_relation(rel1, rel2):
return
async def _destroy_relation(rel1, rel2):
return
async def _add_unit(count=1, to=None):
return
async def _destroy_unit(*unitnames):
return
def _is_leader(leader):
async def _inner_is_leader():
return leader
return _inner_is_leader
self.run_action = mock.MagicMock()
self.run_action.wait.side_effect = _wait
self.action = mock.MagicMock()
self.action.data = {
'model-uuid': '1a035018-71ff-473e-8aab-d1a8d6b6cda7',
'id': 'e26ffb69-6626-4e93-8840-07f7e041e99d',
'receiver': 'glance/0',
'name': 'juju-run',
'parameters': {
'command': 'somecommand someargument', 'timeout': 0},
'status': 'completed',
'message': '',
'results': {'Code': '0', 'Stderr': '', 'Stdout': 'RESULT'},
'enqueued': '2018-04-11T23:13:42Z',
'started': '2018-04-11T23:13:42Z',
'completed': '2018-04-11T23:13:43Z'}
self.unit1 = mock.MagicMock()
self.unit1.public_address = 'ip1'
self.unit1.name = 'app/2'
self.unit1.entity_id = 'app/2'
self.unit1.machine = 'machine3'
self.unit2 = mock.MagicMock()
self.unit2.public_address = 'ip2'
self.unit2.name = 'app/4'
self.unit2.entity_id = 'app/4'
self.unit2.machine = 'machine7'
self.unit2.run.side_effect = _run
self.unit1.run.side_effect = _run
self.unit1.scp_to.side_effect = _scp_to
self.unit2.scp_to.side_effect = _scp_to
self.unit1.scp_from.side_effect = _scp_from
self.unit2.scp_from.side_effect = _scp_from
self.unit1.run_action.side_effect = _run_action
self.unit2.run_action.side_effect = _run_action
self.unit1.is_leader_from_status.side_effect = _is_leader(False)
self.unit2.is_leader_from_status.side_effect = _is_leader(True)
self.unit1.data = {'agent-status': {'current': 'idle'}}
self.unit2.data = {'agent-status': {'current': 'idle'}}
self.units = [self.unit1, self.unit2]
self.relation1 = mock.MagicMock()
self.relation1.id = 42
self.relation1.matches.side_effect = \
lambda x: True if x == 'app' else False
self.relation2 = mock.MagicMock()
self.relation2.id = 51
self.relation2.matches.side_effect = \
lambda x: True if x == 'app:interface' else False
self.relations = [self.relation1, self.relation2]
_units = mock.MagicMock()
_units.units = self.units
_units.relations = self.relations
_units.add_relation.side_effect = _add_relation
_units.destroy_relation.side_effect = _destroy_relation
_units.add_unit.side_effect = _add_unit
_units.destroy_unit.side_effect = _destroy_unit
self.mymodel = mock.MagicMock()
self.mymodel.applications = {
'app': _units
}
self.Model_mock = mock.MagicMock()
# Juju Status Object and data
self.key = "instance-id"
self.key_data = "machine-uuid"
self.machine = "1"
self.machine_data = {self.key: self.key_data}
self.unit = "app/1"
self.application = "app"
self.subordinate_application = "subordinate_application"
self.subordinate_application_data = {
"subordinate-to": [self.application],
"units": None}
self.subordinate_unit = "subordinate_application/1"
self.subordinate_unit_data = {
"workload-status": {"status": "active"}}
self.unit_data = {
"workload-status": {"status": "active"},
"machine": self.machine,
"subordinates": {
self.subordinate_unit: self.subordinate_unit_data}}
self.application_data = {"units": {
self.unit1.name: self.subordinate_unit_data,
self.unit: self.unit_data}}
self.juju_status = mock.MagicMock()
self.juju_status.applications = {
self.application: self.application_data,
self.subordinate_application: self.subordinate_application_data}
self.juju_status.machines = self.machine_data
async def _connect_model(model_name):
return model_name
async def _disconnect():
return
async def _connect():
return
async def _ctrl_connect():
return
async def _ctrl_add_model(model_name, config=None):
return
async def _ctrl_destroy_models(model_name):
return
self.Model_mock.connect.side_effect = _connect
self.Model_mock.connect_model.side_effect = _connect_model
self.Model_mock.disconnect.side_effect = _disconnect
self.Model_mock.applications = self.mymodel.applications
self.Model_mock.units = {
'app/2': self.unit1,
'app/4': self.unit2}
self.model_name = "testmodel"
self.Model_mock.info.name = self.model_name
self.Controller_mock = mock.MagicMock()
self.Controller_mock.connect.side_effect = _ctrl_connect
self.Controller_mock.add_model.side_effect = _ctrl_add_model
self.Controller_mock.destroy_models.side_effect = _ctrl_destroy_models
def test_get_juju_model(self):
self.patch_object(model.os, 'environ')
self.patch_object(model, 'get_current_model')
self.get_current_model.return_value = 'modelsmodel'
def _get_env(key):
return _env[key]
self.environ.__getitem__.side_effect = _get_env
_env = {"JUJU_MODEL": 'envmodel'}
# JUJU_ENV environment variable set
self.assertEqual(model.get_juju_model(), 'envmodel')
self.get_current_model.assert_not_called()
def test_get_juju_model_alt(self):
self.patch_object(model.os, 'environ')
self.patch_object(model, 'get_current_model')
self.get_current_model.return_value = 'modelsmodel'
def _get_env(key):
return _env[key]
self.environ.__getitem__.side_effect = _get_env
_env = {"MODEL_NAME": 'envmodel'}
# JUJU_ENV environment variable set
self.assertEqual(model.get_juju_model(), 'envmodel')
self.get_current_model.assert_not_called()
def test_get_juju_model_noenv(self):
self.patch_object(model.os, 'environ')
self.patch_object(model, 'async_get_current_model')
async def _async_get_current_model():
return 'modelsmodel'
self.async_get_current_model.side_effect = _async_get_current_model
# No envirnment variable
self.environ.__getitem__.side_effect = KeyError
self.assertEqual(model.get_juju_model(), 'modelsmodel')
self.async_get_current_model.assert_called_once()
def test_set_juju_model_aliases(self):
model.set_juju_model_aliases({'alias1': 'model1', 'alias2': 'model2'})
self.assertEqual(
model.MODEL_ALIASES,
{'alias1': 'model1', 'alias2': 'model2'})
def test_unset_juju_model_aliases(self):
model.unset_juju_model_aliases()
self.assertEqual(
model.MODEL_ALIASES,
{})
model.set_juju_model_aliases({'alias1': 'model1', 'alias2': 'model2'})
model.unset_juju_model_aliases()
self.assertEqual(
model.MODEL_ALIASES,
{})
def test_get_juju_model_aliases(self):
model.set_juju_model_aliases({'alias1': 'model1', 'alias2': 'model2'})
self.assertEqual(
model.get_juju_model_aliases(),
{'alias1': 'model1', 'alias2': 'model2'})
def test_run_in_model(self):
self.patch_object(model, 'Model')
self.Model.return_value = self.Model_mock
async def _wrapper():
async with model.run_in_model('modelname') as mymodel:
return mymodel
self.assertEqual(loop.run(_wrapper()), self.Model_mock)
self.Model_mock.connect_model.assert_called_once_with('modelname')
self.Model_mock.disconnect.assert_called_once_with()
def test_run_in_model_exception(self):
self.patch_object(model, 'Model')
self.Model.return_value = self.Model_mock
async def _wrapper():
async with model.run_in_model('modelname'):
raise Exception
with self.assertRaises(Exception):
loop.run(_wrapper())
self.Model_mock.connect_model.assert_called_once_with('modelname')
self.Model_mock.disconnect.assert_called_once_with()
def test_scp_to_unit(self):
self.patch_object(model, 'get_juju_model', return_value='mname')
self.patch_object(model, 'Model')
self.patch_object(model, 'get_unit_from_name')
self.get_unit_from_name.return_value = self.unit1
self.Model.return_value = self.Model_mock
model.scp_to_unit('app/1', '/tmp/src', '/tmp/dest')
self.unit1.scp_to.assert_called_once_with(
'/tmp/src', '/tmp/dest', proxy=False, scp_opts='', user='ubuntu')
def test_scp_to_all_units(self):
self.patch_object(model, 'get_juju_model', return_value='mname')
self.patch_object(model, 'Model')
self.Model.return_value = self.Model_mock
model.scp_to_all_units('app', '/tmp/src', '/tmp/dest')
self.unit1.scp_to.assert_called_once_with(
'/tmp/src', '/tmp/dest', proxy=False, scp_opts='', user='ubuntu')
self.unit2.scp_to.assert_called_once_with(
'/tmp/src', '/tmp/dest', proxy=False, scp_opts='', user='ubuntu')
def test_scp_from_unit(self):
self.patch_object(model, 'get_juju_model', return_value='mname')
self.patch_object(model, 'Model')
self.patch_object(model, 'get_unit_from_name')
self.get_unit_from_name.return_value = self.unit1
self.Model.return_value = self.Model_mock
model.scp_from_unit('app/1', '/tmp/src', '/tmp/dest')
self.unit1.scp_from.assert_called_once_with(
'/tmp/src', '/tmp/dest', proxy=False, scp_opts='', user='ubuntu')
def test_get_units(self):
self.patch_object(model, 'get_juju_model', return_value='mname')
self.patch_object(model, 'Model')
self.Model.return_value = self.Model_mock
self.assertEqual(
model.get_units('app'),
self.units)
def test_get_machines(self):
self.patch_object(model, 'get_juju_model', return_value='mname')
self.patch_object(model, 'Model')
self.Model.return_value = self.Model_mock
self.assertEqual(
model.get_machines('app'),
['machine3', 'machine7'])
def test_get_first_unit_name(self):
self.patch_object(model, 'get_juju_model', return_value='mname')
self.patch_object(model, 'get_units')
self.get_units.return_value = self.units
self.assertEqual(
model.get_first_unit_name('model', 'app'),
'app/2')
def test_get_lead_unit_name(self):
self.patch_object(model, 'get_juju_model', return_value='mname')
self.patch_object(model, 'get_units')
self.get_units.return_value = self.units
self.patch_object(model, 'Model')
self.Model.return_value = self.Model_mock
self.assertEqual(
model.get_lead_unit_name('app', 'model'),
'app/4')
def test_get_lead_unit_ip(self):
self.patch_object(model, 'get_juju_model', return_value='mname')
self.patch_object(model, 'get_units')
self.get_units.return_value = self.units
self.patch_object(model, 'Model')
self.Model.return_value = self.Model_mock
self.assertEqual(
model.get_lead_unit_ip('app', 'model'),
'ip2')
def test_get_unit_from_name(self):
self.patch_object(model, 'get_juju_model', return_value='mname')
self.patch_object(model, 'Model')
self.Model.return_value = self.Model_mock
# Normal case
self.assertEqual(
model.get_unit_from_name('app/4', model_name='mname'),
self.unit2)
# Normal case with Model()
self.assertEqual(
model.get_unit_from_name('app/4', self.mymodel),
self.unit2)
# Normal case, using default
self.assertEqual(
model.get_unit_from_name('app/4'),
self.unit2)
# Unit does not exist
with self.assertRaises(model.UnitNotFound):
model.get_unit_from_name('app/10', model_name='mname')
# Application does not exist
with self.assertRaises(model.UnitNotFound):
model.get_unit_from_name('bad_name', model_name='mname')
def test_get_app_ips(self):
self.patch_object(model, 'get_juju_model', return_value='mname')
self.patch_object(model, 'get_units')
self.get_units.return_value = self.units
self.assertEqual(model.get_app_ips('model', 'app'), ['ip1', 'ip2'])
def test_run_on_unit(self):
self.patch_object(model, 'get_juju_model', return_value='mname')
expected = {'Code': '0', 'Stderr': '', 'Stdout': 'RESULT'}
self.cmd = cmd = 'somecommand someargument'
self.patch_object(model, 'Model')
self.patch_object(model, 'get_unit_from_name')
self.get_unit_from_name.return_value = self.unit1
self.Model.return_value = self.Model_mock
self.assertEqual(model.run_on_unit('app/2', cmd),
expected)
self.unit1.run.assert_called_once_with(cmd, timeout=None)
def test_run_on_unit_missing_stderr(self):
self.patch_object(model, 'get_juju_model', return_value='mname')
expected = {'Code': '0', 'Stderr': '', 'Stdout': 'RESULT'}
self.action.data['results'] = {'Code': '0', 'Stdout': 'RESULT'}
self.cmd = cmd = 'somecommand someargument'
self.patch_object(model, 'Model')
self.patch_object(model, 'get_unit_from_name')
self.get_unit_from_name.return_value = self.unit1
self.Model.return_value = self.Model_mock
self.assertEqual(model.run_on_unit('app/2', cmd),
expected)
self.unit1.run.assert_called_once_with(cmd, timeout=None)
def test_run_on_leader(self):
self.patch_object(model, 'get_juju_model', return_value='mname')
expected = {'Code': '0', 'Stderr': '', 'Stdout': 'RESULT'}
self.cmd = cmd = 'somecommand someargument'
self.patch_object(model, 'Model')
self.Model.return_value = self.Model_mock
self.assertEqual(model.run_on_leader('app', cmd),
expected)
self.unit2.run.assert_called_once_with(cmd, timeout=None)
def test_get_relation_id(self):
self.patch_object(model, 'get_juju_model', return_value='mname')
self.patch_object(model, 'Model')
self.Model.return_value = self.Model_mock
self.assertEqual(model.get_relation_id('app', 'app'), 42)
def test_add_relation(self):
self.patch_object(model, 'get_juju_model', return_value='mname')
self.patch_object(model, 'Model')
self.Model.return_value = self.Model_mock
model.add_relation('app', 'shared-db', 'mysql-shared-db')
self.mymodel.applications['app'].add_relation.assert_called_once_with(
'shared-db',
'mysql-shared-db')
def test_remove_relation(self):
self.patch_object(model, 'get_juju_model', return_value='mname')
self.patch_object(model, 'Model')
self.Model.return_value = self.Model_mock
model.remove_relation('app', 'shared-db', 'mysql-shared-db')
self.mymodel.applications[
'app'].destroy_relation.assert_called_once_with('shared-db',
'mysql-shared-db')
def test_add_unit(self):
self.patch_object(model, 'get_juju_model', return_value='mname')
self.patch_object(model, 'Model')
self.Model.return_value = self.Model_mock
model.add_unit('app', count=2, to='lxd/0')
self.mymodel.applications['app'].add_unit.assert_called_once_with(
count=2, to='lxd/0')
def test_add_unit_wait(self):
self.patch_object(model, 'async_block_until_unit_count')
self.patch_object(model, 'get_juju_model', return_value='mname')
self.patch_object(model, 'Model')
self.Model.return_value = self.Model_mock
model.add_unit('app', count=2, to='lxd/0', wait_appear=True)
self.mymodel.applications['app'].add_unit.assert_called_once_with(
count=2, to='lxd/0')
self.async_block_until_unit_count.assert_called_once_with(
'app', 4, model_name=None)
def test_destroy_unit(self):
self.patch_object(model, 'get_juju_model', return_value='mname')
self.patch_object(model, 'Model')
self.Model.return_value = self.Model_mock
model.destroy_unit('app', 'app/2')
self.mymodel.applications['app'].destroy_unit.assert_called_once_with(
'app/2')
def test_destroy_unit_wait(self):
self.patch_object(model, 'async_block_until_unit_count')
self.patch_object(model, 'get_juju_model', return_value='mname')
self.patch_object(model, 'Model')
self.Model.return_value = self.Model_mock
model.destroy_unit('app', 'app/2', wait_disappear=True)
self.mymodel.applications['app'].destroy_unit.assert_called_once_with(
'app/2')
self.async_block_until_unit_count.assert_called_once_with(
'app', 1, model_name=None)
def test_get_relation_id_interface(self):
self.patch_object(model, 'get_juju_model', return_value='mname')
self.patch_object(model, 'Model')
self.Model.return_value = self.Model_mock
self.assertEqual(
model.get_relation_id('app', 'app',
remote_interface_name='interface'),
51)
def test_run_action(self):
self.patch_object(model, 'get_juju_model', return_value='mname')
self.patch_object(model, 'Model')
self.patch_object(model, 'get_unit_from_name')
self.get_unit_from_name.return_value = self.unit1
self.Model.return_value = self.Model_mock
model.run_action(
'app/2',
'backup',
action_params={'backup_dir': '/dev/null'})
self.unit1.run_action.assert_called_once_with(
'backup',
backup_dir='/dev/null')
self.run_action.status = 'failed'
self.run_action.message = 'aMessage'
self.run_action.id = 'aId'
self.run_action.enqueued = 'aEnqueued'
self.run_action.started = 'aStarted'
self.run_action.completed = 'aCompleted'
self.run_action.name = 'backup2'
self.run_action.parameters = {'backup_dir': '/non-existent'}
self.run_action.receiver = 'app/2'
with self.assertRaises(model.ActionFailed) as e:
model.run_action(
self.run_action.receiver,
self.run_action.name,
action_params=self.run_action.parameters,
raise_on_failure=True)
self.assertEqual(
str(e.exception),
'Run of action "backup2" with parameters '
'"{\'backup_dir\': \'/non-existent\'}" on '
'"app/2" failed with "aMessage" '
'(id=aId status=failed enqueued=aEnqueued '
'started=aStarted completed=aCompleted)')
def test_get_actions(self):
self.patch_object(model, 'get_juju_model', return_value='mname')
self.patch_object(model.subprocess, 'check_output')
self.check_output.return_value = 'action: "action desc"'
self.assertEqual(
model.get_actions('myapp'),
{'action': "action desc"})
self.check_output.assert_called_once_with(
['juju', 'actions', '-m', 'mname', 'myapp', '--format', 'yaml'])
def test_run_action_on_leader(self):
self.patch_object(model, 'get_juju_model', return_value='mname')
self.patch_object(model, 'Model')
self.Model.return_value = self.Model_mock
model.run_action_on_leader(
'app',
'backup',
action_params={'backup_dir': '/dev/null'})
self.assertFalse(self.unit1.called)
self.unit2.run_action.assert_called_once_with(
'backup',
backup_dir='/dev/null')
self.run_action.status = 'failed'
self.run_action.message = 'aMessage'
self.run_action.id = 'aId'
self.run_action.enqueued = 'aEnqueued'
self.run_action.started = 'aStarted'
self.run_action.completed = 'aCompleted'
self.run_action.name = 'backup2'
self.run_action.parameters = {'backup_dir': '/non-existent'}
self.run_action.receiver = 'app/2'
with self.assertRaises(model.ActionFailed) as e:
model.run_action(
self.run_action.receiver,
self.run_action.name,
action_params=self.run_action.parameters,
raise_on_failure=True)
self.assertEqual(
str(e.exception),
'Run of action "backup2" with parameters '
'"{\'backup_dir\': \'/non-existent\'}" on '
'"app/2" failed with "aMessage" '
'(id=aId status=failed enqueued=aEnqueued '
'started=aStarted completed=aCompleted)')
def test_run_action_on_units(self):
self.patch_object(model, 'get_juju_model', return_value='mname')
self.patch_object(model, 'Model')
self.Model.return_value = self.Model_mock
self.patch_object(model, 'get_unit_from_name')
units = {
'app/1': self.unit1,
'app/2': self.unit2}
self.get_unit_from_name.side_effect = lambda x, y: units[x]
self.run_action.status = 'completed'
model.run_action_on_units(
['app/1', 'app/2'],
'backup',
action_params={'backup_dir': '/dev/null'})
self.unit1.run_action.assert_called_once_with(
'backup',
backup_dir='/dev/null')
self.unit2.run_action.assert_called_once_with(
'backup',
backup_dir='/dev/null')
def test_run_action_on_units_timeout(self):
self.patch_object(model, 'get_juju_model', return_value='mname')
self.patch_object(model, 'Model')
self.Model.return_value = self.Model_mock
self.patch_object(model, 'get_unit_from_name')
self.get_unit_from_name.return_value = self.unit1
self.run_action.status = 'running'
with self.assertRaises(AsyncTimeoutError):
model.run_action_on_units(
['app/1'],
'backup',
action_params={'backup_dir': '/dev/null'},
timeout=0.1)
def test_run_action_on_units_fail(self):
self.patch_object(model, 'get_juju_model', return_value='mname')
self.patch_object(model, 'Model')
self.Model.return_value = self.Model_mock
self.patch_object(model, 'get_unit_from_name')
self.get_unit_from_name.return_value = self.unit1
self.run_action.status = 'failed'
with self.assertRaises(model.ActionFailed):
model.run_action_on_units(
['app/1'],
'backup',
raise_on_failure=True,
action_params={'backup_dir': '/dev/null'})
def _application_states_setup(self, setup, units_idle=True):
self.system_ready = True
self._block_until_calls = 0
async def _block_until(f, timeout=0):
# Mimic timeouts
timeout = timeout + self._block_until_calls
self._block_until_calls += 1
if timeout == -1:
raise concurrent.futures._base.TimeoutError("Timeout", 1)
result = f()
if not result:
self.system_ready = False
return
async def _all_units_idle():
return units_idle
self.Model_mock.block_until.side_effect = _block_until
self.patch_object(model, 'Model')
self.Model.return_value = self.Model_mock
self.Model_mock.all_units_idle.return_value = _all_units_idle
p_mock_ws = mock.PropertyMock(
return_value=setup['workload-status'])
p_mock_wsmsg = mock.PropertyMock(
return_value=setup['workload-status-message'])
type(self.unit1).workload_status = p_mock_ws
type(self.unit1).workload_status_message = p_mock_wsmsg
type(self.unit2).workload_status = p_mock_ws
type(self.unit2).workload_status_message = p_mock_wsmsg
def test_units_with_wl_status_state(self):
self._application_states_setup({
'workload-status': 'active',
'workload-status-message': 'Unit is ready'})
units = model.units_with_wl_status_state(self.Model_mock, 'active')
self.assertTrue(len(units) == 2)
self.assertIn(self.unit1, units)
self.assertIn(self.unit2, units)
def test_units_with_wl_status_state_no_match(self):
self._application_states_setup({
'workload-status': 'blocked',
'workload-status-message': 'Unit is ready'})
units = model.units_with_wl_status_state(self.Model_mock, 'active')
self.assertTrue(len(units) == 0)
def test_check_model_for_hard_errors(self):
self.patch_object(model, 'units_with_wl_status_state')
self.units_with_wl_status_state.return_value = []
# Test will fail if an Exception is raised
model.check_model_for_hard_errors(self.Model_mock)
def test_check_model_for_hard_errors_found(self):
self.patch_object(model, 'units_with_wl_status_state')
self.units_with_wl_status_state.return_value = [self.unit1]
with self.assertRaises(model.UnitError):
model.check_model_for_hard_errors(self.Model_mock)
def test_check_unit_workload_status(self):
self.patch_object(model, 'check_model_for_hard_errors')
self._application_states_setup({
'workload-status': 'active',
'workload-status-message': 'Unit is ready'})
self.assertTrue(
model.check_unit_workload_status(self.Model_mock,
self.unit1, ['active']))
def test_check_unit_workload_status_no_match(self):
self.patch_object(model, 'check_model_for_hard_errors')
self._application_states_setup({
'workload-status': 'blocked',
'workload-status-message': 'Unit is ready'})
self.assertFalse(
model.check_unit_workload_status(self.Model_mock,
self.unit1, ['active']))
def test_check_unit_workload_status_multi(self):
self.patch_object(model, 'check_model_for_hard_errors')
self._application_states_setup({
'workload-status': 'blocked',
'workload-status-message': 'Unit is ready'})
self.assertTrue(
model.check_unit_workload_status(
self.Model_mock,
self.unit1, ['active', 'blocked']))
def test_check_unit_workload_status_message_message(self):
self.patch_object(model, 'check_model_for_hard_errors')
self._application_states_setup({
'workload-status': 'blocked',
'workload-status-message': 'Unit is ready'})
self.assertTrue(
model.check_unit_workload_status_message(self.Model_mock,
self.unit1,
message='Unit is ready'))
def test_check_unit_workload_status_message_message_not_found(self):
self.patch_object(model, 'check_model_for_hard_errors')
self._application_states_setup({
'workload-status': 'blocked',
'workload-status-message': 'Something else'})
self.assertFalse(
model.check_unit_workload_status_message(self.Model_mock,
self.unit1,
message='Unit is ready'))
def test_check_unit_workload_status_message_prefix(self):
self.patch_object(model, 'check_model_for_hard_errors')
self._application_states_setup({
'workload-status': 'blocked',
'workload-status-message': 'Unit is ready (OSD Count 23)'})
self.assertTrue(
model.check_unit_workload_status_message(
self.Model_mock,
self.unit1,
prefixes=['Readyish', 'Unit is ready']))
def test_check_unit_workload_status_message_prefix_no_match(self):
self.patch_object(model, 'check_model_for_hard_errors')
self._application_states_setup({
'workload-status': 'blocked',
'workload-status-message': 'On my holidays'})
self.assertFalse(
model.check_unit_workload_status_message(
self.Model_mock,
self.unit1,
prefixes=['Readyish', 'Unit is ready']))
def test_wait_for_application_states(self):
self._application_states_setup({
'workload-status': 'active',
'workload-status-message': 'Unit is ready'})
model.wait_for_application_states('modelname', timeout=1)
self.assertTrue(self.system_ready)
def test_wait_for_application_states_not_ready_ws(self):
self._application_states_setup({
'workload-status': 'blocked',
'workload-status-message': 'Unit is ready'})
model.wait_for_application_states('modelname', timeout=1)
self.assertFalse(self.system_ready)
def test_wait_for_application_states_errored_unit(self):
self._application_states_setup({
'workload-status': 'error',
'workload-status-message': 'Unit is ready'})
with self.assertRaises(model.UnitError):
model.wait_for_application_states('modelname', timeout=1)
self.assertFalse(self.system_ready)
def test_wait_for_application_states_not_ready_wsmsg(self):
self._application_states_setup({
'workload-status': 'active',
'workload-status-message': 'Unit is not ready'})
model.wait_for_application_states('modelname', timeout=1)
self.assertFalse(self.system_ready)
def test_wait_for_application_states_blocked_ok(self):
self._application_states_setup({
'workload-status': 'blocked',
'workload-status-message': 'Unit is ready'})
model.wait_for_application_states(
'modelname',
states={'app': {
'workload-status': 'blocked'}},
timeout=1)
self.assertTrue(self.system_ready)
def test_wait_for_application_states_bespoke_msg(self):
self._application_states_setup({
'workload-status': 'active',
'workload-status-message': 'Sure, I could do something'})
model.wait_for_application_states(
'modelname',
states={'app': {
'workload-status-message': 'Sure, I could do something'}},
timeout=1)
self.assertTrue(self.system_ready)
def test_wait_for_application_states_bespoke_msg_blocked_ok(self):
self._application_states_setup({
'workload-status': 'blocked',
'workload-status-message': 'Sure, I could do something'})
model.wait_for_application_states(
'modelname',
states={'app': {
'workload-status': 'blocked',
'workload-status-message': 'Sure, I could do something'}},
timeout=1)
self.assertTrue(self.system_ready)
def test_wait_for_application_states_idle_timeout(self):
self._application_states_setup({
'agent-status': 'executing',
'workload-status': 'blocked',
'workload-status-message': 'Sure, I could do something'})
with self.assertRaises(model.ModelTimeout) as timeout:
model.wait_for_application_states('modelname', timeout=-2)
self.assertEqual(
timeout.exception.args[0],
"Zaza has timed out waiting on the model to reach idle state.")
def test_wait_for_application_states_timeout(self):
self._application_states_setup({
'agent-status': 'executing',
'workload-status': 'blocked',
'workload-status-message': 'Sure, I could do something'})
with self.assertRaises(model.ModelTimeout) as timeout:
model.wait_for_application_states('modelname', timeout=-3)
self.assertEqual(
timeout.exception.args[0],
("Timed out waiting for 'app/2'. The workload status is 'blocked' "
"which is not one of '['active']'"))
def test_get_current_model(self):
self.patch_object(model, 'Model')
self.Model.return_value = self.Model_mock
self.assertEqual(model.get_current_model(), self.model_name)
def test_block_until_file_has_contents(self):
self.action.data = {
'results': {'Code': '0', 'Stderr': '', 'Stdout': 'somestring'}
}
self.patch_object(model, 'Model')
self.Model.return_value = self.Model_mock
self.patch_object(model, 'get_juju_model', return_value='mname')
self.patch("builtins.open",
new_callable=mock.mock_open(),
name="_open")
_fileobj = mock.MagicMock()
_fileobj.__enter__().read.return_value = "somestring"
self._open.return_value = _fileobj
model.block_until_file_has_contents(
'app',
'/tmp/src/myfile.txt',
'somestring',
timeout=0.1)
self.unit1.run.assert_called_once_with(
'cat /tmp/src/myfile.txt')
self.unit2.run.assert_called_once_with(
'cat /tmp/src/myfile.txt')
def test_block_until_file_has_no_contents(self):
self.action.data = {
'results': {'Code': '0', 'Stderr': ''}
}
self.patch_object(model, 'Model')
self.Model.return_value = self.Model_mock
self.patch_object(model, 'get_juju_model', return_value='mname')
self.patch("builtins.open",
new_callable=mock.mock_open(),
name="_open")
_fileobj = mock.MagicMock()
_fileobj.__enter__().read.return_value = ""
self._open.return_value = _fileobj
model.block_until_file_has_contents(
'app',
'/tmp/src/myfile.txt',
'',
timeout=0.1)
self.unit1.run.assert_called_once_with(
'cat /tmp/src/myfile.txt')
self.unit2.run.assert_called_once_with(
'cat /tmp/src/myfile.txt')
def test_block_until_file_has_contents_missing(self):
self.patch_object(model, 'Model')
self.Model.return_value = self.Model_mock
self.patch_object(model, 'get_juju_model', return_value='mname')
self.patch("builtins.open",
new_callable=mock.mock_open(),
name="_open")
_fileobj = mock.MagicMock()
_fileobj.__enter__().read.return_value = "anything else"
self._open.return_value = _fileobj
with self.assertRaises(AsyncTimeoutError):
model.block_until_file_has_contents(
'app',
'/tmp/src/myfile.txt',
'somestring',
timeout=0.1)
self.unit1.run.assert_called_once_with('cat /tmp/src/myfile.txt')
def test_block_until_file_missing(self):
self.patch_object(model, 'Model')
self.Model.return_value = self.Model_mock
self.patch_object(model, 'get_juju_model', return_value='mname')
self.action.data['results']['Stdout'] = "1"
model.block_until_file_missing(
'app',
'/tmp/src/myfile.txt',
timeout=0.1)
self.unit1.run.assert_called_once_with(
'test -e "/tmp/src/myfile.txt"; echo $?')
def test_block_until_file_missing_isnt_missing(self):
self.patch_object(model, 'Model')
self.Model.return_value = self.Model_mock
self.patch_object(model, 'get_juju_model', return_value='mname')
self.action.data['results']['Stdout'] = "0"
with self.assertRaises(AsyncTimeoutError):
model.block_until_file_missing(
'app',