Merge pull request #3860 from asottile/purge_more_py

Purge more usage of `py` module
This commit is contained in:
Bruno Oliveira 2018-08-23 06:05:32 -03:00 committed by GitHub
commit 6f7365509d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 50 additions and 53 deletions

View File

@ -1,4 +1,4 @@
import py import six
for i in range(1000): for i in range(1000):
py.builtin.exec_("def test_func_%d(): pass" % i) six.exec_("def test_func_%d(): pass" % i)

View File

@ -1,6 +1,6 @@
from pytest import raises from pytest import raises
import _pytest._code import _pytest._code
import py import six
def otherfunc(a, b): def otherfunc(a, b):
@ -177,7 +177,7 @@ def test_dynamic_compile_shows_nicely():
name = "abc-123" name = "abc-123"
module = imp.new_module(name) module = imp.new_module(name)
code = _pytest._code.compile(src, name, "exec") code = _pytest._code.compile(src, name, "exec")
py.builtin.exec_(code, module.__dict__) six.exec_(code, module.__dict__)
sys.modules[name] = module sys.modules[name] = module
module.foo() module.foo()

View File

@ -11,6 +11,7 @@ from weakref import ref
from _pytest.compat import _PY2, _PY3, PY35, safe_str from _pytest.compat import _PY2, _PY3, PY35, safe_str
from six import text_type from six import text_type
import py import py
import six
builtin_repr = repr builtin_repr = repr
@ -128,7 +129,7 @@ class Frame(object):
""" """
f_locals = self.f_locals.copy() f_locals = self.f_locals.copy()
f_locals.update(vars) f_locals.update(vars)
py.builtin.exec_(code, self.f_globals, f_locals) six.exec_(code, self.f_globals, f_locals)
def repr(self, object): def repr(self, object):
""" return a 'safe' (non-recursive, one-line) string repr for 'object' """ return a 'safe' (non-recursive, one-line) string repr for 'object'

View File

@ -223,7 +223,7 @@ class AssertionRewritingHook(object):
mod.__loader__ = self mod.__loader__ = self
# Normally, this attribute is 3.4+ # Normally, this attribute is 3.4+
mod.__spec__ = spec_from_file_location(name, co.co_filename, loader=self) mod.__spec__ = spec_from_file_location(name, co.co_filename, loader=self)
py.builtin.exec_(co, mod.__dict__) six.exec_(co, mod.__dict__)
except: # noqa except: # noqa
if name in sys.modules: if name in sys.modules:
del sys.modules[name] del sys.modules[name]

View File

@ -858,7 +858,7 @@ class FixtureDef(object):
if exceptions: if exceptions:
e = exceptions[0] e = exceptions[0]
del exceptions # ensure we don't keep all frames alive because of the traceback del exceptions # ensure we don't keep all frames alive because of the traceback
py.builtin._reraise(*e) six.reraise(*e)
finally: finally:
hook = self._fixturemanager.session.gethookproxy(request.node.fspath) hook = self._fixturemanager.session.gethookproxy(request.node.fspath)
@ -885,7 +885,7 @@ class FixtureDef(object):
result, cache_key, err = cached_result result, cache_key, err = cached_result
if my_cache_key == cache_key: if my_cache_key == cache_key:
if err is not None: if err is not None:
py.builtin._reraise(*err) six.reraise(*err)
else: else:
return result return result
# we have a previous but differently parametrized fixture instance # we have a previous but differently parametrized fixture instance

View File

@ -3,7 +3,6 @@ exception classes and constants handling test outcomes
as well as functions creating them as well as functions creating them
""" """
from __future__ import absolute_import, division, print_function from __future__ import absolute_import, division, print_function
import py
import sys import sys
@ -21,7 +20,7 @@ class OutcomeException(BaseException):
if self.msg: if self.msg:
val = self.msg val = self.msg
if isinstance(val, bytes): if isinstance(val, bytes):
val = py._builtin._totext(val, errors="replace") val = val.decode("UTF-8", errors="replace")
return val return val
return "<%s instance>" % (self.__class__.__name__,) return "<%s instance>" % (self.__class__.__name__,)

View File

@ -741,7 +741,7 @@ class FunctionMixin(PyobjMixin):
def _repr_failure_py(self, excinfo, style="long"): def _repr_failure_py(self, excinfo, style="long"):
if excinfo.errisinstance(fail.Exception): if excinfo.errisinstance(fail.Exception):
if not excinfo.value.pytrace: if not excinfo.value.pytrace:
return py._builtin._totext(excinfo.value) return six.text_type(excinfo.value)
return super(FunctionMixin, self)._repr_failure_py(excinfo, style=style) return super(FunctionMixin, self)._repr_failure_py(excinfo, style=style)
def repr_failure(self, excinfo, outerr=None): def repr_failure(self, excinfo, outerr=None):

View File

@ -4,7 +4,7 @@ import sys
from numbers import Number from numbers import Number
from decimal import Decimal from decimal import Decimal
import py import six
from six.moves import zip, filterfalse from six.moves import zip, filterfalse
from more_itertools.more import always_iterable from more_itertools.more import always_iterable
@ -680,8 +680,8 @@ def raises(expected_exception, *args, **kwargs):
# print "raises frame scope: %r" % frame.f_locals # print "raises frame scope: %r" % frame.f_locals
try: try:
code = _pytest._code.Source(code).compile() code = _pytest._code.Source(code).compile()
py.builtin.exec_(code, frame.f_globals, loc) six.exec_(code, frame.f_globals, loc)
# XXX didn'T mean f_globals == f_locals something special? # XXX didn't mean f_globals == f_locals something special?
# this is destroyed here ... # this is destroyed here ...
except expected_exception: except expected_exception:
return _pytest._code.ExceptionInfo() return _pytest._code.ExceptionInfo()

View File

@ -4,11 +4,11 @@ from __future__ import absolute_import, division, print_function
import inspect import inspect
import _pytest._code import _pytest._code
import py import re
import sys import sys
import warnings import warnings
import re import six
from _pytest.fixtures import yield_fixture from _pytest.fixtures import yield_fixture
from _pytest.outcomes import fail from _pytest.outcomes import fail
@ -130,7 +130,7 @@ def warns(expected_warning, *args, **kwargs):
with WarningsChecker(expected_warning, match_expr=match_expr): with WarningsChecker(expected_warning, match_expr=match_expr):
code = _pytest._code.Source(code).compile() code = _pytest._code.Source(code).compile()
py.builtin.exec_(code, frame.f_globals, loc) six.exec_(code, frame.f_globals, loc)
else: else:
func = args[0] func = args[0]
with WarningsChecker(expected_warning, match_expr=match_expr): with WarningsChecker(expected_warning, match_expr=match_expr):

View File

@ -6,7 +6,7 @@ import os
import sys import sys
from time import time from time import time
import py import six
from _pytest._code.code import ExceptionInfo from _pytest._code.code import ExceptionInfo
from _pytest.outcomes import skip, Skipped, TEST_OUTCOME from _pytest.outcomes import skip, Skipped, TEST_OUTCOME
@ -317,7 +317,7 @@ class SetupState(object):
if exc is None: if exc is None:
exc = sys.exc_info() exc = sys.exc_info()
if exc: if exc:
py.builtin._reraise(*exc) six.reraise(*exc)
def _teardown_with_finalization(self, colitem): def _teardown_with_finalization(self, colitem):
self._callfinalizers(colitem) self._callfinalizers(colitem)
@ -352,7 +352,7 @@ class SetupState(object):
if exc is None: if exc is None:
exc = sys.exc_info() exc = sys.exc_info()
if exc: if exc:
py.builtin._reraise(*exc) six.reraise(*exc)
def prepare(self, colitem): def prepare(self, colitem):
""" setup objects along the collector chain to the test-method """ setup objects along the collector chain to the test-method
@ -363,7 +363,7 @@ class SetupState(object):
# check if the last collection node has raised an error # check if the last collection node has raised an error
for col in self.stack: for col in self.stack:
if hasattr(col, "_prepare_exc"): if hasattr(col, "_prepare_exc"):
py.builtin._reraise(*col._prepare_exc) six.reraise(*col._prepare_exc)
for col in needed_collectors[len(self.stack) :]: for col in needed_collectors[len(self.stack) :]:
self.stack.append(col) self.stack.append(col)
try: try:

View File

@ -3,7 +3,6 @@ from __future__ import absolute_import, division, print_function
import sys import sys
import _pytest._code import _pytest._code
import py
import pytest import pytest
from test_excinfo import TWMock from test_excinfo import TWMock
from six import text_type from six import text_type
@ -83,7 +82,7 @@ def test_code_from_func():
def test_unicode_handling(): def test_unicode_handling():
value = py.builtin._totext("\xc4\x85\xc4\x87\n", "utf-8").encode("utf8") value = u"ąć".encode("UTF-8")
def f(): def f():
raise Exception(value) raise Exception(value)
@ -96,7 +95,7 @@ def test_unicode_handling():
@pytest.mark.skipif(sys.version_info[0] >= 3, reason="python 2 only issue") @pytest.mark.skipif(sys.version_info[0] >= 3, reason="python 2 only issue")
def test_unicode_handling_syntax_error(): def test_unicode_handling_syntax_error():
value = py.builtin._totext("\xc4\x85\xc4\x87\n", "utf-8").encode("utf8") value = u"ąć".encode("UTF-8")
def f(): def f():
raise SyntaxError("invalid syntax", (None, 1, 3, value)) raise SyntaxError("invalid syntax", (None, 1, 3, value))

View File

@ -8,6 +8,7 @@ import textwrap
import _pytest import _pytest
import py import py
import pytest import pytest
import six
from _pytest._code.code import ( from _pytest._code.code import (
ExceptionInfo, ExceptionInfo,
FormattedExcinfo, FormattedExcinfo,
@ -251,7 +252,7 @@ class TestTraceback_f_g_h(object):
import sys import sys
exc, val, tb = sys.exc_info() exc, val, tb = sys.exc_info()
py.builtin._reraise(exc, val, tb) six.reraise(exc, val, tb)
def f(n): def f(n):
try: try:
@ -884,10 +885,10 @@ raise ValueError()
class MyRepr(TerminalRepr): class MyRepr(TerminalRepr):
def toterminal(self, tw): def toterminal(self, tw):
tw.line(py.builtin._totext("я", "utf-8")) tw.line(u"я")
x = py.builtin._totext(MyRepr()) x = six.text_type(MyRepr())
assert x == py.builtin._totext("я", "utf-8") assert x == u"я"
def test_toterminal_long(self, importasmod): def test_toterminal_long(self, importasmod):
mod = importasmod( mod = importasmod(

View File

@ -6,8 +6,8 @@ import inspect
import sys import sys
import _pytest._code import _pytest._code
import py
import pytest import pytest
import six
from _pytest._code import Source from _pytest._code import Source
from _pytest._code.source import ast from _pytest._code.source import ast
@ -323,7 +323,7 @@ class TestSourceParsingAndCompiling(object):
def test_compile_and_getsource(self): def test_compile_and_getsource(self):
co = self.source.compile() co = self.source.compile()
py.builtin.exec_(co, globals()) six.exec_(co, globals())
f(7) f(7)
excinfo = pytest.raises(AssertionError, "f(6)") excinfo = pytest.raises(AssertionError, "f(6)")
frame = excinfo.traceback[-1].frame frame = excinfo.traceback[-1].frame
@ -392,7 +392,7 @@ def test_getfuncsource_dynamic():
def g(): pass def g(): pass
""" """
co = _pytest._code.compile(source) co = _pytest._code.compile(source)
py.builtin.exec_(co, globals()) six.exec_(co, globals())
assert str(_pytest._code.Source(f)).strip() == "def f():\n raise ValueError" assert str(_pytest._code.Source(f)).strip() == "def f():\n raise ValueError"
assert str(_pytest._code.Source(g)).strip() == "def g(): pass" assert str(_pytest._code.Source(g)).strip() == "def g(): pass"

View File

@ -3,7 +3,6 @@ import re
import sys import sys
import attr import attr
import _pytest._code import _pytest._code
import py
import pytest import pytest
from _pytest import python, fixtures from _pytest import python, fixtures
@ -295,9 +294,7 @@ class TestMetafunc(object):
) )
assert result == ["a0-1.0", "a1-b1"] assert result == ["a0-1.0", "a1-b1"]
# unicode mixing, issue250 # unicode mixing, issue250
result = idmaker( result = idmaker((u"a", "b"), [pytest.param({}, b"\xc3\xb4")])
(py.builtin._totext("a"), "b"), [pytest.param({}, b"\xc3\xb4")]
)
assert result == ["a0-\\xc3\\xb4"] assert result == ["a0-\\xc3\\xb4"]
def test_idmaker_with_bytes_regex(self): def test_idmaker_with_bytes_regex(self):
@ -309,7 +306,6 @@ class TestMetafunc(object):
def test_idmaker_native_strings(self): def test_idmaker_native_strings(self):
from _pytest.python import idmaker from _pytest.python import idmaker
totext = py.builtin._totext
result = idmaker( result = idmaker(
("a", "b"), ("a", "b"),
[ [
@ -324,7 +320,7 @@ class TestMetafunc(object):
pytest.param({7}, set("seven")), pytest.param({7}, set("seven")),
pytest.param(tuple("eight"), (8, -8, 8)), pytest.param(tuple("eight"), (8, -8, 8)),
pytest.param(b"\xc3\xb4", b"name"), pytest.param(b"\xc3\xb4", b"name"),
pytest.param(b"\xc3\xb4", totext("other")), pytest.param(b"\xc3\xb4", u"other"),
], ],
) )
assert result == [ assert result == [

View File

@ -6,6 +6,7 @@ import textwrap
import _pytest.assertion as plugin import _pytest.assertion as plugin
import py import py
import pytest import pytest
import six
from _pytest.assertion import util from _pytest.assertion import util
from _pytest.assertion import truncate from _pytest.assertion import truncate
@ -509,12 +510,12 @@ class TestAssert_reprcompare(object):
assert "raised in repr()" not in expl assert "raised in repr()" not in expl
def test_unicode(self): def test_unicode(self):
left = py.builtin._totext("£€", "utf-8") left = u"£€"
right = py.builtin._totext("£", "utf-8") right = u"£"
expl = callequal(left, right) expl = callequal(left, right)
assert expl[0] == py.builtin._totext("'£€' == '£'", "utf-8") assert expl[0] == u"'£€' == '£'"
assert expl[1] == py.builtin._totext("- £€", "utf-8") assert expl[1] == u"- £€"
assert expl[2] == py.builtin._totext("+ £", "utf-8") assert expl[2] == u"+ £"
def test_nonascii_text(self): def test_nonascii_text(self):
""" """
@ -541,8 +542,8 @@ class TestAssert_reprcompare(object):
right = bytes(right, "utf-8") right = bytes(right, "utf-8")
expl = callequal(left, right) expl = callequal(left, right)
for line in expl: for line in expl:
assert isinstance(line, py.builtin.text) assert isinstance(line, six.text_type)
msg = py.builtin._totext("\n").join(expl) msg = u"\n".join(expl)
assert msg assert msg

View File

@ -9,6 +9,7 @@ import textwrap
import zipfile import zipfile
import py import py
import pytest import pytest
import six
import _pytest._code import _pytest._code
from _pytest.assertion import util from _pytest.assertion import util
@ -49,7 +50,7 @@ def getmsg(f, extra_ns=None, must_pass=False):
ns = {} ns = {}
if extra_ns is not None: if extra_ns is not None:
ns.update(extra_ns) ns.update(extra_ns)
py.builtin.exec_(code, ns) six.exec_(code, ns)
func = ns[f.__name__] func = ns[f.__name__]
try: try:
func() func()
@ -654,12 +655,10 @@ class TestRewriteOnImport(object):
def test_readonly(self, testdir): def test_readonly(self, testdir):
sub = testdir.mkdir("testing") sub = testdir.mkdir("testing")
sub.join("test_readonly.py").write( sub.join("test_readonly.py").write(
py.builtin._totext( b"""
"""
def test_rewritten(): def test_rewritten():
assert "@py_builtins" in globals() assert "@py_builtins" in globals()
""" """,
).encode("utf-8"),
"wb", "wb",
) )
old_mode = sub.stat().mode old_mode = sub.stat().mode

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function from __future__ import absolute_import, division, print_function
# note: py.io capture tests where copied from # note: py.io capture tests where copied from
@ -1083,9 +1084,9 @@ class TestStdCapture(object):
def test_capturing_readouterr_unicode(self): def test_capturing_readouterr_unicode(self):
with self.getcapture() as cap: with self.getcapture() as cap:
print("hx\xc4\x85\xc4\x87") print("hxąć")
out, err = cap.readouterr() out, err = cap.readouterr()
assert out == py.builtin._totext("hx\xc4\x85\xc4\x87\n", "utf8") assert out == u"hxąć\n"
@pytest.mark.skipif( @pytest.mark.skipif(
"sys.version_info >= (3,)", reason="text output different for bytes on python3" "sys.version_info >= (3,)", reason="text output different for bytes on python3"
@ -1095,7 +1096,7 @@ class TestStdCapture(object):
# triggered an internal error in pytest # triggered an internal error in pytest
print("\xa6") print("\xa6")
out, err = cap.readouterr() out, err = cap.readouterr()
assert out == py.builtin._totext("\ufffd\n", "unicode-escape") assert out == u"\ufffd\n"
def test_reset_twice_error(self): def test_reset_twice_error(self):
with self.getcapture() as cap: with self.getcapture() as cap:

View File

@ -941,7 +941,7 @@ def test_double_colon_split_method_issue469(testdir):
def test_unicode_issue368(testdir): def test_unicode_issue368(testdir):
path = testdir.tmpdir.join("test.xml") path = testdir.tmpdir.join("test.xml")
log = LogXML(str(path), None) log = LogXML(str(path), None)
ustr = py.builtin._totext("ВНИ!", "utf-8") ustr = u"ВНИ!"
class Report(BaseReport): class Report(BaseReport):
longrepr = ustr longrepr = ustr