Skip to content

Commit cf9b31b

Browse files
Merge pull request #3068 from asottile/pystd
Replace py.std with stdlib imports
2 parents 962aede + bd1d17e commit cf9b31b

22 files changed

+117
-106
lines changed

_pytest/_code/code.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
from __future__ import absolute_import, division, print_function
2+
import inspect
23
import sys
4+
import traceback
35
from inspect import CO_VARARGS, CO_VARKEYWORDS
46
import re
57
from weakref import ref
@@ -422,7 +424,7 @@ def getrepr(self, showlocals=False, style="long",
422424
"""
423425
if style == 'native':
424426
return ReprExceptionInfo(ReprTracebackNative(
425-
py.std.traceback.format_exception(
427+
traceback.format_exception(
426428
self.type,
427429
self.value,
428430
self.traceback[0]._rawentry,
@@ -556,7 +558,7 @@ def repr_locals(self, locals):
556558
# else:
557559
# self._line("%-10s =\\" % (name,))
558560
# # XXX
559-
# py.std.pprint.pprint(value, stream=self.excinfowriter)
561+
# pprint.pprint(value, stream=self.excinfowriter)
560562
return ReprLocals(lines)
561563

562564
def repr_traceback_entry(self, entry, excinfo=None):
@@ -669,7 +671,7 @@ def repr_excinfo(self, excinfo):
669671
else:
670672
# fallback to native repr if the exception doesn't have a traceback:
671673
# ExceptionInfo objects require a full traceback to work
672-
reprtraceback = ReprTracebackNative(py.std.traceback.format_exception(type(e), e, None))
674+
reprtraceback = ReprTracebackNative(traceback.format_exception(type(e), e, None))
673675
reprcrash = None
674676

675677
repr_chain += [(reprtraceback, reprcrash, descr)]
@@ -886,7 +888,7 @@ def getrawcode(obj, trycall=True):
886888
obj = getattr(obj, 'f_code', obj)
887889
obj = getattr(obj, '__code__', obj)
888890
if trycall and not hasattr(obj, 'co_firstlineno'):
889-
if hasattr(obj, '__call__') and not py.std.inspect.isclass(obj):
891+
if hasattr(obj, '__call__') and not inspect.isclass(obj):
890892
x = getrawcode(obj.__call__, trycall=False)
891893
if hasattr(x, 'co_firstlineno'):
892894
return x

_pytest/_code/source.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import ast
44
from ast import PyCF_ONLY_AST as _AST_FLAG
55
from bisect import bisect_right
6+
import linecache
67
import sys
78
import six
89
import inspect
@@ -191,7 +192,7 @@ def compile(self, filename=None, mode='exec',
191192
if flag & _AST_FLAG:
192193
return co
193194
lines = [(x + "\n") for x in self.lines]
194-
py.std.linecache.cache[filename] = (1, None, lines, filename)
195+
linecache.cache[filename] = (1, None, lines, filename)
195196
return co
196197

197198
#
@@ -223,8 +224,7 @@ def getfslineno(obj):
223224
code = _pytest._code.Code(obj)
224225
except TypeError:
225226
try:
226-
fn = (py.std.inspect.getsourcefile(obj) or
227-
py.std.inspect.getfile(obj))
227+
fn = inspect.getsourcefile(obj) or inspect.getfile(obj)
228228
except TypeError:
229229
return "", -1
230230

@@ -248,7 +248,7 @@ def getfslineno(obj):
248248

249249
def findsource(obj):
250250
try:
251-
sourcelines, lineno = py.std.inspect.findsource(obj)
251+
sourcelines, lineno = inspect.findsource(obj)
252252
except py.builtin._sysex:
253253
raise
254254
except: # noqa

changelog/3067.trivial

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Replace py.std with stdlib imports.

doc/en/example/assertion/failure_demo.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -159,10 +159,10 @@ def func1(self):
159159
def test_dynamic_compile_shows_nicely():
160160
src = 'def foo():\n assert 1 == 0\n'
161161
name = 'abc-123'
162-
module = py.std.imp.new_module(name)
162+
module = imp.new_module(name)
163163
code = _pytest._code.compile(src, name, 'exec')
164164
py.builtin.exec_(code, module.__dict__)
165-
py.std.sys.modules[name] = module
165+
sys.modules[name] = module
166166
module.foo()
167167

168168

doc/en/example/reportingdemo.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -413,10 +413,10 @@ get on the terminal - we are working on that)::
413413
def test_dynamic_compile_shows_nicely():
414414
src = 'def foo():\n assert 1 == 0\n'
415415
name = 'abc-123'
416-
module = py.std.imp.new_module(name)
416+
module = imp.new_module(name)
417417
code = _pytest._code.compile(src, name, 'exec')
418418
py.builtin.exec_(code, module.__dict__)
419-
py.std.sys.modules[name] = module
419+
sys.modules[name] = module
420420
> module.foo()
421421
422422
failure_demo.py:166:

extra/get_issues.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import json
22
import py
3-
import textwrap
43

54
issues_url = "https://api.github.com/repos/pytest-dev/pytest/issues"
65

testing/acceptance_test.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from __future__ import absolute_import, division, print_function
33
import os
44
import sys
5+
import types
56

67
import six
78

@@ -398,7 +399,7 @@ def test_plugins_given_as_strings(self, tmpdir, monkeypatch):
398399

399400
p = tmpdir.join('test_test_plugins_given_as_strings.py')
400401
p.write('def test_foo(): pass')
401-
mod = py.std.types.ModuleType("myplugin")
402+
mod = types.ModuleType("myplugin")
402403
monkeypatch.setitem(sys.modules, 'myplugin', mod)
403404
assert pytest.main(args=[str(tmpdir)], plugins=['myplugin']) == 0
404405

@@ -492,17 +493,17 @@ def test_hello():
492493

493494
def test_python_minus_m_invocation_ok(self, testdir):
494495
p1 = testdir.makepyfile("def test_hello(): pass")
495-
res = testdir.run(py.std.sys.executable, "-m", "pytest", str(p1))
496+
res = testdir.run(sys.executable, "-m", "pytest", str(p1))
496497
assert res.ret == 0
497498

498499
def test_python_minus_m_invocation_fail(self, testdir):
499500
p1 = testdir.makepyfile("def test_fail(): 0/0")
500-
res = testdir.run(py.std.sys.executable, "-m", "pytest", str(p1))
501+
res = testdir.run(sys.executable, "-m", "pytest", str(p1))
501502
assert res.ret == 1
502503

503504
def test_python_pytest_package(self, testdir):
504505
p1 = testdir.makepyfile("def test_pass(): pass")
505-
res = testdir.run(py.std.sys.executable, "-m", "pytest", str(p1))
506+
res = testdir.run(sys.executable, "-m", "pytest", str(p1))
506507
assert res.ret == 0
507508
res.stdout.fnmatch_lines(["*1 passed*"])
508509

@@ -560,7 +561,7 @@ def test_cmdline_python_package(self, testdir, monkeypatch):
560561
])
561562

562563
def join_pythonpath(what):
563-
cur = py.std.os.environ.get('PYTHONPATH')
564+
cur = os.environ.get('PYTHONPATH')
564565
if cur:
565566
return str(what) + os.pathsep + cur
566567
return what
@@ -618,7 +619,7 @@ def test_cmdline_python_namespace_package(self, testdir, monkeypatch):
618619
# └── test_world.py
619620

620621
def join_pythonpath(*dirs):
621-
cur = py.std.os.environ.get('PYTHONPATH')
622+
cur = os.environ.get('PYTHONPATH')
622623
if cur:
623624
dirs += (cur,)
624625
return os.pathsep.join(str(p) for p in dirs)

testing/code/test_excinfo.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
from __future__ import absolute_import, division, print_function
33

44
import operator
5+
import os
6+
import sys
57
import _pytest
68
import py
79
import pytest
@@ -472,7 +474,7 @@ def test_repr_source_not_existing(self):
472474
excinfo = _pytest._code.ExceptionInfo()
473475
repr = pr.repr_excinfo(excinfo)
474476
assert repr.reprtraceback.reprentries[1].lines[0] == "> ???"
475-
if py.std.sys.version_info[0] >= 3:
477+
if sys.version_info[0] >= 3:
476478
assert repr.chain[0][0].reprentries[1].lines[0] == "> ???"
477479

478480
def test_repr_many_line_source_not_existing(self):
@@ -487,7 +489,7 @@ def test_repr_many_line_source_not_existing(self):
487489
excinfo = _pytest._code.ExceptionInfo()
488490
repr = pr.repr_excinfo(excinfo)
489491
assert repr.reprtraceback.reprentries[1].lines[0] == "> ???"
490-
if py.std.sys.version_info[0] >= 3:
492+
if sys.version_info[0] >= 3:
491493
assert repr.chain[0][0].reprentries[1].lines[0] == "> ???"
492494

493495
def test_repr_source_failing_fullsource(self):
@@ -545,13 +547,13 @@ class FakeRawTB(object):
545547
fail = IOError()
546548
repr = pr.repr_excinfo(excinfo)
547549
assert repr.reprtraceback.reprentries[0].lines[0] == "> ???"
548-
if py.std.sys.version_info[0] >= 3:
550+
if sys.version_info[0] >= 3:
549551
assert repr.chain[0][0].reprentries[0].lines[0] == "> ???"
550552

551553
fail = py.error.ENOENT # noqa
552554
repr = pr.repr_excinfo(excinfo)
553555
assert repr.reprtraceback.reprentries[0].lines[0] == "> ???"
554-
if py.std.sys.version_info[0] >= 3:
556+
if sys.version_info[0] >= 3:
555557
assert repr.chain[0][0].reprentries[0].lines[0] == "> ???"
556558

557559
def test_repr_local(self):
@@ -738,7 +740,7 @@ def entry():
738740
repr = p.repr_excinfo(excinfo)
739741
assert repr.reprtraceback
740742
assert len(repr.reprtraceback.reprentries) == len(reprtb.reprentries)
741-
if py.std.sys.version_info[0] >= 3:
743+
if sys.version_info[0] >= 3:
742744
assert repr.chain[0][0]
743745
assert len(repr.chain[0][0].reprentries) == len(reprtb.reprentries)
744746
assert repr.reprcrash.path.endswith("mod.py")
@@ -758,7 +760,7 @@ def entry():
758760
def raiseos():
759761
raise OSError(2)
760762

761-
monkeypatch.setattr(py.std.os, 'getcwd', raiseos)
763+
monkeypatch.setattr(os, 'getcwd', raiseos)
762764
assert p._makepath(__file__) == __file__
763765
p.repr_traceback(excinfo)
764766

@@ -816,10 +818,10 @@ def entry():
816818
for style in ("short", "long", "no"):
817819
for showlocals in (True, False):
818820
repr = excinfo.getrepr(style=style, showlocals=showlocals)
819-
if py.std.sys.version_info[0] < 3:
821+
if sys.version_info[0] < 3:
820822
assert isinstance(repr, ReprExceptionInfo)
821823
assert repr.reprtraceback.style == style
822-
if py.std.sys.version_info[0] >= 3:
824+
if sys.version_info[0] >= 3:
823825
assert isinstance(repr, ExceptionChainRepr)
824826
for repr in repr.chain:
825827
assert repr[0].style == style

testing/code/test_source.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
# disable flake check on this file because some constructs are strange
33
# or redundant on purpose and can't be disable on a line-by-line basis
44
from __future__ import absolute_import, division, print_function
5+
import inspect
56
import sys
67

78
import _pytest._code
@@ -187,9 +188,9 @@ def f():
187188
def f():
188189
raise ValueError()
189190
""")
190-
source1 = py.std.inspect.getsource(co1)
191+
source1 = inspect.getsource(co1)
191192
assert 'KeyError' in source1
192-
source2 = py.std.inspect.getsource(co2)
193+
source2 = inspect.getsource(co2)
193194
assert 'ValueError' in source2
194195

195196
def test_getstatement(self):
@@ -373,7 +374,6 @@ def f():
373374
c = '''while True:
374375
pass
375376
'''
376-
import inspect
377377
lines = deindent(inspect.getsource(f).splitlines())
378378
assert lines == ["def f():", " c = '''while True:", " pass", "'''"]
379379

@@ -461,7 +461,7 @@ class A(object):
461461

462462
fspath, lineno = getfslineno(A)
463463

464-
_, A_lineno = py.std.inspect.findsource(A)
464+
_, A_lineno = inspect.findsource(A)
465465
assert fspath.basename == "test_source.py"
466466
assert lineno == A_lineno
467467

testing/python/collect.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
from textwrap import dedent
55

66
import _pytest._code
7-
import py
87
import pytest
98
from _pytest.main import (
109
Collector,
@@ -25,7 +24,7 @@ def test_import_duplicate(self, testdir):
2524
b = testdir.mkdir("b")
2625
p = a.ensure("test_whatever.py")
2726
p.pyimport()
28-
del py.std.sys.modules['test_whatever']
27+
del sys.modules['test_whatever']
2928
b.ensure("test_whatever.py")
3029
result = testdir.runpytest()
3130
result.stdout.fnmatch_lines([
@@ -754,7 +753,7 @@ def test_fail(): assert 0
754753

755754
assert fn1 == fn2
756755
assert fn1 != modcol
757-
if py.std.sys.version_info < (3, 0):
756+
if sys.version_info < (3, 0):
758757
assert cmp(fn1, fn2) == 0
759758
assert hash(fn1) == hash(fn2)
760759

testing/python/metafunc.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -730,7 +730,7 @@ class TestMetafuncFunctional(object):
730730
def test_attributes(self, testdir):
731731
p = testdir.makepyfile("""
732732
# assumes that generate/provide runs in the same process
733-
import py, pytest
733+
import sys, pytest
734734
def pytest_generate_tests(metafunc):
735735
metafunc.addcall(param=metafunc)
736736
@@ -749,7 +749,7 @@ class TestClass(object):
749749
def test_method(self, metafunc, pytestconfig):
750750
assert metafunc.config == pytestconfig
751751
assert metafunc.module.__name__ == __name__
752-
if py.std.sys.version_info > (3, 0):
752+
if sys.version_info > (3, 0):
753753
unbound = TestClass.test_method
754754
else:
755755
unbound = TestClass.test_method.im_func

testing/test_argcomplete.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from __future__ import absolute_import, division, print_function
2-
import py
2+
import subprocess
3+
import sys
34
import pytest
45

56
# test for _argcomplete but not specific for any application
@@ -23,21 +24,21 @@ def equal_with_bash(prefix, ffc, fc, out=None):
2324

2425
def _wrapcall(*args, **kargs):
2526
try:
26-
if py.std.sys.version_info > (2, 7):
27-
return py.std.subprocess.check_output(*args, **kargs).decode().splitlines()
27+
if sys.version_info > (2, 7):
28+
return subprocess.check_output(*args, **kargs).decode().splitlines()
2829
if 'stdout' in kargs:
2930
raise ValueError('stdout argument not allowed, it will be overridden.')
30-
process = py.std.subprocess.Popen(
31-
stdout=py.std.subprocess.PIPE, *args, **kargs)
31+
process = subprocess.Popen(
32+
stdout=subprocess.PIPE, *args, **kargs)
3233
output, unused_err = process.communicate()
3334
retcode = process.poll()
3435
if retcode:
3536
cmd = kargs.get("args")
3637
if cmd is None:
3738
cmd = args[0]
38-
raise py.std.subprocess.CalledProcessError(retcode, cmd)
39+
raise subprocess.CalledProcessError(retcode, cmd)
3940
return output.decode().splitlines()
40-
except py.std.subprocess.CalledProcessError:
41+
except subprocess.CalledProcessError:
4142
return []
4243

4344

@@ -83,7 +84,7 @@ def test_compare_with_compgen(self):
8384
ffc = FastFilesCompleter()
8485
fc = FilesCompleter()
8586
for x in ['/', '/d', '/data', 'qqq', '']:
86-
assert equal_with_bash(x, ffc, fc, out=py.std.sys.stdout)
87+
assert equal_with_bash(x, ffc, fc, out=sys.stdout)
8788

8889
@pytest.mark.skipif("sys.platform in ('win32', 'darwin')")
8990
def test_remove_dir_prefix(self):
@@ -94,4 +95,4 @@ def test_remove_dir_prefix(self):
9495
ffc = FastFilesCompleter()
9596
fc = FilesCompleter()
9697
for x in '/usr/'.split():
97-
assert not equal_with_bash(x, ffc, fc, out=py.std.sys.stdout)
98+
assert not equal_with_bash(x, ffc, fc, out=sys.stdout)

0 commit comments

Comments
 (0)