-
Notifications
You must be signed in to change notification settings - Fork 145
/
Copy pathtest_utils.py
1904 lines (1626 loc) · 59.7 KB
/
test_utils.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
import datetime
import logging
import queue
import re
import shutil
import signal
import textwrap
import threading
import time
import unittest
import unittest.mock
from datetime import timedelta
from typing import Any, Optional
from unittest.mock import MagicMock
import fmf
import pytest
import tmt
import tmt.config
import tmt.log
import tmt.plugins
import tmt.steps.discover
import tmt.utils
import tmt.utils.jira
from tmt.log import Logger
from tmt.utils import (
Command,
Common,
GeneralError,
Path,
ShellScript,
StructuredFieldError,
WaitingIncompleteError,
WaitingTimedOutError,
_CommonBase,
duration_to_seconds,
filter_paths,
wait,
)
from tmt.utils.git import (
clonable_git_url,
git_add,
inject_auth_git_url,
public_git_url,
validate_git_status,
)
from tmt.utils.structured_field import StructuredField
from . import MATCH, assert_log, assert_not_log
run = Common(logger=tmt.log.Logger.create(verbose=0, debug=0, quiet=False)).run
@pytest.fixture
def local_git_repo(tmppath: Path) -> Path:
origin = tmppath / 'origin'
origin.mkdir()
run(Command('git', 'init', '-b', 'main'), cwd=origin)
run(
Command('git', 'config', '--local', 'user.email', '[email protected]'),
cwd=origin)
run(
Command('git', 'config', '--local', 'user.name', 'LZachar'),
cwd=origin)
# We need to be able to push, --bare repo is another option here however
# that would require to add separate fixture for bare repo (unusable for
# local changes)
run(
Command('git', 'config', '--local', 'receive.denyCurrentBranch', 'ignore'),
cwd=origin)
origin.joinpath('README').write_text('something to have in the repo')
run(Command('git', 'add', '-A'), cwd=origin)
run(
Command('git', 'commit', '-m', 'initial_commit'),
cwd=origin)
return origin
@pytest.fixture
def origin_and_local_git_repo(local_git_repo: Path) -> tuple[Path, Path]:
top_dir = local_git_repo.parent
fork_dir = top_dir / 'fork'
run(ShellScript(f'git clone {local_git_repo} {fork_dir}').to_shell_command(),
cwd=top_dir)
run(ShellScript('git config --local user.email [email protected]').to_shell_command(),
cwd=fork_dir)
run(ShellScript('git config --local user.name LZachar').to_shell_command(),
cwd=fork_dir)
return local_git_repo, fork_dir
@pytest.fixture
def nested_file(tmppath: Path) -> tuple[Path, Path, Path]:
top_dir = tmppath / 'top_dir'
top_dir.mkdir()
sub_dir = top_dir / 'sub_dir'
sub_dir.mkdir()
file = sub_dir / 'file.txt'
file.touch()
return top_dir, sub_dir, file
_test_public_git_url_input = [
(
'[email protected]:teemtee/tmt.git',
'https://github.com/teemtee/tmt.git'
),
(
'ssh://[email protected]/tests/bash',
'https://pkgs.devel.redhat.com/git/tests/bash',
),
(
'git+ssh://[email protected]/tests/bash',
'https://pkgs.devel.redhat.com/git/tests/bash',
),
(
'ssh://pkgs.devel.redhat.com/tests/bash',
'https://pkgs.devel.redhat.com/git/tests/bash',
),
(
'git+ssh://[email protected]/tests/shell',
'https://pkgs.fedoraproject.org/tests/shell',
),
(
'ssh://[email protected]/tests/shell',
'https://pkgs.fedoraproject.org/tests/shell',
),
(
'ssh://[email protected]/fedora-ci/metadata.git',
'https://pagure.io/fedora-ci/metadata.git',
),
(
'[email protected]:redhat/rhel/NAMESPACE/COMPONENT.git',
'https://pkgs.devel.redhat.com/git/NAMESPACE/COMPONENT.git',
),
(
'https://gitlab.com/redhat/rhel/NAMESPACE/COMPONENT',
'https://pkgs.devel.redhat.com/git/NAMESPACE/COMPONENT',
),
(
'https://gitlab.com/redhat/centos-stream/NAMESPACE/COMPONENT.git',
'https://gitlab.com/redhat/centos-stream/NAMESPACE/COMPONENT.git',
)
]
@pytest.mark.parametrize(
('original', 'expected'),
_test_public_git_url_input,
ids=[
f'{original} => {expected}' for original, expected in _test_public_git_url_input
])
def test_public_git_url(original: str, expected: str) -> None:
"""
Verify url conversion
"""
assert public_git_url(original) == expected
def test_clonable_git_url():
assert clonable_git_url('git://pkgs.devel.redhat.com/tests/bash') \
== 'https://pkgs.devel.redhat.com/git/tests/bash'
assert clonable_git_url('git+ssh://pkgs.devel.redhat.com/tests/bash') \
== 'git+ssh://pkgs.devel.redhat.com/tests/bash'
assert clonable_git_url('git://example.com') \
== 'git://example.com'
def test_inject_auth_git_url(monkeypatch) -> None:
"""
Verify injecting tokens
"""
# empty environment
monkeypatch.setattr('os.environ', {})
assert inject_auth_git_url('input_text') == 'input_text'
suffix = '_glab'
# https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html#clone-repository-using-personal-access-token
# username can be anything but cannot be an empty string
monkeypatch.setattr('os.environ', {
f'{tmt.utils.git.INJECT_CREDENTIALS_URL_PREFIX}{suffix}': 'https://gitlab.com/namespace/project',
f'{tmt.utils.git.INJECT_CREDENTIALS_VALUE_PREFIX}{suffix}': 'foo:abcdefgh',
f'{tmt.utils.git.INJECT_CREDENTIALS_VALUE_PREFIX}___': 'FAKE',
})
assert inject_auth_git_url('https://gitlab.com/namespace/project') \
== 'https://foo:[email protected]/namespace/project'
suffix = '_ghub'
# https://github.blog/2012-09-21-easier-builds-and-deployments-using-git-over-https-and-oauth/
# just token or username is used (value before @)
monkeypatch.setattr('os.environ', {
f'{tmt.utils.git.INJECT_CREDENTIALS_URL_PREFIX}{suffix}': 'https://github.com/namespace/project',
f'{tmt.utils.git.INJECT_CREDENTIALS_VALUE_PREFIX}{suffix}': 'abcdefgh',
f'{tmt.utils.git.INJECT_CREDENTIALS_VALUE_PREFIX}___': 'FAKE',
f'{tmt.utils.git.INJECT_CREDENTIALS_URL_PREFIX}{suffix}_2': 'https://github.com/other_namespace',
f'{tmt.utils.git.INJECT_CREDENTIALS_VALUE_PREFIX}{suffix}_2': 'xyzabcde',
f'{tmt.utils.git.INJECT_CREDENTIALS_URL_PREFIX}{suffix}_3': 'https://example.com/broken',
})
assert inject_auth_git_url('https://github.com/namespace/project') \
== 'https://[email protected]/namespace/project'
assert inject_auth_git_url('https://github.com/other_namespace/project') \
== 'https://[email protected]/other_namespace/project'
with pytest.raises(tmt.utils.GitUrlError):
inject_auth_git_url('https://example.com/broken/something')
def test_workdir_env_var(tmppath: Path, monkeypatch, root_logger):
"""
Test TMT_WORKDIR_ROOT environment variable
"""
# Cannot use monkeypatch.context() as it is not present for CentOS Stream 8
monkeypatch.setenv('TMT_WORKDIR_ROOT', str(tmppath))
common = Common(logger=root_logger)
common._workdir_init()
monkeypatch.delenv('TMT_WORKDIR_ROOT')
assert common.workdir == tmppath / 'run-001'
def test_workdir_root_full(tmppath, monkeypatch, root_logger):
"""
Raise if all ids lower than WORKDIR_MAX are exceeded
"""
monkeypatch.setenv('TMT_WORKDIR_ROOT', str(tmppath))
monkeypatch.setattr(tmt.utils, 'WORKDIR_MAX', 1)
possible_workdir = tmppath / 'run-001'
# First call success
common1 = Common(logger=root_logger)
common1._workdir_init()
assert common1.workdir.resolve() == possible_workdir.resolve()
# Second call has no id to try
with pytest.raises(GeneralError):
Common(logger=root_logger)._workdir_init()
# Removed run-001 should be used again
common1._workdir_cleanup(common1.workdir)
assert not possible_workdir.exists()
common2 = Common(logger=root_logger)
common2._workdir_init()
assert common2.workdir.resolve() == possible_workdir.resolve()
def test_workdir_root_race(tmppath, monkeypatch, root_logger):
"""
Avoid race in workdir creation
"""
monkeypatch.setattr(tmt.utils, 'WORKDIR_ROOT', tmppath)
results = queue.Queue()
threads = []
def create_workdir():
try:
common = Common(logger=root_logger)
common._workdir_init()
results.put(common.workdir)
except Exception as err:
results.put(err)
total = 30
for _ in range(total):
threads.append(threading.Thread(target=create_workdir))
for t in threads:
t.start()
for t in threads:
t.join()
all_good = True
unique_workdirs = set()
for _ in threads:
value = results.get()
if isinstance(value, Path):
unique_workdirs.add(value)
else:
# None or Exception: Record to the log and fail test
print(value)
all_good = False
assert all_good, "No exception raised"
assert len(unique_workdirs) == total, "Each workdir is unique"
def test_duration_to_seconds():
"""
Check conversion from extended sleep time format to seconds
"""
assert duration_to_seconds(5) == 5
assert duration_to_seconds('5') == 5
assert duration_to_seconds('5s') == 5
assert duration_to_seconds('5m') == 300
assert duration_to_seconds('5h') == 18000
assert duration_to_seconds('5d') == 432000
assert duration_to_seconds('5d') == 432000
# `man sleep` says: Given two or more arguments, pause for the amount of time
# specified by the sum of their values.
assert duration_to_seconds('1s 2s') == 3
assert duration_to_seconds('1h 2 3m') == 3600 + 2 + 180
# Divergence from 'sleep' as that expects space separated arguments
assert duration_to_seconds('1s2s') == 3
assert duration_to_seconds('1 m2 m') == 180
# Allow multiply but sum first, then multiply: (60+4) * (2+3)
assert duration_to_seconds('*2 1m *3 4') == 384
assert duration_to_seconds('*2 *3 1m4') == 384
# Round up
assert duration_to_seconds('1s *3.3') == 4
# Value might be just the multiplication
# without the default it thus equals zero
assert duration_to_seconds('*2') == 0
# however the supplied "default" can be used: (1m * 2)
assert duration_to_seconds('*2', injected_default="1m") == 120
@pytest.mark.parametrize("duration", [
'*10m',
'**10',
'10w',
'1sm',
'*10m 3',
'3 *10m',
'1 1ss 5',
'bad',
])
def test_duration_to_seconds_invalid(duration):
"""
Catch invalid input duration string
"""
with pytest.raises(tmt.utils.SpecificationError):
duration_to_seconds(duration)
class TestStructuredField(unittest.TestCase):
"""
Self Test
"""
def setUp(self):
self.header = "This is a header.\n"
self.footer = "This is a footer.\n"
self.start = (
"[structured-field-start]\n"
"This is StructuredField version 1. "
"Please, edit with care.\n")
self.end = "[structured-field-end]\n"
self.zeroend = "[end]\n"
self.one = "[one]\n1\n"
self.two = "[two]\n2\n"
self.three = "[three]\n3\n"
self.sections = "\n".join([self.one, self.two, self.three])
def test_everything(self):
"""
Everything
"""
# Version 0
text0 = "\n".join([
self.header,
self.sections, self.zeroend,
self.footer])
inited0 = StructuredField(text0, version=0)
loaded0 = StructuredField()
loaded0.load(text0, version=0)
assert inited0.save() == text0
assert loaded0.save() == text0
# Version 1
text1 = "\n".join([
self.header,
self.start, self.sections, self.end,
self.footer])
inited1 = StructuredField(text1)
loaded1 = StructuredField()
loaded1.load(text1)
assert inited1.save() == text1
assert loaded1.save() == text1
# Common checks
for field in [inited0, loaded0, inited1, loaded1]:
assert field.header() == self.header
assert field.footer() == self.footer
assert field.sections() == ['one', 'two', 'three']
assert field.get('one') == '1\n'
assert field.get('two') == '2\n'
assert field.get('three') == '3\n'
def test_no_header(self):
"""
No header
"""
# Version 0
text0 = "\n".join([self.sections, self.zeroend, self.footer])
field0 = StructuredField(text0, version=0)
assert field0.save() == text0
# Version 1
text1 = "\n".join(
[self.start, self.sections, self.end, self.footer])
field1 = StructuredField(text1)
assert field1.save() == text1
# Common checks
for field in [field0, field1]:
assert field.header() == ''
assert field.footer() == self.footer
assert field.get('one') == '1\n'
assert field.get('two') == '2\n'
assert field.get('three') == '3\n'
def test_no_footer(self):
"""
No footer
"""
# Version 0
text0 = "\n".join([self.header, self.sections, self.zeroend])
field0 = StructuredField(text0, version=0)
assert field0.save() == text0
# Version 1
text1 = "\n".join(
[self.header, self.start, self.sections, self.end])
field1 = StructuredField(text1)
assert field1.save() == text1
# Common checks
for field in [field0, field1]:
assert field.header() == self.header
assert field.footer() == ''
assert field.get('one') == '1\n'
assert field.get('two') == '2\n'
assert field.get('three') == '3\n'
def test_just_sections(self):
"""
Just sections
"""
# Version 0
text0 = "\n".join([self.sections, self.zeroend])
field0 = StructuredField(text0, version=0)
assert field0.save() == text0
# Version 1
text1 = "\n".join([self.start, self.sections, self.end])
field1 = StructuredField(text1)
assert field1.save() == text1
# Common checks
for field in [field0, field1]:
assert field.header() == ''
assert field.footer() == ''
assert field.get('one') == '1\n'
assert field.get('two') == '2\n'
assert field.get('three') == '3\n'
def test_plain_text(self):
"""
Plain text
"""
text = "Some plain text.\n"
field0 = StructuredField(text, version=0)
field1 = StructuredField(text)
for field in [field0, field1]:
assert field.header() == text
assert field.footer() == ''
assert field.save() == text
assert list(field) == []
assert bool(field) is False
def test_missing_end_tag(self):
"""
Missing end tag
"""
text = "\n".join([self.header, self.sections, self.footer])
pytest.raises(StructuredFieldError, StructuredField, text, 0)
def test_broken_field(self):
"""
Broken field
"""
text = "[structured-field-start]"
pytest.raises(StructuredFieldError, StructuredField, text)
def test_set_content(self):
"""
Set section content
"""
field0 = StructuredField(version=0)
field1 = StructuredField()
for field in [field0, field1]:
field.set("one", "1")
assert field.get('one') == '1\n'
field.set("two", "2")
assert field.get('two') == '2\n'
field.set("three", "3")
assert field.get('three') == '3\n'
assert field0.save() == '\n'.join([self.sections, self.zeroend])
assert field1.save() == '\n'.join([self.start, self.sections, self.end])
def test_remove_section(self):
"""
Remove section
"""
field0 = StructuredField(
"\n".join([self.sections, self.zeroend]), version=0)
field1 = StructuredField(
"\n".join([self.start, self.sections, self.end]))
for field in [field0, field1]:
field.remove("one")
field.remove("two")
assert field0.save() == '\n'.join([self.three, self.zeroend])
assert field1.save() == '\n'.join([self.start, self.three, self.end])
def test_section_tag_escaping(self):
"""
Section tag escaping
"""
field = StructuredField()
field.set("section", "\n[content]\n")
reloaded = StructuredField(field.save())
assert 'section' in reloaded
assert 'content' not in reloaded
assert reloaded.get('section') == '\n[content]\n'
def test_nesting(self):
"""
Nesting
"""
# Prepare structure parent -> child -> grandchild
grandchild = StructuredField()
grandchild.set('name', "Grand Child\n")
child = StructuredField()
child.set('name', "Child Name\n")
child.set("child", grandchild.save())
parent = StructuredField()
parent.set("name", "Parent Name\n")
parent.set("child", child.save())
# Reload back and check the names
parent = StructuredField(parent.save())
child = StructuredField(parent.get("child"))
grandchild = StructuredField(child.get("child"))
assert parent.get('name') == 'Parent Name\n'
assert child.get('name') == 'Child Name\n'
assert grandchild.get('name') == 'Grand Child\n'
def test_section_tags_in_header(self):
"""
Section tags in header
"""
field = StructuredField("\n".join(
["[something]", self.start, self.one, self.end]))
assert 'something' not in field
assert 'one' in field
assert field.get('one') == '1\n'
def test_empty_section(self):
"""
Empty section
"""
field = StructuredField()
field.set("section", "")
reloaded = StructuredField(field.save())
assert reloaded.get('section') == ''
def test_section_item_get(self):
"""
Get section item
"""
text = "\n".join([self.start, "[section]\nx = 3\n", self.end])
field = StructuredField(text)
assert field.get('section', 'x') == '3'
def test_section_item_set(self):
"""
Set section item
"""
text = "\n".join([self.start, "[section]\nx = 3\n", self.end])
field = StructuredField()
field.set("section", "3", "x")
assert field.save() == text
def test_section_item_remove(self):
"""
Remove section item
"""
text = "\n".join(
[self.start, "[section]\nx = 3\ny = 7\n", self.end])
field = StructuredField(text)
field.remove("section", "x")
assert field.save() == '\n'.join([self.start, '[section]\ny = 7\n', self.end])
def test_unicode_header(self):
"""
Unicode text in header
"""
text = "Už abychom měli unicode jako defaultní kódování!"
field = StructuredField(text)
field.set("section", "content")
assert text in field.save()
def test_unicode_section_content(self):
"""
Unicode in section content
"""
chars = "ěščřžýáíéů"
text = "\n".join([self.start, "[section]", chars, self.end])
field = StructuredField(text)
assert field.get('section').strip() == chars
def test_unicode_section_name(self):
"""
Unicode in section name
"""
chars = "ěščřžýáíéů"
text = "\n".join([self.start, f"[{chars}]\nx", self.end])
field = StructuredField(text)
assert field.get(chars).strip() == 'x'
def test_header_footer_modify(self):
"""
Modify header & footer
"""
original = StructuredField()
original.set("field", "field-content")
original.header("header-content\n")
original.footer("footer-content\n")
copy = StructuredField(original.save())
assert copy.header() == 'header-content\n'
assert copy.footer() == 'footer-content\n'
def test_trailing_whitespace(self):
"""
Trailing whitespace
"""
original = StructuredField()
original.set("name", "value")
# Test with both space and tab appended after the section tag
for char in [" ", "\t"]:
spaced = re.sub(r"\]\n", f"]{char}\n", original.save())
copy = StructuredField(spaced)
assert original.get('name') == copy.get('name')
def test_carriage_returns(self):
"""
Carriage returns
"""
text1 = "\n".join([self.start, self.sections, self.end])
text2 = re.sub(r"\n", "\r\n", text1)
field1 = StructuredField(text1)
field2 = StructuredField(text2)
assert field1.save() == field2.save()
def test_multiple_values(self):
"""
Multiple values
"""
# Reading multiple values
section = "[section]\nkey=val1 # comment\nkey = val2\n key = val3 "
text = "\n".join([self.start, section, self.end])
field = StructuredField(text, multi=True)
assert field.get('section', 'key') == ['val1', 'val2', 'val3']
# Writing multiple values
values = ['1', '2', '3']
field = StructuredField(multi=True)
field.set("section", values, "key")
assert field.get('section', 'key') == values
assert 'key = 1\nkey = 2\nkey = 3' in field.save()
# Remove multiple values
field.remove("section", "key")
assert 'key = 1\nkey = 2\nkey = 3' not in field.save()
pytest.raises(
StructuredFieldError, field.get, "section", "key")
def test_run_interactive_not_joined(tmppath, root_logger):
output = ShellScript("echo abc; echo def >2").to_shell_command().run(
shell=True,
interactive=True,
cwd=tmppath,
env={},
log=None,
logger=root_logger)
assert output.stdout is None
assert output.stderr is None
def test_run_interactive_joined(tmppath, root_logger):
output = ShellScript("echo abc; echo def >2").to_shell_command().run(
shell=True,
interactive=True,
cwd=tmppath,
env={},
join=True,
log=None,
logger=root_logger)
assert output.stdout is None
assert output.stderr is None
def test_run_not_joined_stdout(root_logger):
output = Command("ls", "/").run(
shell=False,
cwd=Path.cwd(),
env={},
log=None,
logger=root_logger)
assert "sbin" in output.stdout
def test_run_not_joined_stderr(root_logger):
output = ShellScript("ls non_existing || true").to_shell_command().run(
shell=False,
cwd=Path.cwd(),
env={},
log=None,
logger=root_logger)
assert "ls: cannot access" in output.stderr
def test_run_joined(root_logger):
output = ShellScript("ls non_existing / || true").to_shell_command().run(
shell=False,
cwd=Path.cwd(),
env={},
log=None,
join=True,
logger=root_logger)
assert "ls: cannot access" in output.stdout
assert "sbin" in output.stdout
def test_run_big(root_logger):
script = """
for NUM in {1..100}; do
LINE="$LINE n";
done;
for NUM in {1..1000}; do
echo $LINE;
done
"""
output = ShellScript(textwrap.dedent(script)).to_shell_command().run(
shell=False,
cwd=Path.cwd(),
env={},
log=None,
join=True,
logger=root_logger)
assert "n n" in output.stdout
assert len(output.stdout) == 200000
def test_command_run_without_streaming(root_logger: Logger, caplog) -> None:
ShellScript('ls -al /').to_shell_command().run(
cwd=Path.cwd(),
stream_output=True,
logger=root_logger)
assert_log(caplog, message=MATCH('out: drwx.+? mnt'))
caplog.clear()
ShellScript('ls -al /').to_shell_command().run(
cwd=Path.cwd(),
stream_output=False,
logger=root_logger)
assert_not_log(caplog, message=MATCH('out: drwx.+? mnt'))
caplog.clear()
with pytest.raises(tmt.utils.RunError):
ShellScript('ls -al / /does/not/exist').to_shell_command().run(
cwd=Path.cwd(),
stream_output=False,
logger=root_logger)
assert_log(caplog, message=MATCH('out: drwx.+? mnt'))
assert_log(caplog, message=MATCH("err: ls: cannot access '/does/not/exist'"))
def test_get_distgit_handler():
for _wrong_remotes in [[], ["blah"]]:
with pytest.raises(tmt.utils.GeneralError):
tmt.utils.get_distgit_handler([])
# Fedora detection
returned_object = tmt.utils.get_distgit_handler("""
remote.origin.url ssh://[email protected]/rpms/tmt
remote.lzachar.url ssh://[email protected]/forks/lzachar/rpms/tmt.git
""".split('\n'))
assert isinstance(returned_object, tmt.utils.FedoraDistGit)
# CentOS detection
returned_object = tmt.utils.get_distgit_handler("""
remote.origin.url git+ssh://[email protected]/redhat/centos-stream/rpms/ruby.git
""".split('\n'))
assert isinstance(returned_object, tmt.utils.CentOSDistGit)
# RH Gitlab detection
returned_object = tmt.utils.get_distgit_handler([
"remote.origin.url https://<redacted_credentials>@gitlab.com/redhat/rhel/rpms/osbuild.git",
])
assert isinstance(returned_object, tmt.utils.RedHatGitlab)
def test_get_distgit_handler_explicit():
instance = tmt.utils.get_distgit_handler(usage_name='redhatgitlab')
assert instance.__class__.__name__ == 'RedHatGitlab'
def test_fedora_dist_git(tmppath):
# Fake values, production hash is too long
(tmppath / 'sources').write_text('SHA512 (fn-1.tar.gz) = 09af\n')
(tmppath / 'tmt.spec').write_text('')
fedora_sources_obj = tmt.utils.FedoraDistGit()
assert fedora_sources_obj.url_and_name(cwd=tmppath) == [(
"https://src.fedoraproject.org/repo/pkgs/rpms/tmt/fn-1.tar.gz/sha512/09af/fn-1.tar.gz",
"fn-1.tar.gz")]
class TestValidateGitStatus:
@classmethod
@pytest.mark.parametrize("use_path",
[False, True], ids=["without path", "with path"])
def test_all_good(
cls,
origin_and_local_git_repo: tuple[Path, Path],
use_path: bool,
root_logger):
# No need to modify origin, ignoring it
mine = origin_and_local_git_repo[1]
# In local repo:
# Init tmt and add test
fmf_root = mine / 'fmf_root' if use_path else mine
tmt.Tree.init(logger=root_logger, path=fmf_root, template=None, force=None)
fmf_root.joinpath('main.fmf').write_text('test: echo')
run(ShellScript(f'git add {fmf_root} {fmf_root / "main.fmf"}').to_shell_command(),
cwd=mine)
run(ShellScript('git commit -m add_test').to_shell_command(),
cwd=mine)
run(ShellScript('git push').to_shell_command(),
cwd=mine)
test = tmt.Tree(logger=root_logger, path=fmf_root).tests()[0]
validation = validate_git_status(test)
assert validation == (True, '')
@classmethod
def test_no_remote(cls, local_git_repo: Path, root_logger):
tmt.Tree.init(logger=root_logger, path=local_git_repo, template=None, force=None)
with open(local_git_repo / 'main.fmf', 'w') as f:
f.write('test: echo')
run(ShellScript('git add main.fmf .fmf/version').to_shell_command(),
cwd=local_git_repo)
run(ShellScript('git commit -m initial_commit').to_shell_command(),
cwd=local_git_repo)
test = tmt.Tree(logger=root_logger, path=local_git_repo).tests()[0]
val, msg = validate_git_status(test)
assert not val
assert "Failed to get remote branch" in msg
@classmethod
def test_untracked_fmf_root(cls, local_git_repo: Path, root_logger):
# local repo is enough since this can't get passed 'is pushed' check
tmt.Tree.init(logger=root_logger, path=local_git_repo, template=None, force=None)
# Make sure fmf root is not tracked
run(
ShellScript('git rm --cached .fmf/version').to_shell_command(),
cwd=local_git_repo)
local_git_repo.joinpath('main.fmf').write_text('test: echo')
run(
ShellScript('git add main.fmf').to_shell_command(),
cwd=local_git_repo)
run(
ShellScript('git commit -m missing_fmf_root').to_shell_command(),
cwd=local_git_repo)
test = tmt.Tree(logger=root_logger, path=local_git_repo).tests()[0]
validate = validate_git_status(test)
assert validate == (False, 'Uncommitted changes in .fmf/version')
@classmethod
def test_untracked_sources(cls, local_git_repo: Path, root_logger):
tmt.Tree.init(logger=root_logger, path=local_git_repo, template=None, force=None)
local_git_repo.joinpath('main.fmf').write_text('test: echo')
local_git_repo.joinpath('test.fmf').write_text('tag: []')
run(ShellScript('git add .fmf/version test.fmf').to_shell_command(),
cwd=local_git_repo)
run(
ShellScript('git commit -m main.fmf').to_shell_command(),
cwd=local_git_repo)
test = tmt.Tree(logger=root_logger, path=local_git_repo).tests()[0]
validate = validate_git_status(test)
assert validate == (False, 'Uncommitted changes in main.fmf')
@classmethod
@pytest.mark.parametrize("use_path",
[False, True], ids=["without path", "with path"])
def test_local_changes(
cls,
origin_and_local_git_repo: tuple[Path, Path],
use_path,
root_logger):
origin, mine = origin_and_local_git_repo
fmf_root = origin / 'fmf_root' if use_path else origin
tmt.Tree.init(logger=root_logger, path=fmf_root, template=None, force=None)
fmf_root.joinpath('main.fmf').write_text('test: echo')
run(ShellScript('git add -A').to_shell_command(), cwd=origin)
run(ShellScript('git commit -m added_test').to_shell_command(),
cwd=origin)
# Pull changes from previous line
run(ShellScript('git pull').to_shell_command(),
cwd=mine)
mine_fmf_root = mine
if use_path:
mine_fmf_root = mine / 'fmf_root'
mine_fmf_root.joinpath('main.fmf').write_text('test: echo ahoy')
# Change README but since it is not part of metadata we do not check it
mine.joinpath("README").write_text('changed')
test = tmt.Tree(logger=root_logger, path=mine_fmf_root).tests()[0]
validation_result = validate_git_status(test)
assert validation_result == (
False, "Uncommitted changes in " + ('fmf_root/' if use_path else '') + "main.fmf")
@classmethod
def test_not_pushed(cls, origin_and_local_git_repo: tuple[Path, Path], root_logger):
# No need for original repo (it is required just to have remote in
# local clone)
mine = origin_and_local_git_repo[1]
fmf_root = mine
tmt.Tree.init(logger=root_logger, path=fmf_root, template=None, force=None)
fmf_root.joinpath('main.fmf').write_text('test: echo')
run(ShellScript('git add main.fmf .fmf/version').to_shell_command(),
cwd=fmf_root)
run(ShellScript('git commit -m changes').to_shell_command(),
cwd=mine)
test = tmt.Tree(logger=root_logger, path=fmf_root).tests()[0]
validation_result = validate_git_status(test)
assert validation_result == (
False, 'Not pushed changes in .fmf/version main.fmf')
@pytest.mark.parametrize("git_ref",
["tag", "branch", "merge", "commit"])
def test_fmf_id(local_git_repo, root_logger, git_ref):
run(Command('git', 'checkout', '-b', 'other_branch'), cwd=local_git_repo)
# Initialize tmt tree with a test
tmt.Tree.init(logger=root_logger, path=local_git_repo, template="empty", force=False)
with (local_git_repo / "test.fmf").open("w") as f:
f.write('test: echo')
run(Command('git', 'add', '-A'), cwd=local_git_repo)
run(Command('git', 'commit', '-m', 'Initialized tmt tree'), cwd=local_git_repo)
commit_hash = run(Command('git', 'rev-parse', 'HEAD'), cwd=local_git_repo).stdout.strip()
if git_ref == "tag":
run(Command('git', 'tag', 'some_tag'), cwd=local_git_repo)
run(Command('git', 'checkout', 'some_tag'), cwd=local_git_repo)
if git_ref == "commit":
# Create an empty commit and checkout the previous commit
run(Command('git', 'commit', '--allow-empty', '-m',
'Random other commit'), cwd=local_git_repo)
run(Command('git', 'checkout', 'HEAD^'), cwd=local_git_repo)
if git_ref == "merge":
run(Command('git', 'checkout', '--detach', 'main'), cwd=local_git_repo)
run(Command('git', 'merge', 'other_branch'), cwd=local_git_repo)
commit_hash = run(Command('git', 'rev-parse', 'HEAD'),
cwd=local_git_repo).stdout.strip()
fmf_id = tmt.utils.fmf_id(name="/test", fmf_root=local_git_repo, logger=root_logger)
assert fmf_id.git_root == local_git_repo
assert fmf_id.ref is not None
if git_ref == "tag":