sort out flake8 issues and unicode name usage

This commit is contained in:
Ronny Pfannschmidt 2018-05-23 18:12:04 +02:00
parent 703e4b11ba
commit 3e08c4ee64
18 changed files with 73 additions and 80 deletions

View File

@ -4,6 +4,7 @@
# #
from __future__ import absolute_import, division, print_function from __future__ import absolute_import, division, print_function
import types import types
from six import text_type
def format_exception_only(etype, value): def format_exception_only(etype, value):
@ -79,7 +80,7 @@ def _format_final_exc_line(etype, value):
def _some_str(value): def _some_str(value):
try: try:
return unicode(value) return text_type(value)
except Exception: except Exception:
try: try:
return str(value) return str(value)

View File

@ -8,7 +8,7 @@ import attr
import re import re
from weakref import ref 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
import py import py
builtin_repr = repr builtin_repr = repr
@ -479,7 +479,7 @@ class ExceptionInfo(object):
def __unicode__(self): def __unicode__(self):
entry = self.traceback[-1] entry = self.traceback[-1]
loc = ReprFileLocation(entry.path, entry.lineno + 1, self.exconly()) loc = ReprFileLocation(entry.path, entry.lineno + 1, self.exconly())
return unicode(loc) return text_type(loc)
def match(self, regexp): def match(self, regexp):
""" """

View File

@ -13,6 +13,8 @@ import py
import _pytest import _pytest
from _pytest.outcomes import TEST_OUTCOME from _pytest.outcomes import TEST_OUTCOME
from six import text_type
import six
try: try:
import enum import enum
@ -163,7 +165,7 @@ def get_default_arg_names(function):
if _PY3: if _PY3:
STRING_TYPES = bytes, str STRING_TYPES = bytes, str
UNICODE_TYPES = str, UNICODE_TYPES = six.text_type
if PY35: if PY35:
@ -206,8 +208,8 @@ if _PY3:
else: else:
STRING_TYPES = bytes, str, unicode STRING_TYPES = six.string_types
UNICODE_TYPES = unicode, UNICODE_TYPES = six.text_type
def ascii_escaped(val): def ascii_escaped(val):
"""In py2 bytes and str are the same type, so return if it's a bytes """In py2 bytes and str are the same type, so return if it's a bytes
@ -303,8 +305,8 @@ else:
try: try:
return str(v) return str(v)
except UnicodeError: except UnicodeError:
if not isinstance(v, unicode): if not isinstance(v, text_type):
v = unicode(v) v = text_type(v)
errors = "replace" errors = "replace"
return v.encode("utf-8", errors) return v.encode("utf-8", errors)

View File

@ -30,6 +30,8 @@ from _pytest.compat import (
) )
from _pytest.outcomes import fail, TEST_OUTCOME from _pytest.outcomes import fail, TEST_OUTCOME
FIXTURE_MSG = 'fixtures cannot have "pytest_funcarg__" prefix and be decorated with @pytest.fixture:\n{}'
@attr.s(frozen=True) @attr.s(frozen=True)
class PseudoFixtureDef(object): class PseudoFixtureDef(object):
@ -1178,8 +1180,7 @@ class FixtureManager(object):
else: else:
if marker.name: if marker.name:
name = marker.name name = marker.name
msg = 'fixtures cannot have "pytest_funcarg__" prefix ' "and be decorated with @pytest.fixture:\n%s" % name assert not name.startswith(self._argprefix), FIXTURE_MSG.format(name)
assert not name.startswith(self._argprefix), msg
fixture_def = FixtureDef( fixture_def = FixtureDef(
self, self,

View File

@ -343,7 +343,7 @@ class PyCollector(PyobjMixin, nodes.Collector):
obj = safe_getattr(obj, "__func__", False) obj = safe_getattr(obj, "__func__", False)
if obj is False: if obj is False:
# Python 2.6 wraps in a different way that we won't try to handle # Python 2.6 wraps in a different way that we won't try to handle
msg = "cannot collect static method %r because " "it is not a function (always the case in Python 2.6)" msg = "cannot collect static method %r because it is not a function"
self.warn(code="C2", message=msg % name) self.warn(code="C2", message=msg % name)
return False return False
return ( return (

View File

@ -2,14 +2,19 @@ import math
import sys import sys
import py import py
from six import binary_type, text_type
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
from _pytest.compat import isclass from _pytest.compat import isclass
from _pytest.compat import Mapping, Sequence
from _pytest.compat import STRING_TYPES
from _pytest.outcomes import fail from _pytest.outcomes import fail
import _pytest._code import _pytest._code
BASE_TYPE = (type, STRING_TYPES)
def _cmp_raises_type_error(self, other): def _cmp_raises_type_error(self, other):
"""__cmp__ implementation which raises TypeError. Used """__cmp__ implementation which raises TypeError. Used
@ -439,8 +444,6 @@ def approx(expected, rel=None, abs=None, nan_ok=False):
__ https://docs.python.org/3/reference/datamodel.html#object.__ge__ __ https://docs.python.org/3/reference/datamodel.html#object.__ge__
""" """
from _pytest.compat import Mapping, Sequence
from _pytest.compat import STRING_TYPES as String
from decimal import Decimal from decimal import Decimal
# Delegate the comparison to a class that knows how to deal with the type # Delegate the comparison to a class that knows how to deal with the type
@ -461,7 +464,7 @@ def approx(expected, rel=None, abs=None, nan_ok=False):
cls = ApproxNumpy cls = ApproxNumpy
elif isinstance(expected, Mapping): elif isinstance(expected, Mapping):
cls = ApproxMapping cls = ApproxMapping
elif isinstance(expected, Sequence) and not isinstance(expected, String): elif isinstance(expected, Sequence) and not isinstance(expected, STRING_TYPES):
cls = ApproxSequence cls = ApproxSequence
elif isinstance(expected, Decimal): elif isinstance(expected, Decimal):
cls = ApproxDecimal cls = ApproxDecimal
@ -600,8 +603,7 @@ def raises(expected_exception, *args, **kwargs):
""" """
__tracebackhide__ = True __tracebackhide__ = True
base_type = (type, text_type, binary_type) for exc in filterfalse(isclass, always_iterable(expected_exception, BASE_TYPE)):
for exc in filterfalse(isclass, always_iterable(expected_exception, base_type)):
msg = ( msg = (
"exceptions must be old-style classes or" "exceptions must be old-style classes or"
" derived from BaseException, not %s" " derived from BaseException, not %s"

View File

@ -2,7 +2,7 @@ import sys
if __name__ == "__main__": if __name__ == "__main__":
import cProfile import cProfile
import pytest import pytest # NOQA
import pstats import pstats
script = sys.argv[1:] if len(sys.argv) > 1 else "empty.py" script = sys.argv[1:] if len(sys.argv) > 1 else "empty.py"

View File

@ -5,17 +5,18 @@
# FilesCompleter 75.1109 69.2116 # FilesCompleter 75.1109 69.2116
# FastFilesCompleter 0.7383 1.0760 # FastFilesCompleter 0.7383 1.0760
import timeit
imports = [
"from argcomplete.completers import FilesCompleter as completer",
"from _pytest._argcomplete import FastFilesCompleter as completer",
]
count = 1000 # only a few seconds
setup = "%s\nfc = completer()"
run = 'fc("/d")'
if __name__ == "__main__": if __name__ == "__main__":
import sys print(timeit.timeit(run, setup=setup % imports[0], number=count))
import timeit print((timeit.timeit(run, setup=setup % imports[1], number=count)))
from argcomplete.completers import FilesCompleter
from _pytest._argcomplete import FastFilesCompleter
count = 1000 # only a few seconds
setup = "from __main__ import FastFilesCompleter\nfc = FastFilesCompleter()"
run = 'fc("/d")'
sys.stdout.write(
"%s\n" % (timeit.timeit(run, setup=setup.replace("Fast", ""), number=count))
)
sys.stdout.write("%s\n" % (timeit.timeit(run, setup=setup, number=count)))

View File

@ -1,11 +1,11 @@
from six.moves import range
import pytest import pytest
SKIP = True SKIP = True
@pytest.mark.parametrize("x", xrange(5000)) @pytest.mark.parametrize("x", range(5000))
def test_foo(x): def test_foo(x):
if SKIP: if SKIP:
pytest.skip("heh") pytest.skip("heh")

View File

@ -1,4 +1,3 @@
import py
import subprocess import subprocess

View File

@ -153,7 +153,7 @@ def globf(x):
class TestRaises(object): class TestRaises(object):
def test_raises(self): def test_raises(self):
s = "qwe" s = "qwe" # NOQA
raises(TypeError, "int(s)") raises(TypeError, "int(s)")
def test_raises_doesnt(self): def test_raises_doesnt(self):
@ -163,15 +163,15 @@ class TestRaises(object):
raise ValueError("demo error") raise ValueError("demo error")
def test_tupleerror(self): def test_tupleerror(self):
a, b = [1] a, b = [1] # NOQA
def test_reinterpret_fails_with_print_for_the_fun_of_it(self): def test_reinterpret_fails_with_print_for_the_fun_of_it(self):
l = [1, 2, 3] items = [1, 2, 3]
print("l is %r" % l) print("items is %r" % items)
a, b = l.pop() a, b = items.pop()
def test_some_error(self): def test_some_error(self):
if namenotexi: if namenotexi: # NOQA
pass pass
def func1(self): def func1(self):
@ -205,12 +205,12 @@ class TestMoreErrors(object):
somefunc(f(), g()) somefunc(f(), g())
def test_z1_unpack_error(self): def test_z1_unpack_error(self):
l = [] items = []
a, b = l a, b = items
def test_z2_type_error(self): def test_z2_type_error(self):
l = 3 items = 3
a, b = l a, b = items
def test_startswith(self): def test_startswith(self):
s = "123" s = "123"

View File

@ -1,4 +1,5 @@
import pytest, py import pytest
import py
mydir = py.path.local(__file__).dirpath() mydir = py.path.local(__file__).dirpath()

View File

@ -1,6 +1,7 @@
# run this with $ pytest --collect-only test_collectonly.py # run this with $ pytest --collect-only test_collectonly.py
# #
def test_function(): def test_function():
pass pass

View File

@ -1,10 +1,9 @@
import json import json
import py import py
import requests
issues_url = "https://api.github.com/repos/pytest-dev/pytest/issues" issues_url = "https://api.github.com/repos/pytest-dev/pytest/issues"
import requests
def get_issues(): def get_issues():
issues = [] issues = []
@ -55,7 +54,7 @@ def _get_kind(issue):
def report(issues): def report(issues):
for issue in issues: for issue in issues:
title = issue["title"] title = issue["title"]
body = issue["body"] # body = issue["body"]
kind = _get_kind(issue) kind = _get_kind(issue)
status = issue["state"] status = issue["state"]
number = issue["number"] number = issue["number"]

View File

@ -6,6 +6,7 @@ import _pytest._code
import py import py
import pytest import pytest
from test_excinfo import TWMock from test_excinfo import TWMock
from six import text_type
def test_ne(): def test_ne():
@ -93,7 +94,7 @@ def test_unicode_handling():
excinfo = pytest.raises(Exception, f) excinfo = pytest.raises(Exception, f)
str(excinfo) str(excinfo)
if sys.version_info[0] < 3: if sys.version_info[0] < 3:
unicode(excinfo) text_type(excinfo)
@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")
@ -106,7 +107,7 @@ def test_unicode_handling_syntax_error():
excinfo = pytest.raises(Exception, f) excinfo = pytest.raises(Exception, f)
str(excinfo) str(excinfo)
if sys.version_info[0] < 3: if sys.version_info[0] < 3:
unicode(excinfo) text_type(excinfo)
def test_code_getargs(): def test_code_getargs():

View File

@ -847,7 +847,7 @@ class TestSorting(object):
assert fn1 == fn2 assert fn1 == fn2
assert fn1 != modcol assert fn1 != modcol
if sys.version_info < (3, 0): if sys.version_info < (3, 0):
assert cmp(fn1, fn2) == 0 assert cmp(fn1, fn2) == 0 # NOQA
assert hash(fn1) == hash(fn2) assert hash(fn1) == hash(fn2)
fn3 = testdir.collect_by_name(modcol, "test_fail") fn3 = testdir.collect_by_name(modcol, "test_fail")

View File

@ -12,7 +12,7 @@ import _pytest._code
import py import py
import pytest import pytest
import contextlib import contextlib
from six import binary_type, text_type
from _pytest import capture from _pytest import capture
from _pytest.capture import CaptureManager from _pytest.capture import CaptureManager
from _pytest.main import EXIT_NOTESTSCOLLECTED from _pytest.main import EXIT_NOTESTSCOLLECTED
@ -20,34 +20,19 @@ from _pytest.main import EXIT_NOTESTSCOLLECTED
needsosdup = pytest.mark.xfail("not hasattr(os, 'dup')") needsosdup = pytest.mark.xfail("not hasattr(os, 'dup')")
if sys.version_info >= (3, 0):
def tobytes(obj): def tobytes(obj):
if isinstance(obj, str): if isinstance(obj, text_type):
obj = obj.encode("UTF-8") obj = obj.encode("UTF-8")
assert isinstance(obj, bytes) assert isinstance(obj, binary_type)
return obj return obj
def totext(obj):
if isinstance(obj, bytes):
obj = str(obj, "UTF-8")
assert isinstance(obj, str)
return obj
else: def totext(obj):
if isinstance(obj, binary_type):
def tobytes(obj): obj = text_type(obj, "UTF-8")
if isinstance(obj, unicode): assert isinstance(obj, text_type)
obj = obj.encode("UTF-8") return obj
assert isinstance(obj, str)
return obj
def totext(obj):
if isinstance(obj, str):
obj = unicode(obj, "UTF-8")
assert isinstance(obj, unicode)
return obj
def oswritebytes(fd, obj): def oswritebytes(fd, obj):
@ -800,11 +785,11 @@ class TestCaptureIO(object):
f.write("\u00f6") f.write("\u00f6")
pytest.raises(TypeError, "f.write(bytes('hello', 'UTF-8'))") pytest.raises(TypeError, "f.write(bytes('hello', 'UTF-8'))")
else: else:
f.write(unicode("\u00f6", "UTF-8")) f.write(text_type("\u00f6", "UTF-8"))
f.write("hello") # bytes f.write("hello") # bytes
s = f.getvalue() s = f.getvalue()
f.close() f.close()
assert isinstance(s, unicode) assert isinstance(s, text_type)
@pytest.mark.skipif(sys.version_info[0] == 2, reason="python 3 only behaviour") @pytest.mark.skipif(sys.version_info[0] == 2, reason="python 3 only behaviour")
def test_write_bytes_to_buffer(self): def test_write_bytes_to_buffer(self):

View File

@ -44,7 +44,7 @@ class TestCollector(object):
assert fn1 == fn2 assert fn1 == fn2
assert fn1 != modcol assert fn1 != modcol
if sys.version_info < (3, 0): if sys.version_info < (3, 0):
assert cmp(fn1, fn2) == 0 assert cmp(fn1, fn2) == 0 # NOQA
assert hash(fn1) == hash(fn2) assert hash(fn1) == hash(fn2)
fn3 = testdir.collect_by_name(modcol, "test_fail") fn3 = testdir.collect_by_name(modcol, "test_fail")