Merge remote-tracking branch 'upstream/master' into merge-master-into-features

This commit is contained in:
Bruno Oliveira
2018-08-26 16:45:00 -03:00
65 changed files with 1299 additions and 909 deletions

View File

@@ -2,11 +2,11 @@
from __future__ import absolute_import, division, print_function
import os
import sys
import textwrap
import types
import six
import _pytest._code
import py
import pytest
from _pytest.main import EXIT_NOTESTSCOLLECTED, EXIT_USAGEERROR
@@ -131,7 +131,7 @@ class TestGeneralUsage(object):
p2 = testdir.makefile(".pyc", "123")
result = testdir.runpytest(p1, p2)
assert result.ret
result.stderr.fnmatch_lines(["*ERROR: not found:*%s" % (p2.basename,)])
result.stderr.fnmatch_lines(["*ERROR: not found:*{}".format(p2.basename)])
def test_issue486_better_reporting_on_conftest_load_failure(self, testdir):
testdir.makepyfile("")
@@ -201,16 +201,16 @@ class TestGeneralUsage(object):
testdir.tmpdir.join("py").mksymlinkto(py._pydir)
p = testdir.tmpdir.join("main.py")
p.write(
_pytest._code.Source(
textwrap.dedent(
"""\
import sys, os
sys.path.insert(0, '')
import py
print(py.__file__)
print(py.__path__)
os.chdir(os.path.dirname(os.getcwd()))
print(py.log)
"""
import sys, os
sys.path.insert(0, '')
import py
print (py.__file__)
print (py.__path__)
os.chdir(os.path.dirname(os.getcwd()))
print (py.log)
"""
)
)
result = testdir.runpython(p)
@@ -453,7 +453,7 @@ class TestInvocationVariants(object):
@pytest.mark.xfail("sys.platform.startswith('java')")
def test_pydoc(self, testdir):
for name in ("py.test", "pytest"):
result = testdir.runpython_c("import %s;help(%s)" % (name, name))
result = testdir.runpython_c("import {};help({})".format(name, name))
assert result.ret == 0
s = result.stdout.str()
assert "MarkGenerator" in s
@@ -660,6 +660,16 @@ class TestInvocationVariants(object):
["*test_world.py::test_other*PASSED*", "*1 passed*"]
)
def test_invoke_test_and_doctestmodules(self, testdir):
p = testdir.makepyfile(
"""
def test():
pass
"""
)
result = testdir.runpytest(str(p) + "::test", "--doctest-modules")
result.stdout.fnmatch_lines(["*1 passed*"])
@pytest.mark.skipif(not hasattr(os, "symlink"), reason="requires symlinks")
def test_cmdline_python_package_symlink(self, testdir, monkeypatch):
"""
@@ -826,7 +836,7 @@ class TestDurations(object):
if ("test_%s" % x) in line and y in line:
break
else:
raise AssertionError("not found %s %s" % (x, y))
raise AssertionError("not found {} {}".format(x, y))
def test_with_deselected(self, testdir):
testdir.makepyfile(self.source)

View File

@@ -3,8 +3,8 @@ from __future__ import absolute_import, division, print_function
import sys
import _pytest._code
import py
import pytest
import mock
from test_excinfo import TWMock
from six import text_type
@@ -68,12 +68,8 @@ def test_getstatement_empty_fullsource():
f = func()
f = _pytest._code.Frame(f)
prop = f.code.__class__.fullsource
try:
f.code.__class__.fullsource = None
assert f.statement == _pytest._code.Source("")
finally:
f.code.__class__.fullsource = prop
with mock.patch.object(f.code.__class__, "fullsource", None):
assert f.statement == ""
def test_code_from_func():
@@ -83,7 +79,7 @@ def test_code_from_func():
def test_unicode_handling():
value = py.builtin._totext("\xc4\x85\xc4\x87\n", "utf-8").encode("utf8")
value = u"ąć".encode("UTF-8")
def f():
raise Exception(value)
@@ -96,7 +92,7 @@ def test_unicode_handling():
@pytest.mark.skipif(sys.version_info[0] >= 3, reason="python 2 only issue")
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():
raise SyntaxError("invalid syntax", (None, 1, 3, value))

View File

@@ -8,6 +8,7 @@ import textwrap
import _pytest
import py
import pytest
import six
from _pytest._code.code import (
ExceptionInfo,
FormattedExcinfo,
@@ -148,7 +149,7 @@ class TestTraceback_f_g_h(object):
except somenoname:
pass
xyz()
"""
"""
)
try:
exec(source.compile())
@@ -251,7 +252,7 @@ class TestTraceback_f_g_h(object):
import sys
exc, val, tb = sys.exc_info()
py.builtin._reraise(exc, val, tb)
six.reraise(exc, val, tb)
def f(n):
try:
@@ -269,7 +270,7 @@ class TestTraceback_f_g_h(object):
decorator = pytest.importorskip("decorator").decorator
def log(f, *k, **kw):
print("%s %s" % (k, kw))
print("{} {}".format(k, kw))
f(*k, **kw)
log = decorator(log)
@@ -425,7 +426,7 @@ class TestFormattedExcinfo(object):
@pytest.fixture
def importasmod(self, request):
def importasmod(source):
source = _pytest._code.Source(source)
source = textwrap.dedent(source)
tmpdir = request.getfixturevalue("tmpdir")
modpath = tmpdir.join("mod.py")
tmpdir.ensure("__init__.py")
@@ -449,10 +450,10 @@ class TestFormattedExcinfo(object):
def test_repr_source(self):
pr = FormattedExcinfo()
source = _pytest._code.Source(
"""
"""\
def f(x):
pass
"""
"""
).strip()
pr.flow_marker = "|"
lines = pr.get_source(source, 0)
@@ -884,10 +885,10 @@ raise ValueError()
class MyRepr(TerminalRepr):
def toterminal(self, tw):
tw.line(py.builtin._totext("я", "utf-8"))
tw.line(u"я")
x = py.builtin._totext(MyRepr())
assert x == py.builtin._totext("я", "utf-8")
x = six.text_type(MyRepr())
assert x == u"я"
def test_toterminal_long(self, importasmod):
mod = importasmod(

View File

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

View File

@@ -1,6 +1,9 @@
"""Reproduces issue #3774"""
import mock
try:
import mock
except ImportError:
import unittest.mock as mock
import pytest

View File

@@ -0,0 +1,2 @@
[pytest]
python_files = *.py

View File

@@ -0,0 +1,2 @@
def test_init():
pass

View File

@@ -0,0 +1,2 @@
def test_foo():
pass

View File

@@ -878,7 +878,6 @@ def test_live_logging_suspends_capture(has_capture_manager, request):
import logging
import contextlib
from functools import partial
from _pytest.capture import CaptureManager
from _pytest.logging import _LiveLoggingStreamHandler
class MockCaptureManager:
@@ -890,10 +889,6 @@ def test_live_logging_suspends_capture(has_capture_manager, request):
yield
self.calls.append("exit disabled")
# sanity check
assert CaptureManager.suspend_capture_item
assert CaptureManager.resume_global_capture
class DummyTerminal(six.StringIO):
def section(self, *args, **kwargs):
pass

View File

@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
import os
import sys
from textwrap import dedent
import textwrap
import _pytest._code
import pytest
@@ -47,13 +47,14 @@ class TestModule(object):
p = root2.join("test_x456.py")
monkeypatch.syspath_prepend(str(root1))
p.write(
dedent(
textwrap.dedent(
"""\
import x456
def test():
assert x456.__file__.startswith(%r)
"""
% str(root2)
import x456
def test():
assert x456.__file__.startswith({!r})
""".format(
str(root2)
)
)
)
with root2.as_cwd():
@@ -929,23 +930,23 @@ class TestConftestCustomization(object):
def test_customized_pymakemodule_issue205_subdir(self, testdir):
b = testdir.mkdir("a").mkdir("b")
b.join("conftest.py").write(
_pytest._code.Source(
textwrap.dedent(
"""\
import pytest
@pytest.hookimpl(hookwrapper=True)
def pytest_pycollect_makemodule():
outcome = yield
mod = outcome.get_result()
mod.obj.hello = "world"
"""
import pytest
@pytest.hookimpl(hookwrapper=True)
def pytest_pycollect_makemodule():
outcome = yield
mod = outcome.get_result()
mod.obj.hello = "world"
"""
)
)
b.join("test_module.py").write(
_pytest._code.Source(
textwrap.dedent(
"""\
def test_hello():
assert hello == "world"
"""
def test_hello():
assert hello == "world"
"""
)
)
reprec = testdir.inline_run()
@@ -954,31 +955,31 @@ class TestConftestCustomization(object):
def test_customized_pymakeitem(self, testdir):
b = testdir.mkdir("a").mkdir("b")
b.join("conftest.py").write(
_pytest._code.Source(
textwrap.dedent(
"""\
import pytest
@pytest.hookimpl(hookwrapper=True)
def pytest_pycollect_makeitem():
outcome = yield
if outcome.excinfo is None:
result = outcome.get_result()
if result:
for func in result:
func._some123 = "world"
"""
import pytest
@pytest.hookimpl(hookwrapper=True)
def pytest_pycollect_makeitem():
outcome = yield
if outcome.excinfo is None:
result = outcome.get_result()
if result:
for func in result:
func._some123 = "world"
"""
)
)
b.join("test_module.py").write(
_pytest._code.Source(
"""
import pytest
textwrap.dedent(
"""\
import pytest
@pytest.fixture()
def obj(request):
return request.node._some123
def test_hello(obj):
assert obj == "world"
"""
@pytest.fixture()
def obj(request):
return request.node._some123
def test_hello(obj):
assert obj == "world"
"""
)
)
reprec = testdir.inline_run()
@@ -1033,7 +1034,7 @@ class TestConftestCustomization(object):
)
testdir.makefile(
".narf",
"""
"""\
def test_something():
assert 1 + 1 == 2""",
)
@@ -1046,29 +1047,29 @@ def test_setup_only_available_in_subdir(testdir):
sub1 = testdir.mkpydir("sub1")
sub2 = testdir.mkpydir("sub2")
sub1.join("conftest.py").write(
_pytest._code.Source(
textwrap.dedent(
"""\
import pytest
def pytest_runtest_setup(item):
assert item.fspath.purebasename == "test_in_sub1"
def pytest_runtest_call(item):
assert item.fspath.purebasename == "test_in_sub1"
def pytest_runtest_teardown(item):
assert item.fspath.purebasename == "test_in_sub1"
"""
import pytest
def pytest_runtest_setup(item):
assert item.fspath.purebasename == "test_in_sub1"
def pytest_runtest_call(item):
assert item.fspath.purebasename == "test_in_sub1"
def pytest_runtest_teardown(item):
assert item.fspath.purebasename == "test_in_sub1"
"""
)
)
sub2.join("conftest.py").write(
_pytest._code.Source(
textwrap.dedent(
"""\
import pytest
def pytest_runtest_setup(item):
assert item.fspath.purebasename == "test_in_sub2"
def pytest_runtest_call(item):
assert item.fspath.purebasename == "test_in_sub2"
def pytest_runtest_teardown(item):
assert item.fspath.purebasename == "test_in_sub2"
"""
import pytest
def pytest_runtest_setup(item):
assert item.fspath.purebasename == "test_in_sub2"
def pytest_runtest_call(item):
assert item.fspath.purebasename == "test_in_sub2"
def pytest_runtest_teardown(item):
assert item.fspath.purebasename == "test_in_sub2"
"""
)
)
sub1.join("test_in_sub1.py").write("def test_1(): pass")
@@ -1547,12 +1548,12 @@ def test_skip_duplicates_by_default(testdir):
a = testdir.mkdir("a")
fh = a.join("test_a.py")
fh.write(
_pytest._code.Source(
textwrap.dedent(
"""\
import pytest
def test_real():
pass
"""
import pytest
def test_real():
pass
"""
)
)
result = testdir.runpytest(a.strpath, a.strpath)
@@ -1567,12 +1568,12 @@ def test_keep_duplicates(testdir):
a = testdir.mkdir("a")
fh = a.join("test_a.py")
fh.write(
_pytest._code.Source(
textwrap.dedent(
"""\
import pytest
def test_real():
pass
"""
import pytest
def test_real():
pass
"""
)
)
result = testdir.runpytest("--keep-duplicates", a.strpath, a.strpath)
@@ -1623,3 +1624,38 @@ def test_package_with_modules(testdir):
root.chdir()
result = testdir.runpytest("-v", "-s")
result.assert_outcomes(passed=2)
def test_package_ordering(testdir):
"""
.
└── root
├── Test_root.py
├── __init__.py
├── sub1
│ ├── Test_sub1.py
│ └── __init__.py
└── sub2
└── test
└── test_sub2.py
"""
testdir.makeini(
"""
[pytest]
python_files=*.py
"""
)
root = testdir.mkpydir("root")
sub1 = root.mkdir("sub1")
sub1.ensure("__init__.py")
sub2 = root.mkdir("sub2")
sub2_test = sub2.mkdir("sub2")
root.join("Test_root.py").write("def test_1(): pass")
sub1.join("Test_sub1.py").write("def test_2(): pass")
sub2_test.join("test_sub2.py").write("def test_3(): pass")
# Execute from .
result = testdir.runpytest("-v", "-s")
result.assert_outcomes(passed=3)

View File

@@ -1,6 +1,6 @@
from textwrap import dedent
# -*- coding: utf-8 -*-
import textwrap
import _pytest._code
import pytest
from _pytest.pytester import get_public_names
from _pytest.fixtures import FixtureLookupError, FixtureRequest
@@ -208,23 +208,23 @@ class TestFillFixtures(object):
)
subdir = testdir.mkpydir("subdir")
subdir.join("conftest.py").write(
_pytest._code.Source(
"""
import pytest
textwrap.dedent(
"""\
import pytest
@pytest.fixture
def spam():
return 'spam'
"""
@pytest.fixture
def spam():
return 'spam'
"""
)
)
testfile = subdir.join("test_spam.py")
testfile.write(
_pytest._code.Source(
textwrap.dedent(
"""\
def test_spam(spam):
assert spam == "spam"
"""
def test_spam(spam):
assert spam == "spam"
"""
)
)
result = testdir.runpytest()
@@ -276,26 +276,26 @@ class TestFillFixtures(object):
)
subdir = testdir.mkpydir("subdir")
subdir.join("conftest.py").write(
_pytest._code.Source(
"""
import pytest
textwrap.dedent(
"""\
import pytest
@pytest.fixture(params=[1, 2, 3])
def spam(request):
return request.param
"""
@pytest.fixture(params=[1, 2, 3])
def spam(request):
return request.param
"""
)
)
testfile = subdir.join("test_spam.py")
testfile.write(
_pytest._code.Source(
"""
params = {'spam': 1}
textwrap.dedent(
"""\
params = {'spam': 1}
def test_spam(spam):
assert spam == params['spam']
params['spam'] += 1
"""
def test_spam(spam):
assert spam == params['spam']
params['spam'] += 1
"""
)
)
result = testdir.runpytest()
@@ -320,26 +320,26 @@ class TestFillFixtures(object):
)
subdir = testdir.mkpydir("subdir")
subdir.join("conftest.py").write(
_pytest._code.Source(
"""
import pytest
textwrap.dedent(
"""\
import pytest
@pytest.fixture(params=[1, 2, 3])
def spam(request):
return request.param
"""
@pytest.fixture(params=[1, 2, 3])
def spam(request):
return request.param
"""
)
)
testfile = subdir.join("test_spam.py")
testfile.write(
_pytest._code.Source(
"""
params = {'spam': 1}
textwrap.dedent(
"""\
params = {'spam': 1}
def test_spam(spam):
assert spam == params['spam']
params['spam'] += 1
"""
def test_spam(spam):
assert spam == params['spam']
params['spam'] += 1
"""
)
)
result = testdir.runpytest()
@@ -807,13 +807,13 @@ class TestRequestBasic(object):
# this tests that normalization of nodeids takes place
b = testdir.mkdir("tests").mkdir("unit")
b.join("conftest.py").write(
_pytest._code.Source(
textwrap.dedent(
"""\
import pytest
@pytest.fixture
def arg1():
pass
"""
import pytest
@pytest.fixture
def arg1():
pass
"""
)
)
p = b.join("test_module.py")
@@ -1484,41 +1484,41 @@ class TestFixtureManagerParseFactories(object):
runner = testdir.mkdir("runner")
package = testdir.mkdir("package")
package.join("conftest.py").write(
dedent(
textwrap.dedent(
"""\
import pytest
@pytest.fixture
def one():
return 1
"""
"""
)
)
package.join("test_x.py").write(
dedent(
textwrap.dedent(
"""\
def test_x(one):
assert one == 1
"""
def test_x(one):
assert one == 1
"""
)
)
sub = package.mkdir("sub")
sub.join("__init__.py").ensure()
sub.join("conftest.py").write(
dedent(
textwrap.dedent(
"""\
import pytest
@pytest.fixture
def one():
return 2
"""
import pytest
@pytest.fixture
def one():
return 2
"""
)
)
sub.join("test_y.py").write(
dedent(
textwrap.dedent(
"""\
def test_x(one):
assert one == 2
"""
def test_x(one):
assert one == 2
"""
)
)
reprec = testdir.inline_run()
@@ -1535,44 +1535,44 @@ class TestFixtureManagerParseFactories(object):
)
package = testdir.mkdir("package")
package.join("__init__.py").write(
dedent(
textwrap.dedent(
"""\
from .. import values
def setup_module():
values.append("package")
def teardown_module():
values[:] = []
"""
from .. import values
def setup_module():
values.append("package")
def teardown_module():
values[:] = []
"""
)
)
package.join("test_x.py").write(
dedent(
textwrap.dedent(
"""\
from .. import values
def test_x():
assert values == ["package"]
"""
from .. import values
def test_x():
assert values == ["package"]
"""
)
)
package = testdir.mkdir("package2")
package.join("__init__.py").write(
dedent(
textwrap.dedent(
"""\
from .. import values
def setup_module():
values.append("package2")
def teardown_module():
values[:] = []
"""
from .. import values
def setup_module():
values.append("package2")
def teardown_module():
values[:] = []
"""
)
)
package.join("test_x.py").write(
dedent(
textwrap.dedent(
"""\
from .. import values
def test_x():
assert values == ["package2"]
"""
from .. import values
def test_x():
assert values == ["package2"]
"""
)
)
reprec = testdir.inline_run()
@@ -1587,32 +1587,32 @@ class TestFixtureManagerParseFactories(object):
package = testdir.mkdir("package")
package.join("__init__.py").write("")
package.join("conftest.py").write(
dedent(
textwrap.dedent(
"""\
import pytest
from .. import values
@pytest.fixture(scope="package")
def one():
values.append("package")
yield values
values.pop()
@pytest.fixture(scope="package", autouse=True)
def two():
values.append("package-auto")
yield values
values.pop()
"""
import pytest
from .. import values
@pytest.fixture(scope="package")
def one():
values.append("package")
yield values
values.pop()
@pytest.fixture(scope="package", autouse=True)
def two():
values.append("package-auto")
yield values
values.pop()
"""
)
)
package.join("test_x.py").write(
dedent(
textwrap.dedent(
"""\
from .. import values
def test_package_autouse():
assert values == ["package-auto"]
def test_package(one):
assert values == ["package-auto", "package"]
"""
from .. import values
def test_package_autouse():
assert values == ["package-auto"]
def test_package(one):
assert values == ["package-auto", "package"]
"""
)
)
reprec = testdir.inline_run()
@@ -1804,24 +1804,24 @@ class TestAutouseManagement(object):
def test_autouse_conftest_mid_directory(self, testdir):
pkgdir = testdir.mkpydir("xyz123")
pkgdir.join("conftest.py").write(
_pytest._code.Source(
textwrap.dedent(
"""\
import pytest
@pytest.fixture(autouse=True)
def app():
import sys
sys._myapp = "hello"
"""
import pytest
@pytest.fixture(autouse=True)
def app():
import sys
sys._myapp = "hello"
"""
)
)
t = pkgdir.ensure("tests", "test_app.py")
t.write(
_pytest._code.Source(
textwrap.dedent(
"""\
import sys
def test_app():
assert sys._myapp == "hello"
"""
import sys
def test_app():
assert sys._myapp == "hello"
"""
)
)
reprec = testdir.inline_run("-s")
@@ -2715,17 +2715,17 @@ class TestFixtureMarker(object):
)
b = testdir.mkdir("subdir")
b.join("test_overridden_fixture_finalizer.py").write(
dedent(
"""
import pytest
@pytest.fixture
def browser(browser):
browser['visited'] = True
return browser
textwrap.dedent(
"""\
import pytest
@pytest.fixture
def browser(browser):
browser['visited'] = True
return browser
def test_browser(browser):
assert browser['visited'] is True
"""
def test_browser(browser):
assert browser['visited'] is True
"""
)
)
reprec = testdir.runpytest("-s")
@@ -3217,120 +3217,119 @@ class TestShowFixtures(object):
def test_show_fixtures_trimmed_doc(self, testdir):
p = testdir.makepyfile(
dedent(
textwrap.dedent(
'''\
import pytest
@pytest.fixture
def arg1():
"""
line1
line2
"""
@pytest.fixture
def arg2():
"""
line1
line2
"""
'''
import pytest
@pytest.fixture
def arg1():
"""
line1
line2
"""
@pytest.fixture
def arg2():
"""
line1
line2
"""
'''
)
)
result = testdir.runpytest("--fixtures", p)
result.stdout.fnmatch_lines(
dedent(
textwrap.dedent(
"""\
* fixtures defined from test_show_fixtures_trimmed_doc *
arg2
line1
line2
arg1
line1
line2
"""
* fixtures defined from test_show_fixtures_trimmed_doc *
arg2
line1
line2
arg1
line1
line2
"""
)
)
def test_show_fixtures_indented_doc(self, testdir):
p = testdir.makepyfile(
dedent(
textwrap.dedent(
'''\
import pytest
@pytest.fixture
def fixture1():
"""
line1
indented line
"""
'''
import pytest
@pytest.fixture
def fixture1():
"""
line1
indented line
"""
'''
)
)
result = testdir.runpytest("--fixtures", p)
result.stdout.fnmatch_lines(
dedent(
textwrap.dedent(
"""\
* fixtures defined from test_show_fixtures_indented_doc *
fixture1
line1
indented line
"""
* fixtures defined from test_show_fixtures_indented_doc *
fixture1
line1
indented line
"""
)
)
def test_show_fixtures_indented_doc_first_line_unindented(self, testdir):
p = testdir.makepyfile(
dedent(
textwrap.dedent(
'''\
import pytest
@pytest.fixture
def fixture1():
"""line1
line2
indented line
"""
'''
import pytest
@pytest.fixture
def fixture1():
"""line1
line2
indented line
"""
'''
)
)
result = testdir.runpytest("--fixtures", p)
result.stdout.fnmatch_lines(
dedent(
textwrap.dedent(
"""\
* fixtures defined from test_show_fixtures_indented_doc_first_line_unindented *
fixture1
line1
line2
indented line
"""
* fixtures defined from test_show_fixtures_indented_doc_first_line_unindented *
fixture1
line1
line2
indented line
"""
)
)
def test_show_fixtures_indented_in_class(self, testdir):
p = testdir.makepyfile(
dedent(
textwrap.dedent(
'''\
import pytest
class TestClass(object):
@pytest.fixture
def fixture1(self):
"""line1
line2
indented line
"""
'''
import pytest
class TestClass(object):
@pytest.fixture
def fixture1(self):
"""line1
line2
indented line
"""
'''
)
)
result = testdir.runpytest("--fixtures", p)
result.stdout.fnmatch_lines(
dedent(
textwrap.dedent(
"""\
* fixtures defined from test_show_fixtures_indented_in_class *
fixture1
line1
line2
indented line
"""
* fixtures defined from test_show_fixtures_indented_in_class *
fixture1
line1
line2
indented line
"""
)
)
@@ -3667,26 +3666,26 @@ class TestParameterizedSubRequest(object):
fixdir = testdir.mkdir("fixtures")
fixfile = fixdir.join("fix.py")
fixfile.write(
_pytest._code.Source(
"""
import pytest
textwrap.dedent(
"""\
import pytest
@pytest.fixture(params=[0, 1, 2])
def fix_with_param(request):
return request.param
"""
@pytest.fixture(params=[0, 1, 2])
def fix_with_param(request):
return request.param
"""
)
)
testfile = tests_dir.join("test_foos.py")
testfile.write(
_pytest._code.Source(
"""
from fix import fix_with_param
textwrap.dedent(
"""\
from fix import fix_with_param
def test_foo(request):
request.getfixturevalue('fix_with_param')
"""
def test_foo(request):
request.getfixturevalue('fix_with_param')
"""
)
)
@@ -3698,9 +3697,9 @@ class TestParameterizedSubRequest(object):
E*Failed: The requested fixture has no parameter defined for the current test.
E*
E*Requested fixture 'fix_with_param' defined in:
E*fix.py:5
E*fix.py:4
E*Requested here:
E*test_foos.py:5
E*test_foos.py:4
*1 failed*
"""
)
@@ -3979,3 +3978,71 @@ class TestScopeOrdering(object):
items, _ = testdir.inline_genitems()
request = FixtureRequest(items[0])
assert request.fixturenames == "s1 p1 m1 m2 c1 f2 f1".split()
def test_multiple_packages(self, testdir):
"""Complex test involving multiple package fixtures. Make sure teardowns
are executed in order.
.
└── root
├── __init__.py
├── sub1
│ ├── __init__.py
│ ├── conftest.py
│ └── test_1.py
└── sub2
├── __init__.py
├── conftest.py
└── test_2.py
"""
root = testdir.mkdir("root")
root.join("__init__.py").write("values = []")
sub1 = root.mkdir("sub1")
sub1.ensure("__init__.py")
sub1.join("conftest.py").write(
textwrap.dedent(
"""\
import pytest
from .. import values
@pytest.fixture(scope="package")
def fix():
values.append("pre-sub1")
yield values
assert values.pop() == "pre-sub1"
"""
)
)
sub1.join("test_1.py").write(
textwrap.dedent(
"""\
from .. import values
def test_1(fix):
assert values == ["pre-sub1"]
"""
)
)
sub2 = root.mkdir("sub2")
sub2.ensure("__init__.py")
sub2.join("conftest.py").write(
textwrap.dedent(
"""\
import pytest
from .. import values
@pytest.fixture(scope="package")
def fix():
values.append("pre-sub2")
yield values
assert values.pop() == "pre-sub2"
"""
)
)
sub2.join("test_2.py").write(
textwrap.dedent(
"""\
from .. import values
def test_2(fix):
assert values == ["pre-sub2"]
"""
)
)
reprec = testdir.inline_run()
reprec.assertoutcome(passed=2)

View File

@@ -2,8 +2,7 @@
import re
import sys
import attr
import _pytest._code
import py
import textwrap
import pytest
from _pytest import python, fixtures
@@ -295,9 +294,7 @@ class TestMetafunc(object):
)
assert result == ["a0-1.0", "a1-b1"]
# unicode mixing, issue250
result = idmaker(
(py.builtin._totext("a"), "b"), [pytest.param({}, b"\xc3\xb4")]
)
result = idmaker((u"a", "b"), [pytest.param({}, b"\xc3\xb4")])
assert result == ["a0-\\xc3\\xb4"]
def test_idmaker_with_bytes_regex(self):
@@ -309,7 +306,6 @@ class TestMetafunc(object):
def test_idmaker_native_strings(self):
from _pytest.python import idmaker
totext = py.builtin._totext
result = idmaker(
("a", "b"),
[
@@ -324,7 +320,7 @@ class TestMetafunc(object):
pytest.param({7}, set("seven")),
pytest.param(tuple("eight"), (8, -8, 8)),
pytest.param(b"\xc3\xb4", b"name"),
pytest.param(b"\xc3\xb4", totext("other")),
pytest.param(b"\xc3\xb4", u"other"),
],
)
assert result == [
@@ -1275,19 +1271,19 @@ class TestMetafuncFunctional(object):
sub1 = testdir.mkpydir("sub1")
sub2 = testdir.mkpydir("sub2")
sub1.join("conftest.py").write(
_pytest._code.Source(
textwrap.dedent(
"""\
def pytest_generate_tests(metafunc):
assert metafunc.function.__name__ == "test_1"
"""
def pytest_generate_tests(metafunc):
assert metafunc.function.__name__ == "test_1"
"""
)
)
sub2.join("conftest.py").write(
_pytest._code.Source(
textwrap.dedent(
"""\
def pytest_generate_tests(metafunc):
assert metafunc.function.__name__ == "test_2"
"""
def pytest_generate_tests(metafunc):
assert metafunc.function.__name__ == "test_2"
"""
)
)
sub1.join("test_in_sub1.py").write("def test_1(): pass")

View File

@@ -11,7 +11,7 @@ def equal_with_bash(prefix, ffc, fc, out=None):
res_bash = set(fc(prefix))
retval = set(res) == res_bash
if out:
out.write("equal_with_bash %s %s\n" % (retval, res))
out.write("equal_with_bash {} {}\n".format(retval, res))
if not retval:
out.write(" python - bash: %s\n" % (set(res) - res_bash))
out.write(" bash - python: %s\n" % (res_bash - set(res)))

View File

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

View File

@@ -9,6 +9,7 @@ import textwrap
import zipfile
import py
import pytest
import six
import _pytest._code
from _pytest.assertion import util
@@ -49,7 +50,7 @@ def getmsg(f, extra_ns=None, must_pass=False):
ns = {}
if extra_ns is not None:
ns.update(extra_ns)
py.builtin.exec_(code, ns)
six.exec_(code, ns)
func = ns[f.__name__]
try:
func()
@@ -560,7 +561,7 @@ class TestAssertionRewrite(object):
assert getmsg(f) == "assert 42"
def my_reprcompare(op, left, right):
return "%s %s %s" % (left, op, right)
return "{} {} {}".format(left, op, right)
monkeypatch.setattr(util, "_reprcompare", my_reprcompare)
@@ -654,12 +655,10 @@ class TestRewriteOnImport(object):
def test_readonly(self, testdir):
sub = testdir.mkdir("testing")
sub.join("test_readonly.py").write(
py.builtin._totext(
"""
b"""
def test_rewritten():
assert "@py_builtins" in globals()
"""
).encode("utf-8"),
""",
"wb",
)
old_mode = sub.stat().mode
@@ -1040,14 +1039,14 @@ class TestAssertionRewriteHookDetails(object):
"""
path = testdir.mkpydir("foo")
path.join("test_foo.py").write(
_pytest._code.Source(
textwrap.dedent(
"""\
class Test(object):
def test_foo(self):
import pkgutil
data = pkgutil.get_data('foo.test_foo', 'data.txt')
assert data == b'Hey'
"""
class Test(object):
def test_foo(self):
import pkgutil
data = pkgutil.get_data('foo.test_foo', 'data.txt')
assert data == b'Hey'
"""
)
)
path.join("data.txt").write("Hey")

View File

@@ -1,9 +1,9 @@
from __future__ import absolute_import, division, print_function
import sys
import textwrap
import py
import _pytest
import pytest
import os
import shutil
@@ -224,17 +224,17 @@ class TestLastFailed(object):
result = testdir.runpytest()
result.stdout.fnmatch_lines(["*2 failed*"])
p.write(
_pytest._code.Source(
textwrap.dedent(
"""\
def test_1():
assert 1
def test_2():
assert 1
def test_3():
assert 0
"""
def test_1():
assert 1
def test_2():
assert 1
def test_3():
assert 0
"""
)
)
result = testdir.runpytest("--lf")
@@ -252,19 +252,19 @@ class TestLastFailed(object):
def test_failedfirst_order(self, testdir):
testdir.tmpdir.join("test_a.py").write(
_pytest._code.Source(
textwrap.dedent(
"""\
def test_always_passes():
assert 1
"""
def test_always_passes():
assert 1
"""
)
)
testdir.tmpdir.join("test_b.py").write(
_pytest._code.Source(
textwrap.dedent(
"""\
def test_always_fails():
assert 0
"""
def test_always_fails():
assert 0
"""
)
)
result = testdir.runpytest()
@@ -277,14 +277,14 @@ class TestLastFailed(object):
def test_lastfailed_failedfirst_order(self, testdir):
testdir.makepyfile(
**{
"test_a.py": """
"test_a.py": """\
def test_always_passes():
assert 1
""",
"test_b.py": """
""",
"test_b.py": """\
def test_always_fails():
assert 0
""",
""",
}
)
result = testdir.runpytest()
@@ -298,16 +298,16 @@ class TestLastFailed(object):
def test_lastfailed_difference_invocations(self, testdir, monkeypatch):
monkeypatch.setenv("PYTHONDONTWRITEBYTECODE", 1)
testdir.makepyfile(
test_a="""
test_a="""\
def test_a1():
assert 0
def test_a2():
assert 1
""",
test_b="""
""",
test_b="""\
def test_b1():
assert 0
""",
""",
)
p = testdir.tmpdir.join("test_a.py")
p2 = testdir.tmpdir.join("test_b.py")
@@ -317,11 +317,11 @@ class TestLastFailed(object):
result = testdir.runpytest("--lf", p2)
result.stdout.fnmatch_lines(["*1 failed*"])
p2.write(
_pytest._code.Source(
textwrap.dedent(
"""\
def test_b1():
assert 1
"""
def test_b1():
assert 1
"""
)
)
result = testdir.runpytest("--lf", p2)
@@ -332,18 +332,18 @@ class TestLastFailed(object):
def test_lastfailed_usecase_splice(self, testdir, monkeypatch):
monkeypatch.setenv("PYTHONDONTWRITEBYTECODE", 1)
testdir.makepyfile(
"""
"""\
def test_1():
assert 0
"""
"""
)
p2 = testdir.tmpdir.join("test_something.py")
p2.write(
_pytest._code.Source(
textwrap.dedent(
"""\
def test_2():
assert 0
"""
def test_2():
assert 0
"""
)
)
result = testdir.runpytest()

View File

@@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
# note: py.io capture tests where copied from
@@ -5,13 +6,13 @@ from __future__ import absolute_import, division, print_function
import pickle
import os
import sys
import textwrap
from io import UnsupportedOperation
import _pytest._code
import py
import pytest
import contextlib
from six import binary_type, text_type
from six import text_type
from _pytest import capture
from _pytest.capture import CaptureManager
from _pytest.main import EXIT_NOTESTSCOLLECTED
@@ -23,12 +24,12 @@ needsosdup = pytest.mark.xfail("not hasattr(os, 'dup')")
def tobytes(obj):
if isinstance(obj, text_type):
obj = obj.encode("UTF-8")
assert isinstance(obj, binary_type)
assert isinstance(obj, bytes)
return obj
def totext(obj):
if isinstance(obj, binary_type):
if isinstance(obj, bytes):
obj = text_type(obj, "UTF-8")
assert isinstance(obj, text_type)
return obj
@@ -70,19 +71,23 @@ class TestCaptureManager(object):
try:
capman = CaptureManager(method)
capman.start_global_capturing()
outerr = capman.suspend_global_capture()
capman.suspend_global_capture()
outerr = capman.read_global_capture()
assert outerr == ("", "")
outerr = capman.suspend_global_capture()
capman.suspend_global_capture()
outerr = capman.read_global_capture()
assert outerr == ("", "")
print("hello")
out, err = capman.suspend_global_capture()
capman.suspend_global_capture()
out, err = capman.read_global_capture()
if method == "no":
assert old == (sys.stdout, sys.stderr, sys.stdin)
else:
assert not out
capman.resume_global_capture()
print("hello")
out, err = capman.suspend_global_capture()
capman.suspend_global_capture()
out, err = capman.read_global_capture()
if method != "no":
assert out == "hello\n"
capman.stop_global_capturing()
@@ -264,7 +269,7 @@ class TestPerTestCapturing(object):
def test_capturing_outerr(self, testdir):
p1 = testdir.makepyfile(
"""
"""\
import sys
def test_capturing():
print (42)
@@ -273,7 +278,7 @@ class TestPerTestCapturing(object):
print (1)
sys.stderr.write(str(2))
raise ValueError
"""
"""
)
result = testdir.runpytest(p1)
result.stdout.fnmatch_lines(
@@ -293,21 +298,21 @@ class TestPerTestCapturing(object):
class TestLoggingInteraction(object):
def test_logging_stream_ownership(self, testdir):
p = testdir.makepyfile(
"""
"""\
def test_logging():
import logging
import pytest
stream = capture.CaptureIO()
logging.basicConfig(stream=stream)
stream.close() # to free memory/release resources
"""
"""
)
result = testdir.runpytest_subprocess(p)
assert result.stderr.str().find("atexit") == -1
def test_logging_and_immediate_setupteardown(self, testdir):
p = testdir.makepyfile(
"""
"""\
import logging
def setup_function(function):
logging.warn("hello1")
@@ -319,7 +324,7 @@ class TestLoggingInteraction(object):
def teardown_function(function):
logging.warn("hello3")
assert 0
"""
"""
)
for optargs in (("--capture=sys",), ("--capture=fd",)):
print(optargs)
@@ -333,7 +338,7 @@ class TestLoggingInteraction(object):
def test_logging_and_crossscope_fixtures(self, testdir):
p = testdir.makepyfile(
"""
"""\
import logging
def setup_module(function):
logging.warn("hello1")
@@ -345,7 +350,7 @@ class TestLoggingInteraction(object):
def teardown_module(function):
logging.warn("hello3")
assert 0
"""
"""
)
for optargs in (("--capture=sys",), ("--capture=fd",)):
print(optargs)
@@ -359,11 +364,11 @@ class TestLoggingInteraction(object):
def test_conftestlogging_is_shown(self, testdir):
testdir.makeconftest(
"""
"""\
import logging
logging.basicConfig()
logging.warn("hello435")
"""
"""
)
# make sure that logging is still captured in tests
result = testdir.runpytest_subprocess("-s", "-p", "no:capturelog")
@@ -373,19 +378,19 @@ class TestLoggingInteraction(object):
def test_conftestlogging_and_test_logging(self, testdir):
testdir.makeconftest(
"""
"""\
import logging
logging.basicConfig()
"""
"""
)
# make sure that logging is still captured in tests
p = testdir.makepyfile(
"""
"""\
def test_hello():
import logging
logging.warn("hello433")
assert 0
"""
"""
)
result = testdir.runpytest_subprocess(p, "-p", "no:capturelog")
assert result.ret != 0
@@ -398,24 +403,24 @@ class TestCaptureFixture(object):
@pytest.mark.parametrize("opt", [[], ["-s"]])
def test_std_functional(self, testdir, opt):
reprec = testdir.inline_runsource(
"""
"""\
def test_hello(capsys):
print (42)
out, err = capsys.readouterr()
assert out.startswith("42")
""",
""",
*opt
)
reprec.assertoutcome(passed=1)
def test_capsyscapfd(self, testdir):
p = testdir.makepyfile(
"""
"""\
def test_one(capsys, capfd):
pass
def test_two(capfd, capsys):
pass
"""
"""
)
result = testdir.runpytest(p)
result.stdout.fnmatch_lines(
@@ -433,12 +438,12 @@ class TestCaptureFixture(object):
in the same test is an error.
"""
testdir.makepyfile(
"""
"""\
def test_one(capsys, request):
request.getfixturevalue("capfd")
def test_two(capfd, request):
request.getfixturevalue("capsys")
"""
"""
)
result = testdir.runpytest()
result.stdout.fnmatch_lines(
@@ -453,10 +458,10 @@ class TestCaptureFixture(object):
def test_capsyscapfdbinary(self, testdir):
p = testdir.makepyfile(
"""
"""\
def test_one(capsys, capfdbinary):
pass
"""
"""
)
result = testdir.runpytest(p)
result.stdout.fnmatch_lines(
@@ -466,12 +471,13 @@ class TestCaptureFixture(object):
@pytest.mark.parametrize("method", ["sys", "fd"])
def test_capture_is_represented_on_failure_issue128(self, testdir, method):
p = testdir.makepyfile(
"""
def test_hello(cap%s):
"""\
def test_hello(cap{}):
print ("xxx42xxx")
assert 0
"""
% method
""".format(
method
)
)
result = testdir.runpytest(p)
result.stdout.fnmatch_lines(["xxx42xxx"])
@@ -479,21 +485,21 @@ class TestCaptureFixture(object):
@needsosdup
def test_stdfd_functional(self, testdir):
reprec = testdir.inline_runsource(
"""
"""\
def test_hello(capfd):
import os
os.write(1, "42".encode('ascii'))
out, err = capfd.readouterr()
assert out.startswith("42")
capfd.close()
"""
"""
)
reprec.assertoutcome(passed=1)
@needsosdup
def test_capfdbinary(self, testdir):
reprec = testdir.inline_runsource(
"""
"""\
def test_hello(capfdbinary):
import os
# some likely un-decodable bytes
@@ -501,7 +507,7 @@ class TestCaptureFixture(object):
out, err = capfdbinary.readouterr()
assert out == b'\\xfe\\x98\\x20'
assert err == b''
"""
"""
)
reprec.assertoutcome(passed=1)
@@ -510,7 +516,7 @@ class TestCaptureFixture(object):
)
def test_capsysbinary(self, testdir):
reprec = testdir.inline_runsource(
"""
"""\
def test_hello(capsysbinary):
import sys
# some likely un-decodable bytes
@@ -518,7 +524,7 @@ class TestCaptureFixture(object):
out, err = capsysbinary.readouterr()
assert out == b'\\xfe\\x98\\x20'
assert err == b''
"""
"""
)
reprec.assertoutcome(passed=1)
@@ -527,10 +533,10 @@ class TestCaptureFixture(object):
)
def test_capsysbinary_forbidden_in_python2(self, testdir):
testdir.makepyfile(
"""
"""\
def test_hello(capsysbinary):
pass
"""
"""
)
result = testdir.runpytest()
result.stdout.fnmatch_lines(
@@ -543,10 +549,10 @@ class TestCaptureFixture(object):
def test_partial_setup_failure(self, testdir):
p = testdir.makepyfile(
"""
"""\
def test_hello(capsys, missingarg):
pass
"""
"""
)
result = testdir.runpytest(p)
result.stdout.fnmatch_lines(["*test_partial_setup_failure*", "*1 error*"])
@@ -554,12 +560,12 @@ class TestCaptureFixture(object):
@needsosdup
def test_keyboardinterrupt_disables_capturing(self, testdir):
p = testdir.makepyfile(
"""
"""\
def test_hello(capfd):
import os
os.write(1, str(42).encode('ascii'))
raise KeyboardInterrupt()
"""
"""
)
result = testdir.runpytest_subprocess(p)
result.stdout.fnmatch_lines(["*KeyboardInterrupt*"])
@@ -568,7 +574,7 @@ class TestCaptureFixture(object):
@pytest.mark.issue14
def test_capture_and_logging(self, testdir):
p = testdir.makepyfile(
"""
"""\
import logging
def test_log(capsys):
logging.error('x')
@@ -581,7 +587,7 @@ class TestCaptureFixture(object):
@pytest.mark.parametrize("no_capture", [True, False])
def test_disabled_capture_fixture(self, testdir, fixture, no_capture):
testdir.makepyfile(
"""
"""\
def test_disabled({fixture}):
print('captured before')
with {fixture}.disabled():
@@ -615,7 +621,7 @@ class TestCaptureFixture(object):
Ensure that capsys and capfd can be used by other fixtures during setup and teardown.
"""
testdir.makepyfile(
"""
"""\
from __future__ import print_function
import sys
import pytest
@@ -647,15 +653,43 @@ class TestCaptureFixture(object):
assert "stdout contents begin" not in result.stdout.str()
assert "stderr contents begin" not in result.stdout.str()
@pytest.mark.parametrize("cap", ["capsys", "capfd"])
def test_fixture_use_by_other_fixtures_teardown(self, testdir, cap):
"""Ensure we can access setup and teardown buffers from teardown when using capsys/capfd (##3033)"""
testdir.makepyfile(
"""\
import sys
import pytest
import os
@pytest.fixture()
def fix({cap}):
print("setup out")
sys.stderr.write("setup err\\n")
yield
out, err = {cap}.readouterr()
assert out == 'setup out\\ncall out\\n'
assert err == 'setup err\\ncall err\\n'
def test_a(fix):
print("call out")
sys.stderr.write("call err\\n")
""".format(
cap=cap
)
)
reprec = testdir.inline_run()
reprec.assertoutcome(passed=1)
def test_setup_failure_does_not_kill_capturing(testdir):
sub1 = testdir.mkpydir("sub1")
sub1.join("conftest.py").write(
_pytest._code.Source(
textwrap.dedent(
"""\
def pytest_runtest_setup(item):
raise ValueError(42)
"""
def pytest_runtest_setup(item):
raise ValueError(42)
"""
)
)
sub1.join("test_mod.py").write("def test_func1(): pass")
@@ -1051,9 +1085,9 @@ class TestStdCapture(object):
def test_capturing_readouterr_unicode(self):
with self.getcapture() as cap:
print("hx\xc4\x85\xc4\x87")
print("hxąć")
out, err = cap.readouterr()
assert out == py.builtin._totext("hx\xc4\x85\xc4\x87\n", "utf8")
assert out == u"hxąć\n"
@pytest.mark.skipif(
"sys.version_info >= (3,)", reason="text output different for bytes on python3"
@@ -1063,7 +1097,7 @@ class TestStdCapture(object):
# triggered an internal error in pytest
print("\xa6")
out, err = cap.readouterr()
assert out == py.builtin._totext("\ufffd\n", "unicode-escape")
assert out == u"\ufffd\n"
def test_reset_twice_error(self):
with self.getcapture() as cap:
@@ -1387,9 +1421,69 @@ def test_pickling_and_unpickling_encoded_file():
pickle.loads(ef_as_str)
def test_capsys_with_cli_logging(testdir):
def test_global_capture_with_live_logging(testdir):
# Issue 3819
# capsys should work with real-time cli logging
# capture should work with live cli logging
# Teardown report seems to have the capture for the whole process (setup, capture, teardown)
testdir.makeconftest(
"""
def pytest_runtest_logreport(report):
if "test_global" in report.nodeid:
if report.when == "teardown":
with open("caplog", "w") as f:
f.write(report.caplog)
with open("capstdout", "w") as f:
f.write(report.capstdout)
"""
)
testdir.makepyfile(
"""
import logging
import sys
import pytest
logger = logging.getLogger(__name__)
@pytest.fixture
def fix1():
print("fix setup")
logging.info("fix setup")
yield
logging.info("fix teardown")
print("fix teardown")
def test_global(fix1):
print("begin test")
logging.info("something in test")
print("end test")
"""
)
result = testdir.runpytest_subprocess("--log-cli-level=INFO")
assert result.ret == 0
with open("caplog", "r") as f:
caplog = f.read()
assert "fix setup" in caplog
assert "something in test" in caplog
assert "fix teardown" in caplog
with open("capstdout", "r") as f:
capstdout = f.read()
assert "fix setup" in capstdout
assert "begin test" in capstdout
assert "end test" in capstdout
assert "fix teardown" in capstdout
@pytest.mark.parametrize("capture_fixture", ["capsys", "capfd"])
def test_capture_with_live_logging(testdir, capture_fixture):
# Issue 3819
# capture should work with live cli logging
testdir.makepyfile(
"""
import logging
@@ -1397,22 +1491,23 @@ def test_capsys_with_cli_logging(testdir):
logger = logging.getLogger(__name__)
def test_myoutput(capsys): # or use "capfd" for fd-level
def test_capture({0}):
print("hello")
sys.stderr.write("world\\n")
captured = capsys.readouterr()
captured = {0}.readouterr()
assert captured.out == "hello\\n"
assert captured.err == "world\\n"
logging.info("something")
print("next")
logging.info("something")
captured = capsys.readouterr()
captured = {0}.readouterr()
assert captured.out == "next\\n"
"""
""".format(
capture_fixture
)
)
result = testdir.runpytest_subprocess("--log-cli-level=INFO")
assert result.ret == 0

View File

@@ -1,9 +1,9 @@
from __future__ import absolute_import, division, print_function
import pprint
import sys
import textwrap
import pytest
import _pytest._code
from _pytest.main import Session, EXIT_NOTESTSCOLLECTED, _in_venv
@@ -913,13 +913,13 @@ def test_fixture_scope_sibling_conftests(testdir):
"""Regression test case for https://github.com/pytest-dev/pytest/issues/2836"""
foo_path = testdir.mkdir("foo")
foo_path.join("conftest.py").write(
_pytest._code.Source(
textwrap.dedent(
"""\
import pytest
@pytest.fixture
def fix():
return 1
"""
import pytest
@pytest.fixture
def fix():
return 1
"""
)
)
foo_path.join("test_foo.py").write("def test_foo(fix): assert fix == 1")
@@ -938,3 +938,17 @@ def test_fixture_scope_sibling_conftests(testdir):
"*1 passed, 1 error*",
]
)
def test_collect_init_tests(testdir):
"""Check that we collect files from __init__.py files when they patch the 'python_files' (#3773)"""
p = testdir.copy_example("collect/collect_init_tests")
result = testdir.runpytest(p, "--collect-only")
result.stdout.fnmatch_lines(
[
"*<Module '__init__.py'>",
"*<Function 'test_init'>",
"*<Module 'test_foo.py'>",
"*<Function 'test_foo'>",
]
)

View File

@@ -17,11 +17,11 @@ class TestParseIni(object):
sub = tmpdir.mkdir("sub")
sub.chdir()
tmpdir.join(filename).write(
_pytest._code.Source(
"""
[{section}]
name = value
""".format(
textwrap.dedent(
"""\
[{section}]
name = value
""".format(
section=section
)
)
@@ -38,11 +38,11 @@ class TestParseIni(object):
def test_append_parse_args(self, testdir, tmpdir, monkeypatch):
monkeypatch.setenv("PYTEST_ADDOPTS", '--color no -rs --tb="short"')
tmpdir.join("pytest.ini").write(
_pytest._code.Source(
textwrap.dedent(
"""\
[pytest]
addopts = --verbose
"""
[pytest]
addopts = --verbose
"""
)
)
config = testdir.parseconfig(tmpdir)
@@ -438,11 +438,11 @@ class TestConfigFromdictargs(object):
def test_inifilename(self, tmpdir):
tmpdir.join("foo/bar.ini").ensure().write(
_pytest._code.Source(
textwrap.dedent(
"""\
[pytest]
name = value
"""
[pytest]
name = value
"""
)
)
@@ -453,12 +453,12 @@ class TestConfigFromdictargs(object):
cwd = tmpdir.join("a/b")
cwd.join("pytest.ini").ensure().write(
_pytest._code.Source(
textwrap.dedent(
"""\
[pytest]
name = wrong-value
should_not_be_set = true
"""
[pytest]
name = wrong-value
should_not_be_set = true
"""
)
)
with cwd.ensure(dir=True).as_cwd():

View File

@@ -1,7 +1,6 @@
from __future__ import absolute_import, division, print_function
from textwrap import dedent
import textwrap
import _pytest._code
import py
import pytest
from _pytest.config import PytestPluginManager
@@ -174,11 +173,11 @@ def test_conftest_confcutdir(testdir):
testdir.makeconftest("assert 0")
x = testdir.mkdir("x")
x.join("conftest.py").write(
_pytest._code.Source(
textwrap.dedent(
"""\
def pytest_addoption(parser):
parser.addoption("--xyz", action="store_true")
"""
def pytest_addoption(parser):
parser.addoption("--xyz", action="store_true")
"""
)
)
result = testdir.runpytest("-h", "--confcutdir=%s" % x, x)
@@ -198,11 +197,11 @@ def test_no_conftest(testdir):
def test_conftest_existing_resultlog(testdir):
x = testdir.mkdir("tests")
x.join("conftest.py").write(
_pytest._code.Source(
textwrap.dedent(
"""\
def pytest_addoption(parser):
parser.addoption("--xyz", action="store_true")
"""
def pytest_addoption(parser):
parser.addoption("--xyz", action="store_true")
"""
)
)
testdir.makefile(ext=".log", result="") # Writes result.log
@@ -213,11 +212,11 @@ def test_conftest_existing_resultlog(testdir):
def test_conftest_existing_junitxml(testdir):
x = testdir.mkdir("tests")
x.join("conftest.py").write(
_pytest._code.Source(
textwrap.dedent(
"""\
def pytest_addoption(parser):
parser.addoption("--xyz", action="store_true")
"""
def pytest_addoption(parser):
parser.addoption("--xyz", action="store_true")
"""
)
)
testdir.makefile(ext=".xml", junit="") # Writes junit.xml
@@ -247,38 +246,38 @@ def test_fixture_dependency(testdir, monkeypatch):
sub = testdir.mkdir("sub")
sub.join("__init__.py").write("")
sub.join("conftest.py").write(
dedent(
textwrap.dedent(
"""\
import pytest
@pytest.fixture
def not_needed():
assert False, "Should not be called!"
@pytest.fixture
def foo():
assert False, "Should not be called!"
@pytest.fixture
def bar(foo):
return 'bar'
"""
import pytest
@pytest.fixture
def not_needed():
assert False, "Should not be called!"
@pytest.fixture
def foo():
assert False, "Should not be called!"
@pytest.fixture
def bar(foo):
return 'bar'
"""
)
)
subsub = sub.mkdir("subsub")
subsub.join("__init__.py").write("")
subsub.join("test_bar.py").write(
dedent(
textwrap.dedent(
"""\
import pytest
@pytest.fixture
def bar():
return 'sub bar'
def test_event_fixture(bar):
assert bar == 'sub bar'
"""
import pytest
@pytest.fixture
def bar():
return 'sub bar'
def test_event_fixture(bar):
assert bar == 'sub bar'
"""
)
)
result = testdir.runpytest("sub")
@@ -288,11 +287,11 @@ def test_fixture_dependency(testdir, monkeypatch):
def test_conftest_found_with_double_dash(testdir):
sub = testdir.mkdir("sub")
sub.join("conftest.py").write(
dedent(
textwrap.dedent(
"""\
def pytest_addoption(parser):
parser.addoption("--hello-world", action="store_true")
"""
def pytest_addoption(parser):
parser.addoption("--hello-world", action="store_true")
"""
)
)
p = sub.join("test_hello.py")
@@ -313,56 +312,54 @@ class TestConftestVisibility(object):
package = testdir.mkdir("package")
package.join("conftest.py").write(
dedent(
textwrap.dedent(
"""\
import pytest
@pytest.fixture
def fxtr():
return "from-package"
"""
import pytest
@pytest.fixture
def fxtr():
return "from-package"
"""
)
)
package.join("test_pkgroot.py").write(
dedent(
textwrap.dedent(
"""\
def test_pkgroot(fxtr):
assert fxtr == "from-package"
"""
def test_pkgroot(fxtr):
assert fxtr == "from-package"
"""
)
)
swc = package.mkdir("swc")
swc.join("__init__.py").ensure()
swc.join("conftest.py").write(
dedent(
textwrap.dedent(
"""\
import pytest
@pytest.fixture
def fxtr():
return "from-swc"
"""
import pytest
@pytest.fixture
def fxtr():
return "from-swc"
"""
)
)
swc.join("test_with_conftest.py").write(
dedent(
textwrap.dedent(
"""\
def test_with_conftest(fxtr):
assert fxtr == "from-swc"
"""
def test_with_conftest(fxtr):
assert fxtr == "from-swc"
"""
)
)
snc = package.mkdir("snc")
snc.join("__init__.py").ensure()
snc.join("test_no_conftest.py").write(
dedent(
textwrap.dedent(
"""\
def test_no_conftest(fxtr):
assert fxtr == "from-package" # No local conftest.py, so should
# use value from parent dir's
"""
def test_no_conftest(fxtr):
assert fxtr == "from-package" # No local conftest.py, so should
# use value from parent dir's
"""
)
)
print("created directory structure:")
@@ -422,31 +419,31 @@ def test_search_conftest_up_to_inifile(testdir, confcutdir, passed, error):
src = root.join("src").ensure(dir=1)
src.join("pytest.ini").write("[pytest]")
src.join("conftest.py").write(
_pytest._code.Source(
textwrap.dedent(
"""\
import pytest
@pytest.fixture
def fix1(): pass
"""
import pytest
@pytest.fixture
def fix1(): pass
"""
)
)
src.join("test_foo.py").write(
_pytest._code.Source(
textwrap.dedent(
"""\
def test_1(fix1):
pass
def test_2(out_of_reach):
pass
"""
def test_1(fix1):
pass
def test_2(out_of_reach):
pass
"""
)
)
root.join("conftest.py").write(
_pytest._code.Source(
textwrap.dedent(
"""\
import pytest
@pytest.fixture
def out_of_reach(): pass
"""
import pytest
@pytest.fixture
def out_of_reach(): pass
"""
)
)
@@ -464,19 +461,19 @@ def test_search_conftest_up_to_inifile(testdir, confcutdir, passed, error):
def test_issue1073_conftest_special_objects(testdir):
testdir.makeconftest(
"""
"""\
class DontTouchMe(object):
def __getattr__(self, x):
raise Exception('cant touch me')
x = DontTouchMe()
"""
"""
)
testdir.makepyfile(
"""
"""\
def test_some():
pass
"""
"""
)
res = testdir.runpytest()
assert res.ret == 0
@@ -484,15 +481,15 @@ def test_issue1073_conftest_special_objects(testdir):
def test_conftest_exception_handling(testdir):
testdir.makeconftest(
"""
"""\
raise ValueError()
"""
"""
)
testdir.makepyfile(
"""
"""\
def test_some():
pass
"""
"""
)
res = testdir.runpytest()
assert res.ret == 4
@@ -507,7 +504,7 @@ def test_hook_proxy(testdir):
**{
"root/demo-0/test_foo1.py": "def test1(): pass",
"root/demo-a/test_foo2.py": "def test1(): pass",
"root/demo-a/conftest.py": """
"root/demo-a/conftest.py": """\
def pytest_ignore_collect(path, config):
return True
""",
@@ -525,11 +522,11 @@ def test_required_option_help(testdir):
testdir.makeconftest("assert 0")
x = testdir.mkdir("x")
x.join("conftest.py").write(
_pytest._code.Source(
textwrap.dedent(
"""\
def pytest_addoption(parser):
parser.addoption("--xyz", action="store_true", required=True)
"""
def pytest_addoption(parser):
parser.addoption("--xyz", action="store_true", required=True)
"""
)
)
result = testdir.runpytest("-h", x)

View File

@@ -1,7 +1,7 @@
# encoding: utf-8
from __future__ import absolute_import, division, print_function
import sys
import _pytest._code
import textwrap
from _pytest.compat import MODULE_NOT_FOUND_ERROR
from _pytest.doctest import DoctestItem, DoctestModule, DoctestTextfile
import pytest
@@ -258,16 +258,16 @@ class TestDoctests(object):
def test_doctest_linedata_missing(self, testdir):
testdir.tmpdir.join("hello.py").write(
_pytest._code.Source(
textwrap.dedent(
"""\
class Fun(object):
@property
def test(self):
'''
>>> a = 1
>>> 1/0
'''
"""
class Fun(object):
@property
def test(self):
'''
>>> a = 1
>>> 1/0
'''
"""
)
)
result = testdir.runpytest("--doctest-modules")
@@ -300,10 +300,10 @@ class TestDoctests(object):
def test_doctest_unex_importerror_with_module(self, testdir):
testdir.tmpdir.join("hello.py").write(
_pytest._code.Source(
textwrap.dedent(
"""\
import asdalsdkjaslkdjasd
"""
import asdalsdkjaslkdjasd
"""
)
)
testdir.maketxtfile(
@@ -339,27 +339,27 @@ class TestDoctests(object):
def test_doctestmodule_external_and_issue116(self, testdir):
p = testdir.mkpydir("hello")
p.join("__init__.py").write(
_pytest._code.Source(
textwrap.dedent(
"""\
def somefunc():
'''
>>> i = 0
>>> i + 1
2
'''
"""
def somefunc():
'''
>>> i = 0
>>> i + 1
2
'''
"""
)
)
result = testdir.runpytest(p, "--doctest-modules")
result.stdout.fnmatch_lines(
[
"004 *>>> i = 0",
"005 *>>> i + 1",
"003 *>>> i = 0",
"004 *>>> i + 1",
"*Expected:",
"* 2",
"*Got:",
"* 1",
"*:5: DocTestFailure",
"*:4: DocTestFailure",
]
)

View File

@@ -7,7 +7,9 @@ def test_version(testdir, pytestconfig):
result = testdir.runpytest("--version")
assert result.ret == 0
# p = py.path.local(py.__file__).dirpath()
result.stderr.fnmatch_lines(["*pytest*%s*imported from*" % (pytest.__version__,)])
result.stderr.fnmatch_lines(
["*pytest*{}*imported from*".format(pytest.__version__)]
)
if pytestconfig.pluginmanager.list_plugin_distinfo():
result.stderr.fnmatch_lines(["*setuptools registered plugins:", "*at*"])

View File

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

View File

@@ -228,11 +228,15 @@ def test_syspath_prepend(mp):
def test_syspath_prepend_double_undo(mp):
mp.syspath_prepend("hello world")
mp.undo()
sys.path.append("more hello world")
mp.undo()
assert sys.path[-1] == "more hello world"
old_syspath = sys.path[:]
try:
mp.syspath_prepend("hello world")
mp.undo()
sys.path.append("more hello world")
mp.undo()
assert sys.path[-1] == "more hello world"
finally:
sys.path[:] = old_syspath
def test_chdir_with_path_local(mp, tmpdir):

View File

@@ -294,7 +294,7 @@ def test_argcomplete(testdir, monkeypatch):
script = str(testdir.tmpdir.join("test_argcomplete"))
pytest_bin = sys.argv[0]
if "pytest" not in os.path.basename(pytest_bin):
pytest.skip("need to be run with pytest executable, not %s" % (pytest_bin,))
pytest.skip("need to be run with pytest executable, not {}".format(pytest_bin))
with open(str(script), "w") as fp:
# redirect output from argcomplete to stdin and stderr is not trivial

View File

@@ -260,7 +260,9 @@ class TestPDB(object):
assert False
"""
)
child = testdir.spawn_pytest("--show-capture=%s --pdb %s" % (showcapture, p1))
child = testdir.spawn_pytest(
"--show-capture={} --pdb {}".format(showcapture, p1)
)
if showcapture in ("all", "log"):
child.expect("captured log")
child.expect("get rekt")
@@ -473,7 +475,7 @@ class TestPDB(object):
x = 5
"""
)
child = testdir.spawn("%s %s" % (sys.executable, p1))
child = testdir.spawn("{} {}".format(sys.executable, p1))
child.expect("x = 5")
child.sendeof()
self.flush(child)

View File

@@ -25,7 +25,6 @@ class TestPytestPluginInteractions(object):
)
conf = testdir.makeconftest(
"""
import sys ; sys.path.insert(0, '.')
import newhooks
def pytest_addhooks(pluginmanager):
pluginmanager.addhooks(newhooks)
@@ -263,8 +262,7 @@ class TestPytestPluginManager(object):
mod.pytest_plugins = "pytest_a"
aplugin = testdir.makepyfile(pytest_a="#")
reprec = testdir.make_hook_recorder(pytestpm)
# syspath.prepend(aplugin.dirpath())
sys.path.insert(0, str(aplugin.dirpath()))
testdir.syspathinsert(aplugin.dirpath())
pytestpm.consider_module(mod)
call = reprec.getcall(pytestpm.hook.pytest_plugin_registered.name)
assert call.plugin.__name__ == "pytest_a"

View File

@@ -8,7 +8,7 @@ import _pytest.pytester as pytester
from _pytest.pytester import HookRecorder
from _pytest.pytester import CwdSnapshot, SysModulesSnapshot, SysPathsSnapshot
from _pytest.config import PytestPluginManager
from _pytest.main import EXIT_OK, EXIT_TESTSFAILED
from _pytest.main import EXIT_OK, EXIT_TESTSFAILED, EXIT_NOTESTSCOLLECTED
def test_make_hook_recorder(testdir):
@@ -266,57 +266,6 @@ class TestInlineRunModulesCleanup(object):
assert imported.data == 42
def test_inline_run_clean_sys_paths(testdir):
def test_sys_path_change_cleanup(self, testdir):
test_path1 = testdir.tmpdir.join("boink1").strpath
test_path2 = testdir.tmpdir.join("boink2").strpath
test_path3 = testdir.tmpdir.join("boink3").strpath
sys.path.append(test_path1)
sys.meta_path.append(test_path1)
original_path = list(sys.path)
original_meta_path = list(sys.meta_path)
test_mod = testdir.makepyfile(
"""
import sys
sys.path.append({:test_path2})
sys.meta_path.append({:test_path2})
def test_foo():
sys.path.append({:test_path3})
sys.meta_path.append({:test_path3})""".format(
locals()
)
)
testdir.inline_run(str(test_mod))
assert sys.path == original_path
assert sys.meta_path == original_meta_path
def spy_factory(self):
class SysPathsSnapshotSpy(object):
instances = []
def __init__(self):
SysPathsSnapshotSpy.instances.append(self)
self._spy_restore_count = 0
self.__snapshot = SysPathsSnapshot()
def restore(self):
self._spy_restore_count += 1
return self.__snapshot.restore()
return SysPathsSnapshotSpy
def test_inline_run_taking_and_restoring_a_sys_paths_snapshot(
self, testdir, monkeypatch
):
spy_factory = self.spy_factory()
monkeypatch.setattr(pytester, "SysPathsSnapshot", spy_factory)
test_mod = testdir.makepyfile("def test_foo(): pass")
testdir.inline_run(str(test_mod))
assert len(spy_factory.instances) == 1
spy = spy_factory.instances[0]
assert spy._spy_restore_count == 1
def test_assert_outcomes_after_pytest_error(testdir):
testdir.makepyfile("def test_foo(): assert True")
@@ -447,3 +396,8 @@ class TestSysPathsSnapshot(object):
def test_testdir_subprocess(testdir):
testfile = testdir.makepyfile("def test_one(): pass")
assert testdir.runpytest_subprocess(testfile).ret == 0
def test_unicode_args(testdir):
result = testdir.runpytest("-k", u"💩")
assert result.ret == EXIT_NOTESTSCOLLECTED

View File

@@ -4,9 +4,9 @@ terminal reporting of the full testing process.
from __future__ import absolute_import, division, print_function
import collections
import sys
import textwrap
import pluggy
import _pytest._code
import py
import pytest
from _pytest.main import EXIT_NOTESTSCOLLECTED
@@ -161,12 +161,12 @@ class TestTerminal(object):
def test_itemreport_directclasses_not_shown_as_subclasses(self, testdir):
a = testdir.mkpydir("a123")
a.join("test_hello123.py").write(
_pytest._code.Source(
textwrap.dedent(
"""\
class TestClass(object):
def test_method(self):
pass
"""
class TestClass(object):
def test_method(self):
pass
"""
)
)
result = testdir.runpytest("-v")
@@ -312,13 +312,13 @@ class TestCollectonly(object):
result = testdir.runpytest("--collect-only", p)
assert result.ret == 2
result.stdout.fnmatch_lines(
_pytest._code.Source(
textwrap.dedent(
"""\
*ERROR*
*ImportError*
*No module named *Errlk*
*1 error*
"""
*ERROR*
*ImportError*
*No module named *Errlk*
*1 error*
"""
).strip()
)
@@ -948,6 +948,46 @@ def pytest_report_header(config, startdir):
assert "!This is stderr!" not in stdout
assert "!This is a warning log msg!" not in stdout
def test_show_capture_with_teardown_logs(self, testdir):
"""Ensure that the capturing of teardown logs honor --show-capture setting"""
testdir.makepyfile(
"""
import logging
import sys
import pytest
@pytest.fixture(scope="function", autouse="True")
def hook_each_test(request):
yield
sys.stdout.write("!stdout!")
sys.stderr.write("!stderr!")
logging.warning("!log!")
def test_func():
assert False
"""
)
result = testdir.runpytest("--show-capture=stdout", "--tb=short").stdout.str()
assert "!stdout!" in result
assert "!stderr!" not in result
assert "!log!" not in result
result = testdir.runpytest("--show-capture=stderr", "--tb=short").stdout.str()
assert "!stdout!" not in result
assert "!stderr!" in result
assert "!log!" not in result
result = testdir.runpytest("--show-capture=log", "--tb=short").stdout.str()
assert "!stdout!" not in result
assert "!stderr!" not in result
assert "!log!" in result
result = testdir.runpytest("--show-capture=no", "--tb=short").stdout.str()
assert "!stdout!" not in result
assert "!stderr!" not in result
assert "!log!" not in result
@pytest.mark.xfail("not hasattr(os, 'dup')")
def test_fdopen_kept_alive_issue124(testdir):
@@ -1078,9 +1118,9 @@ def test_terminal_summary_warnings_are_displayed(testdir):
)
def test_summary_stats(exp_line, exp_color, stats_arg):
print("Based on stats: %s" % stats_arg)
print('Expect summary: "%s"; with color "%s"' % (exp_line, exp_color))
print('Expect summary: "{}"; with color "{}"'.format(exp_line, exp_color))
(line, color) = build_summary_stats_line(stats_arg)
print('Actually got: "%s"; with color "%s"' % (line, color))
print('Actually got: "{}"; with color "{}"'.format(line, color))
assert line == exp_line
assert color == exp_color