-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathtest_nmci.py
executable file
·2167 lines (1768 loc) · 64.1 KB
/
test_nmci.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 python3l
import datetime
import filecmp
import glob
import os
import pytest
import random
import re
import shutil
import socket
import subprocess
import sys
import tempfile
import time
import warnings
import nmci
def rnd_bool():
return random.random() > 0.5
###############################################################################
class Stub:
def __init__(self, obj, attr, value):
self.value = value
self.obj = obj
self.attr = attr
def __enter__(self):
try:
self.cached = getattr(self.obj, self.attr)
except Exception:
self.has = False
setattr(self.obj, self.attr, self.value)
def __exit__(self, type, value, traceback):
if hasattr(self, "cached"):
setattr(self.obj, self.attr, self.cached)
else:
delattr(self.obj, self.attr)
def __call__(self, func):
# Stub is a context manager, so we can use it with
# "with". But it's also callable, so we can use it as
# function decorator.
def f():
with self:
func()
return f
@staticmethod
def misc_nm_version_detect(version):
return Stub(nmci.misc, "_nm_version_detect_cached", version)
@staticmethod
def misc_distro_detect(version):
return Stub(nmci.misc, "_distro_detect_cached", version)
###############################################################################
def create_test_context():
class ContextTest:
def __init__(self):
import xml.etree.ElementTree as ET
class Formatter:
pass
formatter = Formatter()
formatter.name = "html"
formatter.embedding = None
formatter.actual = {
"act_step_embed_span": ET.SubElement(ET.Element("foo"), "span"),
}
formatter._doEmbed = lambda span, mime_type, data, caption: None
class Runner:
pass
self._runner = Runner()
self._runner.formatters = [formatter]
context = ContextTest()
nmci.cext.setup(context)
nmci.embed._to_embed = []
nmci.cleanup._cleanup_lst = []
return context
###############################################################################
def test_stub1():
v = ("fedora", [35])
assert not hasattr(nmci.misc, "_distro_detect_cached")
with Stub.misc_distro_detect(v):
assert nmci.misc._distro_detect_cached is v
assert nmci.misc.distro_detect() is v
assert not hasattr(nmci.misc, "_distro_detect_cached")
v = ("upstream", [1, 39, 3, 30276])
assert not hasattr(nmci.misc, "_nm_version_detect_cached")
with Stub.misc_nm_version_detect(v):
assert nmci.misc._nm_version_detect_cached is v
assert nmci.misc.nm_version_detect() is v
assert not hasattr(nmci.misc, "_nm_version_detect_cached")
@Stub.misc_distro_detect(("fedora", [35]))
def test_stub2():
v = ("fedora", [35])
assert nmci.misc._distro_detect_cached == v
assert nmci.misc.distro_detect() == v
@Stub.misc_nm_version_detect(("upstream", [1, 39, 3, 30276]))
def test_stub3():
v = ("upstream", [1, 39, 3, 30276])
assert nmci.misc._nm_version_detect_cached == v
assert nmci.misc.nm_version_detect() == v
###############################################################################
def test_util_compare_strv_list():
nmci.util.compare_strv_list([], [])
with pytest.raises(ValueError):
nmci.util.compare_strv_list(["a"], [])
nmci.util.compare_strv_list(["a"], ["a"], ignore_order=True)
nmci.util.compare_strv_list(["a"], ["a"])
nmci.util.compare_strv_list(["a"], ["a", "b"])
with pytest.raises(ValueError):
nmci.util.compare_strv_list(["a"], ["a", "b"], ignore_extra_strv=False)
nmci.util.compare_strv_list(["a", "b"], ["a", "b"])
nmci.util.compare_strv_list(["a", "b"], ["b", "a"])
with pytest.raises(ValueError):
nmci.util.compare_strv_list(["a", "b"], ["b", "a"], ignore_order=False)
nmci.util.compare_strv_list(["/^a", "/b"], ["a", "ab"])
with pytest.raises(ValueError):
nmci.util.compare_strv_list(["/^a", "b"], ["a", "ab"], match_mode="plain")
nmci.util.compare_strv_list(
["b", "."], ["a", "b"], match_mode="regex", ignore_order=True
)
with pytest.raises(ValueError):
nmci.util.compare_strv_list(
["b", "."], ["a", "b"], match_mode="regex", ignore_order=False
)
nmci.util.compare_strv_list(
["b", "[ac]", "[ac]"], ["a", "b", "c"], match_mode="regex", ignore_order=True
)
with pytest.raises(ValueError):
nmci.util.compare_strv_list(
["b", "[ac]", "[ac]"],
["a", "b", "c"],
match_mode="regex",
ignore_order=False,
)
nmci.util.compare_strv_list(["?a"], [], ignore_order=True)
nmci.util.compare_strv_list(["?a"], ["a"], ignore_order=True)
nmci.util.compare_strv_list(["?/a", "aa"], ["aa", ""])
def test_util_compare_strv_list_rnd():
def rnd_match_mode():
if random.random() < 1.0 / 3:
return "plain"
if random.random() < 2.0 / 3:
return "regex"
return "auto"
strv_full = [(chr(c + 97) + "a") for c in range(26)]
for n_rand in range(100):
strv_len = random.randint(0, len(strv_full))
if rnd_bool():
strv = strv_full[:strv_len]
else:
strv = random.choices(strv_full, k=strv_len)
expected_len = random.randint(0, len(strv))
expected = strv[:expected_len]
random.shuffle(expected)
has_extra_strv = [s for s in strv if (s not in expected)]
has_same_order = [s for s in strv if (s in expected)] == expected
expected_regex = []
for e in expected:
r = random.random()
if r < 0.02:
e = ".*"
elif r < 0.04:
e = "a"
elif r < 0.06:
e = f"[{e[0]}a]"
expected_regex.append(e)
nmci.util.compare_strv_list(
expected=expected,
strv=strv,
match_mode=rnd_match_mode(),
ignore_extra_strv=(has_extra_strv or rnd_bool()),
ignore_order=(not has_same_order or rnd_bool()),
)
nmci.util.compare_strv_list(
expected=expected_regex,
strv=strv,
match_mode="regex",
ignore_extra_strv=(has_extra_strv or rnd_bool()),
ignore_order=(not has_same_order or rnd_bool()),
)
if has_extra_strv:
with pytest.raises(ValueError):
nmci.util.compare_strv_list(
expected=expected,
strv=strv,
match_mode=rnd_match_mode(),
ignore_extra_strv=False,
ignore_order=True,
)
if has_same_order:
nmci.util.compare_strv_list(
expected=expected,
strv=strv,
match_mode=rnd_match_mode(),
ignore_extra_strv=has_extra_strv or rnd_bool(),
ignore_order=False,
)
def test_misc_test_version_tag_eval():
def _assert_ver(ver_tags, *versions):
SATISFIED = {True: "satisfied", False: "unsatisfied"}
def _ver_parse(version):
assert re.match("^[0-9.]+$", version)
return [int(x) for x in version.split(".")]
def _ver_parse_tag(version):
if version.startswith("+=") or version.startswith("-="):
op = version[:2]
elif version.startswith("+") or version.startswith("-"):
op = version[:1]
else:
raise Exception(
f'Invalid version tag "{version}" (does not start with +/-/+=/-=)'
)
return op, _ver_parse(version[len(op) :])
def _ver_parse_check(version):
if (
version.endswith("+-")
or version.endswith("-+")
or version.endswith("++")
or version.endswith("--")
):
op, version = version[-2:], version[: len(version) - 2]
else:
raise Exception(
f'Invalid check version "{version}" (does not end with +-/-+/++/--)'
)
return op, _ver_parse(version)
def _invert_op(op):
if op == "+=":
return "-"
if op == "+":
return "-="
if op == "-":
return "+="
assert op == "-="
return "+"
ver_tags_parsed = [_ver_parse_tag(v) for v in ver_tags.split(" ") if v]
versions_parsed = [_ver_parse_check(v) for v in versions]
ver_tags_invert = [(_invert_op(op), ver) for op, ver in ver_tags_parsed]
for check_op, version in versions_parsed:
r = nmci.misc.test_version_tag_eval(ver_tags_parsed, version)
assert r is True or r is False
expected = check_op[0] == "+"
if expected != r:
pytest.fail(
f'Version "{version}" is wrongly {SATISFIED[r]} for "{ver_tags}"'
)
r = nmci.misc.test_version_tag_eval(ver_tags_invert, version)
assert r is True or r is False
expected = check_op[1] == "+"
if expected != r:
pytest.fail(
f'Version "{version}" is wrongly {SATISFIED[r]} for inverted version "{ver_tags}"'
)
_assert_ver(
"+=1.26",
"1.25.0-+",
"1.25.6-+",
"1.26.0+-",
"1.26.5+-",
"1.28.5+-",
)
_assert_ver(
"+1.26",
"1.25.0-+",
"1.25.6-+",
"1.26.0-+",
"1.26.5-+",
"1.28.5+-",
)
_assert_ver(
"-=1.26",
"1.25.0+-",
"1.25.6+-",
"1.26.0+-",
"1.26.5+-",
"1.28.5-+",
)
_assert_ver(
"-1.26",
"1.25.0+-",
"1.25.6+-",
"1.26.0-+",
"1.26.5-+",
"1.28.5-+",
)
_assert_ver(
"+=1.26.0",
"1.25.0-+",
"1.25.6-+",
"1.26.0+-",
"1.26.5+-",
"1.28.5+-",
)
_assert_ver(
"+1.26.0",
"1.25.0-+",
"1.25.6-+",
"1.26.0-+",
"1.26.5+-",
"1.28.5+-",
)
_assert_ver(
"-=1.26.0",
"1.25.0+-",
"1.25.6+-",
"1.26.0+-",
"1.26.5-+",
"1.28.5-+",
)
_assert_ver(
"-1.26.0",
"1.25.0+-",
"1.25.6+-",
"1.26.0-+",
"1.26.5-+",
"1.28.5-+",
)
_assert_ver(
"+=1.26.2",
"1.25.0-+",
"1.25.6-+",
"1.26.0-+",
"1.26.2+-",
"1.26.5+-",
"1.28.5+-",
)
_assert_ver(
"+1.26.2",
"1.25.0-+",
"1.25.6-+",
"1.26.0-+",
"1.26.2-+",
"1.26.5+-",
"1.28.5+-",
)
_assert_ver(
"-=1.26.2",
"1.25.0+-",
"1.25.6+-",
"1.26.0+-",
"1.26.2+-",
"1.26.5-+",
"1.28.5-+",
)
_assert_ver(
"-1.26.2",
"1.25.0+-",
"1.25.6+-",
"1.26.0+-",
"1.26.2-+",
"1.26.5-+",
"1.28.5-+",
)
_assert_ver(
"+1.26.2 +1.27",
"1.25.0-+",
"1.25.6-+",
"1.26.0-+",
"1.26.2-+",
"1.26.5+-",
"1.28.5+-",
)
_assert_ver(
"+=1.26.8 +=1.28.6 +=1.29.4",
"1.28.5-+",
"1.28.8+-",
)
_assert_ver(
"+=1.26.8 +=1.28",
"1.28.5+-",
"1.29.0+-",
"1.28.4+-",
"1.28.5+-",
"1.29.0+-",
)
_assert_ver(
"+=1.26.8 +1.28",
"1.28.5-+",
"1.28.2-+",
"1.28.4-+",
)
# the following is a special case during release candidate phase.
# Imagine a fix/feature gets added to (before) 1.29.3.and also
# backported to nm-1-28 branch. At that time.1.28.0 is not yet released,
# but nm-1-28 is after 1.27.90 and the backport happens (before) 1.27.90.
_assert_ver(
"+=1.26.5 +=1.27.91 +=1.28.0 +=1.29.2",
"1.26.0-+",
"1.26.4-+",
"1.26.5+-",
"1.26.6+-",
"1.27.0-+",
"1.27.90-+",
"1.27.91+-",
"1.27.92+-",
"1.27.99+-",
"1.28.0+-",
"1.28.1+-",
"1.28.2+-",
"1.28.99+-",
"1.29.0-+",
"1.29.1-+",
"1.29.2+-",
"1.29.3+-",
"1.29.99+-",
"1.30.0+-",
"1.30.2+-",
)
# Now the inverse...
_assert_ver(
"-1.26.5 -1.27.91 -1.28.0 -1.29.2",
"1.26.0+-",
"1.26.4+-",
"1.26.5-+",
"1.26.6-+",
"1.27.0+-",
"1.27.90+-",
"1.27.91-+",
"1.27.92-+",
"1.27.99-+",
"1.28.0-+",
"1.28.1-+",
"1.28.2-+",
"1.28.99-+",
"1.29.0+-",
"1.29.1+-",
"1.29.2-+",
"1.29.3-+",
"1.29.99-+",
"1.30.0-+",
"1.30.2-+",
)
# check all subintervals in mixed ranges: +++1.26.5---1.27.91+++1.28.0---1.29.2+++++
# _assert_ver also check inverted intervals
_assert_ver(
"-1.26.5 +1.27.91 -1.28.0 +=1.29.2",
"1.24.2+-",
"1.26.0+-",
"1.26.2+-",
"1.26.5-+",
"1.26.8-+",
"1.27.0-+",
"1.27.91-+",
"1.27.99+-",
"1.28.0-+",
"1.28.2-+",
"1.29.0-+",
"1.29.2+-",
"1.30.2+-",
)
_assert_ver(
"+=1.26.5 -=1.27.91 +=1.28.0 -1.29.2",
"1.24.2-+",
"1.26.0-+",
"1.26.2-+",
"1.26.5+-",
"1.26.8+-",
"1.27.0+-",
"1.27.91+-",
"1.27.99-+",
"1.28.0+-",
"1.28.2+-",
"1.29.0+-",
"1.29.2-+",
"1.30.2-+",
)
# Check mixed intervals with large holes and overlaping intervals
_assert_ver(
"+=1.26.5 +=1.28.4 -=1.34.2 -=1.36.2 +=1.40",
"1.20.1-+",
"1.26.1-+",
"1.26.5+-",
"1.26.6+-",
"1.27.0++",
"1.27.4++",
"1.28.1-+",
"1.28.4+-",
"1.28.6+-",
"1.30.0+-",
"1.34.0+-",
"1.34.2+-",
"1.34.3-+",
"1.35.0++",
"1.35.3++",
"1.36.0+-",
"1.36.1+-",
"1.36.2+-",
"1.36.3-+",
"1.38.0-+",
"1.39.5-+",
"1.40.0+-",
"1.40.5+-",
"1.50.5+-",
)
# and inverted tags
_assert_ver(
"-1.26.5 -1.28.4 +1.34.2 +1.36.2 -1.40",
"1.20.1+-",
"1.26.1+-",
"1.26.5-+",
"1.26.6-+",
"1.27.0++",
"1.27.4++",
"1.28.1+-",
"1.28.4-+",
"1.28.6-+",
"1.30.0-+",
"1.34.0-+",
"1.34.2-+",
"1.34.3+-",
"1.35.0++",
"1.35.3++",
"1.36.0-+",
"1.36.1-+",
"1.36.2-+",
"1.36.3+-",
"1.38.0+-",
"1.39.5+-",
"1.40.0-+",
"1.40.5-+",
"1.50.5-+",
)
# Fix in the same release multiple times
_assert_ver(
"+=1.20.2 -1.20.5 +1.20.7 -1.20.10",
"1.2.1-+",
"1.20.1-+",
"1.20.10-+",
"1.20.16-+",
"1.20.2+-",
"1.20.3+-",
"1.20.4+-",
"1.20.5-+",
"1.20.6-+",
"1.20.7-+",
"1.20.8+-",
"1.20.9+-",
"1.30.4-+",
)
_assert_ver(
"-1.20.2 +=1.20.5 -=1.20.7 +=1.20.10",
"1.2.1+-",
"1.20.0+-",
"1.20.1+-",
"1.20.10+-",
"1.20.16+-",
"1.20.2-+",
"1.20.3-+",
"1.20.4-+",
"1.20.5+-",
"1.20.6+-",
"1.20.7+-",
"1.20.8-+",
"1.20.9-+",
"1.30.4+-",
)
def test_misc_nm_version_parse():
def _assert(version, expect_stream, expect_version):
assert (expect_stream, expect_version) == nmci.misc.nm_version_parse(version)
_assert("1.31.1-28009.copr.067893f8d3.fc33", "upstream", [1, 31, 1, 28009])
_assert("1.26.0-12.el8_3", "rhel-8-3", [1, 26, 0, 12])
_assert("1.26.0-12.el8", "rhel-8", [1, 26, 0, 12])
_assert("1.26.0-0.5.el8", "rhel-8", [1, 26, 0, 0, 5])
_assert("1.26.0-0.5.el8_10", "rhel-8-10", [1, 26, 0, 0, 5])
_assert("1.26.0-foo", "unknown", [1, 26, 0])
_assert("1.26.6-1.fc33", "fedora-33", [1, 26, 6, 1])
_assert("1.26.6-0.2.fc33", "fedora-33", [1, 26, 6, 0, 2])
_assert("1.31.2-28040.11545c0ca0.el8", "upstream", [1, 31, 2, 28040])
_assert("1.36.0-9.rh1000000.1.el8_6", "rhel-8-6", [1, 36, 0, 9])
_assert("1.36.0-9.rh1000000.1.el8", "rhel-8", [1, 36, 0, 9])
_assert("1.31.2-28040.11545c0ca0.el8", "upstream", [1, 31, 2, 28040])
_assert("1.36.0-9.19.rh1000000.1.el8", "rhel-8", [1, 36, 0, 9, 19])
_assert("1.36.0-10009.19.rh1000000.1.el8", "upstream", [1, 36, 0, 10009, 19])
def test_misc_test_version_tag_parse_ver():
def _assert(version_tag, expect_stream, expect_op, expect_version):
(stream, op, version) = nmci.misc.test_version_tag_parse_ver(version_tag)
assert expect_stream == stream
assert expect_op == op
assert expect_version == version
def _assert_inval(version_tag):
with pytest.raises(ValueError):
nmci.misc.test_version_tag_parse_ver(version_tag)
_assert("ver+=1", [], "+=", [1])
_assert("ver/rhel+=1", ["rhel"], "+=", [1])
_assert("ver/rhel/8+=1", ["rhel", "8"], "+=", [1])
_assert_inval("ver/rhel/8")
_assert_inval("ver/rhel/8/+=1")
_assert_inval("ver/rhel//8+=1")
def test_misc_test_version_tag_filter_for_stream():
def _assert(nm_stream, version_tags, expected_tags):
tags2 = [nmci.misc.test_version_tag_parse_ver(v) for v in version_tags]
tags3 = nmci.misc.test_version_tag_filter_for_stream(tags2, nm_stream)
exp2 = [nmci.misc.test_version_tag_parse(e, "") for e in expected_tags]
assert tags3 == exp2
_assert("rhel-8", ["ver+5"], ["+5"])
_assert("rhel-8", ["ver+5", "ver/rhel+6"], ["+6"])
_assert("rhel-8", ["ver+5", "ver/rhel/8+7"], ["+7"])
_assert("rhel-8", ["ver+5", "ver/rhel/7+7"], ["+5"])
def test_misc_list_to_intervals():
lst = list(range(8)) + list(range(10, 12)) + list(range(20, 30)) + [34]
lst_str = nmci.misc.list_to_intervals(lst)
assert lst_str == "0..7,10,11,20..29,34"
lst = [1]
lst_str = nmci.misc.list_to_intervals(lst)
assert lst_str == "1"
lst = [3, 4]
lst_str = nmci.misc.list_to_intervals(lst)
assert lst_str == "3,4"
lst = [3, 4, 5]
lst_str = nmci.misc.list_to_intervals(lst)
assert lst_str == "3..5"
def test_misc_format_dict():
dct = {"a": "x", "b": "y"}
dct_str = nmci.misc.format_dict(dct)
assert dct_str == "a = x, b = y"
dct_str = nmci.misc.format_dict(dct, connector=":", separator=";")
assert dct_str == "a:x;b:y"
dct = {"a": "x"}
dct_str = nmci.misc.format_dict(dct)
assert dct_str == "a = x"
dct = {}
dct_str = nmci.misc.format_dict(dct)
assert dct_str == ""
def test_misc_str_replace_dict():
dct = {"a": "x", "b": "y", "ab": "hey"}
result_str = nmci.misc.str_replace_dict("Hello <noted:a>, I am <noted:b>.", dct)
assert result_str == "Hello x, I am y."
result_str = nmci.misc.str_replace_dict(
"Hello <d:a>, I am <d:b>.", dct, dict_name="d"
)
assert result_str == "Hello x, I am y."
result_str = nmci.misc.str_replace_dict(
"Hello <d:a>, I am <x:ab>.", dct, dict_name="d"
)
assert result_str == "Hello x, I am <x:ab>."
result_str = nmci.misc.str_replace_dict(result_str, dct, dict_name="x")
assert result_str == "Hello x, I am hey."
# empty dict, nothing to replace
assert nmci.misc.str_replace_dict("do not change", {}) == "do not change"
# invalid key
with pytest.raises(AssertionError):
result_str = nmci.misc.str_replace_dict(
"Hello <d:z>, I am <d:b>.", dct, dict_name="d"
)
# unterminated sequence
with pytest.raises(AssertionError):
result_str = nmci.misc.str_replace_dict(
"Hello <d:a, I am <d:b>.", dct, dict_name="d"
)
def test_feature_tags():
from . import tags
mapper = nmci.misc.get_mapper_obj()
mapper_tests = nmci.misc.get_mapper_tests(mapper)
mapper_tests = [test["testname"] for test in mapper_tests]
unique_tags = set()
tag_registry_used = set()
all_test_tags = nmci.misc.test_load_tags_from_features("*")
def check_ver(tag):
for ver_prefix, ver_len in [
["ver", 4],
["rhelver", 2],
["fedoraver", 1],
]:
if not tag.startswith(ver_prefix):
continue
if ver_prefix == "ver":
stream, op, ver = nmci.misc.test_version_tag_parse_ver(tag)
assert type(stream) is list
assert all(
[v.isdigit() for v in stream[1:]]
), f"wrong ver tag @{tag}, example of valid z-stream tag is `@ver/rhel/8/7+=1.40`"
else:
stream = None
op, ver = nmci.misc.test_version_tag_parse(tag, ver_prefix)
assert type(op) is str
assert type(ver) is list
assert op in ["+", "+=", "-", "-="]
if ver == []:
assert op in ["+", "-"]
else:
assert ver
assert all([type(v) is int for v in ver])
assert all([v >= 0 for v in ver])
assert len(ver) <= ver_len
if ver_prefix == "ver":
assert type(stream) is list
assert tag.startswith("/".join(("ver", *stream)) + op)
else:
assert tag.startswith(ver_prefix + op)
assert tag == (
"/".join((ver_prefix, *(stream or [])))
+ op
+ ".".join(str(v) for v in ver)
)
return True
return tag in [
"rhel_pkg",
"not_with_rhel_pkg",
"fedora_pkg",
"not_with_fedora_pkg",
]
def check_bugzilla(tag):
if tag.startswith("rhbz"):
assert re.match("^rhbz[0-9]+$", tag)
return True
if tag.startswith("gnomebz"):
assert re.match("^gnomebz[0-9]+$", tag)
return True
return False
def check_jira(tag):
prefixes = ["RHEL", "RHELDOCS"]
for prefix in prefixes:
if tag.startswith(f"{prefix}-"):
assert re.fullmatch(rf"{prefix}-\d+", tag)
return True
return False
def check_registry(tag):
return tag in tags.tag_registry
def check_mapper(tag):
return tag in mapper_tests
assert check_ver("ver+=1.3")
assert check_ver("ver+=1.43.16.2000")
assert ([], "+=", [1, 3]) == nmci.misc.test_version_tag_parse_ver("ver+=1.03")
with pytest.raises(AssertionError):
assert check_ver("ver+=1.03")
with pytest.raises(AssertionError):
assert check_ver("ver+=1.43.16.2000.1")
for test_tags in all_test_tags:
assert test_tags
assert type(test_tags) is list
test_in_mapper = False
for tag in test_tags:
assert type(tag) is str
assert tag
assert re.match("^[-a-z_.A-Z0-9+=/]+$", tag)
assert re.match("^[" + nmci.misc.TEST_NAME_VALID_CHAR_SET + "]+$", tag)
assert (
test_tags.count(tag) == 1
), f'tag "{tag}" is not unique in {test_tags}'
checks = {
"is_ver": check_ver(tag),
"is_bugzilla": check_bugzilla(tag),
"is_jira": check_jira(tag),
"is_registry": check_registry(tag),
"is_mapper": check_mapper(tag),
}
test_in_mapper = test_in_mapper or checks["is_mapper"]
if checks["is_registry"]:
tag_registry_used.add(tag)
assert True in checks.values(), f'tag "{tag}" has no effect'
assert (
list(checks.values()).count(True) == 1
), f'tag "{tag}" is multipurpose: {[i[0] for i in filter(lambda j: j[1], checks.items())]}'
assert test_in_mapper, f"none of {test_tags} is in mapper"
tt = tuple(test_tags)
if tt in unique_tags:
pytest.fail(f'test_tags "{test_tags}" are duplicate')
unique_tags.add(tt)
# for tag in tags.tag_tag_registry:
# assert tag in tag_registry_used, f'tag "{tag}" is defined but never used'
def test_mapper_feature_file():
"""
Check that feature defined in mapper coresponds to .feature file name
"""
mapper = nmci.misc.get_mapper_obj()
mapper_tests = nmci.misc.get_mapper_tests(mapper)
feature_tests = {}
for test in mapper_tests:
feature = test.get("feature", None)
testname = test["testname"]
if feature is None:
continue
if feature not in feature_tests:
feature_tags = nmci.misc.test_load_tags_from_features(feature)
feature_tests[feature] = feature_tags
else:
feature_tags = feature_tests[feature]
found = False
for test_tags in feature_tags:
if testname in test_tags:
found = True
break
assert found, f"test @{testname} not defined in feature file {feature}"
def test_scen_uniqueness_in_mapper():
"""
Each test name is:
* tagged with just one mapper feature
* found in just one feature file
"""
mapper_tests = nmci.misc.get_mapper_tests(nmci.misc.get_mapper_obj())
feature_files = frozenset(nmci.misc.test_get_feature_files())
# convert mapper_tests to:
# {'test1': ['feature_a'], 'test2': ['feature_b']}
# and assert that length of every list in values is 1
tests_dict = dict()
for mapper_test in mapper_tests:
testname = mapper_test["testname"]
if "feature" not in mapper_test:
# tests that have to be manually enabled by uncommenting feature
# as of now @gsm_hub and @gsm_hub_simple
continue
feature = mapper_test["feature"]
if testname not in tests_dict:
tests_dict[testname] = {feature}
else:
tests_dict[testname].add(feature)
# test mapper uniqueness: only one feature is in set in tests_dict['testname']
for i in tests_dict:
assert len(tests_dict[i]) == 1, (
f"Expected @{i} tagged with exactly one feature, got "
# back to this when we convert featureless_tests to sth else (another tag?)
# f"""{'0' if len(tests_dict[i]) == 0 else f'{tests_dict[i]}'}"""
f"{tests_dict[i]}"
)
# test uniqueness in feature files
path_tmpl = (f"{nmci.util.base_dir('features', 'scenarios')}/", ".feature")
for i in tests_dict:
correct_feature = tests_dict[i].pop()
filtered_files = feature_files.difference(correct_feature.join(path_tmpl))
for file in filtered_files:
match = re.search(
rf"\n\s*@{i}(\s*#[^\n]*)?\n(\s*#[^\n]*\n)*\s*Scenario:",
file,
)
assert (
match is None
), f"in addition to {correct_feature}.feature, {i} was found in {file}"
def test_last_scen_tag_is_test_tag_and_correctly_tagged():
"""
Last scenario tag:
* is alone on the line (save for whitespace and comment)
* exists in mapper
* is correctly tagged with some feature in mapper, or
exists without feature (to handle tags with feature
commented out that have to be enabled manually)
* does not end with suffix "_timeout"
"""
mapper_tests = nmci.misc.get_mapper_tests(nmci.misc.get_mapper_obj())
feature_files = frozenset(nmci.misc.test_get_feature_files())
# do this before mapper_tests conversion
featureless_tests = set(i["testname"] for i in mapper_tests if "feature" not in i)
# convert to dict so we can use feature = mapper_tests[i]
mapper_tests = {i["testname"]: i["feature"] for i in mapper_tests if "feature" in i}
re_last_tag = re.compile(
r"(?P<full>\n\s*(?P<garbage_before_last_tag>[^\n#]*)@(?P<last_tag>[^#\s\n]+)(\s*#[^\n]*)?\n(\s*#[^\n]*\n)*\s*Scenario:[^\n]*\n)"
)
for file in feature_files:
assert file.endswith(
".feature"
), f"feature file {file} must end with '.feature'"
feature = os.path.basename(file)[:-8]
with open(file, "r") as f:
# returns: [{'garbage_before_last_tag': '',