-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_subprocess.py
More file actions
1246 lines (1090 loc) · 37.8 KB
/
test_subprocess.py
File metadata and controls
1246 lines (1090 loc) · 37.8 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
from __future__ import annotations
from logging import INFO, getLogger
from pathlib import Path
from re import MULTILINE, search
from subprocess import CalledProcessError
from typing import TYPE_CHECKING
from pytest import LogCaptureFixture, mark, param, raises
from utilities.grp import EFFECTIVE_GROUP_NAME
from utilities.iterables import one
from utilities.pathlib import get_file_group, get_file_owner
from utilities.permissions import Permissions
from utilities.pwd import EFFECTIVE_USER_NAME
from utilities.pytest import skipif_ci, skipif_mac, throttle
from utilities.subprocess import (
BASH_LC,
BASH_LS,
ChownCmdError,
CpError,
MvFileError,
RsyncCmdNoSourcesError,
RsyncCmdSourcesNotFoundError,
apt_install_cmd,
cat_cmd,
cd_cmd,
chmod,
chmod_cmd,
chown,
chown_cmd,
cp,
cp_cmd,
echo_cmd,
expand_path,
git_clone,
git_clone_cmd,
git_hard_reset_cmd,
maybe_parent,
maybe_sudo_cmd,
mkdir,
mkdir_cmd,
mv,
mv_cmd,
rm,
rm_cmd,
rsync,
rsync_cmd,
rsync_many,
run,
set_hostname_cmd,
ssh,
ssh_cmd,
ssh_keygen_cmd,
ssh_opts_cmd,
sudo_cmd,
sudo_nopasswd_cmd,
symlink,
symlink_cmd,
tee,
tee_cmd,
touch_cmd,
uv_run_cmd,
yield_git_repo,
yield_ssh_temp_dir,
)
from utilities.tempfile import TemporaryDirectory, TemporaryFile
from utilities.text import strip_and_dedent, unique_str
from utilities.whenever import MINUTE, SECOND
if TYPE_CHECKING:
from pytest import CaptureFixture
from utilities.types import PathLike
class TestAptInstallCmd:
def test_main(self) -> None:
result = apt_install_cmd("package")
expected = ["apt", "install", "-y", "package"]
assert result == expected
class TestCatCmd:
def test_main(self) -> None:
result = cat_cmd("path")
expected = ["cat", "path"]
assert result == expected
class TestCDCmd:
def test_main(self) -> None:
result = cd_cmd("path")
expected = ["cd", "path"]
assert result == expected
class TestChMod:
def test_main(self, *, tmp_path: Path) -> None:
path = tmp_path / "file.txt"
path.touch()
perms = Permissions.from_text("u=rw,g=r,o=r")
_ = chmod(path, perms)
current = Permissions.from_path(path)
assert current == perms
class TestChModCmd:
def test_main(self) -> None:
result = chmod_cmd("path", "u=rw,g=r,o=r")
expected = ["chmod", "u=rw,g=r,o=r", "path"]
assert result == expected
class TestChOwn:
def test_none(self, *, tmp_path: Path) -> None:
path = tmp_path / "file.txt"
path.touch()
chown(path)
def test_user(self, *, tmp_path: Path) -> None:
path = tmp_path / "file.txt"
path.touch()
chown(path, user=EFFECTIVE_USER_NAME)
current = get_file_owner(path)
assert current == EFFECTIVE_USER_NAME
def test_group(self, *, tmp_path: Path) -> None:
path = tmp_path / "file.txt"
path.touch()
chown(path, group=EFFECTIVE_GROUP_NAME)
current_group = get_file_group(path)
assert current_group == EFFECTIVE_GROUP_NAME
def test_user_and_group(self, *, tmp_path: Path) -> None:
path = tmp_path / "file.txt"
path.touch()
chown(path, user=EFFECTIVE_USER_NAME, group=EFFECTIVE_GROUP_NAME)
current_owner = get_file_owner(path)
assert current_owner == EFFECTIVE_USER_NAME
current_group = get_file_group(path)
assert current_group == EFFECTIVE_GROUP_NAME
class TestChOwnCmd:
def test_user(self) -> None:
result = chown_cmd("path", user="user")
expected = ["chown", "user", "path"]
assert result == expected
def test_group(self) -> None:
result = chown_cmd("path", group="group")
expected = ["chown", ":group", "path"]
assert result == expected
def test_user_and_group(self) -> None:
result = chown_cmd("path", user="user", group="group")
expected = ["chown", "user:group", "path"]
assert result == expected
def test_error(self) -> None:
with raises(
ChownCmdError,
match=r"At least one of 'user' and/or 'group' must be given; got None",
):
_ = chown_cmd("path")
class TestCp:
def test_file(self, *, tmp_path: Path) -> None:
src = tmp_path / "file.txt"
src.touch()
dest = tmp_path / "file2.txt"
cp(src, dest)
assert src.is_file()
assert dest.is_file()
def test_dir(self, *, tmp_path: Path) -> None:
src = tmp_path / "dir"
src.mkdir()
dest = tmp_path / "dir2"
cp(src, dest)
assert src.is_dir()
assert dest.is_dir()
def test_perms(self, *, tmp_path: Path) -> None:
src = tmp_path / "file.txt"
src.touch()
dest = tmp_path / "file2.txt"
perms = Permissions.from_text("u=rwx,g=,o=")
cp(src, dest, perms=perms)
current = Permissions.from_path(dest)
assert current == perms
def test_owner(self, *, tmp_path: Path) -> None:
src = tmp_path / "file.txt"
src.touch()
dest = tmp_path / "file2.txt"
cp(src, dest, owner=EFFECTIVE_USER_NAME)
current = get_file_owner(dest)
assert current == EFFECTIVE_USER_NAME
def test_error(self, *, tmp_path: Path) -> None:
src = tmp_path / "dir"
dest = tmp_path / "dir2"
with raises(
CpError, match=r"Unable to copy '.+' to '.+'; source does not exist"
):
cp(src, dest)
class TestCpCmd:
def test_main(self) -> None:
result = cp_cmd("src", "dest")
expected = ["cp", "-r", "src", "dest"]
assert result == expected
class TestEchoCmd:
def test_main(self) -> None:
result = echo_cmd("'hello world'")
expected = ["echo", "'hello world'"]
assert result == expected
class TestExpandPath:
def test_main(self) -> None:
result = expand_path("~")
expected = Path.home()
assert result == expected
def test_subs(self) -> None:
result = expand_path("~/${dir}", subs={"dir": "foo"})
expected = Path("~/foo").expanduser()
assert result == expected
class TestGitClone:
@throttle(delta=5 * MINUTE)
def test_main(self, *, tmp_path: Path) -> None:
git_clone("https://github.com/dycw/template-generic", tmp_path)
assert (tmp_path / ".bumpversion.toml").is_file()
class TestGitCloneCmd:
def test_main(self) -> None:
result = git_clone_cmd("https://github.com/dycw/template-generic", "path")
expected = [
"git",
"clone",
"--recurse-submodules",
"https://github.com/dycw/template-generic",
"path",
]
assert result == expected
class TestGitHardResetCmd:
def test_main(self) -> None:
result = git_hard_reset_cmd()
expected = ["git", "hard-reset", "master"]
assert result == expected
def test_branch(self) -> None:
result = git_hard_reset_cmd(branch="dev")
expected = ["git", "hard-reset", "dev"]
assert result == expected
class TestMaybeParent:
def test_main(self) -> None:
result = maybe_parent("~/path")
expected = Path("~/path")
assert result == expected
def test_parent(self) -> None:
result = maybe_parent("~/path", parent=True)
expected = Path("~")
assert result == expected
class TestMaybeSudoCmd:
def test_main(self) -> None:
result = maybe_sudo_cmd("echo", "hi")
expected = ["echo", "hi"]
assert result == expected
def test_sudo(self) -> None:
result = maybe_sudo_cmd("echo", "hi", sudo=True)
expected = ["sudo", "echo", "hi"]
assert result == expected
class TestMkDir:
def test_main(self, *, tmp_path: Path) -> None:
path = tmp_path / "dir"
mkdir(path)
assert Path(path).is_dir()
class TestMkDirCmd:
def test_main(self) -> None:
result = mkdir_cmd("~/path")
expected = ["mkdir", "-p", "~/path"]
assert result == expected
def test_parent(self) -> None:
result = mkdir_cmd("~/path", parent=True)
expected = ["mkdir", "-p", "~"]
assert result == expected
class TestMv:
def test_file(self, *, tmp_path: Path) -> None:
src = tmp_path / "file.txt"
src.touch()
dest = tmp_path / "file2.txt"
mv(src, dest)
assert not src.is_file()
assert dest.is_file()
def test_dir(self, *, tmp_path: Path) -> None:
src = tmp_path / "dir"
src.mkdir()
dest = tmp_path / "dir2"
mv(src, dest)
assert not src.is_dir()
assert dest.is_dir()
def test_perms(self, *, tmp_path: Path) -> None:
src = tmp_path / "file.txt"
src.touch()
dest = tmp_path / "file2.txt"
perms = Permissions.from_text("u=rwx,g=,o=")
mv(src, dest, perms=perms)
current = Permissions.from_path(dest)
assert current == perms
def test_owner(self, *, tmp_path: Path) -> None:
src = tmp_path / "file.txt"
src.touch()
dest = tmp_path / "file2.txt"
mv(src, dest, owner=EFFECTIVE_USER_NAME)
current = get_file_owner(dest)
assert current == EFFECTIVE_USER_NAME
def test_error(self, *, tmp_path: Path) -> None:
src = tmp_path / "dir"
dest = tmp_path / "dir2"
with raises(
MvFileError, match=r"Unable to move '.+' to '.+'; source does not exist"
):
mv(src, dest)
class TestMvCmd:
def test_main(self) -> None:
result = mv_cmd("src", "dest")
expected = ["mv", "src", "dest"]
assert result == expected
class TestRemove:
def test_file(self, *, tmp_path: Path) -> None:
path = tmp_path / "file.txt"
path.touch()
assert path.is_file()
rm(path)
assert not path.is_file()
def test_dir(self, *, tmp_path: Path) -> None:
path = tmp_path / "dir"
path.mkdir()
assert path.is_dir()
rm(path)
assert not path.is_dir()
class TestRmCmd:
def test_main(self) -> None:
result = rm_cmd("path")
expected = ["rm", "-rf", "path"]
assert result == expected
class TestRsync:
@skipif_ci
@throttle(delta=5 * MINUTE)
def test_file(self, *, ssh_user: str, ssh_hostname: str) -> None:
with (
TemporaryFile() as src,
yield_ssh_temp_dir(ssh_user, ssh_hostname) as temp_dest,
):
dest = temp_dest / src.name
rsync(src, ssh_user, ssh_hostname, dest)
ssh(
ssh_user,
ssh_hostname,
*BASH_LS,
input=f"if ! [ -f {dest} ]; then exit 1; fi",
)
@skipif_ci
@throttle(delta=5 * MINUTE)
def test_dir_without_trailing_slash(
self, *, ssh_user: str, ssh_hostname: str
) -> None:
with (
TemporaryDirectory() as src,
yield_ssh_temp_dir(ssh_user, ssh_hostname) as temp_dest,
):
(src / "file.txt").touch()
name = src.name
dest = temp_dest / name
rsync(src, ssh_user, ssh_hostname, dest)
ssh(
ssh_user,
ssh_hostname,
*BASH_LS,
input=strip_and_dedent(f"""
if ! [ -d {dest} ]; then exit 1; fi
if ! [ -d {dest}/{name} ]; then exit 1; fi
if ! [ -f {dest}/{name}/file.txt ]; then exit 1; fi
"""),
)
@skipif_ci
@throttle(delta=5 * MINUTE)
def test_dir_with_trailing_slash(self, *, ssh_user: str, ssh_hostname: str) -> None:
with (
TemporaryDirectory() as src,
yield_ssh_temp_dir(ssh_user, ssh_hostname) as temp_dest,
):
(src / "file.txt").touch()
dest = temp_dest / src.name
rsync(f"{src}/", ssh_user, ssh_hostname, dest)
ssh(
ssh_user,
ssh_hostname,
*BASH_LS,
input=strip_and_dedent(f"""
if ! [ -d {dest} ]; then exit 1; fi
if ! [ -f {dest}/file.txt ]; then exit 1; fi
"""),
)
class TestRsyncCmd:
def test_main(self, *, tmp_path: Path) -> None:
src = tmp_path / "file.txt"
src.touch()
result = rsync_cmd(src, "user", "hostname", "dest")
expected: list[str] = [
"rsync",
"--checksum",
"--compress",
"--rsh",
"ssh -o BatchMode=yes -o HostKeyAlgorithms=ssh-ed25519 -o StrictHostKeyChecking=yes -T",
str(src),
"user@hostname:dest",
]
assert result == expected
def test_multiple_sources(self, *, tmp_path: Path) -> None:
src1, src2 = [tmp_path / f"file{i}.txt" for i in [1, 2]]
src1.touch()
src2.touch()
result = rsync_cmd([src1, src2], "user", "hostname", "dest")
expected: list[str] = [
"rsync",
"--checksum",
"--compress",
"--rsh",
"ssh -o BatchMode=yes -o HostKeyAlgorithms=ssh-ed25519 -o StrictHostKeyChecking=yes -T",
str(src1),
str(src2),
"user@hostname:dest",
]
assert result == expected
def test_source_with_trailing_slash(self, *, tmp_path: Path) -> None:
src = tmp_path / "src"
src.mkdir()
result = rsync_cmd(f"{src}/", "user", "hostname", "dest")
expected: list[str] = [
"rsync",
"--checksum",
"--compress",
"--rsh",
"ssh -o BatchMode=yes -o HostKeyAlgorithms=ssh-ed25519 -o StrictHostKeyChecking=yes -T",
f"{src}/",
"user@hostname:dest",
]
assert result == expected
def test_archive(self, *, tmp_path: Path) -> None:
src = tmp_path / "src"
src.mkdir()
result = rsync_cmd(src, "user", "hostname", "dest", archive=True)
expected: list[str] = [
"rsync",
"--archive",
"--checksum",
"--compress",
"--rsh",
"ssh -o BatchMode=yes -o HostKeyAlgorithms=ssh-ed25519 -o StrictHostKeyChecking=yes -T",
str(src),
"user@hostname:dest",
]
assert result == expected
def test_chown_user(self, *, tmp_path: Path) -> None:
src = tmp_path / "file.txt"
src.touch()
result = rsync_cmd(src, "user", "hostname", "dest", chown_user="user2")
expected: list[str] = [
"rsync",
"--checksum",
"--chown",
"user2",
"--compress",
"--rsh",
"ssh -o BatchMode=yes -o HostKeyAlgorithms=ssh-ed25519 -o StrictHostKeyChecking=yes -T",
str(src),
"user@hostname:dest",
]
assert result == expected
def test_chown_group(self, *, tmp_path: Path) -> None:
src = tmp_path / "file.txt"
src.touch()
result = rsync_cmd(src, "user", "hostname", "dest", chown_group="group")
expected: list[str] = [
"rsync",
"--checksum",
"--chown",
":group",
"--compress",
"--rsh",
"ssh -o BatchMode=yes -o HostKeyAlgorithms=ssh-ed25519 -o StrictHostKeyChecking=yes -T",
str(src),
"user@hostname:dest",
]
assert result == expected
def test_chown_user_and_group(self, *, tmp_path: Path) -> None:
src = tmp_path / "file.txt"
src.touch()
result = rsync_cmd(
src, "user", "hostname", "dest", chown_user="user2", chown_group="group"
)
expected: list[str] = [
"rsync",
"--checksum",
"--chown",
"user2:group",
"--compress",
"--rsh",
"ssh -o BatchMode=yes -o HostKeyAlgorithms=ssh-ed25519 -o StrictHostKeyChecking=yes -T",
str(src),
"user@hostname:dest",
]
assert result == expected
def test_exclude(self, *, tmp_path: Path) -> None:
src = tmp_path / "file.txt"
src.touch()
result = rsync_cmd(src, "user", "hostname", "dest", exclude="exclude")
expected: list[str] = [
"rsync",
"--checksum",
"--compress",
"--exclude",
"exclude",
"--rsh",
"ssh -o BatchMode=yes -o HostKeyAlgorithms=ssh-ed25519 -o StrictHostKeyChecking=yes -T",
str(src),
"user@hostname:dest",
]
assert result == expected
def test_exclude_multiple(self, *, tmp_path: Path) -> None:
src = tmp_path / "file.txt"
src.touch()
result = rsync_cmd(
src, "user", "hostname", "dest", exclude=["exclude1", "exclude2"]
)
expected: list[str] = [
"rsync",
"--checksum",
"--compress",
"--exclude",
"exclude1",
"--exclude",
"exclude2",
"--rsh",
"ssh -o BatchMode=yes -o HostKeyAlgorithms=ssh-ed25519 -o StrictHostKeyChecking=yes -T",
str(src),
"user@hostname:dest",
]
assert result == expected
def test_sudo(self, *, tmp_path: Path) -> None:
src = tmp_path / "file.txt"
src.touch()
result = rsync_cmd(src, "user", "hostname", "dest", sudo=True)
expected: list[str] = [
"rsync",
"--checksum",
"--compress",
"--rsh",
"ssh -o BatchMode=yes -o HostKeyAlgorithms=ssh-ed25519 -o StrictHostKeyChecking=yes -T",
"--rsync-path",
"sudo rsync",
str(src),
"user@hostname:dest",
]
assert result == expected
def test_error_no_sources(self) -> None:
with raises(
RsyncCmdNoSourcesError,
match=r"No sources selected to send to user@hostname:dest",
):
_ = rsync_cmd([], "user", "hostname", "dest")
def test_error_sources_not_found(self, *, tmp_path: Path) -> None:
src = tmp_path / "file.txt"
with raises(
RsyncCmdSourcesNotFoundError,
match=r"Sources selected to send to user@hostname:dest but not found: '.*/file\.txt'",
):
_ = rsync_cmd(src, "user", "hostname", "dest")
class TestRsyncMany:
@skipif_ci
@throttle(delta=5 * MINUTE)
def test_single_file(self, *, ssh_user: str, ssh_hostname: str) -> None:
with (
TemporaryDirectory() as temp_src,
yield_ssh_temp_dir(ssh_user, ssh_hostname) as temp_dest,
):
src = temp_src / "file.txt"
src.touch()
dest = temp_dest / src.name
rsync_many(ssh_user, ssh_hostname, (src, dest))
ssh(
ssh_user,
ssh_hostname,
*BASH_LS,
input=f"if ! [ -f {dest} ]; then exit 1; fi",
)
@skipif_ci
@throttle(delta=5 * MINUTE)
def test_multiple_files(self, *, ssh_user: str, ssh_hostname: str) -> None:
with (
TemporaryDirectory() as temp_src,
yield_ssh_temp_dir(ssh_user, ssh_hostname) as temp_dest,
):
src1, src2 = [temp_src / f"file{i}.txt" for i in [1, 2]]
src1.touch()
src2.touch()
dest1, dest2 = [temp_dest / src.name for src in [src1, src2]]
rsync_many(ssh_user, ssh_hostname, (src1, dest1), (src2, dest2))
ssh(
ssh_user,
ssh_hostname,
*BASH_LS,
input=strip_and_dedent(f"""
if ! [ -f {dest1} ]; then exit 1; fi
if ! [ -f {dest2} ]; then exit 1; fi
"""),
)
@skipif_ci
@throttle(delta=5 * MINUTE)
def test_single_directory(self, *, ssh_user: str, ssh_hostname: str) -> None:
with (
TemporaryDirectory() as temp_src,
yield_ssh_temp_dir(ssh_user, ssh_hostname) as temp_dest,
):
src = temp_src / "dir"
src.mkdir()
(src / "file.txt").touch()
dest = temp_dest / src.name
rsync_many(ssh_user, ssh_hostname, (src, dest))
ssh(
ssh_user,
ssh_hostname,
*BASH_LS,
input=(
f"""
if ! [ -d {dest} ]; then exit 1; fi
if ! [ -f {dest}/file.txt ]; then exit 1; fi
"""
),
)
class TestRun:
def test_main(self, *, capsys: CaptureFixture) -> None:
result = run("echo", "hi")
assert result is None
cap = capsys.readouterr()
assert cap.out == ""
assert cap.err == ""
@skipif_ci
@skipif_mac
def test_user(self, *, capsys: CaptureFixture) -> None:
result = run("whoami", user="root", print=True)
assert result is None
cap = capsys.readouterr()
assert cap.out == "root\n"
assert cap.err == ""
@mark.parametrize("executable", [param("sh"), param("bash")])
def test_executable(self, *, executable: str, capsys: CaptureFixture) -> None:
result = run("echo $0", executable=executable, shell=True, print=True) # noqa: S604
assert result is None
cap = capsys.readouterr()
assert cap.out == f"{executable}\n"
assert cap.err == ""
def test_shell(self, *, capsys: CaptureFixture) -> None:
result = run("echo stdout; echo stderr 1>&2", shell=True, print=True) # noqa: S604
assert result is None
cap = capsys.readouterr()
assert cap.out == "stdout\n"
assert cap.err == "stderr\n"
def test_cwd(self, *, capsys: CaptureFixture, tmp_path: Path) -> None:
result = run("pwd", cwd=tmp_path, print=True)
assert result is None
cap = capsys.readouterr()
assert cap.out == f"{tmp_path}\n"
assert cap.err == ""
def test_env(self, *, capsys: CaptureFixture) -> None:
result = run("env | grep KEY", env={"KEY": "value"}, shell=True, print=True) # noqa: S604
assert result is None
cap = capsys.readouterr()
assert cap.out == "KEY=value\n"
assert cap.err == ""
def test_input_bash(self, *, capsys: CaptureFixture) -> None:
input_ = strip_and_dedent("""
key=value
echo ${key}@stdout
echo ${key}@stderr 1>&2
""")
result = run(*BASH_LC, input_, print=True)
assert result is None
cap = capsys.readouterr()
assert cap.out == "value@stdout\n"
assert cap.err == "value@stderr\n"
def test_input_cat(self, *, capsys: CaptureFixture) -> None:
input_ = strip_and_dedent("""
foo
bar
baz
""")
result = run("cat", input=input_, print=True)
assert result is None
cap = capsys.readouterr()
assert cap.out == input_
assert cap.err == ""
def test_input_and_return(self, *, capsys: CaptureFixture) -> None:
input_ = strip_and_dedent("""
foo
bar
baz
""")
result = run("cat", input=input_, return_=True)
assert result == input_
cap = capsys.readouterr()
assert cap.out == ""
assert cap.err == ""
def test_print(self, *, capsys: CaptureFixture) -> None:
result = run("echo stdout; echo stderr 1>&2", shell=True, print=True) # noqa: S604
assert result is None
cap = capsys.readouterr()
assert cap.out == "stdout\n"
assert cap.err == "stderr\n"
def test_print_stdout(self, *, capsys: CaptureFixture) -> None:
result = run( # noqa: S604
"echo stdout; echo stderr 1>&2", shell=True, print_stdout=True
)
assert result is None
cap = capsys.readouterr()
assert cap.out == "stdout\n"
assert cap.err == ""
def test_print_stderr(self, *, capsys: CaptureFixture) -> None:
result = run( # noqa: S604
"echo stdout; echo stderr 1>&2", shell=True, print_stderr=True
)
assert result is None
cap = capsys.readouterr()
assert cap.out == ""
assert cap.err == "stderr\n"
def test_return(self, *, capsys: CaptureFixture) -> None:
result = run( # noqa: S604
"echo stdout; sleep 0.5; echo stderr 1>&2", shell=True, return_=True
)
expected = "stdout\nstderr"
assert result == expected
cap = capsys.readouterr()
assert cap.out == ""
assert cap.err == ""
def test_return_stdout(self, *, capsys: CaptureFixture) -> None:
result = run( # noqa: S604
"echo stdout; echo stderr 1>&2", shell=True, return_stdout=True
)
expected = "stdout"
assert result == expected
cap = capsys.readouterr()
assert cap.out == ""
assert cap.err == ""
def test_return_stderr(self, *, capsys: CaptureFixture) -> None:
result = run( # noqa: S604
"echo stdout; echo stderr 1>&2", shell=True, return_stderr=True
)
expected = "stderr"
assert result == expected
cap = capsys.readouterr()
assert cap.out == ""
assert cap.err == ""
def test_print_and_return(self, *, capsys: CaptureFixture) -> None:
result = run( # noqa: S604
"echo stdout; sleep 0.5; echo stderr 1>&2",
shell=True,
print=True,
return_=True,
)
expected = "stdout\nstderr"
assert result == expected
cap = capsys.readouterr()
assert cap.out == "stdout\n"
assert cap.err == "stderr\n"
def test_error(self, *, capsys: CaptureFixture) -> None:
with raises(CalledProcessError) as exc_info:
_ = run("echo stdout; echo stderr 1>&2; exit 1", shell=True) # noqa: S604
assert exc_info.value.returncode == 1
assert exc_info.value.stdout == "stdout\n"
assert exc_info.value.stderr == "stderr\n"
cap = capsys.readouterr()
assert cap.out == ""
assert cap.err == ""
def test_error_and_print(self, *, capsys: CaptureFixture) -> None:
with raises(CalledProcessError) as exc_info:
_ = run("echo stdout; echo stderr 1>&2; exit 1", shell=True, print=True) # noqa: S604
assert exc_info.value.returncode == 1
assert exc_info.value.stdout == "stdout\n"
assert exc_info.value.stderr == "stderr\n"
cap = capsys.readouterr()
assert cap.out == "stdout\n"
assert cap.err == "stderr\n"
def test_retry_1_attempt(
self, *, tmp_path: Path, caplog: LogCaptureFixture
) -> None:
name = unique_str()
result = run(
*BASH_LS,
input=self._test_retry_cmd(tmp_path, 1),
retry=(1, None),
logger=name,
)
assert result is None
record = one(r for r in caplog.records if r.name == name)
assert search(
r"^Retrying 1 more time\(s\)...$", record.message, flags=MULTILINE
)
def test_retry_2_attempts(
self, *, tmp_path: Path, caplog: LogCaptureFixture
) -> None:
name = unique_str()
result = run(
*BASH_LS,
input=self._test_retry_cmd(tmp_path, 2),
retry=(2, None),
logger=name,
)
assert result is None
first, second = [r for r in caplog.records if r.name == name]
assert search(r"^Retrying 2 more time\(s\)...$", first.message, flags=MULTILINE)
assert search(
r"^Retrying 1 more time\(s\)...$", second.message, flags=MULTILINE
)
def test_retry_and_leep(self, *, tmp_path: Path, caplog: LogCaptureFixture) -> None:
name = unique_str()
result = run(
*BASH_LS,
input=self._test_retry_cmd(tmp_path, 1),
retry=(1, SECOND),
logger=name,
)
assert result is None
record = one(r for r in caplog.records if r.name == name)
assert search(
r"^Retrying 1 more time\(s\) after PT1S...$",
record.message,
flags=MULTILINE,
)
def test_logger(self, *, caplog: LogCaptureFixture) -> None:
name = unique_str()
with raises(CalledProcessError):
_ = run("echo stdout; echo stderr 1>&2; exit 1", shell=True, logger=name) # noqa: S604
record = one(r for r in caplog.records if r.name == name)
expected = strip_and_dedent("""
'run' failed with:
- cmd = echo stdout; echo stderr 1>&2; exit 1
- cmds_or_args = ()
- user = None
- executable = None
- shell = True
- cwd = None
- env = None
-- stdin ----------------------------------------------------------------------
-------------------------------------------------------------------------------
-- stdout ---------------------------------------------------------------------
stdout
-------------------------------------------------------------------------------
-- stderr ---------------------------------------------------------------------
stderr
-------------------------------------------------------------------------------
""")
assert record.message == expected
def test_logger_and_input(self, *, caplog: LogCaptureFixture) -> None:
name = unique_str()
input_ = strip_and_dedent(
"""
key=value
echo ${key}@stdout
echo ${key}@stderr 1>&2
exit 1
""",
trailing=True,
)
with raises(CalledProcessError):
_ = run(*BASH_LS, input=input_, logger=name)
record = one(r for r in caplog.records if r.name == name)
expected = strip_and_dedent("""
'run' failed with:
- cmd = bash
- cmds_or_args = ('-ls',)
- user = None
- executable = None
- shell = False
- cwd = None
- env = None
-- stdin ----------------------------------------------------------------------
key=value
echo ${key}@stdout
echo ${key}@stderr 1>&2
exit 1
-------------------------------------------------------------------------------
-- stdout ---------------------------------------------------------------------
value@stdout
-------------------------------------------------------------------------------
-- stderr ---------------------------------------------------------------------
value@stderr
-------------------------------------------------------------------------------
""")
assert record.message == expected
def _test_retry_cmd(self, path: PathLike, attempts: int, /) -> str:
return strip_and_dedent(
f"""
count=$(ls -1A "{path}" 2>/dev/null | wc -l)
if [ "${{count}}" -lt {attempts} ]; then
mktemp "{path}/XXX"
exit 1
fi
""",
trailing=True,
)
class TestSetHostnameCmd:
def test_main(self) -> None: