Skip to content

Commit 8d32f8c

Browse files
Merge pull request #132 from pytest-dev/conftest-upgrade
bring the tests up2date with modern patterns
2 parents 10e1b1b + bc151d2 commit 8d32f8c

File tree

4 files changed

+66
-42
lines changed

4 files changed

+66
-42
lines changed

conftest.py

Lines changed: 12 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,25 @@
11
import py
2+
import pytest
23
import sys
34

4-
pytest_plugins = 'doctest pytester'.split()
5+
pytest_plugins = 'doctest', 'pytester'
56

67
collect_ignore = ['build', 'doc/_build']
78

89

9-
import os, py
10-
pid = os.getpid()
11-
1210
def pytest_addoption(parser):
1311
group = parser.getgroup("pylib", "py lib testing options")
1412
group.addoption('--runslowtests',
1513
action="store_true", dest="runslowtests", default=False,
1614
help=("run slow tests"))
1715

18-
def pytest_funcarg__sshhost(request):
16+
@pytest.fixture
17+
def sshhost(request):
1918
val = request.config.getvalue("sshhost")
2019
if val:
2120
return val
2221
py.test.skip("need --sshhost option")
23-
def pytest_generate_tests(metafunc):
24-
multi = getattr(metafunc.function, 'multi', None)
25-
if multi is not None:
26-
assert len(multi.kwargs) == 1
27-
for name, l in multi.kwargs.items():
28-
for val in l:
29-
metafunc.addcall(funcargs={name: val})
30-
elif 'anypython' in metafunc.funcargnames:
31-
for name in ('python2.4', 'python2.5', 'python2.6',
32-
'python2.7', 'python3.1', 'pypy-c', 'jython'):
33-
metafunc.addcall(id=name, param=name)
22+
3423

3524
# XXX copied from execnet's conftest.py - needs to be merged
3625
winpymap = {
@@ -41,6 +30,7 @@ def pytest_generate_tests(metafunc):
4130
'python3.1': r'C:\Python31\python.exe',
4231
}
4332

33+
4434
def getexecutable(name, cache={}):
4535
try:
4636
return cache[name]
@@ -49,15 +39,19 @@ def getexecutable(name, cache={}):
4939
if executable:
5040
if name == "jython":
5141
import subprocess
52-
popen = subprocess.Popen([str(executable), "--version"],
42+
popen = subprocess.Popen(
43+
[str(executable), "--version"],
5344
universal_newlines=True, stderr=subprocess.PIPE)
5445
out, err = popen.communicate()
5546
if not err or "2.5" not in err:
5647
executable = None
5748
cache[name] = executable
5849
return executable
5950

60-
def pytest_funcarg__anypython(request):
51+
52+
@pytest.fixture(params=('python2.4', 'python2.5', 'python2.6',
53+
'python2.7', 'python3.1', 'pypy-c', 'jython'))
54+
def anypython(request):
6155
name = request.param
6256
executable = getexecutable(name)
6357
if executable is None:

testing/code/test_excinfo.py

Lines changed: 51 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
# -*- coding: utf-8 -*-
22

33
import py
4+
import pytest
5+
from test_source import astonly
6+
47
from py._code.code import FormattedExcinfo, ReprExceptionInfo
58
queue = py.builtin._tryimport('queue', 'Queue')
69

710
failsonjython = py.test.mark.xfail("sys.platform.startswith('java')")
8-
from test_source import astonly
911

1012
try:
1113
import importlib
@@ -14,40 +16,49 @@
1416
else:
1517
invalidate_import_caches = getattr(importlib, "invalidate_caches", None)
1618

17-
import pytest
19+
1820
pytest_version_info = tuple(map(int, pytest.__version__.split(".")[:3]))
1921

22+
2023
class TWMock:
2124
def __init__(self):
2225
self.lines = []
26+
2327
def sep(self, sep, line=None):
2428
self.lines.append((sep, line))
29+
2530
def line(self, line, **kw):
2631
self.lines.append(line)
32+
2733
def markup(self, text, **kw):
2834
return text
2935

3036
fullwidth = 80
3137

38+
3239
def test_excinfo_simple():
3340
try:
3441
raise ValueError
3542
except ValueError:
3643
info = py.code.ExceptionInfo()
3744
assert info.type == ValueError
3845

46+
3947
def test_excinfo_getstatement():
4048
def g():
4149
raise ValueError
50+
4251
def f():
4352
g()
4453
try:
4554
f()
4655
except ValueError:
4756
excinfo = py.code.ExceptionInfo()
48-
linenumbers = [py.code.getrawcode(f).co_firstlineno-1+3,
49-
py.code.getrawcode(f).co_firstlineno-1+1,
50-
py.code.getrawcode(g).co_firstlineno-1+1,]
57+
linenumbers = [
58+
py.code.getrawcode(f).co_firstlineno-1+3,
59+
py.code.getrawcode(f).co_firstlineno-1+1,
60+
py.code.getrawcode(g).co_firstlineno-1+1,
61+
]
5162
l = list(excinfo.traceback)
5263
foundlinenumbers = [x.lineno for x in l]
5364
assert foundlinenumbers == linenumbers
@@ -92,7 +103,7 @@ def test_traceback_entries(self):
92103

93104
def test_traceback_entry_getsource(self):
94105
tb = self.excinfo.traceback
95-
s = str(tb[-1].getsource() )
106+
s = str(tb[-1].getsource())
96107
assert s.startswith("def f():")
97108
assert s.endswith("raise ValueError")
98109

@@ -164,10 +175,12 @@ def f(n):
164175
def test_traceback_no_recursion_index(self):
165176
def do_stuff():
166177
raise RuntimeError
178+
167179
def reraise_me():
168180
import sys
169181
exc, val, tb = sys.exc_info()
170182
py.builtin._reraise(exc, val, tb)
183+
171184
def f(n):
172185
try:
173186
do_stuff()
@@ -179,7 +192,7 @@ def f(n):
179192
assert recindex is None
180193

181194
def test_traceback_messy_recursion(self):
182-
#XXX: simplified locally testable version
195+
# XXX: simplified locally testable version
183196
decorator = py.test.importorskip('decorator').decorator
184197

185198
def log(f, *k, **kw):
@@ -195,17 +208,18 @@ def fail():
195208
excinfo = py.test.raises(ValueError, fail)
196209
assert excinfo.traceback.recursionindex() is None
197210

198-
199-
200211
def test_traceback_getcrashentry(self):
201212
def i():
202213
__tracebackhide__ = True
203214
raise ValueError
215+
204216
def h():
205217
i()
218+
206219
def g():
207220
__tracebackhide__ = True
208221
h()
222+
209223
def f():
210224
g()
211225

@@ -221,6 +235,7 @@ def test_traceback_getcrashentry_empty(self):
221235
def g():
222236
__tracebackhide__ = True
223237
raise ValueError
238+
224239
def f():
225240
__tracebackhide__ = True
226241
g()
@@ -233,9 +248,11 @@ def f():
233248
assert entry.lineno == co.firstlineno + 2
234249
assert entry.frame.code.name == 'g'
235250

251+
236252
def hello(x):
237253
x + 5
238254

255+
239256
def test_tbentry_reinterpret():
240257
try:
241258
hello("hello")
@@ -245,6 +262,7 @@ def test_tbentry_reinterpret():
245262
msg = tbentry.reinterpret()
246263
assert msg.startswith("TypeError: ('hello' + 5)")
247264

265+
248266
def test_excinfo_exconly():
249267
excinfo = py.test.raises(ValueError, h)
250268
assert excinfo.exconly().startswith('ValueError')
@@ -254,22 +272,26 @@ def test_excinfo_exconly():
254272
assert msg.startswith('ValueError')
255273
assert msg.endswith("world")
256274

275+
257276
def test_excinfo_repr():
258277
excinfo = py.test.raises(ValueError, h)
259278
s = repr(excinfo)
260279
assert s == "<ExceptionInfo ValueError tblen=4>"
261280

281+
262282
def test_excinfo_str():
263283
excinfo = py.test.raises(ValueError, h)
264284
s = str(excinfo)
265285
assert s.startswith(__file__[:-9]) # pyc file and $py.class
266286
assert s.endswith("ValueError")
267287
assert len(s.split(":")) >= 3 # on windows it's 4
268288

289+
269290
def test_excinfo_errisinstance():
270291
excinfo = py.test.raises(ValueError, h)
271292
assert excinfo.errisinstance(ValueError)
272293

294+
273295
def test_excinfo_no_sourcecode():
274296
try:
275297
exec ("raise ValueError()")
@@ -281,6 +303,7 @@ def test_excinfo_no_sourcecode():
281303
else:
282304
assert s == " File '<string>':1 in <module>\n ???\n"
283305

306+
284307
def test_excinfo_no_python_sourcecode(tmpdir):
285308
#XXX: simplified locally testable version
286309
tmpdir.join('test.txt').write("{{ h()}}:")
@@ -292,7 +315,7 @@ def test_excinfo_no_python_sourcecode(tmpdir):
292315
excinfo = py.test.raises(ValueError,
293316
template.render, h=h)
294317
for item in excinfo.traceback:
295-
print(item) #XXX: for some reason jinja.Template.render is printed in full
318+
print(item) # XXX: for some reason jinja.Template.render is printed in full
296319
item.source # shouldnt fail
297320
if item.path.basename == 'test.txt':
298321
assert str(item.source) == '{{ h()}}:'
@@ -309,6 +332,7 @@ def test_entrysource_Queue_example():
309332
s = str(source).strip()
310333
assert s.startswith("def get")
311334

335+
312336
def test_codepath_Queue_example():
313337
try:
314338
queue.Queue().get(timeout=0.001)
@@ -320,6 +344,7 @@ def test_codepath_Queue_example():
320344
assert path.basename.lower() == "queue.py"
321345
assert path.check()
322346

347+
323348
class TestFormattedExcinfo:
324349
def pytest_funcarg__importasmod(self, request):
325350
def importasmod(source):
@@ -372,7 +397,6 @@ def f():
372397
'E assert 0'
373398
]
374399

375-
376400
def test_repr_source_not_existing(self):
377401
pr = FormattedExcinfo()
378402
co = compile("raise ValueError()", "", "exec")
@@ -842,14 +866,16 @@ def f():
842866
finally:
843867
old.chdir()
844868

845-
@py.test.mark.multi(reproptions=[
846-
{'style': style, 'showlocals': showlocals,
847-
'funcargs': funcargs, 'tbfilter': tbfilter
848-
} for style in ("long", "short", "no")
849-
for showlocals in (True, False)
850-
for tbfilter in (True, False)
851-
for funcargs in (True, False)])
852-
def test_format_excinfo(self, importasmod, reproptions):
869+
@pytest.mark.parametrize('style', ("long", "short", "no"))
870+
@pytest.mark.parametrize('showlocals', (True, False),
871+
ids=['locals', 'nolocals'])
872+
@pytest.mark.parametrize('tbfilter', (True, False),
873+
ids=['tbfilter', 'nofilter'])
874+
@pytest.mark.parametrize('funcargs', (True, False),
875+
ids=['funcargs', 'nofuncargs'])
876+
def test_format_excinfo(self, importasmod,
877+
style, showlocals, tbfilter, funcargs):
878+
853879
mod = importasmod("""
854880
def g(x):
855881
raise ValueError(x)
@@ -858,11 +884,15 @@ def f():
858884
""")
859885
excinfo = py.test.raises(ValueError, mod.f)
860886
tw = py.io.TerminalWriter(stringio=True)
861-
repr = excinfo.getrepr(**reproptions)
887+
repr = excinfo.getrepr(
888+
style=style,
889+
showlocals=showlocals,
890+
funcargs=funcargs,
891+
tbfilter=tbfilter
892+
)
862893
repr.toterminal(tw)
863894
assert tw.stringio.getvalue()
864895

865-
866896
def test_native_style(self):
867897
excinfo = self.excinfo_from_exec("""
868898
assert 0

testing/io_/test_capture.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -460,7 +460,7 @@ def func(x, y):
460460
assert err.startswith("4")
461461

462462
@needsdup
463-
@py.test.mark.multi(use=[True, False])
463+
@py.test.mark.parametrize('use', [True, False])
464464
def test_fdcapture_tmpfile_remains_the_same(tmpfile, use):
465465
if not use:
466466
tmpfile = True
@@ -472,7 +472,7 @@ def test_fdcapture_tmpfile_remains_the_same(tmpfile, use):
472472
capfile2 = cap.err.tmpfile
473473
assert capfile2 == capfile
474474

475-
@py.test.mark.multi(method=['StdCapture', 'StdCaptureFD'])
475+
@py.test.mark.parametrize('method', ['StdCapture', 'StdCaptureFD'])
476476
def test_capturing_and_logging_fundamentals(testdir, method):
477477
if method == "StdCaptureFD" and not hasattr(os, 'dup'):
478478
py.test.skip("need os.dup")

testing/path/test_local.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ def test_write_and_ensure(self, path1):
179179
p.write("hello", ensure=1)
180180
assert p.read() == "hello"
181181

182-
@py.test.mark.multi(bin=(False, True))
182+
@py.test.mark.parametrize('bin', (False, True))
183183
def test_dump(self, tmpdir, bin):
184184
path = tmpdir.join("dumpfile%s" % int(bin))
185185
try:

0 commit comments

Comments
 (0)