summaryrefslogtreecommitdiffhomepage
path: root/libs/tqdm/tests/tests_main.py
blob: 75727071ee6f347603679243384300e0ee16f78e (plain)
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
import sys
import subprocess
from os import path
from shutil import rmtree
from tempfile import mkdtemp
from tqdm.cli import main, TqdmKeyError, TqdmTypeError
from tqdm.utils import IS_WIN
from io import open as io_open

from tests_tqdm import with_setup, pretest, posttest, _range, closing, \
    UnicodeIO, StringIO, SkipTest


def _sh(*cmd, **kwargs):
    return subprocess.Popen(cmd, stdout=subprocess.PIPE,
                            **kwargs).communicate()[0].decode('utf-8')


class Null(object):
    def __call__(self, *_, **__):
        return self

    def __getattr__(self, _):
        return self


IN_DATA_LIST = map(str, _range(int(123)))
NULL = Null()


# WARNING: this should be the last test as it messes with sys.stdin, argv
@with_setup(pretest, posttest)
def test_main():
    """Test command line pipes"""
    ls_out = _sh('ls').replace('\r\n', '\n')
    ls = subprocess.Popen('ls', stdout=subprocess.PIPE,
                          stderr=subprocess.STDOUT)
    res = _sh(sys.executable, '-c', 'from tqdm.cli import main; main()',
              stdin=ls.stdout, stderr=subprocess.STDOUT)
    ls.wait()

    # actual test:

    assert ls_out in res.replace('\r\n', '\n')

    # semi-fake test which gets coverage:
    _SYS = sys.stdin, sys.argv

    with closing(StringIO()) as sys.stdin:
        sys.argv = ['', '--desc', 'Test CLI --delim',
                    '--ascii', 'True', '--delim', r'\0', '--buf_size', '64']
        sys.stdin.write('\0'.join(map(str, _range(int(123)))))
        # sys.stdin.write(b'\xff')  # TODO
        sys.stdin.seek(0)
        main()
    sys.stdin = IN_DATA_LIST

    sys.argv = ['', '--desc', 'Test CLI pipes',
                '--ascii', 'True', '--unit_scale', 'True']
    import tqdm.__main__  # NOQA

    with closing(StringIO()) as sys.stdin:
        IN_DATA = '\0'.join(IN_DATA_LIST)
        sys.stdin.write(IN_DATA)
        sys.stdin.seek(0)
        sys.argv = ['', '--ascii', '--bytes=True', '--unit_scale', 'False']
        with closing(UnicodeIO()) as fp:
            main(fp=fp)
            assert str(len(IN_DATA)) in fp.getvalue()
    sys.stdin = IN_DATA_LIST

    # test --log
    with closing(StringIO()) as sys.stdin:
        sys.stdin.write('\0'.join(map(str, _range(int(123)))))
        sys.stdin.seek(0)
        # with closing(UnicodeIO()) as fp:
        main(argv=['--log', 'DEBUG'], fp=NULL)
        # assert "DEBUG:" in sys.stdout.getvalue()
    sys.stdin = IN_DATA_LIST

    # clean up
    sys.stdin, sys.argv = _SYS


def test_manpath():
    """Test CLI --manpath"""
    if IS_WIN:
        raise SkipTest
    tmp = mkdtemp()
    man = path.join(tmp, "tqdm.1")
    assert not path.exists(man)
    try:
        main(argv=['--manpath', tmp], fp=NULL)
    except SystemExit:
        pass
    else:
        raise SystemExit("Expected system exit")
    assert path.exists(man)
    rmtree(tmp, True)


def test_comppath():
    """Test CLI --comppath"""
    if IS_WIN:
        raise SkipTest
    tmp = mkdtemp()
    man = path.join(tmp, "tqdm_completion.sh")
    assert not path.exists(man)
    try:
        main(argv=['--comppath', tmp], fp=NULL)
    except SystemExit:
        pass
    else:
        raise SystemExit("Expected system exit")
    assert path.exists(man)

    # check most important options appear
    with io_open(man, mode='r', encoding='utf-8') as fd:
        script = fd.read()
    opts = set([
        '--help', '--desc', '--total', '--leave', '--ncols', '--ascii',
        '--dynamic_ncols', '--position', '--bytes', '--nrows', '--delim',
        '--manpath', '--comppath'
    ])
    assert all(args in script for args in opts)
    rmtree(tmp, True)


def test_exceptions():
    """Test CLI Exceptions"""
    _SYS = sys.stdin, sys.argv
    sys.stdin = IN_DATA_LIST

    sys.argv = ['', '-ascii', '-unit_scale', '--bad_arg_u_ment', 'foo']
    try:
        main(fp=NULL)
    except TqdmKeyError as e:
        if 'bad_arg_u_ment' not in str(e):
            raise
    else:
        raise TqdmKeyError('bad_arg_u_ment')

    sys.argv = ['', '-ascii', '-unit_scale', 'invalid_bool_value']
    try:
        main(fp=NULL)
    except TqdmTypeError as e:
        if 'invalid_bool_value' not in str(e):
            raise
    else:
        raise TqdmTypeError('invalid_bool_value')

    sys.argv = ['', '-ascii', '--total', 'invalid_int_value']
    try:
        main(fp=NULL)
    except TqdmTypeError as e:
        if 'invalid_int_value' not in str(e):
            raise
    else:
        raise TqdmTypeError('invalid_int_value')

    # test SystemExits
    for i in ('-h', '--help', '-v', '--version'):
        sys.argv = ['', i]
        try:
            main(fp=NULL)
        except SystemExit:
            pass
        else:
            raise ValueError('expected SystemExit')

    # clean up
    sys.stdin, sys.argv = _SYS