forked from RedHatInsights/insights-host-inventory
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_api.py
executable file
·1866 lines (1343 loc) · 69.2 KB
/
test_api.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
#!/usr/bin/env python
import copy
import json
import tempfile
import unittest.mock
import uuid
from base64 import b64encode
from datetime import datetime
from datetime import timezone
from itertools import chain
from json import dumps
from urllib.parse import parse_qs
from urllib.parse import urlencode
from urllib.parse import urlsplit
from urllib.parse import urlunsplit
import dateutil.parser
from app import create_app
from app import db
from app.auth.identity import Identity
from app.utils import HostWrapper
from tasks import msg_handler
from test_utils import rename_host_table_and_indexes
from test_utils import set_environment
HOST_URL = "/api/inventory/v1/hosts"
HEALTH_URL = "/health"
METRICS_URL = "/metrics"
VERSION_URL = "/version"
NS = "testns"
ID = "whoabuddy"
FACTS = [{"namespace": "ns1", "facts": {"key1": "value1"}}]
TAGS = ["aws/new_tag_1:new_value_1", "aws/k:v"]
ACCOUNT = "000501"
SHARED_SECRET = "SuperSecretStuff"
def generate_uuid():
return str(uuid.uuid4())
def test_data(display_name="hi", facts=None):
return {
"account": ACCOUNT,
"display_name": display_name,
# "insights_id": "1234-56-789",
# "rhel_machine_id": "1234-56-789",
# "ip_addresses": ["10.10.0.1", "10.0.0.2"],
"ip_addresses": ["10.10.0.1"],
# "mac_addresses": ["c2:00:d0:c8:61:01"],
# "external_id": "i-05d2313e6b9a42b16"
"facts": facts if facts else FACTS,
}
def build_auth_header(token):
auth_header = {"Authorization": f"Bearer {token}"}
return auth_header
def build_valid_auth_header():
return build_auth_header(SHARED_SECRET)
def inject_qs(url, **kwargs):
scheme, netloc, path, query, fragment = urlsplit(url)
params = parse_qs(query)
params.update(kwargs)
new_query = urlencode(params, doseq=True)
return urlunsplit((scheme, netloc, path, new_query, fragment))
class APIBaseTestCase(unittest.TestCase):
def _get_valid_auth_header(self):
identity = Identity(account_number=ACCOUNT)
dict_ = {"identity": identity._asdict()}
json_doc = json.dumps(dict_)
auth_header = {"x-rh-identity": b64encode(json_doc.encode())}
return auth_header
def setUp(self):
"""
Creates the application and a test client to make requests.
"""
self.app = create_app(config_name="testing")
self.client = self.app.test_client
def get(self, path, status=200, return_response_as_json=True):
return self._response_check(
self.client().get(path, headers=self._get_valid_auth_header()), status, return_response_as_json
)
def post(self, path, data, status=200, return_response_as_json=True):
return self._make_http_call(self.client().post, path, data, status, return_response_as_json)
def patch(self, path, data, status=200, return_response_as_json=True):
return self._make_http_call(self.client().patch, path, data, status, return_response_as_json)
def put(self, path, data, status=200, return_response_as_json=True):
return self._make_http_call(self.client().put, path, data, status, return_response_as_json)
def delete(self, path, status=200, return_response_as_json=True):
return self._response_check(
self.client().delete(path, headers=self._get_valid_auth_header()), status, return_response_as_json
)
def verify_error_response(
self, response, expected_title=None, expected_status=None, expected_detail=None, expected_type=None
):
def _verify_value(field_name, expected_value):
assert field_name in response
if expected_value is not None:
self.assertEqual(response[field_name], expected_value)
_verify_value("title", expected_title)
_verify_value("status", expected_status)
_verify_value("detail", expected_detail)
_verify_value("type", expected_type)
def _make_http_call(self, http_method, path, data, status, return_response_as_json=True):
json_data = json.dumps(data)
headers = self._get_valid_auth_header()
headers["content-type"] = "application/json"
return self._response_check(
http_method(path, data=json_data, headers=headers), status, return_response_as_json
)
def _response_check(self, response, status, return_response_as_json):
self.assertEqual(response.status_code, status)
if return_response_as_json:
return json.loads(response.data)
else:
return response
class DBAPITestCase(APIBaseTestCase):
@classmethod
def setUpClass(cls):
"""
Temporarily rename the host table while the tests run. This is done
to make dropping the table at the end of the tests a bit safer.
"""
rename_host_table_and_indexes()
def setUp(self):
"""
Initializes the database by creating all tables.
"""
super().setUp()
# binds the app to the current context
with self.app.app_context():
# create all tables
db.create_all()
def tearDown(self):
"""
Cleans up the database by dropping all tables.
"""
with self.app.app_context():
# drop all tables
db.session.remove()
db.drop_all()
def _build_host_id_list_for_url(self, host_list):
host_id_list = [str(h.id) for h in host_list]
return ",".join(host_id_list)
def _verify_host_status(self, response, host_index, expected_status):
self.assertEqual(response["data"][host_index]["status"], expected_status)
def _pluck_host_from_response(self, response, host_index):
return response["data"][host_index]["host"]
def _validate_host(self, received_host, expected_host, expected_id=id):
self.assertIsNotNone(received_host["id"])
self.assertEqual(received_host["id"], expected_id)
self.assertEqual(received_host["account"], expected_host.account)
self.assertEqual(received_host["insights_id"], expected_host.insights_id)
self.assertEqual(received_host["rhel_machine_id"], expected_host.rhel_machine_id)
self.assertEqual(received_host["subscription_manager_id"], expected_host.subscription_manager_id)
self.assertEqual(received_host["satellite_id"], expected_host.satellite_id)
self.assertEqual(received_host["bios_uuid"], expected_host.bios_uuid)
self.assertEqual(received_host["fqdn"], expected_host.fqdn)
self.assertEqual(received_host["mac_addresses"], expected_host.mac_addresses)
self.assertEqual(received_host["ip_addresses"], expected_host.ip_addresses)
self.assertEqual(received_host["display_name"], expected_host.display_name)
self.assertEqual(received_host["facts"], expected_host.facts)
self.assertEqual(received_host["ansible_host"], expected_host.ansible_host)
self.assertIsNotNone(received_host["created"])
self.assertIsNotNone(received_host["updated"])
class CreateHostsTestCase(DBAPITestCase):
def test_create_and_update(self):
facts = None
host_data = HostWrapper(test_data(facts=facts))
# Create the host
response = self.post(HOST_URL, [host_data.data()], 207)
self._verify_host_status(response, 0, 201)
created_host = self._pluck_host_from_response(response, 0)
original_id = created_host["id"]
self._validate_host(created_host, host_data, expected_id=original_id)
created_time = dateutil.parser.parse(created_host["created"])
self.assertGreater(datetime.now(timezone.utc), created_time)
host_data.facts = copy.deepcopy(FACTS)
# Replace facts under the first namespace
host_data.facts[0]["facts"] = {"newkey1": "newvalue1"}
# Add a new set of facts under a new namespace
host_data.facts.append({"namespace": "ns2", "facts": {"key2": "value2"}})
# Add a new canonical fact
host_data.rhel_machine_id = generate_uuid()
host_data.ip_addresses = ["10.10.0.1", "10.0.0.2", "fe80::d46b:2807:f258:c319"]
host_data.mac_addresses = ["c2:00:d0:c8:61:01"]
host_data.external_id = "i-05d2313e6b9a42b16"
host_data.insights_id = generate_uuid()
# Update the host with the new data
response = self.post(HOST_URL, [host_data.data()], 207)
self._verify_host_status(response, 0, 200)
updated_host = self._pluck_host_from_response(response, 0)
# Make sure the id from the update post matches the id from the create
self.assertEqual(updated_host["id"], original_id)
# Verify the timestamp has been modified
self.assertIsNotNone(updated_host["updated"])
modified_time = dateutil.parser.parse(updated_host["updated"])
self.assertGreater(modified_time, created_time)
host_lookup_results = self.get(f"{HOST_URL}/{original_id}", 200)
# sanity check
# host_lookup_results["results"][0]["facts"][0]["facts"]["key2"] = "blah"
# host_lookup_results["results"][0]["insights_id"] = "1.2.3.4"
self._validate_host(host_lookup_results["results"][0], host_data, expected_id=original_id)
def test_create_host_update_with_same_insights_id_and_different_canonical_facts(self):
original_insights_id = generate_uuid()
host_data = HostWrapper(test_data(facts=None))
host_data.insights_id = original_insights_id
host_data.rhel_machine_id = generate_uuid()
host_data.subscription_manager_id = generate_uuid()
host_data.satellite_id = generate_uuid()
host_data.bios_uuid = generate_uuid()
host_data.fqdn = "original_fqdn"
host_data.mac_addresses = ["aa:bb:cc:dd:ee:ff"]
host_data.external_id = "abcdef"
# Create the host
response = self.post(HOST_URL, [host_data.data()], 207)
self._verify_host_status(response, 0, 201)
created_host = self._pluck_host_from_response(response, 0)
original_id = created_host["id"]
self._validate_host(created_host, host_data, expected_id=original_id)
# Change the canonical facts except for the insights_id
host_data.rhel_machine_id = generate_uuid()
host_data.ip_addresses = ["192.168.1.44", "10.0.0.2"]
host_data.subscription_manager_id = generate_uuid()
host_data.satellite_id = generate_uuid()
host_data.bios_uuid = generate_uuid()
host_data.fqdn = "expected_fqdn"
host_data.mac_addresses = ["ff:ee:dd:cc:bb:aa"]
host_data.external_id = "fedcba"
host_data.facts = [{"namespace": "ns1", "facts": {"newkey": "newvalue"}}]
# Update the host
response = self.post(HOST_URL, [host_data.data()], 207)
self._verify_host_status(response, 0, 200)
updated_host = self._pluck_host_from_response(response, 0)
# Verify that the id did not change on the update
self.assertEqual(updated_host["id"], original_id)
# Retrieve the host using the id that we first received
data = self.get(f"{HOST_URL}/{original_id}", 200)
self._validate_host(data["results"][0], host_data, expected_id=original_id)
def test_create_host_with_empty_facts_display_name_then_update(self):
# Create a host with empty facts, and display_name
# then update those fields
host_data = HostWrapper(test_data(facts=None))
del host_data.display_name
del host_data.facts
# Create the host
response = self.post(HOST_URL, [host_data.data()], 207)
self._verify_host_status(response, 0, 201)
created_host = self._pluck_host_from_response(response, 0)
self.assertIsNotNone(created_host["id"])
original_id = created_host["id"]
# Update the facts and display name
host_data.facts = copy.deepcopy(FACTS)
host_data.display_name = "expected_display_name"
# Update the hosts
self.post(HOST_URL, [host_data.data()], 207)
host_lookup_results = self.get(f"{HOST_URL}/{original_id}", 200)
self._validate_host(host_lookup_results["results"][0], host_data, expected_id=original_id)
def test_create_and_update_multiple_hosts_with_account_mismatch(self):
"""
Attempt to create multiple hosts, one host has the wrong account number.
Verify this causes an error response to be returned.
"""
facts = None
host1 = HostWrapper(test_data(display_name="host1", facts=facts))
host1.ip_addresses = ["10.0.0.1"]
host1.rhel_machine_id = generate_uuid()
host2 = HostWrapper(test_data(display_name="host2", facts=facts))
# Set the account number to the wrong account for this request
host2.account = "222222"
host2.ip_addresses = ["10.0.0.2"]
host2.rhel_machine_id = generate_uuid()
host_list = [host1.data(), host2.data()]
# Create the host
created_host = self.post(HOST_URL, host_list, 207)
self.assertEqual(len(host_list), len(created_host["data"]))
self.assertEqual(created_host["errors"], 1)
self.assertEqual(created_host["data"][0]["status"], 201)
self.assertEqual(created_host["data"][1]["status"], 400)
def test_create_host_without_canonical_facts(self):
host_data = HostWrapper(test_data(facts=None))
del host_data.insights_id
del host_data.rhel_machine_id
del host_data.subscription_manager_id
del host_data.satellite_id
del host_data.bios_uuid
del host_data.ip_addresses
del host_data.fqdn
del host_data.mac_addresses
del host_data.external_id
response_data = self.post(HOST_URL, [host_data.data()], 207)
self._verify_host_status(response_data, 0, 400)
response_data = response_data["data"][0]
self.verify_error_response(response_data, expected_title="Invalid request", expected_status=400)
def test_create_host_without_account(self):
host_data = HostWrapper(test_data(facts=None))
del host_data.account
response_data = self.post(HOST_URL, [host_data.data()], 400)
self.verify_error_response(response_data, expected_title="Bad Request")
def test_create_host_with_mismatched_account_numbers(self):
host_data = HostWrapper(test_data(facts=None))
host_data.account = ACCOUNT[::-1]
response_data = self.post(HOST_URL, [host_data.data()], 207)
self._verify_host_status(response_data, 0, 400)
response_data = response_data["data"][0]
self.verify_error_response(response_data, expected_title="Invalid request")
def test_create_host_with_invalid_facts(self):
facts_with_no_namespace = copy.deepcopy(FACTS)
del facts_with_no_namespace[0]["namespace"]
facts_with_no_facts = copy.deepcopy(FACTS)
del facts_with_no_facts[0]["facts"]
facts_with_empty_str_namespace = copy.deepcopy(FACTS)
facts_with_empty_str_namespace[0]["namespace"] = ""
invalid_facts = [facts_with_no_namespace, facts_with_no_facts, facts_with_empty_str_namespace]
for invalid_fact in invalid_facts:
with self.subTest(invalid_fact=invalid_fact):
host_data = HostWrapper(test_data(facts=invalid_fact))
response_data = self.post(HOST_URL, [host_data.data()], 400)
self.verify_error_response(response_data, expected_title="Bad Request")
def test_create_host_with_invalid_uuid_field_values(self):
uuid_field_names = ("insights_id", "rhel_machine_id", "subscription_manager_id", "satellite_id", "bios_uuid")
for field_name in uuid_field_names:
with self.subTest(uuid_field=field_name):
host_data = copy.deepcopy(test_data(facts=None))
host_data[field_name] = "notauuid"
response_data = self.post(HOST_URL, [host_data], 207)
error_host = response_data["data"][0]
self.assertEqual(error_host["status"], 400)
self.verify_error_response(error_host, expected_title="Bad Request")
def test_create_host_with_non_nullable_fields_as_None(self):
non_nullable_field_names = (
"display_name",
"account",
"insights_id",
"rhel_machine_id",
"subscription_manager_id",
"satellite_id",
"fqdn",
"bios_uuid",
"ip_addresses",
"mac_addresses",
"external_id",
"ansible_host",
)
host_data = HostWrapper(test_data(facts=None))
# Have at least one good canonical fact set
host_data.insights_id = generate_uuid()
host_data.rhel_machine_id = generate_uuid()
host_dict = host_data.data()
for field_name in non_nullable_field_names:
with self.subTest(field_as_None=field_name):
invalid_host_dict = copy.deepcopy(host_dict)
invalid_host_dict[field_name] = None
response_data = self.post(HOST_URL, [invalid_host_dict], 400)
self.verify_error_response(response_data, expected_title="Bad Request")
def test_create_host_with_valid_ip_address(self):
valid_ip_arrays = [["blah"], ["1.1.1.1", "sigh"]]
for ip_array in valid_ip_arrays:
with self.subTest(ip_array=ip_array):
host_data = HostWrapper(test_data(facts=None))
host_data.insights_id = generate_uuid()
host_data.ip_addresses = ip_array
response_data = self.post(HOST_URL, [host_data.data()], 207)
error_host = response_data["data"][0]
self.assertEqual(error_host["status"], 201)
def test_create_host_with_invalid_ip_address(self):
invalid_ip_arrays = [[], [""], ["a" * 256]]
for ip_array in invalid_ip_arrays:
with self.subTest(ip_array=ip_array):
host_data = HostWrapper(test_data(facts=None))
host_data.insights_id = generate_uuid()
host_data.ip_addresses = ip_array
response_data = self.post(HOST_URL, [host_data.data()], 207)
error_host = response_data["data"][0]
self.assertEqual(error_host["status"], 400)
self.verify_error_response(error_host, expected_title="Bad Request")
def test_create_host_with_valid_mac_address(self):
valid_mac_arrays = [["blah"], ["11:22:33:44:55:66", "blah"]]
for mac_array in valid_mac_arrays:
with self.subTest(mac_array=mac_array):
host_data = HostWrapper(test_data(facts=None))
host_data.insights_id = generate_uuid()
host_data.mac_addresses = mac_array
response_data = self.post(HOST_URL, [host_data.data()], 207)
error_host = response_data["data"][0]
self.assertEqual(error_host["status"], 201)
def test_create_host_with_invalid_mac_address(self):
invalid_mac_arrays = [[], [""], ["11:22:33:44:55:66", "a" * 256]]
for mac_array in invalid_mac_arrays:
with self.subTest(mac_array=mac_array):
host_data = HostWrapper(test_data(facts=None))
host_data.insights_id = generate_uuid()
host_data.mac_addresses = mac_array
response_data = self.post(HOST_URL, [host_data.data()], 207)
error_host = response_data["data"][0]
self.assertEqual(error_host["status"], 400)
self.verify_error_response(error_host, expected_title="Bad Request")
def test_create_host_with_invalid_display_name(self):
host_data = HostWrapper(test_data(facts=None))
invalid_display_names = ["", "a" * 201]
for display_name in invalid_display_names:
with self.subTest(display_name=display_name):
host_data.display_name = display_name
response = self.post(HOST_URL, [host_data.data()], 207)
error_host = response["data"][0]
self.assertEqual(error_host["status"], 400)
self.verify_error_response(error_host, expected_title="Bad Request")
def test_create_host_with_invalid_fqdn(self):
host_data = HostWrapper(test_data(facts=None))
invalid_fqdns = ["", "a" * 256]
for fqdn in invalid_fqdns:
with self.subTest(fqdn=fqdn):
host_data.fqdn = fqdn
response = self.post(HOST_URL, [host_data.data()], 207)
error_host = response["data"][0]
self.assertEqual(error_host["status"], 400)
self.verify_error_response(error_host, expected_title="Bad Request")
def test_create_host_with_invalid_external_id(self):
host_data = HostWrapper(test_data(facts=None))
invalid_external_ids = ["", "a" * 501]
for external_id in invalid_external_ids:
with self.subTest(external_id=external_id):
host_data.external_id = external_id
response = self.post(HOST_URL, [host_data.data()], 207)
error_host = response["data"][0]
self.assertEqual(error_host["status"], 400)
self.verify_error_response(error_host, expected_title="Bad Request")
def test_create_host_with_ansible_host(self):
# Create a host with ansible_host field
host_data = HostWrapper(test_data(facts=None))
host_data.ansible_host = "ansible_host_" + generate_uuid()
# Create the host
response = self.post(HOST_URL, [host_data.data()], 207)
self._verify_host_status(response, 0, 201)
created_host = self._pluck_host_from_response(response, 0)
original_id = created_host["id"]
host_lookup_results = self.get(f"{HOST_URL}/{original_id}", 200)
self._validate_host(host_lookup_results["results"][0], host_data, expected_id=original_id)
def test_create_host_without_ansible_host_then_update(self):
# Create a host without ansible_host field
# then update those fields
host_data = HostWrapper(test_data(facts=None))
del host_data.ansible_host
# Create the host
response = self.post(HOST_URL, [host_data.data()], 207)
self._verify_host_status(response, 0, 201)
created_host = self._pluck_host_from_response(response, 0)
original_id = created_host["id"]
ansible_hosts = ["ima_ansible_host_" + generate_uuid(), ""]
# Update the ansible_host
for ansible_host in ansible_hosts:
with self.subTest(ansible_host=ansible_host):
host_data.ansible_host = ansible_host
# Update the hosts
self.post(HOST_URL, [host_data.data()], 207)
host_lookup_results = self.get(f"{HOST_URL}/{original_id}", 200)
self._validate_host(host_lookup_results["results"][0], host_data, expected_id=original_id)
def test_create_host_with_invalid_ansible_host(self):
host_data = HostWrapper(test_data(facts=None))
invalid_ansible_host = ["a" * 256]
for ansible_host in invalid_ansible_host:
with self.subTest(ansible_host=ansible_host):
host_data.ansible_host = ansible_host
response = self.post(HOST_URL, [host_data.data()], 207)
error_host = response["data"][0]
self.assertEqual(error_host["status"], 400)
self.verify_error_response(error_host, expected_title="Bad Request")
class ResolveDisplayNameOnCreationTestCase(DBAPITestCase):
def test_create_host_without_display_name_and_without_fqdn(self):
"""
This test should verify that the display_name is set to the id
when neither the display name or fqdn is set.
"""
host_data = HostWrapper(test_data(facts=None))
del host_data.display_name
del host_data.fqdn
# Create the host
response = self.post(HOST_URL, [host_data.data()], 207)
self._verify_host_status(response, 0, 201)
created_host = self._pluck_host_from_response(response, 0)
original_id = created_host["id"]
host_lookup_results = self.get(f"{HOST_URL}/{original_id}", 200)
# Explicitly set the display_name to the be id...this is expected here
host_data.display_name = created_host["id"]
self._validate_host(host_lookup_results["results"][0], host_data, expected_id=original_id)
def test_create_host_without_display_name_and_with_fqdn(self):
"""
This test should verify that the display_name is set to the
fqdn when a display_name is not passed in but the fqdn is passed in.
"""
expected_display_name = "fred.flintstone.bedrock.com"
host_data = HostWrapper(test_data(facts=None))
del host_data.display_name
host_data.fqdn = expected_display_name
# Create the host
response = self.post(HOST_URL, [host_data.data()], 207)
self._verify_host_status(response, 0, 201)
created_host = self._pluck_host_from_response(response, 0)
original_id = created_host["id"]
host_lookup_results = self.get(f"{HOST_URL}/{original_id}", 200)
# Explicitly set the display_name ...this is expected here
host_data.display_name = expected_display_name
self._validate_host(host_lookup_results["results"][0], host_data, expected_id=original_id)
class BulkCreateHostsTestCase(DBAPITestCase):
def _get_valid_auth_header(self):
return build_valid_auth_header()
def test_create_and_update_multiple_hosts_with_different_accounts(self):
with set_environment({"INVENTORY_SHARED_SECRET": SHARED_SECRET}):
facts = None
host1 = HostWrapper(test_data(display_name="host1", facts=facts))
host1.account = "111111"
host1.ip_addresses = ["10.0.0.1"]
host1.rhel_machine_id = generate_uuid()
host2 = HostWrapper(test_data(display_name="host2", facts=facts))
host2.account = "222222"
host2.ip_addresses = ["10.0.0.2"]
host2.rhel_machine_id = generate_uuid()
host_list = [host1.data(), host2.data()]
# Create the host
response = self.post(HOST_URL, host_list, 207)
self.assertEqual(len(host_list), len(response["data"]))
self.assertEqual(response["total"], len(response["data"]))
self.assertEqual(response["errors"], 0)
for host in response["data"]:
self.assertEqual(host["status"], 201)
host_list[0]["id"] = response["data"][0]["host"]["id"]
host_list[0]["bios_uuid"] = generate_uuid()
host_list[0]["display_name"] = "fred"
host_list[1]["id"] = response["data"][1]["host"]["id"]
host_list[1]["bios_uuid"] = generate_uuid()
host_list[1]["display_name"] = "barney"
# Update the host
updated_host = self.post(HOST_URL, host_list, 207)
self.assertEqual(updated_host["errors"], 0)
i = 0
for host in updated_host["data"]:
self.assertEqual(host["status"], 200)
expected_host = HostWrapper(host_list[i])
self._validate_host(host["host"], expected_host, expected_id=expected_host.id)
i += 1
class PaginationBaseTestCase(APIBaseTestCase):
def _base_paging_test(self, url, expected_number_of_hosts):
def _test_get_page(page, expected_count=1):
test_url = inject_qs(url, page=page, per_page="1")
response = self.get(test_url, 200)
self.assertEqual(len(response["results"]), expected_count)
self.assertEqual(response["count"], expected_count)
self.assertEqual(response["total"], expected_number_of_hosts)
if expected_number_of_hosts == 0:
_test_get_page(1, expected_count=0)
return
i = 0
# Iterate through the pages
for i in range(1, expected_number_of_hosts + 1):
with self.subTest(pagination_test=i):
_test_get_page(str(i))
# Go one page past the last page and look for an error
i = i + 1
with self.subTest(pagination_test=i):
test_url = inject_qs(url, page=str(i), per_page="1")
self.get(test_url, 404)
class CreateHostsWithSystemProfileTestCase(DBAPITestCase, PaginationBaseTestCase):
def _valid_system_profile(self):
return {
"number_of_cpus": 1,
"number_of_sockets": 2,
"cores_per_socket": 4,
"system_memory_bytes": 1024,
"infrastructure_type": "massive cpu",
"infrastructure_vendor": "dell",
"network_interfaces": [
{
"ipv4_addresses": ["10.10.10.1"],
"state": "UP",
"ipv6_addresses": ["2001:0db8:85a3:0000:0000:8a2e:0370:7334"],
"mtu": 1500,
"mac_address": "aa:bb:cc:dd:ee:ff",
"type": "loopback",
"name": "eth0",
}
],
"disk_devices": [
{
"device": "/dev/sdb1",
"label": "home drive",
"options": {"uid": "0", "ro": True},
"mount_point": "/home",
"type": "ext3",
}
],
"bios_vendor": "AMI",
"bios_version": "1.0.0uhoh",
"bios_release_date": "10/31/2013",
"cpu_flags": ["flag1", "flag2"],
"os_release": "Red Hat EL 7.0.1",
"os_kernel_version": "Linux 2.0.1",
"arch": "x86-64",
"last_boot_time": "12:25 Mar 19, 2019",
"kernel_modules": ["i915", "e1000e"],
"running_processes": ["vim", "gcc", "python"],
"subscription_status": "valid",
"subscription_auto_attach": "yes",
"katello_agent_running": False,
"satellite_managed": False,
"cloud_provider": "Maclean's Music",
"yum_repos": [{"name": "repo1", "gpgcheck": True, "enabled": True, "base_url": "http://rpms.redhat.com"}],
"installed_products": [
{"name": "eap", "id": "123", "status": "UP"},
{"name": "jbws", "id": "321", "status": "DOWN"},
],
"insights_client_version": "12.0.12",
"insights_egg_version": "120.0.1",
"installed_packages": ["rpm1", "rpm2"],
"installed_services": ["ndb", "krb5"],
"enabled_services": ["ndb", "krb5"],
}
def test_create_host_with_system_profile(self):
facts = None
host = test_data(display_name="host1", facts=facts)
host["ip_addresses"] = ["10.0.0.1"]
host["rhel_machine_id"] = generate_uuid()
host["system_profile"] = self._valid_system_profile()
# Create the host
response = self.post(HOST_URL, [host], 207)
self._verify_host_status(response, 0, 201)
created_host = self._pluck_host_from_response(response, 0)
original_id = created_host["id"]
# verify system_profile is not included
self.assertNotIn("system_profile", created_host)
host_lookup_results = self.get(f"{HOST_URL}/{original_id}/system_profile", 200)
actual_host = host_lookup_results["results"][0]
self.assertEqual(original_id, actual_host["id"])
self.assertEqual(actual_host["system_profile"], host["system_profile"])
def test_create_host_without_system_profile_then_update_with_system_profile(self):
facts = None
host = test_data(display_name="host1", facts=facts)
host["ip_addresses"] = ["10.0.0.1"]
host["rhel_machine_id"] = generate_uuid()
# Create the host without a system profile
response = self.post(HOST_URL, [host], 207)
self._verify_host_status(response, 0, 201)
created_host = self._pluck_host_from_response(response, 0)
original_id = created_host["id"]
# List of tuples (system profile change, expected system profile)
system_profiles = [({}, {})]
# Only set the enabled_services to start out with
enabled_services_only_system_profile = {"enabled_services": ["firewalld"]}
system_profiles.append((enabled_services_only_system_profile, enabled_services_only_system_profile))
# Set the entire system profile...overwriting the enabled_service
# set from before
full_system_profile = self._valid_system_profile()
system_profiles.append((full_system_profile, full_system_profile))
# Change the enabled_services
full_system_profile = {**full_system_profile, **enabled_services_only_system_profile}
system_profiles.append((enabled_services_only_system_profile, full_system_profile))
# Make sure an empty system profile doesn't overwrite the data
system_profiles.append(({}, full_system_profile))
for i, (system_profile, expected_system_profile) in enumerate(system_profiles):
with self.subTest(system_profile=i):
mq_message = {"id": original_id, "request_id": None, "system_profile": system_profile}
with self.app.app_context():
msg_handler(mq_message)
host_lookup_results = self.get(f"{HOST_URL}/{original_id}/system_profile", 200)
actual_host = host_lookup_results["results"][0]
self.assertEqual(original_id, actual_host["id"])
self.assertEqual(actual_host["system_profile"], expected_system_profile)
def test_create_host_with_null_system_profile(self):
facts = None
host = test_data(display_name="host1", facts=facts)
host["ip_addresses"] = ["10.0.0.1"]
host["rhel_machine_id"] = generate_uuid()
host["system_profile"] = None
# Create the host without a system profile
response = self.post(HOST_URL, [host], 400)
self.verify_error_response(response, expected_title="Bad Request", expected_status=400)
def test_create_host_with_system_profile_with_invalid_data(self):
facts = None
host = test_data(display_name="host1", facts=facts)
host["ip_addresses"] = ["10.0.0.1"]
host["rhel_machine_id"] = generate_uuid()
# List of tuples (system profile change, expected system profile)
system_profiles = [
{"infrastructure_type": "i" * 101, "infrastructure_vendor": "i" * 101, "cloud_provider": "i" * 101}
]
for system_profile in system_profiles:
with self.subTest(system_profile=system_profile):
host["system_profile"] = system_profile
# Create the host
response = self.post(HOST_URL, [host], 207)
self._verify_host_status(response, 0, 400)
self.assertEqual(response["errors"], 1)
def test_create_host_with_system_profile_with_different_yum_urls(self):
facts = None
host = test_data(display_name="host1", facts=facts)
yum_urls = [
"file:///cdrom/",
"http://foo.com http://foo.com",
"file:///etc/pki/rpm-gpg/RPM-GPG-KEY-fedora-$releasever-$basearch",
"https://codecs.fedoraproject.org/openh264/$releasever/$basearch/debug/",
]
for yum_url in yum_urls:
with self.subTest(yum_url=yum_url):
host["rhel_machine_id"] = generate_uuid()
host["system_profile"] = {
"yum_repos": [{"name": "repo1", "gpgcheck": True, "enabled": True, "base_url": yum_url}]
}
# Create the host
response = self.post(HOST_URL, [host], 207)
self._verify_host_status(response, 0, 201)
created_host = self._pluck_host_from_response(response, 0)
original_id = created_host["id"]
# Verify that the system profile data is saved
host_lookup_results = self.get(f"{HOST_URL}/{original_id}/system_profile", 200)
actual_host = host_lookup_results["results"][0]
self.assertEqual(original_id, actual_host["id"])
self.assertEqual(actual_host["system_profile"], host["system_profile"])
def test_create_host_with_system_profile_with_different_cloud_providers(self):
facts = None
host = test_data(display_name="host1", facts=facts)