This repository was archived by the owner on Oct 3, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathtest_console.py
237 lines (177 loc) · 7.5 KB
/
test_console.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
# -*- coding: utf-8 -*-
import datetime
import time
import click
from click.testing import CliRunner
from clickclick import (Action, AliasedGroup, FloatRange, OutputFormat,
UrlType, action, choice, error, fatal_error,
format_time, info, ok, print_table, warning)
import pytest
def test_echo():
action('Action..')
ok()
action('Action..')
error(' some error')
action('Action..')
with pytest.raises(SystemExit):
fatal_error(' some fatal error') # noqa
action('Action..')
warning(' some warning')
info('Some info')
def test_action():
try:
with Action('Try and fail..'):
raise Exception()
except:
pass
with Action('Perform and progress..') as act:
act.progress()
act.error('failing..')
with Action('Perform and progress..') as act:
act.progress()
act.warning('warning..')
with Action('Perform and progress..') as act:
act.progress()
act.ok('all fine')
with Action('Perform and progress..') as act:
act.progress()
with Action('Perform, progress and done', ok_msg='DONE') as act:
act.progress()
with Action('Perform action new line', nl=True):
print('In new line!')
with pytest.raises(SystemExit):
with Action('Try and fail badly..') as act:
act.fatal_error('failing..')
def test_print_tables():
print_table('Name Status some_time'.split(), [{'Name': 'foobar', 'Status': True, 'some_time': 'now'},
{'some_time': time.time() - 123},
{'some_time': time.time() - 950},
{'Status': 'long output', 'some_time': 0}])
print_table('Name Status some_time'.split(), [{'Name': 'foobar', 'Status': True, 'some_time': 'now'},
{'some_time': time.time() - 123},
{'some_time': time.time() - 950},
{'Status': 'long output', 'some_time': 0}],
styles='wrong format',
max_column_widths={'Status': 4})
print_table('Name Status some_time'.split(), [{'Name': {'orignal': 'bla', 'other': 'foo'}, 'Status': 'ERROR'}],
styles={'ERROR': {'fg': 'red', 'bold': True}})
def test_text_out(capsys):
with OutputFormat('text'):
warning('this is a warning')
print_table('a b'.split(), [{}, {}])
out, err = capsys.readouterr()
assert u'A│B\n \n \n' == out
assert 'this is a warning\n' == err
def test_json_out(capsys):
with OutputFormat('json'):
warning('this is a warning')
print_table('a b'.split(), [{}, {}])
out, err = capsys.readouterr()
assert '[{"a": null, "b": null}, {"a": null, "b": null}]\n' == out
assert 'this is a warning\n' == err
def test_yaml_out(capsys):
with OutputFormat('yaml'):
warning('this is a warning')
print_table('a b'.split(), [{}, {}])
out, err = capsys.readouterr()
assert 'a: null\nb: null\n---\na: null\nb: null\n\n' == out
assert 'this is a warning\n' == err
def test_tsv_out(capsys):
with OutputFormat('tsv'):
warning('this is a warning')
print_table('a b'.split(), [{"a": 1}, {"b": 2}])
out, err = capsys.readouterr()
assert 'a\tb\n1\t\n\t2\n' == out
assert 'this is a warning\n' == err
def test_float_range():
fr = FloatRange(1, 7.25, clamp=True)
assert str(fr) == 'FloatRange(1, 7.25)'
assert 7.25 == fr.convert('100', None, None)
fr = FloatRange(1, 7.25, clamp=False)
try:
assert 7.25 == fr.convert('100', None, None)
except click.exceptions.BadParameter as e:
assert e.format_message() == 'Invalid value: 100.0 is not in the valid range of 1 to 7.25.'
fr = FloatRange(min=10, clamp=True)
assert 10 == fr.convert('7.25', None, None)
fr = FloatRange(min=10, clamp=False)
try:
assert 10 == fr.convert('7.25', None, None)
except click.exceptions.BadParameter as e:
assert e.format_message() == 'Invalid value: 7.25 is smaller than the minimum valid value 10.'
fr = FloatRange(max=5, clamp=True)
assert 5 == fr.convert('100', None, None)
fr = FloatRange(max=5, clamp=False)
try:
assert 5 == fr.convert('100', None, None)
except click.exceptions.BadParameter as e:
assert e.format_message() == 'Invalid value: 100.0 is bigger than the maximum valid value 5.'
fr = FloatRange(0, 5)
assert 3 == fr.convert('3', None, None)
def test_url_type():
ut = UrlType()
assert str(ut) == "UrlType('https', ('http', 'https'))"
assert 'https://foobar' == ut.convert(' foobar ', None, None)
try:
ut.convert(' ', None, None)
except click.exceptions.BadParameter as e:
assert e.format_message() == 'Invalid value: "" is not a valid URL'
try:
ut.convert('ftp://test', None, None)
except click.exceptions.BadParameter as e:
assert e.format_message() == 'Invalid value: "ftp" is not one of the allowed URL schemes (http, https)'
def test_choice(monkeypatch):
def get_number():
yield 50
while True:
yield 1
generator = get_number()
def returnnumber(*args, **vargs):
return next(generator)
monkeypatch.setattr('click.prompt', returnnumber)
assert 'a' == choice('Please choose', ['a', 'b'])
assert 'a' == choice('Please choose', [('a', 'Label A')])
def test_format_time(monkeypatch):
now = datetime.datetime.now()
one_minute = datetime.timedelta(minutes=1)
two_hours = datetime.timedelta(hours=2)
two_days = datetime.timedelta(days=2)
three_days = datetime.timedelta(days=3)
monkeypatch.setattr('clickclick.get_now', lambda: now)
assert 's ago' in format_time(time.mktime((now - one_minute).timetuple()))
assert '2h ago' == format_time(time.mktime((now - two_hours).timetuple()))
assert '48h ago' == format_time(time.mktime((now - two_days).timetuple()))
assert '3d ago' == format_time(time.mktime((now - three_days).timetuple()))
def test_cli(monkeypatch):
runner = CliRunner()
result = runner.invoke(cli, ['l'])
assert 'Error: Too many matches: last, list' in result.output
runner = CliRunner()
result = runner.invoke(cli, ['li'])
assert 'list\n' == result.output
runner = CliRunner()
result = runner.invoke(cli, ['last'])
assert 'last\n' == result.output
runner = CliRunner()
result = runner.invoke(cli, ['notexists'])
assert 'Error: No such command "notexists"' in result.output
def test_choice_default(monkeypatch):
runner = CliRunner()
result = runner.invoke(cli, ['testchoice'], input='\n\n\n1\n')
assert '3) c\nPlease select (1-3) [3]: \n>>c<<\n' in result.output
assert '3) Label C\nPlease select (1-3) [2]: \n>>b<<\n' in result.output
assert '3) Label C\nPlease select (1-3): \nPlease select (1-3): 1\n>>a<<\n' in result.output
@click.group(cls=AliasedGroup)
def cli():
pass
@cli.command('list')
def list():
print('list')
@cli.command('last')
def last():
print('last')
@cli.command('testchoice')
def choicetest():
print('>>{}<<'.format(choice('Please choose', ['a', 'b', 'c'], default='c')))
print('>>{}<<'.format(choice('Please choose', [('a', 'Label A'), ('b', 'Label B'), ('c', 'Label C')], default='b')))
print('>>{}<<'.format(choice('Please choose', [('a', 'Label A'), ('b', 'Label B'), ('c', 'Label C')], default='x')))