-
Notifications
You must be signed in to change notification settings - Fork 3
/
tests.py
388 lines (290 loc) · 12.4 KB
/
tests.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
# -*- coding: utf-8 -*-
from __future__ import (unicode_literals, print_function)
import os
import sys
import shlex
import tempfile
import subprocess
from io import BytesIO
try:
import pytest
except ImportError:
sys.exit("The unit tests require the package 'pytest' to be installed.")
import six
from pyped import execute_statements, __VERSION__
@pytest.fixture
def assert_print(capfd):
""" Return a function that check expected strings have been printed """
def _(*expected):
""" Check was expected strings have been printed """
expected = "\n".join(expected)
if not expected.endswith("\n"):
expected += "\n"
resout, reserr = capfd.readouterr()
assert resout == expected
return _
@pytest.fixture
def assert_cmd_print():
""" Return a function that check a command printed expected strings"""
def _(cmd_args, expected_strings, stdin=None):
""" Check a command printed expected strings """
if isinstance(cmd_args, six.binary_type):
cmd_args = [cmd_args]
cmd = [sys.executable.encode('ascii'), b"pyped.py"]
cmd.extend(cmd_args)
if six.PY3:
cmd = [x.decode('utf8') for x in cmd]
if not isinstance(expected_strings, six.binary_type):
expected_strings = b"\n".join(expected_strings)
if not expected_strings.endswith(b"\n"):
expected_strings += b"\n"
try:
if stdin is not None:
if not isinstance(stdin, six.binary_type):
stdin = b"\n".join(stdin)
if not stdin.endswith(b"\n"):
stdin += b"\n"
# using a temporary file as pipe since real pipes cause
# trouble with line breaks
fake_pipe = tempfile.TemporaryFile()
fake_pipe.write(stdin)
fake_pipe.seek(0)
# piped_stdin = subprocess.Popen(['echo', stdin], stdout=subprocess.PIPE, shell=True)
# piped_stdin = subprocess.Popen(['echo', stdin], stdout=subprocess.PIPE, shell=True, universal_newlines=True)
res = subprocess.check_output(cmd, stdin=fake_pipe,
# stderr=subprocess.PIPE,
universal_newlines=True)
else:
res = subprocess.check_output(cmd, stderr=subprocess.PIPE, universal_newlines=True)
except subprocess.CalledProcessError as e:
print(e.output)
raise
if six.PY3:
expected_strings = expected_strings.decode('utf8')
assert res == expected_strings
return _
def wrapper(statements, stdin=None, *args, **kwargs):
""" A wrapper around pyped.execute_statements() to make testing easier.
Convert scalar arguments in lists when required, and strings to
file like objects if necessary.
Add an empty list, named "lst", to the context so it can be filled
with values
"""
if isinstance(statements, six.binary_type):
statements = [statements]
if stdin:
if not isinstance(stdin, six.binary_type):
stdin = b"\n".join(stdin)
stdin = BytesIO(stdin)
return execute_statements(statements, stdin, *args, **kwargs)
# For non command tests, we use the OS separator in inputs, and the
# universal separator as ouput (since this is what print() add)
def test_execute_python_onliner(assert_print):
wrapper(b"print(1)")
assert_print("1")
def test_print_stdin_lines(assert_print):
wrapper(b"print(x)", b"a")
assert_print("a")
wrapper(b"print(x)", [b"a", b"b"])
assert_print("a", "b")
# testing counter
wrapper(b"print(i)", [b"a", b"b"])
assert_print("1", "2")
def test_option_additional_context(assert_print):
wrapper(b"print(foo)", b"1", additional_context={'foo': 'bar'})
assert_print("bar")
def test_option_autoprint(assert_print):
wrapper(b"1", autoprint=True)
assert_print("1")
wrapper(b"x", b"1", autoprint=True)
assert_print("1")
def test_option_charset(assert_print):
wrapper("print('é')".encode('cp1252'), stdin_charset="cp1252")
assert_print("é")
with pytest.raises(UnicodeDecodeError):
wrapper("print('é')".encode('cp1252'))
def test_option_before(assert_print):
wrapper(b"print(foo)", before=b"foo = 'bar'")
assert_print("bar")
with pytest.raises(NameError):
wrapper(b"print(foo)")
def test_option_after(assert_print):
wrapper(b"foo = 'bar'", after=b"print(foo)")
assert_print("bar")
with pytest.raises(NameError):
wrapper(b"do = 'bar'", after=b"print(foo)")
def test_option_split(assert_print):
wrapper(b"print('-'.join(f))", b"1\t2 3", split=b"\s+")
assert_print("1-2-3")
def test_option_iterable(assert_print):
wrapper(b"print(sum(map(int, l)))", [b"1", b"2"], iterable=True)
assert_print("3")
# split and iterable are not compatible
with pytest.raises(ValueError):
wrapper(b"print(sum(map(int, l)))", [b"1", b"2"],
iterable=True, split="-")
def test_option_rstrip(capfd):
execute_statements([b"print(x)"], BytesIO(b"1\n2\n"))
resout, reserr = capfd.readouterr()
assert resout == "1\n2\n"
execute_statements([b"print(x)"], BytesIO(b"1\n2\n"),
rstrip="")
resout, reserr = capfd.readouterr()
assert resout == "1\n\n2\n\n"
execute_statements([b"print(x)"],
BytesIO(b"1.\n2.\n"),
rstrip=".\n")
resout, reserr = capfd.readouterr()
assert resout == "1\n2\n"
def test_option_full(capfd):
execute_statements([b"print(stdin)"], BytesIO(b"1\n2\n"),
full=True)
resout, reserr = capfd.readouterr()
assert resout == "1\n2\n\n"
# x should not exists
with pytest.raises(NameError):
execute_statements([b"print(x)"], BytesIO(b"1\n2\n"),
full=True)
# split should work
execute_statements([b"print(f[0])"],
BytesIO(b"1-\n" + b"2\n"),
full=True, split=b"-")
resout, reserr = capfd.readouterr()
assert resout == "1\n"
# rstrip should have no effect
execute_statements([b"print(stdin)"], BytesIO(b"1\n2\n"),
full=True, rstrip=b"")
resout, reserr = capfd.readouterr()
assert resout == "1\n2\n\n"
# you should not be able to set full and iterable together
with pytest.raises(ValueError):
execute_statements([b"print(x)"], BytesIO(b"1\n2\n"),
full=True, iterable=True)
# decode works with full
execute_statements([b"print(stdin)"], BytesIO("é".encode('cp1252')),
full=True, stdin_charset="cp1252")
resout, reserr = capfd.readouterr()
assert resout == "é\n"
# autoprint works with full
execute_statements([b"stdin"], BytesIO(b"1"), autoprint=True, full=True)
resout, reserr = capfd.readouterr()
assert resout == "1\n"
def test_option_json(assert_print, capfd):
wrapper(b"print(j[0]['a'])", b'[{"a": 1}]', parse_json=True)
assert_print("1")
# x is not available
with pytest.raises(NameError):
wrapper(b"print(x)", b'[{"a": 1}]', parse_json=True)
# you can't mix json parsing with iterable, full or split
with pytest.raises(ValueError):
wrapper(b"print(j[0]['a'])", b'[{"a": 1}]', parse_json=True, full=True)
with pytest.raises(ValueError):
wrapper(b"print(j[0]['a'])", b'[{"a": 1}]', parse_json=True, split="-")
with pytest.raises(ValueError):
wrapper(b"print(j[0]['a'])", b'[{"a": 1}]',
parse_json=True, iterable=True)
# works with charset
wrapper(b"print(j[0]['a'])", '[{"a": "é"}]'.encode('cp1252'),
parse_json=True, stdin_charset='cp1252')
assert_print("é")
# works with autoprint
wrapper(b"j[0]['a']", b'[{"a": "1"}]', parse_json=True, autoprint="True")
assert_print("1")
# rstrip should have no effect
execute_statements([b"print(j[0]['a'])"], BytesIO(b'[{"a": 1}]'),
parse_json=True, rstrip="")
resout, reserr = capfd.readouterr()
assert resout == "1\n"
def test_option_quiet(capfd):
with pytest.raises(ZeroDivisionError):
wrapper(b"1/0")
wrapper(b"1/0", quiet=True)
resout, reserr = capfd.readouterr()
assert resout == ""
def test_option_filter(assert_print):
wrapper(b"not int(x) % 2", [b"1", b"2", b"3", b"4"], filter_input=True)
assert_print("2", "4")
# works with decode
data = ["é".encode('cp1252'), "è".encode('cp1252'),
"é".encode('cp1252'), "è".encode('cp1252')]
wrapper("x == 'é'".encode('cp1252'), data, filter_input=True,
stdin_charset='cp1252')
assert_print("é", "é")
# works with split
wrapper(b"not int(f[0]) % 2", [b"1,1", b"2,2", b"3,3", b"4,4"],
split=b',', filter_input=True)
assert_print("2,2", "4,4")
# works with rstrip
wrapper(b"not int(x) % 2", [b"1.", b"2.", b"3.", b"4."],
filter_input=True, rstrip=".\n")
assert_print("2", "4")
# quiet makes it skip lines
with pytest.raises(ZeroDivisionError):
wrapper(b"1 / int(x)", [b"0", b"1", b"2", b"3"], filter_input=True)
wrapper(b"1 / int(x)", [b"0", b"1", b"2", b"3"], filter_input=True, quiet=True)
assert_print("1", "2", "3")
def test_command_version(assert_cmd_print):
assert_cmd_print(b"--version", b"Pyped " + __VERSION__.encode('ascii'))
def test_command_one_liner(assert_cmd_print):
assert_cmd_print(b"print(1)", b"1" )
def test_command_stdin_lines(assert_cmd_print):
# iterate on lines
assert_cmd_print(b"print(x)", [b"1"], stdin=[b"1"])
assert_cmd_print(b"print(x)", [b"a", b"b"], stdin=[b"a", b"b"])
# testing counter
assert_cmd_print(b"print(i)", [b"1", b"2"], stdin=[b"a", b"b"])
def test_command_autoprint(assert_cmd_print):
assert_cmd_print([b"1", b"-p"], b"1")
assert_cmd_print([b"x", b"-p"], [b"a", b"b"], stdin=[b"a", b"b"])
def test_command_before(assert_cmd_print):
assert_cmd_print([b'print(foo)', b'-b', b"foo = 'bar'"], b"bar")
def test_command_after(assert_cmd_print):
assert_cmd_print([b'foo = "bar"', b'-a', b"print(foo)"], b"bar")
def test_command_split(assert_cmd_print):
assert_cmd_print([ b"print('-'.join(f))", b"-s", b"\s+"],
b"1-2-3", b"1\t2 3")
def test_command_iterable(assert_cmd_print):
assert_cmd_print([b"print(sum(map(int, l)))", b"-i"], b"3", [b"1", b"2"])
def test_command_rstrip(assert_cmd_print):
assert_cmd_print([b"print(x)", b"--rstrip=''"],
[b"1", b"", b"2", b"\n"], [b"1", b"2"])
def test_command_full(assert_cmd_print):
assert_cmd_print([b"print(stdin)", b"--full"],
b"1\n2\n\n", b"1\n" + b"2")
def test_command_json(assert_cmd_print):
assert_cmd_print([b"print(j[0]['a'])", b"--json"], b"1", b'[{"a": 1}]')
def test_command_quiet():
res = subprocess.check_output([sys.executable, "pyped.py", "1/0", "-q"])
assert not res
def test_command_filter(assert_cmd_print):
assert_cmd_print([b"not int(x) % 2", b'-f'],
[b"2", b"4"], [b"1", b"2", b"3", b"4"])
def test_command_error(capfd):
res = subprocess.Popen([sys.executable, "pyped.py", "1/0"],
stderr=subprocess.PIPE)
if not six.PY3:
assert res.stderr.read().strip() == "ZeroDivisionError: integer division or modulo by zero"
else:
assert res.stderr.read().strip() == b"ZeroDivisionError: division by zero"
# I can't find a way to reliably test encoding on Python 2/3 and Linux/Windows
# so this will have to wait.
# def test_command_charset(assert_cmd_print):
# cmd = [sys.executable, "pyped.py", 'print(x.encode("cp1252"))',
# "--stdin-charset", "cp1252"]
# if not six.PY3:
# cmd = [sys.executable, "pyped.py", 'print(x.encode("cp1252"))',
# "--stdin-charset", "cp1252"]
# cmd = [x.encode('cp1252') for x in cmd]
# else:
# cmd = [sys.executable, "pyped.py", 'print(x)',
# "--stdin-charset", "cp1252"]
# # using a temporary file as pipe since real pipes cause
# # trouble with line breaks
# fake_pipe = tempfile.TemporaryFile()
# fake_pipe.write("é".encode('cp1252'))
# fake_pipe.seek(0)
# res = subprocess.check_output(cmd, stdin=fake_pipe, universal_newlines=True)
# if not six.PY3:
# assert res == "é\n".encode("cp1252")
# else:
# assert res == "é\n"