-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathtest_entity_mixins.py
More file actions
1297 lines (1077 loc) · 49.8 KB
/
Copy pathtest_entity_mixins.py
File metadata and controls
1297 lines (1077 loc) · 49.8 KB
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
"""Tests for :mod:`nailgun.entity_mixins`."""
import http.client as http_client
from unittest import TestCase, mock
from fauxfactory import gen_integer
from requests.exceptions import HTTPError, JSONDecodeError
from nailgun import client, config, entity_mixins
from nailgun.entity_fields import (
IntegerField,
ListField,
OneToManyField,
OneToOneField,
StringField,
)
# The size of this module is a direct reflection of the size of module
# `nailgun.entity_mixins`. It would be good to split that module up, then split
# this module up similarly.
# This module is divided in to the following sections:
#
# 1. Entity defintions.
# 2. Tests for private methods.
# 3. Tests for public methods.
#
# 1. Entity definitions. ------------------------------------------------- {{{1
# Due to the length of the with statements, nested is preferred over combined
# ruff: noqa: SIM117
# Tests use a unused nailgun and tests imports
# ruff: noqa: F401
# Cannot use ast.literal_eval because ServerConfig isn't a basic type
# ruff: noqa: S307
class SampleEntity(entity_mixins.Entity):
"""Sample entity to be used in the tests."""
def __init__(self, server_config=None, **kwargs):
self._fields = {
'name': StringField(),
'number': IntegerField(),
'unique': StringField(unique=True),
}
self._meta = {'api_path': 'foo'}
super().__init__(server_config=server_config, **kwargs)
class SampleEntityTwo(entity_mixins.Entity):
"""An entity with foreign key fields.
This class has a :class:`nailgun.entity_fields.OneToManyField` called
"one_to_many" pointing to :class:`tests.test_entity_mixins.SampleEntity`.
"""
def __init__(self, server_config=None, **kwargs):
self._fields = {'one_to_many': OneToManyField(SampleEntity)}
super().__init__(server_config=server_config, **kwargs)
class SampleEntityThree(entity_mixins.Entity):
"""An entity with foreign key fields as One to One and ListField.
This class has a :class:`nailgun.entity_fields.OneToOneField` called
"one_to_one" pointing to :class:`tests.test_entity_mixins.SampleEntityTwo`.
This class has a :class:`nailgun.entity_fields.ListField` called "list"
containing instances of :class:`tests.test_entity_mixins.SampleEntity`.
"""
def __init__(self, server_config=None, **kwargs):
self._fields = {'one_to_one': OneToOneField(SampleEntityTwo), 'list': ListField()}
super().__init__(server_config=server_config, **kwargs)
class EntityWithCreate(entity_mixins.Entity, entity_mixins.EntityCreateMixin):
"""Inherits from :class:`nailgun.entity_mixins.EntityCreateMixin`."""
def __init__(self, server_config=None, **kwargs):
self._meta = {'api_path': ''}
super().__init__(server_config=server_config, **kwargs)
class EntityWithRead(entity_mixins.Entity, entity_mixins.EntityReadMixin):
"""Inherits from :class:`nailgun.entity_mixins.EntityReadMixin`."""
def __init__(self, server_config=None, **kwargs):
self._meta = {'api_path': ''}
super().__init__(server_config=server_config, **kwargs)
class EntityWithUpdate(entity_mixins.Entity, entity_mixins.EntityUpdateMixin):
"""Inherits from :class:`nailgun.entity_mixins.EntityUpdateMixin`."""
def __init__(self, server_config=None, **kwargs):
self._meta = {'api_path': ''}
super().__init__(server_config=server_config, **kwargs)
class EntityWithDelete(entity_mixins.Entity, entity_mixins.EntityDeleteMixin):
"""Inherits from :class:`nailgun.entity_mixins.EntityDeleteMixin`."""
def __init__(self, server_config=None, **kwargs):
self._meta = {'api_path': ''}
super().__init__(server_config=server_config, **kwargs)
class EntityWithSearch(entity_mixins.Entity, entity_mixins.EntitySearchMixin):
"""Inherits from :class:`nailgun.entity_mixins.EntitySearchMixin`."""
def __init__(self, server_config=None, **kwargs):
self._meta = {'api_path': ''}
super().__init__(server_config=server_config, **kwargs)
class EntityWithSearch2(EntityWithSearch):
"""An entity with integer, one to one and one to many fields."""
def __init__(self, server_config=None, **kwargs):
self._fields = {
'one': OneToOneField(SampleEntity),
'many': OneToManyField(SampleEntity),
}
super().__init__(server_config=server_config, **kwargs)
# 2. Tests for private methods. ------------------------------------------ {{{1
class MakeEntityFromIdTestCase(TestCase):
"""Tests for :func:`nailgun.entity_mixins._make_entity_from_id`."""
def setUp(self):
"""Set ``self.cfg``."""
self.cfg = config.ServerConfig('example.com')
def test_pass_in_entity_obj(self):
"""Let the ``entity_obj_or_id`` argument be an entity object."""
self.assertIsInstance(
entity_mixins._make_entity_from_id(SampleEntity, SampleEntity(self.cfg), self.cfg),
SampleEntity,
)
def test_pass_in_entity_id(self):
"""Let the ``entity_obj_or_id`` argument be an integer."""
entity_id = gen_integer(min_value=1)
entity_obj = entity_mixins._make_entity_from_id(SampleEntity, entity_id, self.cfg)
self.assertIsInstance(entity_obj, SampleEntity)
self.assertEqual(entity_obj.id, entity_id)
class MakeEntitiesFromIdsTestCase(TestCase):
"""Tests for :func:`nailgun.entity_mixins._make_entities_from_ids`."""
def setUp(self):
"""Set ``self.cfg``."""
self.cfg = config.ServerConfig('example.com')
def test_pass_in_emtpy_iterable(self):
"""Let the ``entity_objs_and_ids`` argument be an empty iterable."""
for iterable in ([], ()):
self.assertEqual(
entity_mixins._make_entities_from_ids(SampleEntity, iterable, self.cfg),
[],
)
def test_pass_in_entity_obj(self):
"""Let the ``entity_objs_and_ids`` arg be an iterable of entities."""
for num_entities in range(4):
input_entities = [SampleEntity(self.cfg) for _ in range(num_entities)]
output_entities = entity_mixins._make_entities_from_ids(
SampleEntity, input_entities, self.cfg
)
self.assertEqual(num_entities, len(output_entities))
for output_entity in output_entities:
self.assertIsInstance(output_entity, SampleEntity)
def test_pass_in_entity_ids(self):
"""Let the ``entity_objs_and_ids`` arg be an iterable of integers."""
for num_entities in range(4):
entity_ids = [gen_integer(min_value=1) for _ in range(num_entities)]
entities = entity_mixins._make_entities_from_ids(SampleEntity, entity_ids, self.cfg)
self.assertEqual(len(entities), len(entity_ids))
for i, entity_id in enumerate(entity_ids):
self.assertIsInstance(entities[i], SampleEntity)
self.assertEqual(entities[i].id, entity_id)
def test_pass_in_both(self):
"""Let ``entity_objs_and_ids`` be an iterable of integers and IDs."""
entities = entity_mixins._make_entities_from_ids(
SampleEntity, [SampleEntity(self.cfg), 5], self.cfg
)
self.assertEqual(len(entities), 2)
for entity in entities:
self.assertIsInstance(entity, SampleEntity)
class PollTaskTestCase(TestCase):
"""Tests for :func:`nailgun.entity_mixins._poll_task`."""
def setUp(self):
"""Create a bogus server configuration object."""
self.cfg = config.ServerConfig('bogus url')
def test__poll_task_failure(self):
"""Check what happens when a foreman task completes but does not succeed.
Assert that a :class:`nailgun.entity_mixins.TaskFailedError` exception
is raised.
"""
for state in ('paused', 'stopped'):
with self.subTest(state):
with mock.patch.object(client, 'get') as get:
get.return_value.json.return_value = {'state': state, 'result': 'not success'}
with self.assertRaises(entity_mixins.TaskFailedError):
entity_mixins._poll_task(gen_integer(), self.cfg)
def test__poll_task_success(self):
"""Check what happens when a foreman task completes and does succeed.
Assert that the server's response is returned.
"""
for state in ('paused', 'stopped'):
with self.subTest(state):
with mock.patch.object(client, 'get') as get:
get.return_value.json.return_value = {'state': state, 'result': 'success'}
self.assertEqual(
get.return_value.json.return_value,
entity_mixins._poll_task(gen_integer(), self.cfg),
)
def test__poll_task_timeout(self):
"""Assert that the task is still running after timeout."""
with self.assertRaises(entity_mixins.TaskTimedOutError):
with mock.patch.object(client, 'get') as get:
get.return_value.json.return_value = {'state': 'running', 'result': 'pending'}
entity_mixins._poll_task(gen_integer(), self.cfg, timeout=1)
# 3. Tests for public methods. ------------------------------------------- {{{1
class EntityTestCase(TestCase):
"""Tests for :class:`nailgun.entity_mixins.Entity`."""
def setUp(self):
"""Set ``self.cfg``."""
self.cfg = config.ServerConfig('http://example.com')
def test_init_v1(self):
"""Provide no value for the ``server_config`` argument."""
with mock.patch.object(config.ServerConfig, 'get') as sc_get:
self.assertEqual(
SampleEntity()._server_config,
sc_get.return_value,
)
self.assertEqual(sc_get.call_count, 1)
def test_init_v2(self):
"""Provide a server config object via ``DEFAULT_SERVER_CONFIG``."""
backup = entity_mixins.DEFAULT_SERVER_CONFIG
try:
entity_mixins.DEFAULT_SERVER_CONFIG = config.ServerConfig('url')
self.assertEqual(
SampleEntity()._server_config,
entity_mixins.DEFAULT_SERVER_CONFIG,
)
finally:
entity_mixins.DEFAULT_SERVER_CONFIG = backup
def test_entity_get_fields(self):
"""Test :meth:`nailgun.entity_mixins.Entity.get_fields`."""
fields = SampleEntity(self.cfg).get_fields()
self.assertEqual(len(fields), 4)
self.assertEqual(set(fields.keys()), {'id', 'name', 'number', 'unique'})
self.assertIsInstance(fields['name'], StringField)
self.assertIsInstance(fields['number'], IntegerField)
def test_entity_get_values(self):
"""Test :meth:`nailgun.entity_mixins.Entity.get_values`."""
for values in (
{},
{'id': gen_integer()},
{'name': gen_integer()},
{'number': gen_integer()},
{'name': gen_integer(), 'number': gen_integer()},
{
'id': gen_integer(),
'name': gen_integer(),
'number': gen_integer(),
},
):
self.assertEqual(
SampleEntity(self.cfg, **values).get_values(),
values,
)
def test_entity_get_values_v2(self):
"""Test :meth:`nailgun.entity_mixins.Entity.get_values`.
ensure ``_path_fields`` are never returned.
"""
for values in (
{},
{'id': gen_integer()},
{'name': gen_integer()},
{'number': gen_integer()},
{'name': gen_integer(), 'number': gen_integer()},
{
'id': gen_integer(),
'name': gen_integer(),
'number': gen_integer(),
},
):
entity = SampleEntity(self.cfg, **values)
entity._path_fields = {'foo': 1}
self.assertEqual(
entity.get_values(),
values,
)
def test_path(self):
"""Test :meth:`nailgun.entity_mixins.Entity.path`."""
# e.g. 'https://sat.example.com/katello/api/v2'
api_path = SampleEntity(self.cfg)._meta["api_path"]
path = f'{self.cfg.url}/{api_path}'
# Call `path()` on an entity with no ID.
self.assertEqual(SampleEntity(self.cfg).path(), path)
self.assertEqual(SampleEntity(self.cfg).path('base'), path)
with self.assertRaises(entity_mixins.NoSuchPathError):
SampleEntity(self.cfg).path('self')
# Call `path()` on an entity with an ID.
self.assertEqual(SampleEntity(self.cfg, id=5).path(), f'{path}/5')
self.assertEqual(SampleEntity(self.cfg, id=5).path('base'), path)
self.assertEqual(SampleEntity(self.cfg, id=5).path('self'), f'{path}/5')
def test_no_such_field_error(self):
"""Try to raise a :class:`nailgun.entity_mixins.NoSuchFieldError`."""
SampleEntity(self.cfg, name='Alice')
with self.assertRaises(entity_mixins.NoSuchFieldError):
SampleEntity(self.cfg, namee='Alice')
def test_bad_value_error(self):
"""Try to raise a :class:`nailgun.entity_mixins.BadValueError`."""
SampleEntityTwo(self.cfg, one_to_many=[1])
with self.assertRaises(entity_mixins.BadValueError):
SampleEntityTwo(self.cfg, one_to_many=1)
def test_eq_none(self):
"""Test method ``nailgun.entity_mixins.Entity.__eq__`` against None.
Assert that ``__eq__`` returns False when compared to None.
"""
alice = SampleEntity(self.cfg, id=1, name='Alice')
self.assertFalse(alice.__eq__(None))
def test_eq(self):
"""Test method ``nailgun.entity_mixins.Entity.__eq__``.
Assert that ``__eq__`` works comparing all attributes, even from
nested structures.
"""
# Testing simple properties
alice = SampleEntity(self.cfg, id=1, name='Alice')
alice_clone = SampleEntity(self.cfg, id=1, name='Alice')
self.assertEqual(alice, alice_clone)
alice_2 = SampleEntity(self.cfg, id=2, name='Alice2')
self.assertNotEqual(alice, alice_2)
# Testing OneToMany nested objects
john = SampleEntityTwo(self.cfg, one_to_many=[alice, alice_2])
john_clone = SampleEntityTwo(self.cfg, one_to_many=[alice, alice_2])
self.assertEqual(john, john_clone)
john_different_order = SampleEntityTwo(
self.cfg,
one_to_many=[
alice_2,
alice,
],
)
self.assertNotEqual(john, john_different_order)
john_missing_alice = SampleEntityTwo(self.cfg, one_to_many=[alice])
self.assertNotEqual(john, john_missing_alice)
john_without_alice = SampleEntityTwo(self.cfg)
self.assertNotEqual(john, john_without_alice)
# Testing OneToOne nested objects
mary = SampleEntityThree(self.cfg, one_to_one=john)
mary_clone = SampleEntityThree(self.cfg, one_to_one=john_clone)
self.assertEqual(mary, mary_clone)
mary_different = SampleEntityThree(self.cfg, one_to_one=john_different_order)
self.assertNotEqual(mary, mary_different)
mary_none_john = SampleEntityThree(self.cfg, one_to_one=None)
mary_none_john.to_json_dict()
self.assertNotEqual(mary, mary_none_john)
# Testing List nested objects
mary.list = [alice]
self.assertNotEqual(mary, mary_clone)
mary_clone.list = [alice_clone]
self.assertEqual(mary, mary_clone)
def test_compare_to_null(self):
"""Assert entity comparison to None."""
alice = SampleEntity(self.cfg, id=1, name='Alice', unique='a')
self.assertFalse(alice.compare(None))
def test_compare(self):
"""Assert compare take only not unique fields into account."""
alice = SampleEntity(self.cfg, id=1, name='Alice', unique='a')
alice_2 = SampleEntity(self.cfg, id=2, name='Alice', unique='b')
self.assertTrue(
alice.compare(alice_2),
'Both "id" and "unique" are unique fields, thus must be ignored compare by default',
)
self.assertFalse(
alice.compare(SampleEntity(self.cfg, id=1, name='Not Alice', unique='a')),
'Name is not unique, so it compare should return False',
)
def test_compare_with_filter(self):
"""Assert compare can filter fields based on callable."""
alice = SampleEntity(self.cfg, id=1, name='Alice', unique='a')
alice_2 = SampleEntity(self.cfg, id=2, name='Alice', unique='a')
def filter_example(fields_name, _):
"""Filter function to avoid comparison only on id."""
return fields_name != 'id'
self.assertTrue(
alice.compare(alice_2, filter_example),
'Only id is ignored, so it should return True because other properties are equal',
)
self.assertFalse(
alice.compare(
SampleEntity(self.cfg, id=1, name='Not Alice', unique='a'), filter_example
),
'Only id is ignored, so it should return False because "name" is different',
)
self.assertFalse(
alice.compare(SampleEntity(self.cfg, id=1, name='Alice', unique='b'), filter_example),
'Only id is ignored, so it should return False because "unique" is different',
)
def test_repr_v1(self):
"""Test method ``nailgun.entity_mixins.Entity.__repr__``.
Assert that ``__repr__`` works correctly when no arguments are passed
to an entity.
"""
entity = SampleEntityTwo(self.cfg)
target = 'tests.test_entity_mixins.SampleEntityTwo()'
self.assertEqual(repr(entity), target)
# create default config if it does not exist
try:
config.ServerConfig.get()
except (KeyError, config.ConfigFileError):
self.cfg.save()
import nailgun # noqa: PLC0415
import tests # noqa: PLC0415
self.assertEqual(repr(eval(repr(entity))), target)
def test_repr_v2(self):
"""Test method ``nailgun.entity_mixins.Entity.__repr__``.
Assert that ``__repr__`` works correctly when an ID is passed to an
entity.
"""
entity = SampleEntityTwo(self.cfg, id=gen_integer())
target = f'tests.test_entity_mixins.SampleEntityTwo(id={entity.id})'
self.assertEqual(repr(entity), target)
# create default config if it does not exist
try:
config.ServerConfig.get()
except (KeyError, config.ConfigFileError):
self.cfg.save()
import nailgun # noqa: PLC0415
import tests # noqa: PLC0415
self.assertEqual(repr(eval(repr(entity))), target)
def test_repr_v3(self):
"""Test method ``nailgun.entity_mixins.Entity.__repr__``.
Assert that ``__repr__`` works correctly when one entity has a foreign
key relationship to a second entity.
"""
entity_id = gen_integer()
target = (
'tests.test_entity_mixins.SampleEntityTwo('
f'one_to_many=[tests.test_entity_mixins.SampleEntity(id={entity_id})])'
)
entity = SampleEntityTwo(self.cfg, one_to_many=[SampleEntity(self.cfg, id=entity_id)])
self.assertEqual(repr(entity), target)
# create default config if it does not exist
try:
config.ServerConfig.get()
except (KeyError, config.ConfigFileError):
self.cfg.save()
import nailgun # noqa: PLC0415
import tests # noqa: PLC0415
self.assertEqual(repr(eval(repr(entity))), target)
class EntityCreateMixinTestCase(TestCase):
"""Tests for :class:`nailgun.entity_mixins.EntityCreateMixin`."""
def setUp(self):
"""Set ``self.entity = EntityWithCreate(…)``."""
self.entity = EntityWithCreate(
config.ServerConfig('example.com'),
id=gen_integer(min_value=1),
)
def test_create_missing(self):
"""Call method ``create_missing``."""
class FKEntityWithCreate(entity_mixins.Entity, entity_mixins.EntityCreateMixin):
"""An entity that can be created and has foreign key fields."""
def __init__(self, server_config=None, **kwargs):
self._fields = {
'int': IntegerField(required=True),
'int_choices': IntegerField(choices=(1, 2), required=True),
'int_default': IntegerField(default=5, required=True),
'many': OneToManyField(SampleEntity, required=True),
'one': OneToOneField(SampleEntity, required=True),
}
super().__init__(server_config=server_config, **kwargs)
cfg = config.ServerConfig('example.com')
entity = FKEntityWithCreate(cfg)
with mock.patch.object(entity._fields['many'], 'gen_value') as gen1:
with mock.patch.object(entity._fields['one'], 'gen_value') as gen2:
self.assertEqual(entity.create_missing(), None)
for gen_value in gen1, gen2:
self.assertEqual(
gen_value.mock_calls,
[
mock.call(), # gen_value() returns a class. The returned
mock.call()(cfg), # class is instantiated, and
mock.call()().create(True), # create(True) is called.
],
)
self.assertEqual(
set(entity.get_fields().keys()) - {'id'},
set(entity.get_values().keys()),
)
self.assertIn(entity.int_choices, (1, 2))
self.assertEqual(entity.int_default, 5)
def test_create_raw_v1(self):
"""Check what happens if the ``create_missing`` arg is not specified.
:meth:`nailgun.entity_mixins.EntityCreateMixin.create_raw` should
default to :data:`nailgun.entity_mixins.CREATE_MISSING`. We do not set
``CREATE_MISSING`` in this test. It is a process-wide variable, and
setting it may prevent tests from being run in parallel.
"""
with mock.patch.object(self.entity, 'create_missing') as c_missing:
with mock.patch.object(self.entity, 'create_payload') as c_payload:
with mock.patch.object(client, 'post') as post:
self.entity.create_raw()
self.assertEqual(c_missing.call_count, 1 if entity_mixins.CREATE_MISSING else 0)
self.assertEqual(c_payload.call_count, 1)
self.assertEqual(post.call_count, 1)
def test_create_raw_v2(self):
"""Check what happens if the ``create_missing`` arg is ``True``."""
with mock.patch.object(self.entity, 'create_missing') as c_missing:
with mock.patch.object(self.entity, 'create_payload') as c_payload:
with mock.patch.object(client, 'post') as post:
self.entity.create_raw(True)
self.assertEqual(c_missing.call_count, 1)
self.assertEqual(c_payload.call_count, 1)
self.assertEqual(post.call_count, 1)
def test_create_raw_v3(self):
"""Check what happens if the ``create_missing`` arg is ``False``."""
with mock.patch.object(self.entity, 'create_missing') as c_missing:
with mock.patch.object(self.entity, 'create_payload') as c_payload:
with mock.patch.object(client, 'post') as post:
self.entity.create_raw(False)
self.assertEqual(c_missing.call_count, 0)
self.assertEqual(c_payload.call_count, 1)
self.assertEqual(post.call_count, 1)
def test_create_json(self):
"""Test :meth:`nailgun.entity_mixins.EntityCreateMixin.create_json`."""
for create_missing in (None, True, False):
response = mock.Mock()
response.json.return_value = gen_integer()
with mock.patch.object(self.entity, 'create_raw') as create_raw:
create_raw.return_value = response
self.entity.create_json(create_missing)
self.assertEqual(create_raw.call_count, 1)
self.assertEqual(create_raw.call_args[0][0], create_missing)
self.assertEqual(response.raise_for_status.call_count, 1)
self.assertEqual(response.json.call_count, 1)
def test_create_json_with_exception(self):
"""Check what happens if the server returns an error HTTP status code for :meth:`nailgun.entity_mixins.EntityCreateMixin.create_json`."""
for valid_json in (True, False):
response = mock.Mock()
return_value = {"a": "b"}
response.raise_for_status.side_effect = HTTPError("foo")
if valid_json:
response.json.return_value = return_value
else:
response.json.side_effect = JSONDecodeError("msg", "foo", 2)
with (
mock.patch.object(self.entity, 'create_raw', return_value=response),
self.assertRaises(HTTPError) as error,
):
self.entity.create_json()
self.assertEqual(response.raise_for_status.call_count, 1)
self.assertEqual(response.json.call_count, 1)
if valid_json:
self.assertEqual(error.exception.args[1], return_value)
else:
self.assertEqual(len(error.exception.args), 1)
def test_create(self):
"""Test :meth:`nailgun.entity_mixins.EntityCreateMixin.create`."""
class EntityWithCreateRead(EntityWithCreate, entity_mixins.EntityReadMixin):
"""An entity that can be created and read."""
readable = EntityWithCreateRead(
config.ServerConfig('example.com'),
id=gen_integer(),
)
for create_missing in (None, True, False):
with mock.patch.object(readable, 'create_json') as create_json:
create_json.return_value = gen_integer()
with mock.patch.object(readable, 'read') as read:
readable.create(create_missing)
self.assertEqual(create_json.call_count, 1)
self.assertEqual(create_json.call_args[0][0], create_missing)
self.assertEqual(read.call_count, 1)
self.assertEqual(
read.call_args[1]['attrs'],
create_json.return_value,
)
class EntityReadMixinTestCase(TestCase):
"""Tests for :class:`nailgun.entity_mixins.EntityReadMixin`."""
@classmethod
def setUpClass(cls):
"""Set ``cls.test_entity``.
``test_entity`` is a class having one to one and one to many fields.
"""
class TestEntity(entity_mixins.Entity, entity_mixins.EntityReadMixin):
"""An entity with several different types of fields."""
def __init__(self, server_config=None, **kwargs):
self._fields = {
'ignore_me': IntegerField(),
'many': OneToManyField(SampleEntity),
'none': OneToOneField(SampleEntity),
'one': OneToOneField(SampleEntity),
}
self._meta = {'api_path': ''}
super().__init__(server_config=server_config, **kwargs)
cls.test_entity = TestEntity
def setUp(self):
"""Set ``self.entity = EntityWithRead(…)``."""
self.cfg = config.ServerConfig('example.com')
self.entity = EntityWithRead(self.cfg, id=gen_integer(min_value=1))
def test_read_raw(self):
"""Call :meth:`nailgun.entity_mixins.EntityReadMixin.read_raw`."""
with mock.patch.object(client, 'get') as get:
self.entity.read_raw()
self.assertEqual(get.call_count, 1)
self.assertEqual(len(get.call_args[0]), 1) # path='…'
self.assertEqual(get.call_args[0][0], self.entity.path())
self.assertEqual(
get.call_args[1], dict(params=None, **self.entity._server_config.get_client_kwargs())
)
def test_read_json(self):
"""Call :meth:`nailgun.entity_mixins.EntityReadMixin.read_json`."""
response = mock.Mock()
response.json.return_value = gen_integer()
with mock.patch.object(self.entity, 'read_raw') as read_raw:
read_raw.return_value = response
self.entity.read_json()
self.assertEqual(read_raw.call_count, 1)
self.assertEqual(response.raise_for_status.call_count, 1)
self.assertEqual(response.json.call_count, 1)
def test_read_v1(self):
"""Make ``read_json`` return hashes."""
# Generate some bogus values and call `read`.
entity_1 = self.test_entity(self.cfg)
attrs = {
'id': gen_integer(min_value=1),
'manies': [{'id': gen_integer(min_value=1)}],
'none': None,
'one': {'id': gen_integer(min_value=1)},
}
with mock.patch.object(entity_1, 'read_json') as read_json:
read_json.return_value = attrs
entity_2 = entity_1.read(ignore={'ignore_me'})
# Make assertions about the call and the returned entity.
self.assertEqual(
entity_2._server_config,
self.cfg,
)
self.assertEqual(read_json.call_count, 1)
self.assertEqual(
set(entity_1.get_fields().keys()),
set(entity_2.get_fields().keys()),
)
self.assertEqual(entity_2.id, attrs['id'])
self.assertEqual(entity_2.many[0].id, attrs['manies'][0]['id'])
self.assertEqual(entity_2.one.id, attrs['one']['id'])
def test_read_v2(self):
"""Make ``read_json`` return hashes, but with different field names."""
# Generate some bogus values and call `read`.
entity_1 = self.test_entity(self.cfg)
attrs = {'many': [{'id': gen_integer(min_value=1)}]}
with mock.patch.object(entity_1, 'read_json') as read_json:
read_json.return_value = attrs
entity_2 = entity_1.read(ignore={'id', 'none', 'one', 'ignore_me'})
# Make assertions about the call and the returned entity.
self.assertEqual(
entity_2._server_config,
self.cfg,
)
self.assertEqual(read_json.call_count, 1)
self.assertEqual(
set(entity_1.get_fields().keys()),
set(entity_2.get_fields().keys()),
)
self.assertEqual(entity_2.many[0].id, attrs['many'][0]['id'])
def test_read_v3(self):
"""Make ``read_json`` return IDs."""
# Generate some bogus values and call `read`.
entity_1 = self.test_entity(self.cfg)
attrs = {
'id': gen_integer(min_value=1),
'many_ids': [gen_integer(min_value=1)],
'none': None,
'one_id': gen_integer(min_value=1),
}
with mock.patch.object(entity_1, 'read_json') as read_json:
read_json.return_value = attrs
entity_2 = entity_1.read(ignore={'ignore_me'})
# Make assertions about the call and the returned entity.
self.assertEqual(
entity_2._server_config,
self.cfg,
)
self.assertEqual(read_json.call_count, 1)
self.assertEqual(
set(entity_1.get_fields().keys()),
set(entity_2.get_fields().keys()),
)
self.assertEqual(entity_2.id, attrs['id'])
self.assertEqual(entity_2.many[0].id, attrs['many_ids'][0])
self.assertEqual(entity_2.one.id, attrs['one_id'])
def test_read_v4(self):
"""Do not ignore any fields."""
with mock.patch.object(
entity_mixins.EntityReadMixin,
'read_json',
return_value={'id': gen_integer()},
) as read_json:
entity = EntityWithRead(self.cfg).read()
self.assertEqual(entity.get_values(), read_json.return_value)
def test_missing_value_error(self):
"""Raise a :class:`nailgun.entity_mixins.MissingValueError`."""
entity = self.test_entity(config.ServerConfig('example.com'))
for attrs in (
{
'id': gen_integer(min_value=1),
'none': None,
'one_id': gen_integer(min_value=1),
},
{
'id': gen_integer(min_value=1),
'many_ids': [gen_integer(min_value=1)],
'none': None,
},
):
with self.subTest(attrs):
with mock.patch.object(entity, 'read_json') as read_json:
read_json.return_value = attrs
with self.assertRaises(entity_mixins.MissingValueError):
entity.read(ignore={'ignore_me'})
class EntityUpdateMixinTestCase(TestCase):
"""Tests for :class:`nailgun.entity_mixins.EntityUpdateMixin`."""
def setUp(self):
"""Set ``self.entity = EntityWithUpdate(…)``."""
self.entity = EntityWithUpdate(
config.ServerConfig('example.com'),
id=gen_integer(min_value=1),
)
def test_update_payload_v1(self):
"""Call :meth:`nailgun.entity_mixins.EntityUpdateMixin.update_payload`.
Assert that the method behaves correctly given various values for the
``field`` argument.
"""
class TestEntity(EntityWithUpdate):
"""Just like its parent class, but with fields."""
def __init__(self, server_config=None, **kwargs):
self._fields = {'one': IntegerField(), 'two': IntegerField()}
super().__init__(server_config=server_config, **kwargs)
cfg = config.ServerConfig('url')
args_list = (
{},
{'one': gen_integer()},
{'two': gen_integer()},
{'one': gen_integer(), 'two': gen_integer()},
)
# Make `update_payload` return all or no values.
for args in args_list:
entity = TestEntity(cfg, **args)
self.assertEqual(entity.update_payload(), args)
self.assertEqual(entity.update_payload(list(args.keys())), args)
self.assertEqual(entity.update_payload([]), {})
# Make `update_payload` return only some values.
entity = TestEntity(cfg, **args_list[-1])
self.assertEqual(
entity.update_payload(['one']),
{'one': args_list[-1]['one']},
)
self.assertEqual(
entity.update_payload(['two']),
{'two': args_list[-1]['two']},
)
# Ask `update_payload` to return unavailable values.
entity = TestEntity(cfg)
for field_names in (['one'], ['two'], ['one', 'two']):
with self.assertRaises(KeyError):
entity.update_payload(field_names)
def test_update_payload_v2(self):
"""Call :meth:`nailgun.entity_mixins.EntityUpdateMixin.update_payload`.
Assign ``None`` to a ``OneToOneField`` and call ``update_payload``.
"""
class TestEntity(EntityWithUpdate):
"""Just like its parent class, but with fields."""
def __init__(self, server_config=None, **kwargs):
self._fields = {'other': OneToOneField(SampleEntity)}
super().__init__(server_config=server_config, **kwargs)
cfg = config.ServerConfig('url')
entities = [TestEntity(cfg, other=None), TestEntity(cfg)]
entities[1].other = None
for entity in entities:
with self.subTest(entity):
self.assertEqual(entity.update_payload(), {'other_id': None})
def test_update_raw(self):
"""Call :meth:`nailgun.entity_mixins.EntityUpdateMixin.update_raw`."""
with mock.patch.object(self.entity, 'update_payload') as u_payload:
with mock.patch.object(client, 'put') as put:
self.entity.update_raw()
self.assertEqual(u_payload.call_count, 1)
self.assertEqual(put.call_count, 1)
self.assertEqual(len(put.call_args[0]), 2) # path='…' and data={…}
self.assertEqual(put.call_args[0][0], self.entity.path())
self.assertEqual(
put.call_args[1],
self.entity._server_config.get_client_kwargs(),
)
def test_update_json(self):
"""Call :meth:`nailgun.entity_mixins.EntityUpdateMixin.update_json`."""
response = mock.Mock()
response.json.return_value = gen_integer()
with mock.patch.object(self.entity, 'update_raw') as update_raw:
update_raw.return_value = response
self.entity.update_json()
self.assertEqual(update_raw.call_count, 1)
self.assertEqual(response.raise_for_status.call_count, 1)
self.assertEqual(response.json.call_count, 1)
def test_update(self):
"""Test :meth:`nailgun.entity_mixins.EntityUpdateMixin.update`."""
class EntityWithUpdateRead(EntityWithUpdate, entity_mixins.EntityReadMixin):
"""An entity that can be updated and read."""
readable = EntityWithUpdateRead(
config.ServerConfig('example.com'),
id=gen_integer(),
)
with mock.patch.object(readable, 'update_json') as update_json:
update_json.return_value = gen_integer()
with mock.patch.object(readable, 'read') as read:
readable.update()
self.assertEqual(update_json.call_count, 1)
self.assertEqual(read.call_count, 1)
self.assertEqual(
read.call_args[1]['attrs'],
update_json.return_value,
)
class EntityDeleteMixinTestCase(TestCase):
"""Tests for :class:`nailgun.entity_mixins.EntityDeleteMixin`."""
def setUp(self):
"""Set ``self.entity = EntityWithDelete(…)``."""
self.entity = EntityWithDelete(
config.ServerConfig('example.com'),
id=gen_integer(min_value=1),
)
def test_delete_raw(self):
"""Call :meth:`nailgun.entity_mixins.EntityDeleteMixin.delete_raw`."""
with mock.patch.object(client, 'delete') as delete:
self.entity.delete_raw()
self.assertEqual(delete.call_count, 1)
self.assertEqual(len(delete.call_args[0]), 1)
self.assertEqual(delete.call_args[0][0], self.entity.path())
self.assertEqual(
delete.call_args[1],
self.entity._server_config.get_client_kwargs(),
)
def test_delete_v1(self):
"""Check what happens if the server returns an error HTTP status code."""
response = mock.Mock()
response.raise_for_status.side_effect = HTTPError('oh no!')
with (
mock.patch.object(
entity_mixins.EntityDeleteMixin,
'delete_raw',
return_value=response,
),
self.assertRaises(HTTPError),
):
self.entity.delete()
def test_delete_v2(self):
"""Check what happens if the server returns an HTTP ACCEPTED status code."""
response = mock.Mock()
response.status_code = http_client.ACCEPTED
response.json.return_value = {'id': gen_integer()}
with (
mock.patch.object(