-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathtest_nautobot_device_sync.py
More file actions
1140 lines (896 loc) · 39.6 KB
/
test_nautobot_device_sync.py
File metadata and controls
1140 lines (896 loc) · 39.6 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 nautobot_device_sync module."""
import uuid
from unittest.mock import MagicMock
from unittest.mock import patch
import pytest
import requests
from understack_workflows.oslo_event.nautobot_device_sync import EXIT_STATUS_FAILURE
from understack_workflows.oslo_event.nautobot_device_sync import EXIT_STATUS_SUCCESS
from understack_workflows.oslo_event.nautobot_device_sync import DeviceInfo
from understack_workflows.oslo_event.nautobot_device_sync import _create_nautobot_device
from understack_workflows.oslo_event.nautobot_device_sync import (
_extract_node_uuid_from_event,
)
from understack_workflows.oslo_event.nautobot_device_sync import _generate_device_name
from understack_workflows.oslo_event.nautobot_device_sync import _get_record_value
from understack_workflows.oslo_event.nautobot_device_sync import _is_retryable_error
from understack_workflows.oslo_event.nautobot_device_sync import _normalise_manufacturer
from understack_workflows.oslo_event.nautobot_device_sync import (
_populate_from_inventory,
)
from understack_workflows.oslo_event.nautobot_device_sync import _populate_from_node
from understack_workflows.oslo_event.nautobot_device_sync import (
_set_location_from_switches,
)
from understack_workflows.oslo_event.nautobot_device_sync import _update_nautobot_device
from understack_workflows.oslo_event.nautobot_device_sync import (
delete_device_from_nautobot,
)
from understack_workflows.oslo_event.nautobot_device_sync import (
handle_node_delete_event,
)
from understack_workflows.oslo_event.nautobot_device_sync import handle_node_event
from understack_workflows.oslo_event.nautobot_device_sync import sync_device_to_nautobot
class TestNormaliseManufacturer:
"""Test cases for _normalise_manufacturer function."""
def test_normalise_dell_uppercase(self):
assert _normalise_manufacturer("DELL INC.") == "Dell"
def test_normalise_dell_lowercase(self):
assert _normalise_manufacturer("dell") == "Dell"
def test_normalise_dell_mixed_case(self):
assert _normalise_manufacturer("Dell Inc.") == "Dell"
def test_normalise_hp(self):
assert _normalise_manufacturer("HP") == "HPE"
def test_unsupported_manufacturer_raises(self):
with pytest.raises(ValueError, match="not supported"):
_normalise_manufacturer("Lenovo")
class TestPopulateFromNode:
"""Test cases for _populate_from_node function."""
@pytest.fixture
def device_info(self):
return DeviceInfo(uuid="test-uuid")
@pytest.fixture
def mock_node(self):
node = MagicMock()
node.properties = {
"memory_mb": 65536,
"cpus": 32,
"cpu_arch": "x86_64",
"local_gb": 500,
}
node.traits = ["CUSTOM_TRAIT1", "CUSTOM_TRAIT2"]
node.provision_state = "active"
node.lessee = "12345678-1234-5678-9abc-123456789abc"
return node
def test_populate_all_fields(self, device_info, mock_node):
_populate_from_node(device_info, mock_node)
assert device_info.memory_mb == 65536
assert device_info.cpus == 32
assert device_info.cpu_arch == "x86_64"
assert device_info.local_gb == 500
assert device_info.traits == ["CUSTOM_TRAIT1", "CUSTOM_TRAIT2"]
assert device_info.status == "Active"
assert device_info.tenant_id == "12345678-1234-5678-9abc-123456789abc"
def test_populate_with_empty_properties(self, device_info):
node = MagicMock()
node.properties = {}
node.traits = None
node.provision_state = "enroll"
node.lessee = None
_populate_from_node(device_info, node)
assert device_info.manufacturer is None
assert device_info.memory_mb is None
assert device_info.cpus is None
assert device_info.traits == []
assert device_info.tenant_id is None
def test_populate_with_invalid_lessee(self, device_info):
node = MagicMock()
node.properties = {}
node.traits = None
node.provision_state = "active"
node.lessee = "invalid-uuid"
_populate_from_node(device_info, node)
assert device_info.tenant_id is None
class TestPopulateFromInventory:
"""Test cases for _populate_from_inventory function."""
@pytest.fixture
def device_info(self):
return DeviceInfo(uuid="test-uuid")
def test_populate_from_inventory_full(self, device_info):
inventory = {
"inventory": {
"system_vendor": {
"manufacturer": "Dell Inc.",
"product_name": "PowerEdge R7615 (SKU=0AF7)",
"sku": "ABC1234",
"serial_number": "SN123456",
}
}
}
_populate_from_inventory(device_info, inventory)
assert device_info.manufacturer == "Dell"
assert device_info.model == "PowerEdge R7615"
assert device_info.serial_number == "SN123456"
def test_populate_from_inventory_agent_format(self, device_info):
"""Test AGENT inspection format (no sku, serial_number as service tag)."""
inventory = {
"inventory": {
"system_vendor": {
"manufacturer": "Dell Inc.",
"product_name": "PowerEdge R640",
"serial_number": "SERVICETAG123",
}
}
}
_populate_from_inventory(device_info, inventory)
assert device_info.serial_number == "SERVICETAG123"
def test_populate_from_inventory_empty(self, device_info):
_populate_from_inventory(device_info, None)
assert device_info.model is None
def test_populate_from_inventory_system_product_name(self, device_info):
"""Test that 'System' product name is ignored."""
inventory = {
"inventory": {
"system_vendor": {
"product_name": "System",
}
}
}
_populate_from_inventory(device_info, inventory)
assert device_info.model is None
def test_manufacturer_fallback(self, device_info):
"""Test manufacturer is set from inventory."""
device_info.manufacturer = "Dell" # Already set
inventory = {
"inventory": {
"system_vendor": {
"manufacturer": "HP", # Different - normalised to HPE
}
}
}
_populate_from_inventory(device_info, inventory)
# Inventory always sets manufacturer (HP normalised to HPE)
assert device_info.manufacturer == "HPE"
class TestGenerateDeviceName:
"""Test cases for _generate_device_name function."""
def test_generate_name_with_both_fields(self):
device_info = DeviceInfo(
uuid="test-uuid",
manufacturer="Dell",
serial_number="ABC1234",
)
_generate_device_name(device_info)
assert device_info.name == "Dell-ABC1234"
def test_generate_name_missing_manufacturer(self):
device_info = DeviceInfo(
uuid="test-uuid",
serial_number="ABC1234",
)
_generate_device_name(device_info)
assert device_info.name is None
def test_generate_name_missing_serial_number(self):
device_info = DeviceInfo(
uuid="test-uuid",
manufacturer="Dell",
)
_generate_device_name(device_info)
assert device_info.name is None
class TestSetLocationFromSwitches:
"""Test cases for _set_location_from_switches function."""
@pytest.fixture
def device_info(self):
return DeviceInfo(uuid="test-uuid")
@pytest.fixture
def mock_nautobot(self):
return MagicMock()
def test_set_location_from_switch_info(self, device_info, mock_nautobot):
ports = [
MagicMock(
local_link_connection={
"switch_info": "switch1.example.com",
"switch_id": "aa:bb:cc:dd:ee:ff",
}
)
]
mock_device = MagicMock()
mock_device.location.id = "location-uuid"
mock_device.rack.id = "rack-uuid"
mock_nautobot.dcim.devices.get.return_value = mock_device
_set_location_from_switches(device_info, ports, mock_nautobot)
assert device_info.location_id == "location-uuid"
assert device_info.rack_id == "rack-uuid"
def test_set_location_no_switch_info(self, device_info, mock_nautobot):
ports = [MagicMock(local_link_connection={})]
_set_location_from_switches(device_info, ports, mock_nautobot)
assert device_info.location_id is None
assert device_info.rack_id is None
def test_set_location_switch_info_is_string_none(self, device_info, mock_nautobot):
"""Test that literal string 'None' in switch_info is skipped."""
ports = [
MagicMock(
local_link_connection={
"switch_info": "None",
"switch_id": "00:00:00:00:00:00",
"port_id": "None",
}
)
]
_set_location_from_switches(device_info, ports, mock_nautobot)
# Should not make any API calls
mock_nautobot.dcim.devices.get.assert_not_called()
assert device_info.location_id is None
assert device_info.rack_id is None
def test_set_location_switch_not_found(self, device_info, mock_nautobot):
ports = [
MagicMock(
local_link_connection={
"switch_info": "unknown-switch",
}
)
]
mock_nautobot.dcim.devices.get.return_value = None
mock_nautobot.dcim.interfaces.filter.return_value = []
_set_location_from_switches(device_info, ports, mock_nautobot)
assert device_info.location_id is None
class TestGetRecordValue:
"""Test cases for _get_record_value function."""
def test_get_value_from_record(self):
record = MagicMock()
record.value = "test-value"
assert _get_record_value(record) == "test-value"
def test_get_id_from_record(self):
record = MagicMock()
record.id = "test-id"
assert _get_record_value(record, "id") == "test-id"
def test_get_value_from_none(self):
assert _get_record_value(None) is None
def test_get_value_from_primitive(self):
assert _get_record_value("simple-string") == "simple-string"
class TestCreateNautobotDevice:
"""Test cases for _create_nautobot_device function."""
@pytest.fixture
def mock_nautobot(self):
return MagicMock()
def test_create_device_success(self, mock_nautobot):
device_info = DeviceInfo(
uuid="test-uuid",
name="Dell-ABC123",
manufacturer="Dell",
model="PowerEdge R640",
location_id="location-uuid",
role="server",
)
mock_nautobot.dcim.devices.create.return_value = MagicMock(id="test-uuid")
_create_nautobot_device(device_info, mock_nautobot)
mock_nautobot.dcim.devices.create.assert_called_once()
call_kwargs = mock_nautobot.dcim.devices.create.call_args.kwargs
assert call_kwargs["id"] == "test-uuid"
assert call_kwargs["name"] == "Dell-ABC123"
assert call_kwargs["location"] == "location-uuid"
def test_create_device_without_location_raises(self, mock_nautobot):
device_info = DeviceInfo(
uuid="test-uuid",
name="Dell-ABC123",
)
with pytest.raises(ValueError, match="without location"):
_create_nautobot_device(device_info, mock_nautobot)
def test_create_device_fallback_name_to_uuid(self, mock_nautobot):
device_info = DeviceInfo(
uuid="test-uuid",
manufacturer="Dell",
model="PowerEdge R640",
location_id="location-uuid",
)
_create_nautobot_device(device_info, mock_nautobot)
call_kwargs = mock_nautobot.dcim.devices.create.call_args.kwargs
assert call_kwargs["name"] == "test-uuid"
class TestUpdateNautobotDevice:
"""Test cases for _update_nautobot_device function."""
@pytest.fixture
def mock_nautobot_device(self):
device = MagicMock()
device.status = MagicMock(name="Planned")
device.name = "Old-Name"
device.serial = None
device.location = MagicMock(id="old-location")
device.rack = MagicMock(id="old-rack")
device.tenant = None
device.custom_fields = {}
return device
def test_update_status(self, mock_nautobot_device):
device_info = DeviceInfo(uuid="test-uuid", status="Active")
result = _update_nautobot_device(device_info, mock_nautobot_device)
assert result is True
mock_nautobot_device.save.assert_called_once()
def test_update_name(self, mock_nautobot_device):
device_info = DeviceInfo(uuid="test-uuid", name="New-Name")
result = _update_nautobot_device(device_info, mock_nautobot_device)
assert result is True
assert mock_nautobot_device.name == "New-Name"
def test_update_tenant(self, mock_nautobot_device):
device_info = DeviceInfo(
uuid="test-uuid",
tenant_id="12345678-1234-5678-9abc-123456789abc",
)
result = _update_nautobot_device(device_info, mock_nautobot_device)
assert result is True
assert mock_nautobot_device.tenant == "12345678-1234-5678-9abc-123456789abc"
def test_no_changes(self, mock_nautobot_device):
device_info = DeviceInfo(uuid="test-uuid")
result = _update_nautobot_device(device_info, mock_nautobot_device)
assert result is False
mock_nautobot_device.save.assert_not_called()
def test_update_position_and_face(self, mock_nautobot_device):
"""Test that position and face are updated when preserved from old device."""
mock_nautobot_device.position = None
mock_nautobot_device.face = None
device_info = DeviceInfo(
uuid="test-uuid",
position=42,
face="front",
)
result = _update_nautobot_device(device_info, mock_nautobot_device)
assert result is True
assert mock_nautobot_device.position == 42
assert mock_nautobot_device.face == "front"
mock_nautobot_device.save.assert_called_once()
def test_update_position_defaults_face_to_front(self, mock_nautobot_device):
"""Test that face defaults to 'front' when position is set but face is not."""
mock_nautobot_device.position = None
mock_nautobot_device.face = None
device_info = DeviceInfo(
uuid="test-uuid",
position=10,
# face is None
)
result = _update_nautobot_device(device_info, mock_nautobot_device)
assert result is True
assert mock_nautobot_device.position == 10
assert mock_nautobot_device.face == "front"
def test_update_position_no_change_when_same(self, mock_nautobot_device):
"""Test that no update occurs when position/face are already set correctly."""
mock_nautobot_device.position = 42
mock_nautobot_device.face = MagicMock(value="front")
device_info = DeviceInfo(
uuid="test-uuid",
position=42,
face="front",
)
result = _update_nautobot_device(device_info, mock_nautobot_device)
assert result is False
mock_nautobot_device.save.assert_not_called()
class TestExtractNodeUuidFromEvent:
"""Test cases for _extract_node_uuid_from_event function."""
def test_extract_from_payload(self):
event_data = {
"payload": {
"ironic_object.data": {"uuid": "12345678-1234-5678-9abc-123456789abc"}
}
}
result = _extract_node_uuid_from_event(event_data)
assert result == "12345678-1234-5678-9abc-123456789abc"
def test_extract_from_ironic_object(self):
event_data = {"ironic_object": {"uuid": "12345678-1234-5678-9abc-123456789abc"}}
result = _extract_node_uuid_from_event(event_data)
assert result == "12345678-1234-5678-9abc-123456789abc"
def test_extract_returns_none_for_missing_uuid(self):
event_data = {"payload": {"ironic_object.data": {}}}
result = _extract_node_uuid_from_event(event_data)
assert result is None
class TestSyncDeviceToNautobot:
"""Test cases for sync_device_to_nautobot function."""
@pytest.fixture
def mock_nautobot(self):
return MagicMock()
@patch("understack_workflows.oslo_event.nautobot_device_sync.IronicClient")
@patch("understack_workflows.oslo_event.nautobot_device_sync.fetch_node_details")
@patch(
"understack_workflows.oslo_event.nautobot_device_sync.sync_interfaces_from_data"
)
def test_sync_creates_new_device(
self, mock_sync_interfaces, mock_fetch, mock_ironic_class, mock_nautobot
):
node_uuid = str(uuid.uuid4())
device_info = DeviceInfo(
uuid=node_uuid,
name="Dell-ABC123",
manufacturer="Dell",
model="PowerEdge R640",
location_id="location-uuid",
status="Active",
)
mock_fetch.return_value = (device_info, {}, [])
mock_nautobot.dcim.devices.get.return_value = None
mock_nautobot.dcim.devices.create.return_value = MagicMock()
mock_sync_interfaces.return_value = EXIT_STATUS_SUCCESS
result = sync_device_to_nautobot(node_uuid, mock_nautobot)
assert result == EXIT_STATUS_SUCCESS
mock_nautobot.dcim.devices.create.assert_called_once()
@patch("understack_workflows.oslo_event.nautobot_device_sync.IronicClient")
@patch("understack_workflows.oslo_event.nautobot_device_sync.fetch_node_details")
@patch(
"understack_workflows.oslo_event.nautobot_device_sync.sync_interfaces_from_data"
)
def test_sync_updates_existing_device(
self, mock_sync_interfaces, mock_fetch, mock_ironic_class, mock_nautobot
):
node_uuid = str(uuid.uuid4())
device_info = DeviceInfo(
uuid=node_uuid,
name="Dell-ABC123",
status="Active",
)
mock_fetch.return_value = (device_info, {}, [])
existing_device = MagicMock()
existing_device.status = MagicMock(name="Planned")
existing_device.name = "Dell-ABC123"
existing_device.serial = None
existing_device.location = None
existing_device.rack = None
existing_device.tenant = None
existing_device.custom_fields = {}
mock_nautobot.dcim.devices.get.return_value = existing_device
mock_sync_interfaces.return_value = EXIT_STATUS_SUCCESS
result = sync_device_to_nautobot(node_uuid, mock_nautobot)
assert result == EXIT_STATUS_SUCCESS
mock_nautobot.dcim.devices.create.assert_not_called()
def test_sync_with_empty_uuid_returns_error(self, mock_nautobot):
result = sync_device_to_nautobot("", mock_nautobot)
assert result == EXIT_STATUS_FAILURE
@patch("understack_workflows.oslo_event.nautobot_device_sync.IronicClient")
@patch("understack_workflows.oslo_event.nautobot_device_sync.fetch_node_details")
def test_sync_without_location_skips_for_uninspected_node(
self, mock_fetch, mock_ironic_class, mock_nautobot
):
"""Test that sync skips gracefully for uninspected nodes without location."""
node_uuid = str(uuid.uuid4())
device_info = DeviceInfo(uuid=node_uuid) # No location
mock_fetch.return_value = (device_info, {}, [])
mock_nautobot.dcim.devices.get.return_value = None
result = sync_device_to_nautobot(node_uuid, mock_nautobot)
# Should fail since no location available
assert result == EXIT_STATUS_FAILURE
# Should not attempt to create device
mock_nautobot.dcim.devices.create.assert_not_called()
@patch("understack_workflows.oslo_event.nautobot_device_sync.IronicClient")
@patch("understack_workflows.oslo_event.nautobot_device_sync.fetch_node_details")
@patch(
"understack_workflows.oslo_event.nautobot_device_sync.sync_interfaces_from_data"
)
def test_sync_recreates_device_with_mismatched_uuid(
self, mock_sync_interfaces, mock_fetch, mock_ironic_class, mock_nautobot
):
"""Test device with mismatched UUID is deleted and recreated."""
node_uuid = str(uuid.uuid4())
old_uuid = str(uuid.uuid4()) # Different UUID
device_info = DeviceInfo(
uuid=node_uuid,
name="Dell-ABC123",
manufacturer="Dell",
model="PowerEdge R640",
location_id="location-uuid",
status="Active",
)
mock_fetch.return_value = (device_info, {}, [])
# First get by ID returns None
# Second get by name returns device with different UUID
existing_device = MagicMock()
existing_device.id = old_uuid # Different UUID
existing_device.status = MagicMock(name="Planned")
existing_device.name = "Dell-ABC123"
mock_nautobot.dcim.devices.get.side_effect = [None, existing_device]
mock_nautobot.dcim.devices.create.return_value = MagicMock()
mock_sync_interfaces.return_value = EXIT_STATUS_SUCCESS
result = sync_device_to_nautobot(node_uuid, mock_nautobot)
assert result == EXIT_STATUS_SUCCESS
# Should delete old device
existing_device.delete.assert_called_once()
# Should create new device with correct UUID
mock_nautobot.dcim.devices.create.assert_called_once()
@patch("understack_workflows.oslo_event.nautobot_device_sync.IronicClient")
@patch("understack_workflows.oslo_event.nautobot_device_sync.fetch_node_details")
@patch(
"understack_workflows.oslo_event.nautobot_device_sync.sync_interfaces_from_data"
)
def test_sync_device_not_found_by_name_creates_new(
self, mock_sync_interfaces, mock_fetch, mock_ironic_class, mock_nautobot
):
"""Test that device not found by UUID or name is created."""
node_uuid = str(uuid.uuid4())
device_info = DeviceInfo(
uuid=node_uuid,
name="Dell-ABC123",
manufacturer="Dell",
model="PowerEdge R640",
location_id="location-uuid",
status="Active",
)
mock_fetch.return_value = (device_info, {}, [])
# Both lookups return None
mock_nautobot.dcim.devices.get.side_effect = [None, None]
mock_nautobot.dcim.devices.create.return_value = MagicMock()
mock_sync_interfaces.return_value = EXIT_STATUS_SUCCESS
result = sync_device_to_nautobot(node_uuid, mock_nautobot)
assert result == EXIT_STATUS_SUCCESS
mock_nautobot.dcim.devices.create.assert_called_once()
@patch("understack_workflows.oslo_event.nautobot_device_sync.IronicClient")
@patch("understack_workflows.oslo_event.nautobot_device_sync.fetch_node_details")
@patch(
"understack_workflows.oslo_event.nautobot_device_sync.sync_interfaces_from_data"
)
def test_sync_uuid_mismatch_uses_old_device_location(
self, mock_sync_interfaces, mock_fetch, mock_ironic_class, mock_nautobot
):
"""Test that location is preserved from old device when new node has none.
When re-enrolling a node that hasn't been inspected yet, we should use
the location from the old Nautobot device to create the new one.
"""
node_uuid = str(uuid.uuid4())
old_uuid = str(uuid.uuid4())
device_info = DeviceInfo(
uuid=node_uuid,
name="Dell-ABC123",
manufacturer="Dell",
model="PowerEdge R640",
# No location_id from switch lookup
status="Active",
)
mock_fetch.return_value = (device_info, {}, [])
# Old device has location
existing_device = MagicMock()
existing_device.id = old_uuid
existing_device.name = "Dell-ABC123"
existing_device.location = MagicMock(id="old-location-uuid")
existing_device.rack = MagicMock(id="old-rack-uuid")
existing_device.position = 42
existing_device.face = MagicMock(value="front")
mock_nautobot.dcim.devices.get.side_effect = [None, existing_device]
mock_nautobot.dcim.devices.create.return_value = MagicMock()
mock_sync_interfaces.return_value = EXIT_STATUS_SUCCESS
result = sync_device_to_nautobot(node_uuid, mock_nautobot)
assert result == EXIT_STATUS_SUCCESS
# Should delete old device after preserving location
existing_device.delete.assert_called_once()
# Should create new device
mock_nautobot.dcim.devices.create.assert_called_once()
class TestDeleteDeviceFromNautobot:
"""Test cases for delete_device_from_nautobot function."""
@pytest.fixture
def mock_nautobot(self):
return MagicMock()
def test_delete_existing_device(self, mock_nautobot):
node_uuid = str(uuid.uuid4())
mock_device = MagicMock()
mock_nautobot.dcim.devices.get.return_value = mock_device
result = delete_device_from_nautobot(node_uuid, mock_nautobot)
assert result == EXIT_STATUS_SUCCESS
mock_device.delete.assert_called_once()
def test_delete_nonexistent_device(self, mock_nautobot):
node_uuid = str(uuid.uuid4())
mock_nautobot.dcim.devices.get.return_value = None
result = delete_device_from_nautobot(node_uuid, mock_nautobot)
assert result == EXIT_STATUS_SUCCESS
def test_delete_with_empty_uuid(self, mock_nautobot):
result = delete_device_from_nautobot("", mock_nautobot)
assert result == EXIT_STATUS_FAILURE
class TestHandleNodeEvent:
"""Test cases for handle_node_event function."""
@pytest.fixture
def mock_conn(self):
return MagicMock()
@pytest.fixture
def mock_nautobot(self):
return MagicMock()
@patch(
"understack_workflows.oslo_event.nautobot_device_sync.sync_device_to_nautobot"
)
def test_handle_node_event_success(self, mock_sync, mock_conn, mock_nautobot):
node_uuid = str(uuid.uuid4())
event_data = {
"event_type": "baremetal.node.provision_set.end",
"payload": {
"ironic_object.data": {
"uuid": node_uuid,
}
},
}
mock_sync.return_value = EXIT_STATUS_SUCCESS
result = handle_node_event(mock_conn, mock_nautobot, event_data)
assert result == EXIT_STATUS_SUCCESS
mock_sync.assert_called_once_with(node_uuid, mock_nautobot)
def test_handle_node_event_no_uuid(self, mock_conn, mock_nautobot):
event_data = {"payload": {"ironic_object.data": {}}}
result = handle_node_event(mock_conn, mock_nautobot, event_data)
assert result == EXIT_STATUS_FAILURE
class TestHandleNodeDeleteEvent:
"""Test cases for handle_node_delete_event function."""
@pytest.fixture
def mock_conn(self):
return MagicMock()
@pytest.fixture
def mock_nautobot(self):
return MagicMock()
@patch(
"understack_workflows.oslo_event.nautobot_device_sync.delete_device_from_nautobot"
)
def test_handle_delete_event_success(self, mock_delete, mock_conn, mock_nautobot):
node_uuid = str(uuid.uuid4())
event_data = {
"payload": {
"ironic_object.data": {
"uuid": node_uuid,
}
},
}
mock_delete.return_value = EXIT_STATUS_SUCCESS
result = handle_node_delete_event(mock_conn, mock_nautobot, event_data)
assert result == EXIT_STATUS_SUCCESS
mock_delete.assert_called_once_with(node_uuid, mock_nautobot)
class TestIsRetryableError:
"""Test cases for _is_retryable_error function."""
def test_connection_error_is_retryable(self):
exc = requests.exceptions.ConnectionError("Connection refused")
assert _is_retryable_error(exc) is True
def test_503_service_unavailable_is_retryable(self):
from pynautobot import RequestError
mock_response = MagicMock()
mock_response.status_code = 503
mock_response.reason = "Service Unavailable"
mock_response.json.return_value = {"detail": "Service temporarily unavailable"}
mock_response.request.body = None
mock_response.url = "http://nautobot/api/dcim/devices/"
mock_response.text = "Service Unavailable"
exc = RequestError(mock_response)
assert _is_retryable_error(exc) is True
def test_502_bad_gateway_is_retryable(self):
from pynautobot import RequestError
mock_response = MagicMock()
mock_response.status_code = 502
mock_response.reason = "Bad Gateway"
mock_response.json.return_value = {}
mock_response.request.body = None
mock_response.url = "http://nautobot/api/dcim/devices/"
mock_response.text = "Bad Gateway"
exc = RequestError(mock_response)
assert _is_retryable_error(exc) is True
def test_504_gateway_timeout_is_retryable(self):
from pynautobot import RequestError
mock_response = MagicMock()
mock_response.status_code = 504
mock_response.reason = "Gateway Timeout"
mock_response.json.return_value = {}
mock_response.request.body = None
mock_response.url = "http://nautobot/api/dcim/devices/"
mock_response.text = "Gateway Timeout"
exc = RequestError(mock_response)
assert _is_retryable_error(exc) is True
def test_400_bad_request_is_not_retryable(self):
from pynautobot import RequestError
mock_response = MagicMock()
mock_response.status_code = 400
mock_response.reason = "Bad Request"
mock_response.json.return_value = {"device_type": ["Not found"]}
mock_response.request.body = None
mock_response.url = "http://nautobot/api/dcim/devices/"
mock_response.text = "Bad Request"
exc = RequestError(mock_response)
assert _is_retryable_error(exc) is False
def test_404_not_found_is_not_retryable(self):
from pynautobot import RequestError
mock_response = MagicMock()
mock_response.status_code = 404
mock_response.reason = "Not Found"
mock_response.json.return_value = {}
mock_response.request.body = None
mock_response.url = "http://nautobot/api/dcim/devices/123/"
mock_response.text = "Not Found"
exc = RequestError(mock_response)
assert _is_retryable_error(exc) is False
def test_value_error_is_not_retryable(self):
exc = ValueError("Invalid value")
assert _is_retryable_error(exc) is False
class TestExternalCmdbIdPopulateFromNode:
"""Test cases for external_cmdb_id handling in _populate_from_node."""
@pytest.fixture
def device_info(self):
return DeviceInfo(uuid="test-uuid")
@pytest.fixture
def mock_node_with_external_cmdb_id(self):
"""Node with external_cmdb_id in extra field."""
node = MagicMock()
node.properties = {}
node.traits = None
node.provision_state = "active"
node.lessee = None
node.extra = {"external_cmdb_id": "CORE-12345"}
return node
@pytest.fixture
def mock_node_without_external_cmdb_id(self):
"""Node without external_cmdb_id in extra field."""
node = MagicMock()
node.properties = {}
node.traits = None
node.provision_state = "active"
node.lessee = None
node.extra = {}
return node
@pytest.fixture
def mock_node_with_empty_external_cmdb_id(self):
"""Node with empty external_cmdb_id (cleared) in extra field."""
node = MagicMock()
node.properties = {}
node.traits = None
node.provision_state = "active"
node.lessee = None
node.extra = {"external_cmdb_id": ""}
return node
@pytest.fixture
def mock_node_with_null_external_cmdb_id(self):
"""Node with null external_cmdb_id in extra field."""
node = MagicMock()
node.properties = {}
node.traits = None
node.provision_state = "active"
node.lessee = None
node.extra = {"external_cmdb_id": None}
return node
def test_populate_with_external_cmdb_id(
self, device_info, mock_node_with_external_cmdb_id
):
"""Test that external_cmdb_id is populated from node extra field.
WHEN a Nautobot_Device is synced from
an Ironic_Node containing external_cmdb_id in extra, THE Nautobot_Device
SHALL have the value set in a custom field named "external_cmdb_id"
"""
_populate_from_node(device_info, mock_node_with_external_cmdb_id)
assert device_info.external_cmdb_id == "CORE-12345"
def test_populate_without_external_cmdb_id(
self, device_info, mock_node_without_external_cmdb_id
):
"""Test that external_cmdb_id is None when not in node extra field.
WHEN a Nautobot_Device is synced from
an Ironic_Node without external_cmdb_id in extra, THE Nautobot_Device
SHALL NOT have the "external_cmdb_id" custom field modified
"""
_populate_from_node(device_info, mock_node_without_external_cmdb_id)
# None means "don't modify" the custom field
assert device_info.external_cmdb_id is None
def test_populate_with_empty_external_cmdb_id(
self, device_info, mock_node_with_empty_external_cmdb_id
):
"""Test that empty external_cmdb_id is normalized to None.
WHEN the external_cmdb_id is empty in Ironic_Node extra,
THE device_info.external_cmdb_id SHALL be None (no value)
"""
_populate_from_node(device_info, mock_node_with_empty_external_cmdb_id)
# Empty string is normalized to None
assert device_info.external_cmdb_id is None
def test_populate_with_null_external_cmdb_id(
self, device_info, mock_node_with_null_external_cmdb_id
):
"""Test that null external_cmdb_id stays None.
WHEN the external_cmdb_id is null in Ironic_Node extra,
THE device_info.external_cmdb_id SHALL be None
"""
_populate_from_node(device_info, mock_node_with_null_external_cmdb_id)
# Null value stays None
assert device_info.external_cmdb_id is None
class TestExternalCmdbIdUpdateNautobotDevice:
"""Test cases for external_cmdb_id handling in _update_nautobot_device."""