File: test_cmd.py

package info (click to toggle)
ubelt 1.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,180 kB
  • sloc: python: 15,487; sh: 807; makefile: 24
file content (545 lines) | stat: -rw-r--r-- 18,849 bytes parent folder | download | duplicates (2)
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
import pytest
import sys
import ubelt as ub

# import shlex
# PYEXE = shlex.quote(sys.executable)
PYEXE = sys.executable


def test_cmd_stdout():
    """
    Debug:

        # Issues on windows
        python -c "import ubelt; ubelt.cmd('echo hello stdout')"

        python -c "import subprocess; subprocess.call(['echo', 'hi'])"

        proc = subprocess.Popen(args, stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE, shell=shell,
                                universal_newlines=True, cwd=cwd, env=env)

    """
    with ub.CaptureStdout() as cap:
        result = ub.cmd('echo hello stdout', verbose=True)
    assert result['out'].strip() == 'hello stdout'
    assert cap.text.strip() == 'hello stdout'


def test_cmd_veryverbose():
    with ub.CaptureStdout() as cap:
        result = ub.cmd('echo hello stdout', verbose=3)
    assert result['out'].strip() == 'hello stdout'
    print(cap.text)
    # assert cap.text.strip() == 'hello stdout'


def test_tee_false():
    with ub.CaptureStdout() as cap:
        result = ub.cmd('echo hello stdout', verbose=3, tee=False)
    assert result['out'].strip() == 'hello stdout'
    assert 'hello world' not in cap.text
    print(cap.text)


def test_cmd_stdout_quiet():
    with ub.CaptureStdout() as cap:
        result = ub.cmd('echo hello stdout', verbose=False)
    assert result['out'].strip() == 'hello stdout', 'should still capture internally'
    assert cap.text.strip() == '', 'nothing should print to stdout'


def test_cmd_stderr():
    result = ub.cmd('echo hello stderr 1>&2', shell=True, verbose=True)
    assert result['err'].strip() == 'hello stderr'


def test_cmd_with_list_of_pathlib():
    """
    ub.cmd can accept a pathlib.Path in a list of its arguments.
    """
    if not ub.POSIX:
        pytest.skip('posix only')
    fpath = ub.Path(ub.__file__)
    result = ub.cmd(['ls', fpath])
    assert str(fpath) in result['out']


def test_cmd_with_single_pathlib():
    """
    ub.cmd can accept a pathlib.Path as its single argument
    """
    if not ub.POSIX:
        pytest.skip('posix only')
    ls_exe = ub.Path(ub.find_exe('ls'))
    result = ub.cmd(ls_exe)
    result.check_returncode()


def test_cmd_tee_auto():
    """
    pytest ubelt/tests/test_cmd.py -k tee_backend
    pytest ubelt/tests/test_cmd.py
    """
    command = '{pyexe} -c "for i in range(100): print(str(i))"'.format(pyexe=PYEXE)
    result = ub.cmd(command, verbose=0, tee_backend='auto')
    assert result['out'] == '\n'.join(list(map(str, range(100)))) + '\n'


def test_cmd_tee_thread():
    """
    CommandLine:
        pytest ubelt/tests/test_cmd.py::test_cmd_tee_thread -s
        python ubelt/tests/test_cmd.py test_cmd_tee_thread
    """
    if 'tqdm' in sys.modules:
        if tuple(map(int, sys.modules['tqdm'].__version__.split('.'))) < (4, 19):
            pytest.skip('threads cause issues with early tqdms')

    import threading
    # check which threads currently exist (ideally 1)
    existing_threads = list(threading.enumerate())
    print('existing_threads = {!r}'.format(existing_threads))

    if ub.WIN32:
        # Windows cant break apart commands consistently
        command = [PYEXE, '-c', "for i in range(10): print(str(i))"]
    else:
        command = '{pyexe} -c "for i in range(10): print(str(i))"'.format(pyexe=PYEXE)
    result = ub.cmd(command, verbose=0, tee_backend='thread')
    assert result['out'] == '\n'.join(list(map(str, range(10)))) + '\n'

    after_threads = list(threading.enumerate())
    print('after_threads = {!r}'.format(after_threads))
    assert len(existing_threads) <= len(after_threads), (
        'we should be cleaning up our threads')


@pytest.mark.skipif(sys.platform == 'win32', reason='not available on win32')
def test_cmd_tee_select():
    command = '{pyexe} -c "for i in range(100): print(str(i))"'.format(pyexe=PYEXE)
    result = ub.cmd(command, verbose=1, tee_backend='select')
    assert result['out'] == '\n'.join(list(map(str, range(100)))) + '\n'

    command = '{pyexe} -c "for i in range(100): print(str(i))"'.format(pyexe=PYEXE)
    result = ub.cmd(command, verbose=0, tee_backend='select')
    assert result['out'] == '\n'.join(list(map(str, range(100)))) + '\n'


@pytest.mark.skipif(sys.platform == 'win32', reason='not available on win32')
def test_cmd_tee_badmethod():
    """
    pytest tests/test_cmd.py::test_cmd_tee_badmethod
    """
    command = '{pyexe} -c "for i in range(100): print(str(i))"'.format(pyexe=PYEXE)
    with pytest.raises(ValueError):
        ub.cmd(command, verbose=2, tee_backend='bad tee backend')


def test_cmd_multiline_stdout():
    """
    python ubelt/tests/test_cmd.py test_cmd_multiline_stdout
    pytest ubelt/tests/test_cmd.py::test_cmd_multiline_stdout
    """
    if ub.WIN32:
        # Windows cant break apart commands consistently
        command = [PYEXE, '-c', "for i in range(10): print(str(i))"]
    else:
        command = '{pyexe} -c "for i in range(10): print(str(i))"'.format(pyexe=PYEXE)
    result = ub.cmd(command, verbose=0)
    assert result['out'] == '\n'.join(list(map(str, range(10)))) + '\n'


@pytest.mark.skipif(sys.platform == 'win32', reason='does not run on win32')
def test_cmd_interleaved_streams_sh():
    """
    A test that ``Crosses the Streams'' of stdout and stderr

    pytest ubelt/tests/test_cmd.py::test_cmd_interleaved_streams_sh
    """
    if False:
        sh_script = ub.codeblock(
            r'''
            for i in `seq 0 29`;
            do
                sleep .001
                >&1 echo "O$i"
                if [ "$(($i % 5))" = "0" ]; then
                    >&2 echo "!E$i"
                fi
            done
            ''').lstrip()
        result = ub.cmd(sh_script, shell=True, verbose=0)

        assert result['out'] == 'O0\nO1\nO2\nO3\nO4\nO5\nO6\nO7\nO8\nO9\nO10\nO11\nO12\nO13\nO14\nO15\nO16\nO17\nO18\nO19\nO20\nO21\nO22\nO23\nO24\nO25\nO26\nO27\nO28\nO29\n'
        assert result['err'] == '!E0\n!E5\n!E10\n!E15\n!E20\n!E25\n'
    else:
        sh_script = ub.codeblock(
            r'''
            for i in `seq 0 15`;
            do
                sleep .000001
                >&1 echo "O$i"
                if [ "$(($i % 5))" = "0" ]; then
                    >&2 echo "!E$i"
                fi
            done
            ''').lstrip()
        result = ub.cmd(sh_script, shell=True, verbose=0)

        assert result['out'] == 'O0\nO1\nO2\nO3\nO4\nO5\nO6\nO7\nO8\nO9\nO10\nO11\nO12\nO13\nO14\nO15\n'
        assert result['err'] == '!E0\n!E5\n!E10\n!E15\n'


@pytest.mark.skipif(sys.platform == 'win32', reason='does not run on win32')
def test_cmd_interleaved_streams_py():
    # apparently multiline quotes dont work on win32
    if False:
        # slow mode
        py_script = ub.codeblock(
            r'''
            python -c "
            import sys
            import time
            for i in range(30):
                time.sleep(.001)
                sys.stdout.write('O{}\n'.format(i))
                sys.stdout.flush()
                if i % 5 == 0:
                    sys.stderr.write('!E{}\n'.format(i))
                    sys.stderr.flush()
            "
            ''').lstrip().format(pyexe=PYEXE)
        result = ub.cmd(py_script, verbose=0)

        assert result['out'] == 'O0\nO1\nO2\nO3\nO4\nO5\nO6\nO7\nO8\nO9\nO10\nO11\nO12\nO13\nO14\nO15\nO16\nO17\nO18\nO19\nO20\nO21\nO22\nO23\nO24\nO25\nO26\nO27\nO28\nO29\n'
        assert result['err'] == '!E0\n!E5\n!E10\n!E15\n!E20\n!E25\n'
    else:
        # faster mode
        py_script = PYEXE + ' ' + ub.codeblock(
            r'''
            -c "
            import sys
            import time
            for i in range(15):
                time.sleep(.000001)
                sys.stdout.write('O{}\n'.format(i))
                sys.stdout.flush()
                if i % 5 == 0:
                    sys.stderr.write('!E{}\n'.format(i))
                    sys.stderr.flush()
            "
            ''').lstrip()
        result = ub.cmd(py_script, verbose=0)

        assert result['out'] == 'O0\nO1\nO2\nO3\nO4\nO5\nO6\nO7\nO8\nO9\nO10\nO11\nO12\nO13\nO14\n'
        assert result['err'] == '!E0\n!E5\n!E10\n'


def test_cwd():
    """
    CommandLine:
        python ~/code/ubelt/ubelt/tests/test_cmd.py test_cwd
    """
    import sys
    import os
    import ubelt as ub
    if not sys.platform.startswith('win32'):
        dpath = ub.Path.appdir('ubelt/tests').ensuredir()
        dpath = os.path.realpath(dpath)
        info = ub.cmd('pwd', cwd=dpath, shell=True)
        print('info = {}'.format(ub.urepr(info, nl=1)))
        print('dpath = {!r}'.format(dpath))
        assert info['out'].strip() == dpath


def test_env():
    import sys
    import ubelt as ub
    import os
    if not sys.platform.startswith('win32'):
        env = os.environ.copy()
        env.update({'UBELT_TEST_ENV': '42'})
        info = ub.cmd('echo $UBELT_TEST_ENV', env=env, shell=True)
        print(info['out'])
        assert info['out'].strip() == env['UBELT_TEST_ENV']


# @pytest.mark.skipif(sys.platform == 'win32', reason='does not run on win32')
def test_timeout():
    """
    xdoctest ~/code/ubelt/tests/test_cmd.py test_timeout
    """
    import subprocess
    import pytest
    # Infinite script
    py_script = ub.codeblock(
        r'''
        {pyexe} -c "
        while True:
            pass
        "
        ''').lstrip().format(pyexe=PYEXE)

    # if ub.WIN32:
    #     # Windows cant break apart commands consistently
    #     py_script = [PYEXE, '-c', ub.codeblock(
    #         r'''
    #         "
    #         while True:
    #             pass
    #         "
    #         ''').lstrip()]

    initial_grid = list(ub.named_product({
        'tee': [0, 1],
        'capture': [0, 1],
        'timeout': [0, 0.001, 0.01],
    }))
    expanded_grid = []
    for kw in initial_grid:
        kw = ub.udict(kw)
        if kw['tee']:
            if not ub.WIN32:
                expanded_grid.append(kw | {'tee_backend': 'select'})
            expanded_grid.append(kw | {'tee_backend': 'thread'})
        else:
            expanded_grid.append(kw)

    for kw in expanded_grid:
        print('kw = {}'.format(ub.urepr(kw, nl=0)))
        with pytest.raises(subprocess.TimeoutExpired):
            ub.cmd(py_script, **kw)
            return


def test_subprocess_compatability():
    import subprocess
    import ubelt as ub

    def check_compatability(command, common_kwargs):
        ub_out = ub.cmd(command, verbose=1, capture=False, **common_kwargs)
        sp_out = subprocess.run(command, **common_kwargs)
        assert sp_out.stderr == ub_out.stderr
        assert sp_out.stdout == ub_out.stdout
        assert sp_out.returncode == ub_out.returncode
        assert sp_out.args == ub_out.args
        assert ub_out.check_returncode() == sp_out.check_returncode()

        if sys.version_info[0:2] >= (3, 11):
            ub_out = ub.cmd(command, verbose=0, capture=True, **common_kwargs)
            sp_out = subprocess.run(command, capture_output=True, universal_newlines=True, **common_kwargs)
            assert sp_out.stderr == ub_out.stderr
            assert sp_out.stdout == ub_out.stdout
            assert sp_out.returncode == ub_out.returncode
            assert sp_out.args == ub_out.args
            assert ub_out.check_returncode() == sp_out.check_returncode()

        ub_out = ub.cmd(command, verbose=0, capture=False, **common_kwargs)
        sp_out = subprocess.run(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, **common_kwargs)
        assert sp_out.stderr == ub_out.stderr
        assert sp_out.stdout == ub_out.stdout
        assert sp_out.returncode == ub_out.returncode
        assert sp_out.args == ub_out.args
        assert ub_out.check_returncode() == sp_out.check_returncode()

    command = ['echo', 'hello world']
    common_kwargs = {'shell': False}
    check_compatability(command, common_kwargs)

    command = 'echo hello world'
    common_kwargs = {'shell': True}
    check_compatability(command, common_kwargs)

    if not ub.WIN32:
        command = ['ls', '-l']
        common_kwargs = {'shell': False}
        check_compatability(command, common_kwargs)

        command = 'ls -l'
        common_kwargs = {'shell': True}
        check_compatability(command, common_kwargs)


def test_failing_subprocess_compatability():
    import subprocess
    import pytest
    import ubelt as ub

    def check_failing_compatability(command, common_kwargs):
        ub_out = ub.cmd(command, verbose=1, capture=False, **common_kwargs)
        sp_out = subprocess.run(command, **common_kwargs)
        assert sp_out.stderr == ub_out.stderr
        assert sp_out.stdout == ub_out.stdout
        assert sp_out.returncode == ub_out.returncode
        assert sp_out.args == ub_out.args
        with pytest.raises(subprocess.CalledProcessError):
            ub_out.check_returncode()
        with pytest.raises(subprocess.CalledProcessError):
            sp_out.check_returncode()

        if sys.version_info[0:2] >= (3, 11):
            ub_out = ub.cmd(command, verbose=0, capture=True, **common_kwargs)
            sp_out = subprocess.run(command, capture_output=True, universal_newlines=True, **common_kwargs)
            assert sp_out.stderr == ub_out.stderr
            assert sp_out.stdout == ub_out.stdout
            assert sp_out.returncode == ub_out.returncode
            assert sp_out.args == ub_out.args
            with pytest.raises(subprocess.CalledProcessError):
                ub_out.check_returncode()
            with pytest.raises(subprocess.CalledProcessError):
                sp_out.check_returncode()

        ub_out = ub.cmd(command, verbose=0, capture=False, **common_kwargs)
        sp_out = subprocess.run(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, **common_kwargs)
        assert sp_out.stderr == ub_out.stderr
        assert sp_out.stdout == ub_out.stdout
        assert sp_out.returncode == ub_out.returncode
        assert sp_out.args == ub_out.args
        with pytest.raises(subprocess.CalledProcessError):
            ub_out.check_returncode()
        with pytest.raises(subprocess.CalledProcessError):
            sp_out.check_returncode()

    if not ub.WIN32:
        command = ['ls', '-l', 'does not exist']
        common_kwargs = {'shell': False}
        check_failing_compatability(command, common_kwargs)

        command = 'ls -l does not exist'
        common_kwargs = {'shell': True}
        check_failing_compatability(command, common_kwargs)


def test_cmdoutput_object_with_non_subprocess_backends():
    import ubelt as ub
    import pytest

    info = ub.cmd('echo hello world', verbose=1)
    assert info.stdout.strip() == 'hello world'
    assert info.stderr.strip() == ''
    info.check_returncode()

    # In this case, when tee=0 the user can still capture the output
    info = ub.cmd('echo hello world', detach=True, capture=True, tee=0)
    with pytest.raises(KeyError):
        info.stdout
    with pytest.raises(KeyError):
        info.stderr
    assert info['proc'].communicate()[0] is not None

    # In this case, when tee=0 and capture=False, the user cannot capture the output
    info = ub.cmd('echo hello world', detach=True, capture=False, tee=0)
    with pytest.raises(KeyError):
        info.stdout
    with pytest.raises(KeyError):
        info.stderr
    assert info['proc'].communicate()[0] is None

    # In this case when tee=1, a detached process will show its output but
    # capturing will not be possible.
    info = ub.cmd('echo hello world', detach=True, capture=False, tee=1)
    with pytest.raises(KeyError):
        info.stdout
    with pytest.raises(KeyError):
        info.stderr
    info['proc'].communicate()
    info.args
    with pytest.raises(KeyError):
        info.check_returncode()

    # Check attributes when system=True
    info = ub.cmd('echo hello world', system=True)
    assert info.stdout is None
    assert info.stderr is None
    assert info.args == 'echo hello world'
    info.check_returncode()

    info = ub.cmd(['echo', 'hello', 'world'], system=True, shell=True)
    assert info.stdout is None
    assert info.stderr is None
    assert info.args == 'echo hello world'
    info.check_returncode()


def _dev_debug_timeouts():
    """
    Notes used when implementing timeout

    Ignore:
        # For debugging and development
        import sys
        from ubelt.util_cmd import (
            _textio_iterlines, _proc_async_iter_stream,
            _proc_iteroutput_thread, _proc_iteroutput_select, _tee_output, logger)

        import logging
        logging.basicConfig(
            format='[%(asctime)s %(threadName)s %(levelname)s] %(message)s',
            level=logging.DEBUG,
            force=True
        )
        logging.info('hi')
        logging.debug('hi')

        import subprocess
        args = ['ping', 'localhost', '-c', '1000']
        args = ['python', '-c', "{}".format(chr(10) + ub.codeblock(
            '''
            import sys
            import time
            import random
            import ubelt as ub
            wait_times = [0.5, 1.0, 2.0]
            def pseudo_sleep(sec):
                timer = ub.Timer().tic()
                while timer.toc() < sec:
                    ...
            print('Starting a process')
            while True:
                sec = random.choice(wait_times)
                print('Sleep for {} seconds'.format(sec))
                #pseudo_sleep(sec)
                #time.sleep(sec)
                time.sleep(0.05)
                print('Slept for {} seconds'.format(sec))
            ''') + chr(10))]
        args = ['python', '-c', "{}".format(chr(10) + ub.codeblock(
            '''
            import sys
            import ubelt as ub
            import time
            print('Starting a process')
            for i in range(4):
                print('Step {} {}'.format(i, ub.timestamp(precision=4)))
                time.sleep(1.0)
            ''') + chr(10))]
        lines = []
        log = lines.append
        info = ub.cmd(args, verbose=3, shell=True, tee_backend='thread', timeout=10)

        try:
            ub.cmd(args, verbose=0, shell=True, tee_backend='thread', timeout=2)
        except subprocess.TimeoutExpired as e:
            std_ex = e

        try:
            ub.cmd(args, verbose=3, shell=True, tee_backend='thread', timeout=2)
        except subprocess.TimeoutExpired as e:
            verb_ex = e

        print('verb_ex.__dict__ = {}'.format(ub.urepr(verb_ex.__dict__, nl=1)))
        print('std_ex.__dict__ = {}'.format(ub.urepr(std_ex.__dict__, nl=1)))
    """


if __name__ == '__main__':
    """
        pytest ubelt/tests/test_cmd.py -s

        python ~/code/ubelt/ubelt/tests/test_cmd.py test_cmd_veryverbose
    """

    import xdoctest
    xdoctest.doctest_module(__file__)