forked from sonic-net/sonic-mgmt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconftest.py
More file actions
2879 lines (2393 loc) · 117 KB
/
conftest.py
File metadata and controls
2879 lines (2393 loc) · 117 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
import concurrent.futures
import os
import glob
import json
import logging
import getpass
import random
import re
from concurrent.futures import as_completed
import pytest
import yaml
import jinja2
import copy
import time
import subprocess
import threading
from datetime import datetime
from ipaddress import ip_interface, IPv4Interface
from tests.common.connections.base_console_conn import (
CONSOLE_SSH_CISCO_CONFIG,
CONSOLE_SSH_DIGI_CONFIG,
CONSOLE_SSH_SONIC_CONFIG
)
from tests.common.fixtures.conn_graph_facts import conn_graph_facts # noqa F401
from tests.common.devices.local import Localhost
from tests.common.devices.ptf import PTFHost
from tests.common.devices.eos import EosHost
from tests.common.devices.sonic import SonicHost
from tests.common.devices.fanout import FanoutHost
from tests.common.devices.k8s import K8sMasterHost
from tests.common.devices.k8s import K8sMasterCluster
from tests.common.devices.duthosts import DutHosts
from tests.common.devices.vmhost import VMHost
from tests.common.devices.base import NeighborDevice
from tests.common.devices.cisco import CiscoHost
from tests.common.helpers.parallel import parallel_run
from tests.common.fixtures.duthost_utils import backup_and_restore_config_db_session # noqa F401
from tests.common.fixtures.ptfhost_utils import ptf_portmap_file # noqa F401
from tests.common.fixtures.ptfhost_utils import ptf_test_port_map_active_active # noqa F401
from tests.common.fixtures.ptfhost_utils import run_icmp_responder_session # noqa F401
from tests.common.dualtor.dual_tor_utils import disable_timed_oscillation_active_standby# noqa F401
from tests.common.helpers.constants import (
ASIC_PARAM_TYPE_ALL, ASIC_PARAM_TYPE_FRONTEND, DEFAULT_ASIC_ID, ASICS_PRESENT, DUT_CHECK_NAMESPACE
)
from tests.common.helpers.custom_msg_utils import add_custom_msg
from tests.common.helpers.dut_ports import encode_dut_port_name
from tests.common.helpers.dut_utils import encode_dut_and_container_name
from tests.common.helpers.parallel_utils import InitialCheckState, InitialCheckStatus
from tests.common.plugins.sanity_check import recover_chassis
from tests.common.system_utils import docker
from tests.common.testbed import TestbedInfo
from tests.common.utilities import get_inventory_files
from tests.common.utilities import get_host_vars
from tests.common.utilities import get_host_visible_vars
from tests.common.utilities import get_test_server_host
from tests.common.utilities import str2bool
from tests.common.utilities import safe_filename
from tests.common.utilities import get_dut_current_passwd
from tests.common.utilities import get_duts_from_host_pattern
from tests.common.helpers.dut_utils import is_supervisor_node, is_frontend_node
from tests.common.cache import FactsCache
from tests.common.config_reload import config_reload
from tests.common.connections.console_host import ConsoleHost
from tests.common.helpers.assertions import pytest_assert as pt_assert
from tests.common.helpers.inventory_utils import trim_inventory
from tests.common.utilities import InterruptableThread
from tests.common.plugins.ptfadapter.dummy_testutils import DummyTestUtils
try:
from tests.common.macsec import MacsecPluginT2, MacsecPluginT0
except ImportError as e:
logging.error(e)
from tests.common.platform.args.advanced_reboot_args import add_advanced_reboot_args
from tests.common.platform.args.cont_warm_reboot_args import add_cont_warm_reboot_args
from tests.common.platform.args.normal_reboot_args import add_normal_reboot_args
from ptf import testutils
from ptf.mask import Mask
logger = logging.getLogger(__name__)
cache = FactsCache()
DUTHOSTS_FIXTURE_FAILED_RC = 15
CUSTOM_MSG_PREFIX = "sonic_custom_msg"
pytest_plugins = ('tests.common.plugins.ptfadapter',
'tests.common.plugins.ansible_fixtures',
'tests.common.plugins.dut_monitor',
'tests.common.plugins.loganalyzer',
'tests.common.plugins.pdu_controller',
'tests.common.plugins.sanity_check',
'tests.common.plugins.custom_markers',
'tests.common.plugins.test_completeness',
'tests.common.plugins.log_section_start',
'tests.common.plugins.custom_fixtures',
'tests.common.dualtor',
'tests.decap',
'tests.platform_tests.api',
'tests.common.plugins.allure_server',
'tests.common.plugins.conditional_mark',
'tests.common.plugins.random_seed',
'tests.common.plugins.memory_utilization')
def pytest_addoption(parser):
parser.addoption("--testbed", action="store", default=None, help="testbed name")
parser.addoption("--testbed_file", action="store", default=None, help="testbed file name")
# test_vrf options
parser.addoption("--vrf_capacity", action="store", default=None, type=int, help="vrf capacity of dut (4-1000)")
parser.addoption("--vrf_test_count", action="store", default=None, type=int,
help="number of vrf to be tested (1-997)")
# qos_sai options
parser.addoption("--ptf_portmap", action="store", default=None, type=str,
help="PTF port index to DUT port alias map")
parser.addoption("--qos_swap_syncd", action="store", type=str2bool, default=True,
help="Swap syncd container with syncd-rpc container")
# Kubernetes master options
parser.addoption("--kube_master", action="store", default=None, type=str,
help="Name of k8s master group used in k8s inventory, format: k8s_vms{msetnumber}_{servernumber}")
# neighbor device type
parser.addoption("--neighbor_type", action="store", default="eos", type=str, choices=["eos", "sonic", "cisco"],
help="Neighbor devices type")
# FWUtil options
parser.addoption('--fw-pkg', action='store', help='Firmware package file')
############################
# pfc_asym options #
############################
parser.addoption("--server_ports_num", action="store", default=20, type=int, help="Number of server ports to use")
parser.addoption("--fanout_inventory", action="store", default="lab", help="Inventory with defined fanout hosts")
############################
# test_techsupport options #
############################
parser.addoption("--loop_num", action="store", default=2, type=int,
help="Change default loop range for show techsupport command")
parser.addoption("--loop_delay", action="store", default=2, type=int,
help="Change default loops delay")
parser.addoption("--logs_since", action="store", type=int,
help="number of minutes for show techsupport command")
parser.addoption("--collect_techsupport", action="store", default=True, type=str2bool,
help="Enable/Disable tech support collection. Default is enabled (True)")
############################
# sanity_check options #
############################
parser.addoption("--skip_sanity", action="store_true", default=False,
help="Skip sanity check")
parser.addoption("--allow_recover", action="store_true", default=False,
help="Allow recovery attempt in sanity check in case of failure")
parser.addoption("--check_items", action="store", default=False,
help="Change (add|remove) check items in the check list")
parser.addoption("--post_check", action="store_true", default=False,
help="Perform post test sanity check if sanity check is enabled")
parser.addoption("--post_check_items", action="store", default=False,
help="Change (add|remove) post test check items based on pre test check items")
parser.addoption("--recover_method", action="store", default="adaptive",
help="Set method to use for recover if sanity failed")
########################
# pre-test options #
########################
parser.addoption("--deep_clean", action="store_true", default=False,
help="Deep clean DUT before tests (remove old logs, cores, dumps)")
parser.addoption("--py_saithrift_url", action="store", default=None, type=str,
help="Specify the url of the saithrift package to be installed on the ptf "
"(should be http://<serverip>/path/python-saithrift_0.9.4_amd64.deb")
#########################
# post-test options #
#########################
parser.addoption("--posttest_show_tech_since", action="store", default="yesterday",
help="collect show techsupport since <date>. <date> should be a string which can "
"be parsed by bash command 'date --d <date>'. Default value is yesterday. "
"To collect all time spans, please use '@0' as the value.")
############################
# keysight ixanvl options #
############################
parser.addoption("--testnum", action="store", default=None, type=str)
##################################
# advance-reboot,upgrade options #
##################################
add_advanced_reboot_args(parser)
add_cont_warm_reboot_args(parser)
add_normal_reboot_args(parser)
############################
# loop_times options #
############################
parser.addoption("--loop_times", metavar="LOOP_TIMES", action="store", default=1, type=int,
help="Define the loop times of the test")
############################
# collect logs option #
############################
parser.addoption("--collect_db_data", action="store_true", default=False, help="Collect db info if test failed")
############################
# macsec options #
############################
parser.addoption("--enable_macsec", action="store_true", default=False,
help="Enable macsec on some links of testbed")
parser.addoption("--macsec_profile", action="store", default="all",
type=str, help="profile name list in macsec/profile.json")
############################
# QoS options #
############################
parser.addoption("--public_docker_registry", action="store_true", default=False,
help="To use public docker registry for syncd swap, by default is disabled (False)")
##############################
# ansible inventory option #
##############################
parser.addoption("--trim_inv", action="store_true", default=False, help="Trim inventory files")
############################
# Parallel run options #
############################
parser.addoption("--target_hostname", action="store", default=None, type=str,
help="Target hostname to run the test in parallel")
parser.addoption("--parallel_state_file", action="store", default=None, type=str,
help="File to store the state of the parallel run")
parser.addoption("--is_parallel_leader", action="store_true", default=False, help="Is the parallel leader")
parser.addoption("--parallel_followers", action="store", default=0, type=int, help="Number of parallel followers")
############################
# SmartSwitch options #
############################
parser.addoption("--dpu-pattern", action="store", default="all", help="dpu host name")
def pytest_configure(config):
if config.getoption("enable_macsec"):
topo = config.getoption("topology")
if topo is not None and "t2" in topo:
config.pluginmanager.register(MacsecPluginT2())
else:
config.pluginmanager.register(MacsecPluginT0())
@pytest.fixture(scope="session", autouse=True)
def enhance_inventory(request, tbinfo):
"""
This fixture is to enhance the capability of parsing the value of pytest cli argument '--inventory'.
The pytest-ansible plugin always assumes that the value of cli argument '--inventory' is a single
inventory file. With this enhancement, we can pass in multiple inventory files using the cli argument
'--inventory'. The multiple inventory files can be separated by comma ','.
For example:
pytest --inventory "inventory1, inventory2" <other arguments>
pytest --inventory inventory1,inventory2 <other arguments>
This fixture is automatically applied, you don't need to declare it in your test script.
"""
inv_opt = request.config.getoption("ansible_inventory")
if isinstance(inv_opt, list):
return
inv_files = [inv_file.strip() for inv_file in inv_opt.split(",")]
if request.config.getoption("trim_inv"):
trim_inventory(inv_files, tbinfo)
try:
logger.info(f"Inventory file: {inv_files}")
setattr(request.config.option, "ansible_inventory", inv_files)
except AttributeError:
logger.error("Failed to set enhanced 'ansible_inventory' to request.config.option")
def pytest_cmdline_main(config):
# Filter out unnecessary pytest_ansible plugin log messages
pytest_ansible_logger = logging.getLogger("pytest_ansible")
if pytest_ansible_logger:
pytest_ansible_logger.setLevel(logging.WARNING)
# Filter out unnecessary ansible log messages (ansible v2.8)
# The logger name of ansible v2.8 is nasty
mypid = str(os.getpid())
user = getpass.getuser()
ansible_loggerv28 = logging.getLogger("p=%s u=%s | " % (mypid, user))
if ansible_loggerv28:
ansible_loggerv28.setLevel(logging.WARNING)
# Filter out unnecessary ansible log messages (latest ansible)
ansible_logger = logging.getLogger("ansible")
if ansible_logger:
ansible_logger.setLevel(logging.WARNING)
# Filter out unnecessary logs generated by calling the ptfadapter plugin
dataplane_logger = logging.getLogger("dataplane")
if dataplane_logger:
dataplane_logger.setLevel(logging.ERROR)
def pytest_collection(session):
"""Workaround to reduce messy plugin logs generated during collection only
Args:
session (ojb): Pytest session object
"""
if session.config.option.collectonly:
root_logger = logging.getLogger()
root_logger.setLevel(logging.WARNING)
def get_target_hostname(request):
return request.config.getoption("--target_hostname")
def get_parallel_state_file(request):
return request.config.getoption("--parallel_state_file")
def is_parallel_run(request):
return get_target_hostname(request) is not None
def is_parallel_leader(request):
return request.config.getoption("--is_parallel_leader")
def get_parallel_followers(request):
return request.config.getoption("--parallel_followers")
def get_tbinfo(request):
"""
Helper function to create and return testbed information
"""
tbname = request.config.getoption("--testbed")
tbfile = request.config.getoption("--testbed_file")
if tbname is None or tbfile is None:
raise ValueError("testbed and testbed_file are required!")
testbedinfo = cache.read(tbname, 'tbinfo')
if testbedinfo is cache.NOTEXIST:
testbedinfo = TestbedInfo(tbfile)
cache.write(tbname, 'tbinfo', testbedinfo)
return tbname, testbedinfo.testbed_topo.get(tbname, {})
@pytest.fixture(scope="session")
def tbinfo(request):
"""
Create and return testbed information
"""
_, testbedinfo = get_tbinfo(request)
return testbedinfo
@pytest.fixture(scope="session")
def parallel_run_context(request):
return (
is_parallel_run(request),
get_target_hostname(request),
is_parallel_leader(request),
get_parallel_followers(request),
get_parallel_state_file(request),
)
def get_specified_device_info(request, device_pattern):
"""
Get a list of device hostnames specified with the --host-pattern or --dpu-pattern CLI option
"""
tbname, tbinfo = get_tbinfo(request)
testbed_duts = tbinfo['duts']
if is_parallel_run(request):
return [get_target_hostname(request)]
host_pattern = request.config.getoption(device_pattern)
if host_pattern == 'all':
if device_pattern == '--dpu-pattern':
testbed_duts = [dut for dut in testbed_duts if 'dpu' in dut]
logger.info(f"dpu duts: {testbed_duts}")
return testbed_duts
else:
specified_duts = get_duts_from_host_pattern(host_pattern)
if any([dut not in testbed_duts for dut in specified_duts]):
pytest.fail("One of the specified DUTs {} does not belong to the testbed {}".format(specified_duts, tbname))
if len(testbed_duts) != specified_duts:
duts = specified_duts
logger.debug("Different DUTs specified than in testbed file, using {}"
.format(str(duts)))
return duts
def get_specified_duts(request):
"""
Get a list of DUT hostnames specified with the --host-pattern CLI option
or -d if using `run_tests.sh`
"""
return get_specified_device_info(request, "--host-pattern")
def get_specified_dpus(request):
"""
Get a list of DUT hostnames specified with the --dpu-pattern CLI option
"""
return get_specified_device_info(request, "--dpu-pattern")
def pytest_sessionstart(session):
# reset all the sonic_custom_msg keys from cache
# reset here because this fixture will always be very first fixture to be called
cache_dir = session.config.cache._cachedir
keys = [p.name for p in cache_dir.glob('**/*') if p.is_file() and p.name.startswith(CUSTOM_MSG_PREFIX)]
for key in keys:
logger.debug("reset existing key: {}".format(key))
session.config.cache.set(key, None)
def pytest_sessionfinish(session, exitstatus):
if session.config.cache.get("duthosts_fixture_failed", None):
session.config.cache.set("duthosts_fixture_failed", None)
session.exitstatus = DUTHOSTS_FIXTURE_FAILED_RC
@pytest.fixture(name="duthosts", scope="session")
def fixture_duthosts(enhance_inventory, ansible_adhoc, tbinfo, request):
"""
@summary: fixture to get DUT hosts defined in testbed.
@param enhance_inventory: fixture to enhance the capability of parsing the value of pytest cli argument
@param ansible_adhoc: Fixture provided by the pytest-ansible package.
Source of the various device objects. It is
mandatory argument for the class constructors.
@param tbinfo: fixture provides information about testbed.
@param request: pytest request object
"""
try:
host = DutHosts(ansible_adhoc, tbinfo, request, get_specified_duts(request),
target_hostname=get_target_hostname(request), is_parallel_leader=is_parallel_leader(request))
return host
except BaseException as e:
logger.error("Failed to initialize duthosts.")
request.config.cache.set("duthosts_fixture_failed", True)
pt_assert(False, "!!!!!!!!!!!!!!!! duthosts fixture failed !!!!!!!!!!!!!!!!"
"Exception: {}".format(repr(e)))
@pytest.fixture(scope="session")
def duthost(duthosts, request):
'''
@summary: Shortcut fixture for getting DUT host. For a lengthy test case, test case module can
pass a request to disable sh time out mechanis on dut in order to avoid ssh timeout.
After test case completes, the fixture will restore ssh timeout.
@param duthosts: fixture to get DUT hosts
@param request: request parameters for duthost test fixture
'''
dut_index = getattr(request.session, "dut_index", 0)
assert dut_index < len(duthosts), \
"DUT index '{0}' is out of bound '{1}'".format(dut_index,
len(duthosts))
duthost = duthosts[dut_index]
return duthost
@pytest.fixture(name="dpuhosts", scope="session")
def fixture_dpuhosts(enhance_inventory, ansible_adhoc, tbinfo, request):
"""
@summary: fixture to get DPU hosts defined in testbed.
@param ansible_adhoc: Fixture provided by the pytest-ansible package.
Source of the various device objects. It is
mandatory argument for the class constructors.
@param tbinfo: fixture provides information about testbed.
"""
# Before calling dpuhosts, we must enable NAT on NPU.
# E.g. run sonic-dpu-mgmt-traffic.sh on NPU to enable NAT
# sonic-dpu-mgmt-traffic.sh inbound -e --dpus all --ports 5021,5022,5023,5024
try:
host = DutHosts(ansible_adhoc, tbinfo, request, get_specified_dpus(request),
target_hostname=get_target_hostname(request), is_parallel_leader=is_parallel_leader(request))
return host
except BaseException as e:
logger.error("Failed to initialize dpuhosts.")
request.config.cache.set("dpuhosts_fixture_failed", True)
pt_assert(False, "!!!!!!!!!!!!!!!! dpuhosts fixture failed !!!!!!!!!!!!!!!!"
"Exception: {}".format(repr(e)))
@pytest.fixture(scope="session")
def dpuhost(dpuhosts, request):
'''
@summary: Shortcut fixture for getting DPU host. For a lengthy test case, test case module can
pass a request to disable sh time out mechanis on dut in order to avoid ssh timeout.
After test case completes, the fixture will restore ssh timeout.
@param duthosts: fixture to get DPU hosts
@param request: request parameters for duphost test fixture
'''
dpu_index = getattr(request.session, "dpu_index", 0)
assert dpu_index < len(dpuhosts), \
"DPU index '{0}' is out of bound '{1}'".format(dpu_index,
len(dpuhosts))
duthost = dpuhosts[dpu_index]
return duthost
@pytest.fixture(scope="session")
def mg_facts(duthost):
return duthost.minigraph_facts(host=duthost.hostname)['ansible_facts']
@pytest.fixture(scope="session")
def macsec_duthost(duthosts, tbinfo):
# get the first macsec capable node
macsec_dut = None
if 't2' in tbinfo['topo']['name']:
# currently in the T2 topo only the uplink linecard will have
# macsec enabled
for duthost in duthosts:
if duthost.is_macsec_capable_node():
macsec_dut = duthost
break
else:
return duthosts[0]
return macsec_dut
# Make sure in same test module, always use same random DUT
rand_one_dut_hostname_var = None
def set_rand_one_dut_hostname(request):
global rand_one_dut_hostname_var
if rand_one_dut_hostname_var is None:
dut_hostnames = generate_params_dut_hostname(request)
if len(dut_hostnames) > 1:
dut_hostnames = random.sample(dut_hostnames, 1)
rand_one_dut_hostname_var = dut_hostnames[0]
logger.info("Randomly select dut {} for testing".format(rand_one_dut_hostname_var))
@pytest.fixture(scope="module")
def rand_one_dut_hostname(request):
"""
"""
global rand_one_dut_hostname_var
if rand_one_dut_hostname_var is None:
set_rand_one_dut_hostname(request)
return rand_one_dut_hostname_var
@pytest.fixture(scope="module")
def rand_selected_dut(duthosts, rand_one_dut_hostname):
"""
Return the randomly selected duthost
"""
return duthosts[rand_one_dut_hostname]
@pytest.fixture(scope="module")
def selected_rand_dut(request):
global rand_one_dut_hostname_var
if rand_one_dut_hostname_var is None:
set_rand_one_dut_hostname(request)
return rand_one_dut_hostname_var
@pytest.fixture(scope="module")
def rand_one_dut_front_end_hostname(request):
"""
"""
dut_hostnames = generate_params_frontend_hostname(request)
if len(dut_hostnames) > 1:
dut_hostnames = random.sample(dut_hostnames, 1)
logger.info("Randomly select dut {} for testing".format(dut_hostnames[0]))
return dut_hostnames[0]
@pytest.fixture(scope="module")
def rand_one_tgen_dut_hostname(request, tbinfo, rand_one_dut_front_end_hostname, rand_one_dut_hostname):
"""
Return the randomly selected duthost for TGEN test cases
"""
# For T2, we need to skip supervisor, only use linecards.
if 't2' in tbinfo['topo']['name']:
return rand_one_dut_front_end_hostname
return rand_one_dut_hostname
@pytest.fixture(scope="module")
def rand_selected_front_end_dut(duthosts, rand_one_dut_front_end_hostname):
"""
Return the randomly selected duthost
"""
return duthosts[rand_one_dut_front_end_hostname]
@pytest.fixture(scope="module")
def rand_unselected_dut(request, duthosts, rand_one_dut_hostname):
"""
Return the left duthost after random selection.
Return None for non dualtor testbed
"""
dut_hostnames = generate_params_dut_hostname(request)
if len(dut_hostnames) <= 1:
return None
idx = dut_hostnames.index(rand_one_dut_hostname)
return duthosts[dut_hostnames[1 - idx]]
@pytest.fixture(scope="module")
def selected_rand_one_per_hwsku_hostname(request):
"""
Return the selected hostnames for the given module.
This fixture will return the list of selected dut hostnames
when another fixture like enum_rand_one_per_hwsku_hostname
or enum_rand_one_per_hwsku_frontend_hostname is used.
"""
if request.module in _hosts_per_hwsku_per_module:
return _hosts_per_hwsku_per_module[request.module]
else:
return []
@pytest.fixture(scope="module")
def rand_one_dut_portname_oper_up(request):
oper_up_ports = generate_port_lists(request, "oper_up_ports")
if len(oper_up_ports) > 1:
oper_up_ports = random.sample(oper_up_ports, 1)
return oper_up_ports[0]
@pytest.fixture(scope="module")
def rand_one_dut_lossless_prio(request):
lossless_prio_list = generate_priority_lists(request, 'lossless')
if len(lossless_prio_list) > 1:
lossless_prio_list = random.sample(lossless_prio_list, 1)
return lossless_prio_list[0]
@pytest.fixture(scope="module", autouse=True)
def reset_critical_services_list(duthosts):
"""
Resets the critical services list between test modules to ensure that it is
left in a known state after tests finish running.
"""
[a_dut.critical_services_tracking_list() for a_dut in duthosts]
@pytest.fixture(scope="session")
def localhost(ansible_adhoc):
return Localhost(ansible_adhoc)
@pytest.fixture(scope="session")
def ptfhost(enhance_inventory, ansible_adhoc, tbinfo, duthost, request):
if 'ptp' in tbinfo['topo']['name']:
return None
if "ptf_image_name" in tbinfo and "docker-keysight-api-server" in tbinfo["ptf_image_name"]:
return None
if "ptf" in tbinfo:
return PTFHost(ansible_adhoc, tbinfo["ptf"], duthost, tbinfo,
macsec_enabled=request.config.option.enable_macsec)
else:
# when no ptf defined in testbed.csv
# try to parse it from inventory
ptf_host = duthost.host.options["inventory_manager"].get_host(duthost.hostname).get_vars()["ptf_host"]
return PTFHost(ansible_adhoc, ptf_host, duthost, tbinfo, macsec_enabled=request.config.option.enable_macsec)
@pytest.fixture(scope="module")
def k8smasters(enhance_inventory, ansible_adhoc, request):
"""
Shortcut fixture for getting Kubernetes master hosts
"""
k8s_master_ansible_group = request.config.getoption("--kube_master")
master_vms = {}
inv_files = request.config.getoption("ansible_inventory")
k8s_inv_file = None
for inv_file in inv_files:
if "k8s" in inv_file:
k8s_inv_file = inv_file
if not k8s_inv_file:
pytest.skip("k8s inventory not found, skipping tests")
with open('../ansible/{}'.format(k8s_inv_file), 'r') as kinv:
k8sinventory = yaml.safe_load(kinv)
for hostname, attributes in list(k8sinventory[k8s_master_ansible_group]['hosts'].items()):
if 'haproxy' in attributes:
is_haproxy = True
else:
is_haproxy = False
master_vms[hostname] = {'host': K8sMasterHost(ansible_adhoc,
hostname,
is_haproxy)}
return master_vms
@pytest.fixture(scope="module")
def k8scluster(k8smasters):
k8s_master_cluster = K8sMasterCluster(k8smasters)
return k8s_master_cluster
@pytest.fixture(scope="session")
def nbrhosts(enhance_inventory, ansible_adhoc, tbinfo, creds, request):
"""
Shortcut fixture for getting VM host
"""
logger.info("Fixture nbrhosts started")
devices = {}
if (not tbinfo['vm_base'] and 'tgen' in tbinfo['topo']['name']) or 'ptf' in tbinfo['topo']['name']:
logger.info("No VMs exist for this topology: {}".format(tbinfo['topo']['name']))
return devices
vm_base = int(tbinfo['vm_base'][2:])
vm_name_fmt = 'VM%0{}d'.format(len(tbinfo['vm_base']) - 2)
neighbor_type = request.config.getoption("--neighbor_type")
if 'VMs' not in tbinfo['topo']['properties']['topology']:
logger.info("No VMs exist for this topology: {}".format(tbinfo['topo']['properties']['topology']))
return devices
def initial_neighbor(neighbor_name, vm_name):
logger.info(f"nbrhosts started: {neighbor_name}_{vm_name}")
if neighbor_type == "eos":
device = NeighborDevice(
{
'host': EosHost(
ansible_adhoc,
vm_name,
creds['eos_login'],
creds['eos_password'],
shell_user=creds['eos_root_user'] if 'eos_root_user' in creds else None,
shell_passwd=creds['eos_root_password'] if 'eos_root_password' in creds else None
),
'conf': tbinfo['topo']['properties']['configuration'][neighbor_name]
}
)
elif neighbor_type == "sonic":
device = NeighborDevice(
{
'host': SonicHost(
ansible_adhoc,
vm_name,
ssh_user=creds['sonic_login'] if 'sonic_login' in creds else None,
ssh_passwd=creds['sonic_password'] if 'sonic_password' in creds else None
),
'conf': tbinfo['topo']['properties']['configuration'][neighbor_name]
}
)
elif neighbor_type == "cisco":
device = NeighborDevice(
{
'host': CiscoHost(
ansible_adhoc,
vm_name,
creds['cisco_login'],
creds['cisco_password'],
),
'conf': tbinfo['topo']['properties']['configuration'][neighbor_name]
}
)
else:
raise ValueError("Unknown neighbor type %s" % (neighbor_type,))
devices[neighbor_name] = device
logger.info(f"nbrhosts finished: {neighbor_name}_{vm_name}")
executor = concurrent.futures.ThreadPoolExecutor(max_workers=8)
futures = []
for neighbor_name, neighbor in list(tbinfo['topo']['properties']['topology']['VMs'].items()):
vm_name = vm_name_fmt % (vm_base + neighbor['vm_offset'])
futures.append(executor.submit(initial_neighbor, neighbor_name, vm_name))
for future in as_completed(futures):
# if exception caught in the sub-thread, .result() will raise it in the main thread
_ = future.result()
executor.shutdown(wait=True)
logger.info("Fixture nbrhosts finished")
return devices
@pytest.fixture(scope="module")
def fanouthosts(enhance_inventory, ansible_adhoc, conn_graph_facts, creds, duthosts): # noqa F811
"""
Shortcut fixture for getting Fanout hosts
"""
dev_conn = conn_graph_facts.get('device_conn', {})
fanout_hosts = {}
# WA for virtual testbed which has no fanout
for dut_host, value in list(dev_conn.items()):
duthost = duthosts[dut_host]
if duthost.facts['platform'] == 'x86_64-kvm_x86_64-r0':
continue # skip for kvm platform which has no fanout
mg_facts = duthost.minigraph_facts(host=duthost.hostname)['ansible_facts']
for dut_port in list(value.keys()):
fanout_rec = value[dut_port]
fanout_host = str(fanout_rec['peerdevice'])
fanout_port = str(fanout_rec['peerport'])
if fanout_host in list(fanout_hosts.keys()):
fanout = fanout_hosts[fanout_host]
else:
host_vars = ansible_adhoc().options[
'inventory_manager'].get_host(fanout_host).vars
os_type = host_vars.get('os', 'eos')
if 'fanout_tacacs_user' in creds:
fanout_user = creds['fanout_tacacs_user']
fanout_password = creds['fanout_tacacs_password']
elif 'fanout_tacacs_{}_user'.format(os_type) in creds:
fanout_user = creds['fanout_tacacs_{}_user'.format(os_type)]
fanout_password = creds['fanout_tacacs_{}_password'.format(os_type)]
elif os_type == 'sonic':
fanout_user = creds.get('fanout_sonic_user', None)
fanout_password = creds.get('fanout_sonic_password', None)
elif os_type == 'eos':
fanout_user = creds.get('fanout_network_user', None)
fanout_password = creds.get('fanout_network_password', None)
elif os_type == 'onyx':
fanout_user = creds.get('fanout_mlnx_user', None)
fanout_password = creds.get('fanout_mlnx_password', None)
elif os_type == 'ixia':
# Skip for ixia device which has no fanout
continue
else:
# when os is mellanox, not supported
pytest.fail("os other than sonic and eos not supported")
eos_shell_user = None
eos_shell_password = None
if os_type == "eos":
admin_user = creds['fanout_admin_user']
admin_password = creds['fanout_admin_password']
eos_shell_user = creds.get('fanout_shell_user', admin_user)
eos_shell_password = creds.get('fanout_shell_password', admin_password)
fanout = FanoutHost(ansible_adhoc,
os_type,
fanout_host,
'FanoutLeaf',
fanout_user,
fanout_password,
eos_shell_user=eos_shell_user,
eos_shell_passwd=eos_shell_password)
fanout.dut_hostnames = [dut_host]
fanout_hosts[fanout_host] = fanout
if fanout.os == 'sonic':
ifs_status = fanout.host.get_interfaces_status()
for key, interface_info in list(ifs_status.items()):
fanout.fanout_port_alias_to_name[interface_info['alias']] = interface_info['interface']
logging.info("fanout {} fanout_port_alias_to_name {}"
.format(fanout_host, fanout.fanout_port_alias_to_name))
fanout.add_port_map(encode_dut_port_name(dut_host, dut_port), fanout_port)
# Add port name to fanout port mapping port if dut_port is alias.
if dut_port in mg_facts['minigraph_port_alias_to_name_map']:
mapped_port = mg_facts['minigraph_port_alias_to_name_map'][dut_port]
# only add the mapped port which isn't in device_conn ports to avoid overwriting port map wrongly,
# it happens when an interface has the same name with another alias, for example:
# Interface Alias
# --------------------
# Ethernet108 Ethernet32
# Ethernet32 Ethernet13/1
if mapped_port not in list(value.keys()):
fanout.add_port_map(encode_dut_port_name(dut_host, mapped_port), fanout_port)
if dut_host not in fanout.dut_hostnames:
fanout.dut_hostnames.append(dut_host)
return fanout_hosts
@pytest.fixture(scope="session")
def vmhost(enhance_inventory, ansible_adhoc, request, tbinfo):
if 'ptp' in tbinfo['topo']['name']:
return None
server = tbinfo["server"]
inv_files = get_inventory_files(request)
vmhost = get_test_server_host(inv_files, server)
return VMHost(ansible_adhoc, vmhost.name)
@pytest.fixture(scope='session')
def eos():
""" read and yield eos configuration """
with open('eos/eos.yml') as stream:
eos = yaml.safe_load(stream)
return eos
@pytest.fixture(scope='session')
def sonic():
""" read and yield sonic configuration """
with open('sonic/sonic.yml') as stream:
eos = yaml.safe_load(stream)
return eos
@pytest.fixture(scope='session')
def pdu():
""" read and yield pdu configuration """
with open('../ansible/group_vars/pdu/pdu.yml') as stream:
pdu = yaml.safe_load(stream)
return pdu
def creds_on_dut(duthost):
""" read credential information according to the dut inventory """
groups = duthost.host.options['inventory_manager'].get_host(duthost.hostname).get_vars()['group_names']
groups.append("fanout")
logger.info("dut {} belongs to groups {}".format(duthost.hostname, groups))
exclude_regex_patterns = [
r'topo_.*\.yml',
r'breakout_speed\.yml',
r'lag_fanout_ports_test_vars\.yml',
r'qos\.yml',
r'sku-sensors-data\.yml',
r'mux_simulator_http_port_map\.yml'
]
files = glob.glob("../ansible/group_vars/all/*.yml")
files += glob.glob("../ansible/vars/*.yml")
for group in groups:
files += glob.glob("../ansible/group_vars/{}/*.yml".format(group))
filtered_files = [
f for f in files if not re.search('|'.join(exclude_regex_patterns), f)
]
creds = {}
for f in filtered_files:
with open(f) as stream:
v = yaml.safe_load(stream)
if v is not None:
creds.update(v)
else:
logging.info("skip empty var file {}".format(f))
cred_vars = [
"sonicadmin_user",
"sonicadmin_password",
"docker_registry_host",
"docker_registry_username",
"docker_registry_password",
"public_docker_registry_host"
]
hostvars = duthost.host.options['variable_manager']._hostvars[duthost.hostname]
for cred_var in cred_vars:
if cred_var in creds:
creds[cred_var] = jinja2.Template(creds[cred_var]).render(**hostvars)
# load creds for console
if "console_login" not in list(hostvars.keys()):
console_login_creds = {}
else:
console_login_creds = hostvars["console_login"]
creds["console_user"] = {}
creds["console_password"] = {}
creds["ansible_altpasswords"] = []
# If ansible_altpasswords is empty, add ansible_altpassword to it
if len(creds["ansible_altpasswords"]) == 0:
creds["ansible_altpasswords"].append(hostvars["ansible_altpassword"])
passwords = creds["ansible_altpasswords"] + [creds["sonicadmin_password"]]
creds['sonicadmin_password'] = get_dut_current_passwd(
duthost.mgmt_ip,
duthost.mgmt_ipv6,
creds['sonicadmin_user'],
passwords
)
for k, v in list(console_login_creds.items()):
creds["console_user"][k] = v["user"]
creds["console_password"][k] = v["passwd"]
return creds
@pytest.fixture(scope="session")
def creds(duthost):
return creds_on_dut(duthost)
@pytest.fixture(scope='module')
def creds_all_duts(duthosts):
creds_all_duts = dict()
for duthost in duthosts.nodes:
creds_all_duts[duthost.hostname] = creds_on_dut(duthost)