forked from amoffat/sh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.py
3217 lines (2545 loc) · 86.5 KB
/
test.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
# -*- coding: utf8 -*-
from contextlib import contextmanager
from functools import wraps
from os.path import exists, join, realpath, dirname, split
import errno
import fcntl
import inspect
import logging
import os
import platform
import pty
import resource
import sh
import signal
import stat
import sys
import tempfile
import time
import unittest
import warnings
IS_PY3 = sys.version_info[0] == 3
IS_PY2 = not IS_PY3
MINOR_VER = sys.version_info[1]
# coverage doesn't work in python 3.1, 3.2 due to it just being a shit
# python
HAS_UNICODE_LITERAL = not (IS_PY3 and MINOR_VER in (1, 2))
cov = None
if HAS_UNICODE_LITERAL:
run_idx = int(os.environ.pop("SH_TEST_RUN_IDX", "0"))
first_run = run_idx == 0
try:
import coverage
except ImportError:
pass
else:
# for some reason, we can't run auto_data on the first run, or the coverage
# numbers get really screwed up
auto_data = True
if first_run:
auto_data = False
cov = coverage.Coverage(auto_data=auto_data)
if first_run:
cov.erase()
cov.start()
try:
import unittest.mock
except ImportError:
HAS_MOCK = False
else:
HAS_MOCK = True
# we have to use the real path because on osx, /tmp is a symlink to
# /private/tmp, and so assertions that gettempdir() == sh.pwd() will fail
tempdir = realpath(tempfile.gettempdir())
IS_MACOS = platform.system() in ("AIX", "Darwin")
# these 3 functions are helpers for modifying PYTHONPATH with a module's main
# directory
def append_pythonpath(env, path):
key = "PYTHONPATH"
pypath = [p for p in env.get(key, "").split(":") if p]
pypath.insert(0, path)
pypath = ":".join(pypath)
env[key] = pypath
def get_module_import_dir(m):
mod_file = inspect.getsourcefile(m)
is_package = mod_file.endswith("__init__.py")
mod_dir = dirname(mod_file)
if is_package:
mod_dir, _ = split(mod_dir)
return mod_dir
def append_module_path(env, m):
append_pythonpath(env, get_module_import_dir(m))
if IS_PY3:
xrange = range
unicode = str
long = int
from io import StringIO
ioStringIO = StringIO
from io import BytesIO as cStringIO
iocStringIO = cStringIO
else:
from StringIO import StringIO
from cStringIO import StringIO as cStringIO
from io import StringIO as ioStringIO
from io import BytesIO as iocStringIO
THIS_DIR = dirname(os.path.abspath(__file__))
system_python = sh.Command(sys.executable)
# this is to ensure that our `python` helper here is able to import our local sh
# module, and not the system one
baked_env = os.environ.copy()
append_module_path(baked_env, sh)
python = system_python.bake(_env=baked_env)
if hasattr(logging, 'NullHandler'):
NullHandler = logging.NullHandler
else:
class NullHandler(logging.Handler):
def handle(self, record):
pass
def emit(self, record):
pass
def createLock(self):
self.lock = None
skipUnless = getattr(unittest, "skipUnless", None)
if not skipUnless:
# our stupid skipUnless wrapper for python2.6
def skipUnless(condition, reason):
def wrapper(test):
if condition:
return test
else:
@wraps(test)
def skip(*args, **kwargs):
return
return skip
return wrapper
skip_unless = skipUnless
def requires_progs(*progs):
missing = []
for prog in progs:
try:
sh.Command(prog)
except sh.CommandNotFound:
missing.append(prog)
friendly_missing = ", ".join(missing)
return skipUnless(len(missing) == 0, "Missing required system programs: %s"
% friendly_missing)
requires_posix = skipUnless(os.name == "posix", "Requires POSIX")
requires_utf8 = skipUnless(sh.DEFAULT_ENCODING == "UTF-8", "System encoding must be UTF-8")
not_macos = skipUnless(not IS_MACOS, "Doesn't work on MacOS")
requires_py3 = skipUnless(IS_PY3, "Test only works on Python 3")
requires_py35 = skipUnless(IS_PY3 and MINOR_VER >= 5, "Test only works on Python 3.5 or higher")
def requires_poller(poller):
use_select = bool(int(os.environ.get("SH_TESTS_USE_SELECT", "0")))
cur_poller = "select" if use_select else "poll"
return skipUnless(cur_poller == poller, "Only enabled for select.%s" % cur_poller)
@contextmanager
def ulimit(key, new_soft):
soft, hard = resource.getrlimit(key)
resource.setrlimit(key, (new_soft, hard))
try:
yield
finally:
resource.setrlimit(key, (soft, hard))
def create_tmp_test(code, prefix="tmp", delete=True, **kwargs):
""" creates a temporary test file that lives on disk, on which we can run
python with sh """
py = tempfile.NamedTemporaryFile(prefix=prefix, delete=delete)
code = code.format(**kwargs)
if IS_PY3:
code = code.encode("UTF-8")
py.write(code)
py.flush()
# make the file executable
st = os.stat(py.name)
os.chmod(py.name, st.st_mode | stat.S_IEXEC)
# we don't explicitly close, because close will remove the file, and we
# don't want that until the test case is done. so we let the gc close it
# when it goes out of scope
return py
class BaseTests(unittest.TestCase):
def assert_oserror(self, num, fn, *args, **kwargs):
try:
fn(*args, **kwargs)
except OSError as e:
self.assertEqual(e.errno, num)
def assert_deprecated(self, fn, *args, **kwargs):
with warnings.catch_warnings(record=True) as w:
fn(*args, **kwargs)
self.assertEqual(len(w), 1)
self.assertTrue(issubclass(w[-1].category, DeprecationWarning))
# python2.6 lacks this
def assertIn(self, needle, haystack):
s = super(BaseTests, self)
if hasattr(s, "assertIn"):
s.assertIn(needle, haystack)
else:
self.assertTrue(needle in haystack)
# python2.6 lacks this
def assertNotIn(self, needle, haystack):
s = super(BaseTests, self)
if hasattr(s, "assertNotIn"):
s.assertNotIn(needle, haystack)
else:
self.assertTrue(needle not in haystack)
# python2.6 lacks this
def assertLess(self, a, b):
s = super(BaseTests, self)
if hasattr(s, "assertLess"):
s.assertLess(a, b)
else:
self.assertTrue(a < b)
# python2.6 lacks this
def assertGreater(self, a, b):
s = super(BaseTests, self)
if hasattr(s, "assertGreater"):
s.assertGreater(a, b)
else:
self.assertTrue(a > b)
# python2.6 lacks this
def skipTest(self, msg):
s = super(BaseTests, self)
if hasattr(s, "skipTest"):
s.skipTest(msg)
else:
return
@requires_posix
class FunctionalTests(BaseTests):
def setUp(self):
self._environ = os.environ.copy()
def tearDown(self):
os.environ = self._environ
def test_print_command(self):
from sh import ls, which
actual_location = which("ls")
out = str(ls)
self.assertEqual(out, actual_location)
def test_unicode_arg(self):
from sh import echo
test = "漢字"
if not IS_PY3:
test = test.decode("utf8")
p = echo(test, _encoding="utf8")
output = p.strip()
self.assertEqual(test, output)
def test_unicode_exception(self):
from sh import ErrorReturnCode
py = create_tmp_test("exit(1)")
arg = "漢字"
native_arg = arg
if not IS_PY3:
arg = arg.decode("utf8")
try:
python(py.name, arg, _encoding="utf8")
except ErrorReturnCode as e:
self.assertIn(native_arg, str(e))
else:
self.fail("exception wasn't raised")
def test_pipe_fd(self):
py = create_tmp_test("""print("hi world")""")
read_fd, write_fd = os.pipe()
python(py.name, _out=write_fd)
out = os.read(read_fd, 10)
self.assertEqual(out, b"hi world\n")
def test_trunc_exc(self):
py = create_tmp_test("""
import sys
sys.stdout.write("a" * 1000)
sys.stderr.write("b" * 1000)
exit(1)
""")
self.assertRaises(sh.ErrorReturnCode_1, python, py.name)
def test_number_arg(self):
py = create_tmp_test("""
from optparse import OptionParser
parser = OptionParser()
options, args = parser.parse_args()
print(args[0])
""")
out = python(py.name, 3).strip()
self.assertEqual(out, "3")
def test_empty_stdin_no_hang(self):
py = create_tmp_test("""
import sys
data = sys.stdin.read()
sys.stdout.write("no hang")
""")
out = python(py.name, _in="", _timeout=2)
self.assertEqual(out, "no hang")
out = python(py.name, _in=None, _timeout=2)
self.assertEqual(out, "no hang")
def test_exit_code(self):
from sh import ErrorReturnCode_3
py = create_tmp_test("""
exit(3)
""")
self.assertRaises(ErrorReturnCode_3, python, py.name)
def test_patched_glob(self):
from glob import glob
py = create_tmp_test("""
import sys
print(sys.argv[1:])
""")
files = glob("*.faowjefoajweofj")
out = python(py.name, files).strip()
self.assertEqual(out, "['*.faowjefoajweofj']")
@requires_py35
def test_patched_glob_with_recursive_argument(self):
from glob import glob
py = create_tmp_test("""
import sys
print(sys.argv[1:])
""")
files = glob("*.faowjefoajweofj", recursive=True)
out = python(py.name, files).strip()
self.assertEqual(out, "['*.faowjefoajweofj']")
def test_exit_code_with_hasattr(self):
from sh import ErrorReturnCode_3
py = create_tmp_test("""
exit(3)
""")
try:
out = python(py.name, _iter=True)
# hasattr can swallow exceptions
hasattr(out, 'something_not_there')
list(out)
self.assertEqual(out.exit_code, 3)
self.fail("Command exited with error, but no exception thrown")
except ErrorReturnCode_3:
pass
def test_exit_code_from_exception(self):
from sh import ErrorReturnCode_3
py = create_tmp_test("""
exit(3)
""")
self.assertRaises(ErrorReturnCode_3, python, py.name)
try:
python(py.name)
except Exception as e:
self.assertEqual(e.exit_code, 3)
def test_stdin_from_string(self):
from sh import sed
self.assertEqual(sed(_in="one test three", e="s/test/two/").strip(),
"one two three")
def test_ok_code(self):
from sh import ls, ErrorReturnCode_1, ErrorReturnCode_2
exc_to_test = ErrorReturnCode_2
code_to_pass = 2
if IS_MACOS:
exc_to_test = ErrorReturnCode_1
code_to_pass = 1
self.assertRaises(exc_to_test, ls, "/aofwje/garogjao4a/eoan3on")
ls("/aofwje/garogjao4a/eoan3on", _ok_code=code_to_pass)
ls("/aofwje/garogjao4a/eoan3on", _ok_code=[code_to_pass])
ls("/aofwje/garogjao4a/eoan3on", _ok_code=range(code_to_pass + 1))
def test_ok_code_none(self):
py = create_tmp_test("exit(0)")
python(py.name, _ok_code=None)
def test_ok_code_exception(self):
from sh import ErrorReturnCode_0
py = create_tmp_test("exit(0)")
self.assertRaises(ErrorReturnCode_0, python, py.name, _ok_code=2)
def test_none_arg(self):
py = create_tmp_test("""
import sys
print(sys.argv[1:])
""")
maybe_arg = "some"
out = python(py.name, maybe_arg).strip()
self.assertEqual(out, "['some']")
maybe_arg = None
out = python(py.name, maybe_arg).strip()
self.assertEqual(out, "[]")
def test_quote_escaping(self):
py = create_tmp_test("""
from optparse import OptionParser
parser = OptionParser()
options, args = parser.parse_args()
print(args)
""")
out = python(py.name, "one two three").strip()
self.assertEqual(out, "['one two three']")
out = python(py.name, "one \"two three").strip()
self.assertEqual(out, "['one \"two three']")
out = python(py.name, "one", "two three").strip()
self.assertEqual(out, "['one', 'two three']")
out = python(py.name, "one", "two \"haha\" three").strip()
self.assertEqual(out, "['one', 'two \"haha\" three']")
out = python(py.name, "one two's three").strip()
self.assertEqual(out, "[\"one two's three\"]")
out = python(py.name, 'one two\'s three').strip()
self.assertEqual(out, "[\"one two's three\"]")
def test_multiple_pipes(self):
import time
py = create_tmp_test("""
import sys
import os
import time
for l in "andrew":
sys.stdout.write(l)
time.sleep(.2)
""")
inc_py = create_tmp_test("""
import sys
while True:
letter = sys.stdin.read(1)
if not letter:
break
sys.stdout.write(chr(ord(letter)+1))
""")
def inc(proc, *args, **kwargs):
return python(proc, "-u", inc_py.name, *args, **kwargs)
class Derp(object):
def __init__(self):
self.times = []
self.stdout = []
self.last_received = None
def agg(self, line):
self.stdout.append(line.strip())
now = time.time()
if self.last_received:
self.times.append(now - self.last_received)
self.last_received = now
derp = Derp()
p = inc(
inc(
inc(
python("-u", py.name, _piped=True),
_piped=True),
_piped=True),
_out=derp.agg)
p.wait()
self.assertEqual("".join(derp.stdout), "dqguhz")
self.assertTrue(all([t > .15 for t in derp.times]))
def test_manual_stdin_string(self):
from sh import tr
out = tr("[:lower:]", "[:upper:]", _in="andrew").strip()
self.assertEqual(out, "ANDREW")
def test_manual_stdin_iterable(self):
from sh import tr
test = ["testing\n", "herp\n", "derp\n"]
out = tr("[:lower:]", "[:upper:]", _in=test)
match = "".join([t.upper() for t in test])
self.assertEqual(out, match)
def test_manual_stdin_file(self):
from sh import tr
import tempfile
test_string = "testing\nherp\nderp\n"
stdin = tempfile.NamedTemporaryFile()
stdin.write(test_string.encode())
stdin.flush()
stdin.seek(0)
out = tr("[:lower:]", "[:upper:]", _in=stdin)
self.assertEqual(out, test_string.upper())
def test_manual_stdin_queue(self):
from sh import tr
try:
from Queue import Queue
except ImportError:
from queue import Queue
test = ["testing\n", "herp\n", "derp\n"]
q = Queue()
for t in test:
q.put(t)
q.put(None) # EOF
out = tr("[:lower:]", "[:upper:]", _in=q)
match = "".join([t.upper() for t in test])
self.assertEqual(out, match)
def test_environment(self):
""" tests that environments variables that we pass into sh commands
exist in the environment, and on the sh module """
import os
# this is the environment we'll pass into our commands
env = {"HERP": "DERP"}
# first we test that the environment exists in our child process as
# we've set it
py = create_tmp_test("""
import os
for key in list(os.environ.keys()):
if key != "HERP":
del os.environ[key]
print(dict(os.environ))
""")
out = python(py.name, _env=env).strip()
self.assertEqual(out, "{'HERP': 'DERP'}")
py = create_tmp_test("""
import os, sys
sys.path.insert(0, os.getcwd())
import sh
for key in list(os.environ.keys()):
if key != "HERP":
del os.environ[key]
print(dict(HERP=sh.HERP))
""")
out = python(py.name, _env=env, _cwd=THIS_DIR).strip()
self.assertEqual(out, "{'HERP': 'DERP'}")
# Test that _env also accepts os.environ which is a mpping but not a dict.
os.environ["HERP"] = "DERP"
out = python(py.name, _env=os.environ, _cwd=THIS_DIR).strip()
self.assertEqual(out, "{'HERP': 'DERP'}")
def test_which(self):
from sh import which, ls
self.assertEqual(which("fjoawjefojawe"), None)
self.assertEqual(which("ls"), str(ls))
def test_which_paths(self):
from sh import which
py = create_tmp_test("""
print("hi")
""")
test_path = dirname(py.name)
_, test_name = os.path.split(py.name)
found_path = which(test_name)
self.assertEqual(found_path, None)
found_path = which(test_name, [test_path])
self.assertEqual(found_path, py.name)
def test_no_close_fds(self):
# guarantee some extra fds in our parent process that don't close on exec. we have to explicitly do this
# because at some point (I believe python 3.4), python started being more stringent with closing fds to prevent
# security vulnerabilities. python 2.7, for example, doesn't set CLOEXEC on tempfile.TemporaryFile()s
#
# https://www.python.org/dev/peps/pep-0446/
tmp = [tempfile.TemporaryFile() for i in range(10)]
for t in tmp:
flags = fcntl.fcntl(t.fileno(), fcntl.F_GETFD)
flags &= ~fcntl.FD_CLOEXEC
fcntl.fcntl(t.fileno(), fcntl.F_SETFD, flags)
py = create_tmp_test("""
import os
print(len(os.listdir("/dev/fd")))
""")
out = python(py.name, _close_fds=False).strip()
# pick some number greater than 4, since it's hard to know exactly how many fds will be open/inherted in the
# child
self.assertGreater(int(out), 7)
for t in tmp:
t.close()
def test_close_fds(self):
# guarantee some extra fds in our parent process that don't close on exec. we have to explicitly do this
# because at some point (I believe python 3.4), python started being more stringent with closing fds to prevent
# security vulnerabilities. python 2.7, for example, doesn't set CLOEXEC on tempfile.TemporaryFile()s
#
# https://www.python.org/dev/peps/pep-0446/
tmp = [tempfile.TemporaryFile() for i in range(10)]
for t in tmp:
flags = fcntl.fcntl(t.fileno(), fcntl.F_GETFD)
flags &= ~fcntl.FD_CLOEXEC
fcntl.fcntl(t.fileno(), fcntl.F_SETFD, flags)
py = create_tmp_test("""
import os
print(os.listdir("/dev/fd"))
""")
out = python(py.name).strip()
self.assertEqual(out, "['0', '1', '2', '3']")
for t in tmp:
t.close()
def test_pass_fds(self):
# guarantee some extra fds in our parent process that don't close on exec. we have to explicitly do this
# because at some point (I believe python 3.4), python started being more stringent with closing fds to prevent
# security vulnerabilities. python 2.7, for example, doesn't set CLOEXEC on tempfile.TemporaryFile()s
#
# https://www.python.org/dev/peps/pep-0446/
tmp = [tempfile.TemporaryFile() for i in range(10)]
for t in tmp:
flags = fcntl.fcntl(t.fileno(), fcntl.F_GETFD)
flags &= ~fcntl.FD_CLOEXEC
fcntl.fcntl(t.fileno(), fcntl.F_SETFD, flags)
last_fd = tmp[-1].fileno()
py = create_tmp_test("""
import os
print(os.listdir("/dev/fd"))
""")
out = python(py.name, _pass_fds=[last_fd]).strip()
inherited = [0, 1, 2, 3, last_fd]
inherited_str = [str(i) for i in inherited]
self.assertEqual(out, str(inherited_str))
for t in tmp:
t.close()
def test_no_arg(self):
import pwd
from sh import whoami
u1 = whoami().strip()
u2 = pwd.getpwuid(os.geteuid())[0]
self.assertEqual(u1, u2)
def test_incompatible_special_args(self):
from sh import ls
self.assertRaises(TypeError, ls, _iter=True, _piped=True)
def test_invalid_env(self):
from sh import ls
exc = TypeError
if IS_PY2 and MINOR_VER == 6:
exc = ValueError
self.assertRaises(exc, ls, _env="XXX")
self.assertRaises(exc, ls, _env={"foo": 123})
self.assertRaises(exc, ls, _env={123: "bar"})
def test_exception(self):
from sh import ErrorReturnCode_2
py = create_tmp_test("""
exit(2)
""")
self.assertRaises(ErrorReturnCode_2, python, py.name)
def test_piped_exception1(self):
from sh import ErrorReturnCode_2
py = create_tmp_test("""
import sys
sys.stdout.write("line1\\n")
sys.stdout.write("line2\\n")
exit(2)
""")
py2 = create_tmp_test("")
def fn():
list(python(python(py.name, _piped=True), "-u", py2.name, _iter=True))
self.assertRaises(ErrorReturnCode_2, fn)
def test_piped_exception2(self):
from sh import ErrorReturnCode_2
py = create_tmp_test("""
import sys
sys.stdout.write("line1\\n")
sys.stdout.write("line2\\n")
exit(2)
""")
py2 = create_tmp_test("")
def fn():
python(python(py.name, _piped=True), "-u", py2.name)
self.assertRaises(ErrorReturnCode_2, fn)
def test_command_not_found(self):
from sh import CommandNotFound
def do_import():
from sh import aowjgoawjoeijaowjellll # noqa: F401
self.assertRaises(ImportError, do_import)
def do_import():
import sh
sh.awoefaowejfw
self.assertRaises(CommandNotFound, do_import)
def do_import():
import sh
sh.Command("ofajweofjawoe")
self.assertRaises(CommandNotFound, do_import)
def test_command_wrapper_equivalence(self):
from sh import Command, ls, which
self.assertEqual(Command(which("ls")), ls)
def test_doesnt_execute_directories(self):
save_path = os.environ['PATH']
bin_dir1 = tempfile.mkdtemp()
bin_dir2 = tempfile.mkdtemp()
gcc_dir1 = os.path.join(bin_dir1, 'gcc')
gcc_file2 = os.path.join(bin_dir2, 'gcc')
try:
os.environ['PATH'] = os.pathsep.join((bin_dir1, bin_dir2))
# a folder named 'gcc', its executable, but should not be
# discovered by internal which(1)-clone
os.makedirs(gcc_dir1)
# an executable named gcc -- only this should be executed
bunk_header = '#!/bin/sh\necho $*'
with open(gcc_file2, "w") as h:
h.write(bunk_header)
os.chmod(gcc_file2, int(0o755))
import sh
from sh import gcc
if IS_PY3:
self.assertEqual(gcc._path,
gcc_file2.encode(sh.DEFAULT_ENCODING))
else:
self.assertEqual(gcc._path, gcc_file2)
self.assertEqual(gcc('no-error').stdout.strip(),
'no-error'.encode("ascii"))
finally:
os.environ['PATH'] = save_path
if exists(gcc_file2):
os.unlink(gcc_file2)
if exists(gcc_dir1):
os.rmdir(gcc_dir1)
if exists(bin_dir1):
os.rmdir(bin_dir1)
if exists(bin_dir1):
os.rmdir(bin_dir2)
def test_multiple_args_short_option(self):
py = create_tmp_test("""
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-l", dest="long_option")
options, args = parser.parse_args()
print(len(options.long_option.split()))
""")
num_args = int(python(py.name, l="one two three")) # noqa: E741
self.assertEqual(num_args, 3)
num_args = int(python(py.name, "-l", "one's two's three's"))
self.assertEqual(num_args, 3)
def test_multiple_args_long_option(self):
py = create_tmp_test("""
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-l", "--long-option", dest="long_option")
options, args = parser.parse_args()
print(len(options.long_option.split()))
""")
num_args = int(python(py.name, long_option="one two three",
nothing=False))
self.assertEqual(num_args, 3)
num_args = int(python(py.name, "--long-option", "one's two's three's"))
self.assertEqual(num_args, 3)
def test_short_bool_option(self):
py = create_tmp_test("""
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-s", action="store_true", default=False, dest="short_option")
options, args = parser.parse_args()
print(options.short_option)
""")
self.assertTrue(python(py.name, s=True).strip() == "True")
self.assertTrue(python(py.name, s=False).strip() == "False")
self.assertTrue(python(py.name).strip() == "False")
def test_long_bool_option(self):
py = create_tmp_test("""
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-l", "--long-option", action="store_true", default=False, dest="long_option")
options, args = parser.parse_args()
print(options.long_option)
""")
self.assertTrue(python(py.name, long_option=True).strip() == "True")
self.assertTrue(python(py.name).strip() == "False")
def test_false_bool_ignore(self):
py = create_tmp_test("""
import sys
print(sys.argv[1:])
""")
test = True
self.assertEqual(python(py.name, test and "-n").strip(), "['-n']")
test = False
self.assertEqual(python(py.name, test and "-n").strip(), "[]")
def test_composition(self):
from sh import ls, wc
c1 = int(wc(ls("-A1"), l=True)) # noqa: E741
c2 = len(os.listdir("."))
self.assertEqual(c1, c2)
def test_incremental_composition(self):
from sh import ls, wc
c1 = int(wc(ls("-A1", _piped=True), l=True).strip()) # noqa: E741
c2 = len(os.listdir("."))
self.assertEqual(c1, c2)
def test_short_option(self):
from sh import sh
s1 = sh(c="echo test").strip()
s2 = "test"
self.assertEqual(s1, s2)
def test_long_option(self):
py = create_tmp_test("""
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-l", "--long-option", action="store", default="", dest="long_option")
options, args = parser.parse_args()
print(options.long_option.upper())
""")
self.assertTrue(python(py.name, long_option="testing").strip() == "TESTING")
self.assertTrue(python(py.name).strip() == "")
def test_raw_args(self):
py = create_tmp_test("""
from optparse import OptionParser
parser = OptionParser()
parser.add_option("--long_option", action="store", default=None,
dest="long_option1")
parser.add_option("--long-option", action="store", default=None,
dest="long_option2")
options, args = parser.parse_args()
if options.long_option1:
print(options.long_option1.upper())
else:
print(options.long_option2.upper())
""")
self.assertEqual(python(py.name,
{"long_option": "underscore"}).strip(), "UNDERSCORE")
self.assertEqual(python(py.name, long_option="hyphen").strip(), "HYPHEN")
def test_custom_separator(self):
py = create_tmp_test("""
import sys
print(sys.argv[1])
""")
opt = {"long-option": "underscore"}
correct = "--long-option=custom=underscore"
out = python(py.name, opt, _long_sep="=custom=").strip()
self.assertEqual(out, correct)
# test baking too
correct = "--long-option=baked=underscore"
python_baked = python.bake(py.name, opt, _long_sep="=baked=")
out = python_baked().strip()
self.assertEqual(out, correct)
def test_custom_separator_space(self):
py = create_tmp_test("""
import sys
print(str(sys.argv[1:]))
""")
opt = {"long-option": "space"}
correct = ["--long-option", "space"]
out = python(py.name, opt, _long_sep=" ").strip()
self.assertEqual(out, str(correct))
def test_custom_long_prefix(self):
py = create_tmp_test("""
import sys
print(sys.argv[1])
""")
out = python(py.name, {"long-option": "underscore"},
_long_prefix="-custom-").strip()
self.assertEqual(out, "-custom-long-option=underscore")
out = python(py.name, {"long-option": True},
_long_prefix="-custom-").strip()
self.assertEqual(out, "-custom-long-option")
# test baking too
out = python.bake(py.name, {"long-option": "underscore"},
_long_prefix="-baked-")().strip()
self.assertEqual(out, "-baked-long-option=underscore")
out = python.bake(py.name, {"long-option": True},
_long_prefix="-baked-")().strip()
self.assertEqual(out, "-baked-long-option")
def test_command_wrapper(self):
from sh import Command, which
ls = Command(which("ls"))
wc = Command(which("wc"))
c1 = int(wc(ls("-A1"), l=True)) # noqa: E741
c2 = len(os.listdir("."))
self.assertEqual(c1, c2)
def test_background(self):
from sh import sleep
import time