2013-10-12 21:39:22 +08:00
|
|
|
import os
|
2019-04-06 15:55:56 +08:00
|
|
|
import subprocess
|
2017-12-09 04:04:52 +08:00
|
|
|
import sys
|
2018-10-05 10:11:02 +08:00
|
|
|
import time
|
2020-12-16 12:16:05 +08:00
|
|
|
from pathlib import Path
|
|
|
|
from types import ModuleType
|
2019-12-03 20:25:28 +08:00
|
|
|
from typing import List
|
2018-10-25 15:01:29 +08:00
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
import _pytest.pytester as pytester_mod
|
2018-10-25 15:01:29 +08:00
|
|
|
import pytest
|
2020-02-11 05:43:30 +08:00
|
|
|
from _pytest.config import ExitCode
|
2015-04-22 19:31:46 +08:00
|
|
|
from _pytest.config import PytestPluginManager
|
2020-12-16 12:16:05 +08:00
|
|
|
from _pytest.monkeypatch import MonkeyPatch
|
2018-10-25 15:01:29 +08:00
|
|
|
from _pytest.pytester import CwdSnapshot
|
|
|
|
from _pytest.pytester import HookRecorder
|
2019-03-15 11:14:07 +08:00
|
|
|
from _pytest.pytester import LineMatcher
|
2020-10-25 08:03:20 +08:00
|
|
|
from _pytest.pytester import Pytester
|
2018-10-25 15:01:29 +08:00
|
|
|
from _pytest.pytester import SysModulesSnapshot
|
|
|
|
from _pytest.pytester import SysPathsSnapshot
|
2021-01-04 21:58:11 +08:00
|
|
|
from _pytest.pytester import Testdir
|
2015-04-21 10:18:04 +08:00
|
|
|
|
2009-09-06 22:59:39 +08:00
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_make_hook_recorder(pytester: Pytester) -> None:
|
|
|
|
item = pytester.getitem("def test_func(): pass")
|
|
|
|
recorder = pytester.make_hook_recorder(item.config.pluginmanager)
|
2009-12-29 19:36:17 +08:00
|
|
|
assert not recorder.getfailures()
|
2010-09-15 16:30:50 +08:00
|
|
|
|
2020-08-04 00:15:21 +08:00
|
|
|
# (The silly condition is to fool mypy that the code below this is reachable)
|
|
|
|
if 1 + 1 == 2:
|
|
|
|
pytest.xfail("internal reportrecorder tests need refactoring")
|
2016-11-21 04:59:15 +08:00
|
|
|
|
2019-06-03 06:32:00 +08:00
|
|
|
class rep:
|
2009-09-06 22:59:39 +08:00
|
|
|
excinfo = None
|
|
|
|
passed = False
|
2010-07-27 03:15:15 +08:00
|
|
|
failed = True
|
2009-09-06 22:59:39 +08:00
|
|
|
skipped = False
|
2010-07-27 03:15:15 +08:00
|
|
|
when = "call"
|
2009-09-06 22:59:39 +08:00
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
recorder.hook.pytest_runtest_logreport(report=rep) # type: ignore[attr-defined]
|
2009-09-06 22:59:39 +08:00
|
|
|
failures = recorder.getfailures()
|
2020-12-16 12:16:05 +08:00
|
|
|
assert failures == [rep] # type: ignore[comparison-overlap]
|
2009-09-06 22:59:39 +08:00
|
|
|
failures = recorder.getfailures()
|
2020-12-16 12:16:05 +08:00
|
|
|
assert failures == [rep] # type: ignore[comparison-overlap]
|
2009-09-06 22:59:39 +08:00
|
|
|
|
2019-12-03 20:25:28 +08:00
|
|
|
class rep2:
|
2009-09-06 22:59:39 +08:00
|
|
|
excinfo = None
|
|
|
|
passed = False
|
|
|
|
failed = False
|
|
|
|
skipped = True
|
2010-07-27 03:15:15 +08:00
|
|
|
when = "call"
|
2018-05-23 22:48:46 +08:00
|
|
|
|
2019-12-03 20:25:28 +08:00
|
|
|
rep2.passed = False
|
|
|
|
rep2.skipped = True
|
2020-12-16 12:16:05 +08:00
|
|
|
recorder.hook.pytest_runtest_logreport(report=rep2) # type: ignore[attr-defined]
|
2009-09-06 22:59:39 +08:00
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
modcol = pytester.getmodulecol("")
|
2019-12-03 20:25:28 +08:00
|
|
|
rep3 = modcol.config.hook.pytest_make_collect_report(collector=modcol)
|
|
|
|
rep3.passed = False
|
|
|
|
rep3.failed = True
|
|
|
|
rep3.skipped = False
|
2020-12-16 12:16:05 +08:00
|
|
|
recorder.hook.pytest_collectreport(report=rep3) # type: ignore[attr-defined]
|
2009-09-06 22:59:39 +08:00
|
|
|
|
|
|
|
passed, skipped, failed = recorder.listoutcomes()
|
|
|
|
assert not passed and skipped and failed
|
|
|
|
|
|
|
|
numpassed, numskipped, numfailed = recorder.countoutcomes()
|
|
|
|
assert numpassed == 0
|
|
|
|
assert numskipped == 1
|
|
|
|
assert numfailed == 1
|
|
|
|
assert len(recorder.getfailedcollections()) == 1
|
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
recorder.unregister() # type: ignore[attr-defined]
|
2010-07-27 03:15:15 +08:00
|
|
|
recorder.clear()
|
2020-12-16 12:16:05 +08:00
|
|
|
recorder.hook.pytest_runtest_logreport(report=rep3) # type: ignore[attr-defined]
|
2018-11-23 02:05:10 +08:00
|
|
|
pytest.raises(ValueError, recorder.getfailures)
|
2009-09-06 22:59:39 +08:00
|
|
|
|
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_parseconfig(pytester: Pytester) -> None:
|
|
|
|
config1 = pytester.parseconfig()
|
|
|
|
config2 = pytester.parseconfig()
|
2019-06-30 23:24:51 +08:00
|
|
|
assert config2 is not config1
|
2009-09-06 22:59:39 +08:00
|
|
|
|
2017-07-17 07:25:09 +08:00
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_pytester_runs_with_plugin(pytester: Pytester) -> None:
|
|
|
|
pytester.makepyfile(
|
2018-05-23 22:48:46 +08:00
|
|
|
"""
|
2015-04-22 19:44:37 +08:00
|
|
|
pytest_plugins = "pytester"
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_hello(pytester):
|
2009-09-06 22:59:39 +08:00
|
|
|
assert 1
|
2018-05-23 22:48:46 +08:00
|
|
|
"""
|
|
|
|
)
|
2020-12-16 12:16:05 +08:00
|
|
|
result = pytester.runpytest()
|
2015-04-28 17:54:53 +08:00
|
|
|
result.assert_outcomes(passed=1)
|
2009-09-06 22:59:39 +08:00
|
|
|
|
2014-10-01 18:20:11 +08:00
|
|
|
|
2020-12-19 04:36:20 +08:00
|
|
|
def test_pytester_with_doctest(pytester: Pytester) -> None:
|
2020-12-16 12:16:05 +08:00
|
|
|
"""Check that pytester can be used within doctests.
|
2020-03-04 12:33:50 +08:00
|
|
|
|
|
|
|
It used to use `request.function`, which is `None` with doctests."""
|
2020-12-16 12:16:05 +08:00
|
|
|
pytester.makepyfile(
|
2020-03-04 12:33:50 +08:00
|
|
|
**{
|
|
|
|
"sub/t-doctest.py": """
|
|
|
|
'''
|
|
|
|
>>> import os
|
2020-12-16 12:16:05 +08:00
|
|
|
>>> pytester = getfixture("pytester")
|
|
|
|
>>> str(pytester.makepyfile("content")).replace(os.sep, '/')
|
2020-03-04 12:33:50 +08:00
|
|
|
'.../basetemp/sub.t-doctest0/sub.py'
|
|
|
|
'''
|
|
|
|
""",
|
|
|
|
"sub/__init__.py": "",
|
|
|
|
}
|
|
|
|
)
|
2020-12-16 12:16:05 +08:00
|
|
|
result = pytester.runpytest(
|
2020-03-04 12:33:50 +08:00
|
|
|
"-p", "pytester", "--doctest-modules", "sub/t-doctest.py"
|
|
|
|
)
|
|
|
|
assert result.ret == 0
|
|
|
|
|
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_runresult_assertion_on_xfail(pytester: Pytester) -> None:
|
|
|
|
pytester.makepyfile(
|
2018-08-20 14:10:44 +08:00
|
|
|
"""
|
|
|
|
import pytest
|
|
|
|
|
|
|
|
pytest_plugins = "pytester"
|
|
|
|
|
|
|
|
@pytest.mark.xfail
|
|
|
|
def test_potato():
|
|
|
|
assert False
|
|
|
|
"""
|
|
|
|
)
|
2020-12-16 12:16:05 +08:00
|
|
|
result = pytester.runpytest()
|
2018-08-20 14:10:44 +08:00
|
|
|
result.assert_outcomes(xfailed=1)
|
|
|
|
assert result.ret == 0
|
|
|
|
|
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_runresult_assertion_on_xpassed(pytester: Pytester) -> None:
|
|
|
|
pytester.makepyfile(
|
2018-08-20 14:10:44 +08:00
|
|
|
"""
|
|
|
|
import pytest
|
|
|
|
|
|
|
|
pytest_plugins = "pytester"
|
|
|
|
|
|
|
|
@pytest.mark.xfail
|
|
|
|
def test_potato():
|
|
|
|
assert True
|
|
|
|
"""
|
|
|
|
)
|
2020-12-16 12:16:05 +08:00
|
|
|
result = pytester.runpytest()
|
2018-08-20 14:10:44 +08:00
|
|
|
result.assert_outcomes(xpassed=1)
|
|
|
|
assert result.ret == 0
|
|
|
|
|
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_xpassed_with_strict_is_considered_a_failure(pytester: Pytester) -> None:
|
|
|
|
pytester.makepyfile(
|
2018-08-20 14:10:44 +08:00
|
|
|
"""
|
|
|
|
import pytest
|
|
|
|
|
|
|
|
pytest_plugins = "pytester"
|
|
|
|
|
|
|
|
@pytest.mark.xfail(strict=True)
|
|
|
|
def test_potato():
|
|
|
|
assert True
|
|
|
|
"""
|
|
|
|
)
|
2020-12-16 12:16:05 +08:00
|
|
|
result = pytester.runpytest()
|
2018-08-20 14:10:44 +08:00
|
|
|
result.assert_outcomes(failed=1)
|
|
|
|
assert result.ret != 0
|
|
|
|
|
|
|
|
|
2014-10-01 18:20:11 +08:00
|
|
|
def make_holder():
|
2019-06-03 06:32:00 +08:00
|
|
|
class apiclass:
|
2010-10-12 19:10:39 +08:00
|
|
|
def pytest_xyz(self, arg):
|
2020-07-18 17:35:13 +08:00
|
|
|
"""X"""
|
2017-07-17 07:25:09 +08:00
|
|
|
|
2014-10-01 18:20:11 +08:00
|
|
|
def pytest_xyz_noarg(self):
|
2020-07-18 17:35:13 +08:00
|
|
|
"""X"""
|
2010-10-12 19:10:39 +08:00
|
|
|
|
2018-05-23 22:48:46 +08:00
|
|
|
apimod = type(os)("api")
|
2016-11-21 04:59:15 +08:00
|
|
|
|
2014-10-01 18:20:11 +08:00
|
|
|
def pytest_xyz(arg):
|
2020-07-18 17:35:13 +08:00
|
|
|
"""X"""
|
2016-11-21 04:59:15 +08:00
|
|
|
|
2014-10-01 18:20:11 +08:00
|
|
|
def pytest_xyz_noarg():
|
2020-07-18 17:35:13 +08:00
|
|
|
"""X"""
|
2016-11-21 04:59:15 +08:00
|
|
|
|
2019-12-03 20:25:28 +08:00
|
|
|
apimod.pytest_xyz = pytest_xyz # type: ignore
|
|
|
|
apimod.pytest_xyz_noarg = pytest_xyz_noarg # type: ignore
|
2014-10-01 18:20:11 +08:00
|
|
|
return apiclass, apimod
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.parametrize("holder", make_holder())
|
2019-12-03 20:25:28 +08:00
|
|
|
def test_hookrecorder_basic(holder) -> None:
|
2015-04-22 19:31:46 +08:00
|
|
|
pm = PytestPluginManager()
|
2018-12-12 06:02:36 +08:00
|
|
|
pm.add_hookspecs(holder)
|
2014-10-01 18:20:11 +08:00
|
|
|
rec = HookRecorder(pm)
|
2014-10-04 21:49:31 +08:00
|
|
|
pm.hook.pytest_xyz(arg=123)
|
2010-10-12 19:10:39 +08:00
|
|
|
call = rec.popcall("pytest_xyz")
|
2014-10-01 18:20:11 +08:00
|
|
|
assert call.arg == 123
|
2010-10-12 19:10:39 +08:00
|
|
|
assert call._name == "pytest_xyz"
|
Use a hack to make typing of pytest.fail.Exception & co work
Mypy currently is unable to handle assigning attributes on function:
https://github.com/python/mypy/issues/2087.
pytest uses this for the outcome exceptions -- `pytest.fail.Exception`,
`pytest.exit.Exception` etc, and this is the canonical name by which they
are referred.
Initially we started working around this with type: ignores, and later
by switching e.g. `pytest.fail.Exception` with the direct exception
`Failed`. But this causes a lot of churn and is not as nice. And I also
found that some code relies on it, in skipping.py:
def pytest_configure(config):
if config.option.runxfail:
# yay a hack
import pytest
old = pytest.xfail
config._cleanup.append(lambda: setattr(pytest, "xfail", old))
def nop(*args, **kwargs):
pass
nop.Exception = xfail.Exception
setattr(pytest, "xfail", nop)
...
So it seems better to support it. Use a hack to make it work. The rest
of the commit rolls back all of the workarounds we added up to now.
`pytest.raises.Exception` also exists, but it's not used much so I kept
it as-is for now.
Hopefully in the future mypy supports this and this ugliness can be
removed.
2020-02-17 03:46:11 +08:00
|
|
|
pytest.raises(pytest.fail.Exception, rec.popcall, "abc")
|
2014-10-04 21:49:31 +08:00
|
|
|
pm.hook.pytest_xyz_noarg()
|
2014-10-01 18:20:11 +08:00
|
|
|
call = rec.popcall("pytest_xyz_noarg")
|
|
|
|
assert call._name == "pytest_xyz_noarg"
|
|
|
|
|
2010-10-12 19:10:39 +08:00
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_makepyfile_unicode(pytester: Pytester) -> None:
|
|
|
|
pytester.makepyfile(chr(0xFFFD))
|
2012-09-03 16:12:30 +08:00
|
|
|
|
2017-07-17 07:25:09 +08:00
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_makepyfile_utf8(pytester: Pytester) -> None:
|
2017-09-01 04:40:05 +08:00
|
|
|
"""Ensure makepyfile accepts utf-8 bytes as input (#2738)"""
|
2019-06-03 06:32:00 +08:00
|
|
|
utf8_contents = """
|
2017-09-01 04:40:05 +08:00
|
|
|
def setup_function(function):
|
2019-06-05 08:48:06 +08:00
|
|
|
mixed_encoding = 'São Paulo'
|
|
|
|
""".encode()
|
2020-12-16 12:16:05 +08:00
|
|
|
p = pytester.makepyfile(utf8_contents)
|
|
|
|
assert "mixed_encoding = 'São Paulo'".encode() in p.read_bytes()
|
2017-09-01 04:40:05 +08:00
|
|
|
|
|
|
|
|
2019-06-03 06:32:00 +08:00
|
|
|
class TestInlineRunModulesCleanup:
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_inline_run_test_module_not_cleaned_up(self, pytester: Pytester) -> None:
|
|
|
|
test_mod = pytester.makepyfile("def test_foo(): assert True")
|
|
|
|
result = pytester.inline_run(str(test_mod))
|
2019-06-07 18:58:51 +08:00
|
|
|
assert result.ret == ExitCode.OK
|
2017-12-09 04:04:52 +08:00
|
|
|
# rewrite module, now test should fail if module was re-imported
|
2020-12-16 12:16:05 +08:00
|
|
|
test_mod.write_text("def test_foo(): assert False")
|
|
|
|
result2 = pytester.inline_run(str(test_mod))
|
2019-06-07 18:58:51 +08:00
|
|
|
assert result2.ret == ExitCode.TESTS_FAILED
|
2017-12-09 04:04:52 +08:00
|
|
|
|
|
|
|
def spy_factory(self):
|
2019-06-03 06:32:00 +08:00
|
|
|
class SysModulesSnapshotSpy:
|
2020-10-06 09:13:05 +08:00
|
|
|
instances: List["SysModulesSnapshotSpy"] = [] # noqa: F821
|
2017-12-09 04:04:52 +08:00
|
|
|
|
2019-12-03 20:25:28 +08:00
|
|
|
def __init__(self, preserve=None) -> None:
|
2017-12-09 04:04:52 +08:00
|
|
|
SysModulesSnapshotSpy.instances.append(self)
|
|
|
|
self._spy_restore_count = 0
|
|
|
|
self._spy_preserve = preserve
|
|
|
|
self.__snapshot = SysModulesSnapshot(preserve=preserve)
|
|
|
|
|
|
|
|
def restore(self):
|
|
|
|
self._spy_restore_count += 1
|
|
|
|
return self.__snapshot.restore()
|
2018-05-23 22:48:46 +08:00
|
|
|
|
2017-12-09 04:04:52 +08:00
|
|
|
return SysModulesSnapshotSpy
|
|
|
|
|
|
|
|
def test_inline_run_taking_and_restoring_a_sys_modules_snapshot(
|
2020-12-16 12:16:05 +08:00
|
|
|
self, pytester: Pytester, monkeypatch: MonkeyPatch
|
2019-12-03 20:25:28 +08:00
|
|
|
) -> None:
|
2017-12-09 04:04:52 +08:00
|
|
|
spy_factory = self.spy_factory()
|
2020-12-16 12:16:05 +08:00
|
|
|
monkeypatch.setattr(pytester_mod, "SysModulesSnapshot", spy_factory)
|
|
|
|
pytester.syspathinsert()
|
2019-07-21 02:17:30 +08:00
|
|
|
original = dict(sys.modules)
|
2020-12-16 12:16:05 +08:00
|
|
|
pytester.makepyfile(import1="# you son of a silly person")
|
|
|
|
pytester.makepyfile(import2="# my hovercraft is full of eels")
|
|
|
|
test_mod = pytester.makepyfile(
|
2018-05-23 22:48:46 +08:00
|
|
|
"""
|
2017-12-09 04:04:52 +08:00
|
|
|
import import1
|
2018-05-23 22:48:46 +08:00
|
|
|
def test_foo(): import import2"""
|
|
|
|
)
|
2020-12-16 12:16:05 +08:00
|
|
|
pytester.inline_run(str(test_mod))
|
2017-12-09 04:04:52 +08:00
|
|
|
assert len(spy_factory.instances) == 1
|
|
|
|
spy = spy_factory.instances[0]
|
|
|
|
assert spy._spy_restore_count == 1
|
|
|
|
assert sys.modules == original
|
|
|
|
assert all(sys.modules[x] is original[x] for x in sys.modules)
|
|
|
|
|
|
|
|
def test_inline_run_sys_modules_snapshot_restore_preserving_modules(
|
2020-12-16 12:16:05 +08:00
|
|
|
self, pytester: Pytester, monkeypatch: MonkeyPatch
|
2019-12-03 20:25:28 +08:00
|
|
|
) -> None:
|
2017-12-09 04:04:52 +08:00
|
|
|
spy_factory = self.spy_factory()
|
2020-12-16 12:16:05 +08:00
|
|
|
monkeypatch.setattr(pytester_mod, "SysModulesSnapshot", spy_factory)
|
|
|
|
test_mod = pytester.makepyfile("def test_foo(): pass")
|
|
|
|
pytester.inline_run(str(test_mod))
|
2017-12-09 04:04:52 +08:00
|
|
|
spy = spy_factory.instances[0]
|
|
|
|
assert not spy._spy_preserve("black_knight")
|
|
|
|
assert spy._spy_preserve("zope")
|
|
|
|
assert spy._spy_preserve("zope.interface")
|
|
|
|
assert spy._spy_preserve("zopelicious")
|
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_external_test_module_imports_not_cleaned_up(
|
|
|
|
self, pytester: Pytester
|
|
|
|
) -> None:
|
|
|
|
pytester.syspathinsert()
|
|
|
|
pytester.makepyfile(imported="data = 'you son of a silly person'")
|
2017-12-09 04:04:52 +08:00
|
|
|
import imported
|
2018-05-23 22:48:46 +08:00
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
test_mod = pytester.makepyfile(
|
2018-05-23 22:48:46 +08:00
|
|
|
"""
|
2017-12-09 04:04:52 +08:00
|
|
|
def test_foo():
|
|
|
|
import imported
|
2018-05-23 22:48:46 +08:00
|
|
|
imported.data = 42"""
|
|
|
|
)
|
2020-12-16 12:16:05 +08:00
|
|
|
pytester.inline_run(str(test_mod))
|
2017-12-09 04:04:52 +08:00
|
|
|
assert imported.data == 42
|
|
|
|
|
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_assert_outcomes_after_pytest_error(pytester: Pytester) -> None:
|
|
|
|
pytester.makepyfile("def test_foo(): assert True")
|
2017-01-11 22:49:09 +08:00
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
result = pytester.runpytest("--unexpected-argument")
|
2019-08-10 20:14:57 +08:00
|
|
|
with pytest.raises(ValueError, match="Pytest terminal summary report not found"):
|
2017-01-11 22:49:09 +08:00
|
|
|
result.assert_outcomes(passed=0)
|
2017-12-09 04:04:52 +08:00
|
|
|
|
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_cwd_snapshot(pytester: Pytester) -> None:
|
|
|
|
foo = pytester.mkdir("foo")
|
|
|
|
bar = pytester.mkdir("bar")
|
|
|
|
os.chdir(foo)
|
2017-12-09 04:04:52 +08:00
|
|
|
snapshot = CwdSnapshot()
|
2020-12-16 12:16:05 +08:00
|
|
|
os.chdir(bar)
|
|
|
|
assert Path().absolute() == bar
|
2017-12-09 04:04:52 +08:00
|
|
|
snapshot.restore()
|
2020-12-16 12:16:05 +08:00
|
|
|
assert Path().absolute() == foo
|
2017-12-09 04:04:52 +08:00
|
|
|
|
|
|
|
|
2019-06-03 06:32:00 +08:00
|
|
|
class TestSysModulesSnapshot:
|
2018-05-23 22:48:46 +08:00
|
|
|
key = "my-test-module"
|
2017-12-09 04:04:52 +08:00
|
|
|
|
2019-12-03 20:25:28 +08:00
|
|
|
def test_remove_added(self) -> None:
|
2017-12-09 04:04:52 +08:00
|
|
|
original = dict(sys.modules)
|
|
|
|
assert self.key not in sys.modules
|
|
|
|
snapshot = SysModulesSnapshot()
|
2020-12-19 04:36:20 +08:00
|
|
|
sys.modules[self.key] = ModuleType("something")
|
2017-12-09 04:04:52 +08:00
|
|
|
assert self.key in sys.modules
|
|
|
|
snapshot.restore()
|
|
|
|
assert sys.modules == original
|
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_add_removed(self, monkeypatch: MonkeyPatch) -> None:
|
2017-12-09 04:04:52 +08:00
|
|
|
assert self.key not in sys.modules
|
2020-12-19 04:36:20 +08:00
|
|
|
monkeypatch.setitem(sys.modules, self.key, ModuleType("something"))
|
2017-12-09 04:04:52 +08:00
|
|
|
assert self.key in sys.modules
|
|
|
|
original = dict(sys.modules)
|
|
|
|
snapshot = SysModulesSnapshot()
|
|
|
|
del sys.modules[self.key]
|
|
|
|
assert self.key not in sys.modules
|
|
|
|
snapshot.restore()
|
|
|
|
assert sys.modules == original
|
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_restore_reloaded(self, monkeypatch: MonkeyPatch) -> None:
|
2017-12-09 04:04:52 +08:00
|
|
|
assert self.key not in sys.modules
|
2020-12-19 04:36:20 +08:00
|
|
|
monkeypatch.setitem(sys.modules, self.key, ModuleType("something"))
|
2017-12-09 04:04:52 +08:00
|
|
|
assert self.key in sys.modules
|
|
|
|
original = dict(sys.modules)
|
|
|
|
snapshot = SysModulesSnapshot()
|
2020-12-19 04:36:20 +08:00
|
|
|
sys.modules[self.key] = ModuleType("something else")
|
2017-12-09 04:04:52 +08:00
|
|
|
snapshot.restore()
|
|
|
|
assert sys.modules == original
|
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_preserve_modules(self, monkeypatch: MonkeyPatch) -> None:
|
2017-12-09 04:04:52 +08:00
|
|
|
key = [self.key + str(i) for i in range(3)]
|
|
|
|
assert not any(k in sys.modules for k in key)
|
|
|
|
for i, k in enumerate(key):
|
2020-12-16 12:16:05 +08:00
|
|
|
mod = ModuleType("something" + str(i))
|
|
|
|
monkeypatch.setitem(sys.modules, k, mod)
|
2017-12-09 04:04:52 +08:00
|
|
|
original = dict(sys.modules)
|
|
|
|
|
|
|
|
def preserve(name):
|
2018-05-23 22:48:46 +08:00
|
|
|
return name in (key[0], key[1], "some-other-key")
|
2017-12-09 04:04:52 +08:00
|
|
|
|
|
|
|
snapshot = SysModulesSnapshot(preserve=preserve)
|
2020-12-19 04:36:20 +08:00
|
|
|
sys.modules[key[0]] = original[key[0]] = ModuleType("something else0")
|
|
|
|
sys.modules[key[1]] = original[key[1]] = ModuleType("something else1")
|
|
|
|
sys.modules[key[2]] = ModuleType("something else2")
|
2017-12-09 04:04:52 +08:00
|
|
|
snapshot.restore()
|
|
|
|
assert sys.modules == original
|
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_preserve_container(self, monkeypatch: MonkeyPatch) -> None:
|
2017-12-09 04:04:52 +08:00
|
|
|
original = dict(sys.modules)
|
|
|
|
assert self.key not in original
|
|
|
|
replacement = dict(sys.modules)
|
2020-12-19 04:36:20 +08:00
|
|
|
replacement[self.key] = ModuleType("life of brian")
|
2017-12-09 04:04:52 +08:00
|
|
|
snapshot = SysModulesSnapshot()
|
2018-05-23 22:48:46 +08:00
|
|
|
monkeypatch.setattr(sys, "modules", replacement)
|
2017-12-09 04:04:52 +08:00
|
|
|
snapshot.restore()
|
|
|
|
assert sys.modules is replacement
|
|
|
|
assert sys.modules == original
|
|
|
|
|
|
|
|
|
2018-05-23 22:48:46 +08:00
|
|
|
@pytest.mark.parametrize("path_type", ("path", "meta_path"))
|
2019-06-03 06:32:00 +08:00
|
|
|
class TestSysPathsSnapshot:
|
2018-05-23 22:48:46 +08:00
|
|
|
other_path = {"path": "meta_path", "meta_path": "path"}
|
2017-12-09 04:04:52 +08:00
|
|
|
|
|
|
|
@staticmethod
|
2019-12-03 20:25:28 +08:00
|
|
|
def path(n: int) -> str:
|
2018-05-23 22:48:46 +08:00
|
|
|
return "my-dirty-little-secret-" + str(n)
|
2017-12-09 04:04:52 +08:00
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_restore(self, monkeypatch: MonkeyPatch, path_type) -> None:
|
2017-12-09 04:04:52 +08:00
|
|
|
other_path_type = self.other_path[path_type]
|
|
|
|
for i in range(10):
|
|
|
|
assert self.path(i) not in getattr(sys, path_type)
|
|
|
|
sys_path = [self.path(i) for i in range(6)]
|
|
|
|
monkeypatch.setattr(sys, path_type, sys_path)
|
|
|
|
original = list(sys_path)
|
|
|
|
original_other = list(getattr(sys, other_path_type))
|
|
|
|
snapshot = SysPathsSnapshot()
|
2018-07-09 07:57:18 +08:00
|
|
|
transformation = {"source": (0, 1, 2, 3, 4, 5), "target": (6, 2, 9, 7, 5, 8)}
|
2018-05-23 22:48:46 +08:00
|
|
|
assert sys_path == [self.path(x) for x in transformation["source"]]
|
2017-12-09 04:04:52 +08:00
|
|
|
sys_path[1] = self.path(6)
|
|
|
|
sys_path[3] = self.path(7)
|
|
|
|
sys_path.append(self.path(8))
|
|
|
|
del sys_path[4]
|
|
|
|
sys_path[3:3] = [self.path(9)]
|
|
|
|
del sys_path[0]
|
2018-05-23 22:48:46 +08:00
|
|
|
assert sys_path == [self.path(x) for x in transformation["target"]]
|
2017-12-09 04:04:52 +08:00
|
|
|
snapshot.restore()
|
|
|
|
assert getattr(sys, path_type) is sys_path
|
|
|
|
assert getattr(sys, path_type) == original
|
|
|
|
assert getattr(sys, other_path_type) == original_other
|
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_preserve_container(self, monkeypatch: MonkeyPatch, path_type) -> None:
|
2017-12-09 04:04:52 +08:00
|
|
|
other_path_type = self.other_path[path_type]
|
|
|
|
original_data = list(getattr(sys, path_type))
|
|
|
|
original_other = getattr(sys, other_path_type)
|
|
|
|
original_other_data = list(original_other)
|
2020-10-06 09:13:05 +08:00
|
|
|
new: List[object] = []
|
2017-12-09 04:04:52 +08:00
|
|
|
snapshot = SysPathsSnapshot()
|
|
|
|
monkeypatch.setattr(sys, path_type, new)
|
|
|
|
snapshot.restore()
|
|
|
|
assert getattr(sys, path_type) is new
|
|
|
|
assert getattr(sys, path_type) == original_data
|
|
|
|
assert getattr(sys, other_path_type) is original_other
|
|
|
|
assert getattr(sys, other_path_type) == original_other_data
|
2018-07-08 08:18:44 +08:00
|
|
|
|
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_pytester_subprocess(pytester: Pytester) -> None:
|
|
|
|
testfile = pytester.makepyfile("def test_one(): pass")
|
|
|
|
assert pytester.runpytest_subprocess(testfile).ret == 0
|
2018-08-23 00:00:51 +08:00
|
|
|
|
2018-08-23 00:27:36 +08:00
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_pytester_subprocess_via_runpytest_arg(pytester: Pytester) -> None:
|
|
|
|
testfile = pytester.makepyfile(
|
2019-10-22 06:05:02 +08:00
|
|
|
"""
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_pytester_subprocess(pytester):
|
2019-10-22 06:05:02 +08:00
|
|
|
import os
|
2020-12-16 12:16:05 +08:00
|
|
|
testfile = pytester.makepyfile(
|
2019-10-22 06:05:02 +08:00
|
|
|
\"""
|
|
|
|
import os
|
|
|
|
def test_one():
|
|
|
|
assert {} != os.getpid()
|
|
|
|
\""".format(os.getpid())
|
|
|
|
)
|
2020-12-16 12:16:05 +08:00
|
|
|
assert pytester.runpytest(testfile).ret == 0
|
2019-10-22 06:05:02 +08:00
|
|
|
"""
|
|
|
|
)
|
2020-12-19 04:36:20 +08:00
|
|
|
result = pytester.runpytest_inprocess(
|
|
|
|
"-p", "pytester", "--runpytest", "subprocess", testfile
|
|
|
|
)
|
2019-10-22 06:05:02 +08:00
|
|
|
assert result.ret == 0
|
|
|
|
|
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_unicode_args(pytester: Pytester) -> None:
|
|
|
|
result = pytester.runpytest("-k", "אבג")
|
2019-06-07 18:58:51 +08:00
|
|
|
assert result.ret == ExitCode.NO_TESTS_COLLECTED
|
2018-10-04 11:50:42 +08:00
|
|
|
|
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_pytester_run_no_timeout(pytester: Pytester) -> None:
|
|
|
|
testfile = pytester.makepyfile("def test_no_timeout(): pass")
|
|
|
|
assert pytester.runpytest_subprocess(testfile).ret == ExitCode.OK
|
2018-10-04 11:50:42 +08:00
|
|
|
|
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_pytester_run_with_timeout(pytester: Pytester) -> None:
|
|
|
|
testfile = pytester.makepyfile("def test_no_timeout(): pass")
|
2018-10-05 10:11:02 +08:00
|
|
|
|
2018-10-09 03:54:14 +08:00
|
|
|
timeout = 120
|
|
|
|
|
2018-10-05 10:11:02 +08:00
|
|
|
start = time.time()
|
2020-12-16 12:16:05 +08:00
|
|
|
result = pytester.runpytest_subprocess(testfile, timeout=timeout)
|
2018-10-05 10:11:02 +08:00
|
|
|
end = time.time()
|
|
|
|
duration = end - start
|
|
|
|
|
2019-06-07 18:58:51 +08:00
|
|
|
assert result.ret == ExitCode.OK
|
2018-10-09 03:54:14 +08:00
|
|
|
assert duration < timeout
|
2018-10-05 10:11:02 +08:00
|
|
|
|
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_pytester_run_timeout_expires(pytester: Pytester) -> None:
|
|
|
|
testfile = pytester.makepyfile(
|
2018-10-04 11:50:42 +08:00
|
|
|
"""
|
|
|
|
import time
|
2018-10-05 05:45:30 +08:00
|
|
|
|
2018-10-04 11:50:42 +08:00
|
|
|
def test_timeout():
|
|
|
|
time.sleep(10)"""
|
|
|
|
)
|
2020-12-16 12:16:05 +08:00
|
|
|
with pytest.raises(pytester.TimeoutExpired):
|
|
|
|
pytester.runpytest_subprocess(testfile, timeout=1)
|
2019-03-15 11:14:07 +08:00
|
|
|
|
|
|
|
|
2019-12-03 20:25:28 +08:00
|
|
|
def test_linematcher_with_nonlist() -> None:
|
2019-03-15 11:14:07 +08:00
|
|
|
"""Test LineMatcher with regard to passing in a set (accidentally)."""
|
2020-02-02 05:06:15 +08:00
|
|
|
from _pytest._code.source import Source
|
2019-03-15 11:14:07 +08:00
|
|
|
|
|
|
|
lm = LineMatcher([])
|
2020-02-02 05:06:15 +08:00
|
|
|
with pytest.raises(TypeError, match="invalid type for lines2: set"):
|
2020-07-10 14:44:14 +08:00
|
|
|
lm.fnmatch_lines(set()) # type: ignore[arg-type]
|
2020-02-02 05:06:15 +08:00
|
|
|
with pytest.raises(TypeError, match="invalid type for lines2: dict"):
|
2020-07-10 14:44:14 +08:00
|
|
|
lm.fnmatch_lines({}) # type: ignore[arg-type]
|
2020-02-02 05:06:15 +08:00
|
|
|
with pytest.raises(TypeError, match="invalid type for lines2: set"):
|
2020-07-10 14:44:14 +08:00
|
|
|
lm.re_match_lines(set()) # type: ignore[arg-type]
|
2020-02-02 05:06:15 +08:00
|
|
|
with pytest.raises(TypeError, match="invalid type for lines2: dict"):
|
2020-07-10 14:44:14 +08:00
|
|
|
lm.re_match_lines({}) # type: ignore[arg-type]
|
2020-02-02 05:06:15 +08:00
|
|
|
with pytest.raises(TypeError, match="invalid type for lines2: Source"):
|
2020-07-10 14:44:14 +08:00
|
|
|
lm.fnmatch_lines(Source()) # type: ignore[arg-type]
|
2019-03-15 11:14:07 +08:00
|
|
|
lm.fnmatch_lines([])
|
|
|
|
lm.fnmatch_lines(())
|
2020-02-02 05:06:15 +08:00
|
|
|
lm.fnmatch_lines("")
|
2020-07-10 14:44:14 +08:00
|
|
|
assert lm._getlines({}) == {} # type: ignore[arg-type,comparison-overlap]
|
|
|
|
assert lm._getlines(set()) == set() # type: ignore[arg-type,comparison-overlap]
|
2020-02-02 05:06:15 +08:00
|
|
|
assert lm._getlines(Source()) == []
|
|
|
|
assert lm._getlines(Source("pass\npass")) == ["pass", "pass"]
|
2019-04-03 18:05:49 +08:00
|
|
|
|
|
|
|
|
2019-12-03 20:25:28 +08:00
|
|
|
def test_linematcher_match_failure() -> None:
|
2019-10-22 07:33:43 +08:00
|
|
|
lm = LineMatcher(["foo", "foo", "bar"])
|
Use a hack to make typing of pytest.fail.Exception & co work
Mypy currently is unable to handle assigning attributes on function:
https://github.com/python/mypy/issues/2087.
pytest uses this for the outcome exceptions -- `pytest.fail.Exception`,
`pytest.exit.Exception` etc, and this is the canonical name by which they
are referred.
Initially we started working around this with type: ignores, and later
by switching e.g. `pytest.fail.Exception` with the direct exception
`Failed`. But this causes a lot of churn and is not as nice. And I also
found that some code relies on it, in skipping.py:
def pytest_configure(config):
if config.option.runxfail:
# yay a hack
import pytest
old = pytest.xfail
config._cleanup.append(lambda: setattr(pytest, "xfail", old))
def nop(*args, **kwargs):
pass
nop.Exception = xfail.Exception
setattr(pytest, "xfail", nop)
...
So it seems better to support it. Use a hack to make it work. The rest
of the commit rolls back all of the workarounds we added up to now.
`pytest.raises.Exception` also exists, but it's not used much so I kept
it as-is for now.
Hopefully in the future mypy supports this and this ugliness can be
removed.
2020-02-17 03:46:11 +08:00
|
|
|
with pytest.raises(pytest.fail.Exception) as e:
|
2019-10-22 07:33:43 +08:00
|
|
|
lm.fnmatch_lines(["foo", "f*", "baz"])
|
2019-12-03 20:25:28 +08:00
|
|
|
assert e.value.msg is not None
|
2019-10-22 07:33:43 +08:00
|
|
|
assert e.value.msg.splitlines() == [
|
|
|
|
"exact match: 'foo'",
|
|
|
|
"fnmatch: 'f*'",
|
|
|
|
" with: 'foo'",
|
|
|
|
"nomatch: 'baz'",
|
|
|
|
" and: 'bar'",
|
|
|
|
"remains unmatched: 'baz'",
|
|
|
|
]
|
|
|
|
|
|
|
|
lm = LineMatcher(["foo", "foo", "bar"])
|
Use a hack to make typing of pytest.fail.Exception & co work
Mypy currently is unable to handle assigning attributes on function:
https://github.com/python/mypy/issues/2087.
pytest uses this for the outcome exceptions -- `pytest.fail.Exception`,
`pytest.exit.Exception` etc, and this is the canonical name by which they
are referred.
Initially we started working around this with type: ignores, and later
by switching e.g. `pytest.fail.Exception` with the direct exception
`Failed`. But this causes a lot of churn and is not as nice. And I also
found that some code relies on it, in skipping.py:
def pytest_configure(config):
if config.option.runxfail:
# yay a hack
import pytest
old = pytest.xfail
config._cleanup.append(lambda: setattr(pytest, "xfail", old))
def nop(*args, **kwargs):
pass
nop.Exception = xfail.Exception
setattr(pytest, "xfail", nop)
...
So it seems better to support it. Use a hack to make it work. The rest
of the commit rolls back all of the workarounds we added up to now.
`pytest.raises.Exception` also exists, but it's not used much so I kept
it as-is for now.
Hopefully in the future mypy supports this and this ugliness can be
removed.
2020-02-17 03:46:11 +08:00
|
|
|
with pytest.raises(pytest.fail.Exception) as e:
|
2019-10-22 07:33:43 +08:00
|
|
|
lm.re_match_lines(["foo", "^f.*", "baz"])
|
2019-12-03 20:25:28 +08:00
|
|
|
assert e.value.msg is not None
|
2019-10-22 07:33:43 +08:00
|
|
|
assert e.value.msg.splitlines() == [
|
|
|
|
"exact match: 'foo'",
|
|
|
|
"re.match: '^f.*'",
|
|
|
|
" with: 'foo'",
|
|
|
|
" nomatch: 'baz'",
|
|
|
|
" and: 'bar'",
|
|
|
|
"remains unmatched: 'baz'",
|
|
|
|
]
|
|
|
|
|
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_linematcher_consecutive() -> None:
|
2020-02-02 06:33:24 +08:00
|
|
|
lm = LineMatcher(["1", "", "2"])
|
|
|
|
with pytest.raises(pytest.fail.Exception) as excinfo:
|
|
|
|
lm.fnmatch_lines(["1", "2"], consecutive=True)
|
|
|
|
assert str(excinfo.value).splitlines() == [
|
|
|
|
"exact match: '1'",
|
|
|
|
"no consecutive match: '2'",
|
|
|
|
" with: ''",
|
|
|
|
]
|
|
|
|
|
|
|
|
lm.re_match_lines(["1", r"\d?", "2"], consecutive=True)
|
|
|
|
with pytest.raises(pytest.fail.Exception) as excinfo:
|
|
|
|
lm.re_match_lines(["1", r"\d", "2"], consecutive=True)
|
|
|
|
assert str(excinfo.value).splitlines() == [
|
|
|
|
"exact match: '1'",
|
|
|
|
r"no consecutive match: '\\d'",
|
|
|
|
" with: ''",
|
|
|
|
]
|
|
|
|
|
|
|
|
|
2019-10-05 23:17:20 +08:00
|
|
|
@pytest.mark.parametrize("function", ["no_fnmatch_line", "no_re_match_line"])
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_linematcher_no_matching(function: str) -> None:
|
2019-10-05 23:17:20 +08:00
|
|
|
if function == "no_fnmatch_line":
|
|
|
|
good_pattern = "*.py OK*"
|
|
|
|
bad_pattern = "*X.py OK*"
|
|
|
|
else:
|
|
|
|
assert function == "no_re_match_line"
|
|
|
|
good_pattern = r".*py OK"
|
|
|
|
bad_pattern = r".*Xpy OK"
|
|
|
|
|
|
|
|
lm = LineMatcher(
|
|
|
|
[
|
|
|
|
"cachedir: .pytest_cache",
|
|
|
|
"collecting ... collected 1 item",
|
|
|
|
"",
|
|
|
|
"show_fixtures_per_test.py OK",
|
|
|
|
"=== elapsed 1s ===",
|
|
|
|
]
|
|
|
|
)
|
|
|
|
|
|
|
|
# check the function twice to ensure we don't accumulate the internal buffer
|
|
|
|
for i in range(2):
|
Use a hack to make typing of pytest.fail.Exception & co work
Mypy currently is unable to handle assigning attributes on function:
https://github.com/python/mypy/issues/2087.
pytest uses this for the outcome exceptions -- `pytest.fail.Exception`,
`pytest.exit.Exception` etc, and this is the canonical name by which they
are referred.
Initially we started working around this with type: ignores, and later
by switching e.g. `pytest.fail.Exception` with the direct exception
`Failed`. But this causes a lot of churn and is not as nice. And I also
found that some code relies on it, in skipping.py:
def pytest_configure(config):
if config.option.runxfail:
# yay a hack
import pytest
old = pytest.xfail
config._cleanup.append(lambda: setattr(pytest, "xfail", old))
def nop(*args, **kwargs):
pass
nop.Exception = xfail.Exception
setattr(pytest, "xfail", nop)
...
So it seems better to support it. Use a hack to make it work. The rest
of the commit rolls back all of the workarounds we added up to now.
`pytest.raises.Exception` also exists, but it's not used much so I kept
it as-is for now.
Hopefully in the future mypy supports this and this ugliness can be
removed.
2020-02-17 03:46:11 +08:00
|
|
|
with pytest.raises(pytest.fail.Exception) as e:
|
2019-10-05 23:17:20 +08:00
|
|
|
func = getattr(lm, function)
|
|
|
|
func(good_pattern)
|
|
|
|
obtained = str(e.value).splitlines()
|
2019-10-22 07:33:43 +08:00
|
|
|
if function == "no_fnmatch_line":
|
|
|
|
assert obtained == [
|
2020-10-03 04:16:22 +08:00
|
|
|
f"nomatch: '{good_pattern}'",
|
2019-10-22 07:33:43 +08:00
|
|
|
" and: 'cachedir: .pytest_cache'",
|
|
|
|
" and: 'collecting ... collected 1 item'",
|
|
|
|
" and: ''",
|
2020-10-03 04:16:22 +08:00
|
|
|
f"fnmatch: '{good_pattern}'",
|
2019-10-22 07:33:43 +08:00
|
|
|
" with: 'show_fixtures_per_test.py OK'",
|
|
|
|
]
|
|
|
|
else:
|
|
|
|
assert obtained == [
|
2020-10-03 04:16:22 +08:00
|
|
|
f" nomatch: '{good_pattern}'",
|
2019-10-22 07:33:43 +08:00
|
|
|
" and: 'cachedir: .pytest_cache'",
|
|
|
|
" and: 'collecting ... collected 1 item'",
|
|
|
|
" and: ''",
|
2020-10-03 04:16:22 +08:00
|
|
|
f"re.match: '{good_pattern}'",
|
2019-10-22 07:33:43 +08:00
|
|
|
" with: 'show_fixtures_per_test.py OK'",
|
|
|
|
]
|
2019-10-05 23:17:20 +08:00
|
|
|
|
|
|
|
func = getattr(lm, function)
|
|
|
|
func(bad_pattern) # bad pattern does not match any line: passes
|
|
|
|
|
|
|
|
|
2020-02-02 04:41:25 +08:00
|
|
|
def test_linematcher_no_matching_after_match() -> None:
|
2019-11-04 06:02:30 +08:00
|
|
|
lm = LineMatcher(["1", "2", "3"])
|
|
|
|
lm.fnmatch_lines(["1", "3"])
|
Use a hack to make typing of pytest.fail.Exception & co work
Mypy currently is unable to handle assigning attributes on function:
https://github.com/python/mypy/issues/2087.
pytest uses this for the outcome exceptions -- `pytest.fail.Exception`,
`pytest.exit.Exception` etc, and this is the canonical name by which they
are referred.
Initially we started working around this with type: ignores, and later
by switching e.g. `pytest.fail.Exception` with the direct exception
`Failed`. But this causes a lot of churn and is not as nice. And I also
found that some code relies on it, in skipping.py:
def pytest_configure(config):
if config.option.runxfail:
# yay a hack
import pytest
old = pytest.xfail
config._cleanup.append(lambda: setattr(pytest, "xfail", old))
def nop(*args, **kwargs):
pass
nop.Exception = xfail.Exception
setattr(pytest, "xfail", nop)
...
So it seems better to support it. Use a hack to make it work. The rest
of the commit rolls back all of the workarounds we added up to now.
`pytest.raises.Exception` also exists, but it's not used much so I kept
it as-is for now.
Hopefully in the future mypy supports this and this ugliness can be
removed.
2020-02-17 03:46:11 +08:00
|
|
|
with pytest.raises(pytest.fail.Exception) as e:
|
2019-11-04 06:02:30 +08:00
|
|
|
lm.no_fnmatch_line("*")
|
|
|
|
assert str(e.value).splitlines() == ["fnmatch: '*'", " with: '1'"]
|
|
|
|
|
|
|
|
|
2020-11-22 02:45:20 +08:00
|
|
|
def test_linematcher_string_api() -> None:
|
|
|
|
lm = LineMatcher(["foo", "bar"])
|
|
|
|
assert str(lm) == "foo\nbar"
|
|
|
|
|
|
|
|
|
2021-03-14 03:22:54 +08:00
|
|
|
def test_pytest_addopts_before_pytester(request, monkeypatch: MonkeyPatch) -> None:
|
2019-11-18 23:00:01 +08:00
|
|
|
orig = os.environ.get("PYTEST_ADDOPTS", None)
|
2019-04-03 18:05:49 +08:00
|
|
|
monkeypatch.setenv("PYTEST_ADDOPTS", "--orig-unused")
|
2021-03-14 03:22:54 +08:00
|
|
|
pytester: Pytester = request.getfixturevalue("pytester")
|
2019-11-18 23:00:01 +08:00
|
|
|
assert "PYTEST_ADDOPTS" not in os.environ
|
2021-03-14 03:22:54 +08:00
|
|
|
pytester._finalize()
|
2019-11-18 23:00:01 +08:00
|
|
|
assert os.environ.get("PYTEST_ADDOPTS") == "--orig-unused"
|
|
|
|
monkeypatch.undo()
|
|
|
|
assert os.environ.get("PYTEST_ADDOPTS") == orig
|
2019-04-06 15:55:56 +08:00
|
|
|
|
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_run_stdin(pytester: Pytester) -> None:
|
|
|
|
with pytest.raises(pytester.TimeoutExpired):
|
|
|
|
pytester.run(
|
2019-04-06 15:55:56 +08:00
|
|
|
sys.executable,
|
|
|
|
"-c",
|
2019-04-10 06:03:49 +08:00
|
|
|
"import sys, time; time.sleep(1); print(sys.stdin.read())",
|
2019-04-06 15:55:56 +08:00
|
|
|
stdin=subprocess.PIPE,
|
|
|
|
timeout=0.1,
|
|
|
|
)
|
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
with pytest.raises(pytester.TimeoutExpired):
|
|
|
|
result = pytester.run(
|
2019-04-06 15:55:56 +08:00
|
|
|
sys.executable,
|
|
|
|
"-c",
|
|
|
|
"import sys, time; time.sleep(1); print(sys.stdin.read())",
|
|
|
|
stdin=b"input\n2ndline",
|
|
|
|
timeout=0.1,
|
|
|
|
)
|
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
result = pytester.run(
|
2019-04-06 15:55:56 +08:00
|
|
|
sys.executable,
|
|
|
|
"-c",
|
|
|
|
"import sys; print(sys.stdin.read())",
|
|
|
|
stdin=b"input\n2ndline",
|
|
|
|
)
|
|
|
|
assert result.stdout.lines == ["input", "2ndline"]
|
|
|
|
assert result.stderr.str() == ""
|
|
|
|
assert result.ret == 0
|
|
|
|
|
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_popen_stdin_pipe(pytester: Pytester) -> None:
|
|
|
|
proc = pytester.popen(
|
2019-04-06 15:55:56 +08:00
|
|
|
[sys.executable, "-c", "import sys; print(sys.stdin.read())"],
|
|
|
|
stdout=subprocess.PIPE,
|
|
|
|
stderr=subprocess.PIPE,
|
|
|
|
stdin=subprocess.PIPE,
|
|
|
|
)
|
|
|
|
stdin = b"input\n2ndline"
|
|
|
|
stdout, stderr = proc.communicate(input=stdin)
|
|
|
|
assert stdout.decode("utf8").splitlines() == ["input", "2ndline"]
|
|
|
|
assert stderr == b""
|
|
|
|
assert proc.returncode == 0
|
|
|
|
|
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_popen_stdin_bytes(pytester: Pytester) -> None:
|
|
|
|
proc = pytester.popen(
|
2019-04-06 15:55:56 +08:00
|
|
|
[sys.executable, "-c", "import sys; print(sys.stdin.read())"],
|
|
|
|
stdout=subprocess.PIPE,
|
|
|
|
stderr=subprocess.PIPE,
|
|
|
|
stdin=b"input\n2ndline",
|
|
|
|
)
|
|
|
|
stdout, stderr = proc.communicate()
|
|
|
|
assert stdout.decode("utf8").splitlines() == ["input", "2ndline"]
|
|
|
|
assert stderr == b""
|
|
|
|
assert proc.returncode == 0
|
2019-04-06 18:09:31 +08:00
|
|
|
|
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_popen_default_stdin_stderr_and_stdin_None(pytester: Pytester) -> None:
|
2019-04-06 18:09:31 +08:00
|
|
|
# stdout, stderr default to pipes,
|
|
|
|
# stdin can be None to not close the pipe, avoiding
|
|
|
|
# "ValueError: flush of closed file" with `communicate()`.
|
2020-04-06 14:30:56 +08:00
|
|
|
#
|
2020-04-09 00:16:03 +08:00
|
|
|
# Wraps the test to make it not hang when run with "-s".
|
2020-12-16 12:16:05 +08:00
|
|
|
p1 = pytester.makepyfile(
|
2020-04-06 14:30:56 +08:00
|
|
|
'''
|
2019-04-06 18:09:31 +08:00
|
|
|
import sys
|
2020-04-06 14:30:56 +08:00
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_inner(pytester):
|
|
|
|
p1 = pytester.makepyfile(
|
2020-04-06 14:30:56 +08:00
|
|
|
"""
|
|
|
|
import sys
|
|
|
|
print(sys.stdin.read()) # empty
|
|
|
|
print('stdout')
|
|
|
|
sys.stderr.write('stderr')
|
|
|
|
"""
|
|
|
|
)
|
2020-12-16 12:16:05 +08:00
|
|
|
proc = pytester.popen([sys.executable, str(p1)], stdin=None)
|
2020-04-06 14:30:56 +08:00
|
|
|
stdout, stderr = proc.communicate(b"ignored")
|
|
|
|
assert stdout.splitlines() == [b"", b"stdout"]
|
|
|
|
assert stderr.splitlines() == [b"stderr"]
|
|
|
|
assert proc.returncode == 0
|
|
|
|
'''
|
2019-04-06 18:09:31 +08:00
|
|
|
)
|
2020-12-16 12:16:05 +08:00
|
|
|
result = pytester.runpytest("-p", "pytester", str(p1))
|
2020-04-06 14:30:56 +08:00
|
|
|
assert result.ret == 0
|
2019-05-24 22:46:50 +08:00
|
|
|
|
|
|
|
|
2020-10-25 08:03:20 +08:00
|
|
|
def test_spawn_uses_tmphome(pytester: Pytester) -> None:
|
|
|
|
tmphome = str(pytester.path)
|
2019-11-18 23:00:01 +08:00
|
|
|
assert os.environ.get("HOME") == tmphome
|
2019-05-24 22:46:50 +08:00
|
|
|
|
2020-10-25 08:03:20 +08:00
|
|
|
pytester._monkeypatch.setenv("CUSTOMENV", "42")
|
2019-05-24 23:49:14 +08:00
|
|
|
|
2020-10-25 08:03:20 +08:00
|
|
|
p1 = pytester.makepyfile(
|
2019-05-24 22:46:50 +08:00
|
|
|
"""
|
|
|
|
import os
|
|
|
|
|
|
|
|
def test():
|
|
|
|
assert os.environ["HOME"] == {tmphome!r}
|
2019-05-24 23:49:14 +08:00
|
|
|
assert os.environ["CUSTOMENV"] == "42"
|
2019-05-24 22:46:50 +08:00
|
|
|
""".format(
|
|
|
|
tmphome=tmphome
|
|
|
|
)
|
|
|
|
)
|
2020-10-25 08:03:20 +08:00
|
|
|
child = pytester.spawn_pytest(str(p1))
|
2019-05-24 22:46:50 +08:00
|
|
|
out = child.read()
|
|
|
|
assert child.wait() == 0, out.decode("utf8")
|
2019-10-23 06:33:54 +08:00
|
|
|
|
|
|
|
|
2019-12-03 20:25:28 +08:00
|
|
|
def test_run_result_repr() -> None:
|
2019-10-23 06:33:54 +08:00
|
|
|
outlines = ["some", "normal", "output"]
|
|
|
|
errlines = ["some", "nasty", "errors", "happened"]
|
|
|
|
|
|
|
|
# known exit code
|
2020-12-16 12:16:05 +08:00
|
|
|
r = pytester_mod.RunResult(1, outlines, errlines, duration=0.5)
|
2021-07-12 22:32:27 +08:00
|
|
|
assert (
|
|
|
|
repr(r) == "<RunResult ret=ExitCode.TESTS_FAILED len(stdout.lines)=3"
|
|
|
|
" len(stderr.lines)=4 duration=0.50s>"
|
|
|
|
)
|
2019-10-23 06:33:54 +08:00
|
|
|
|
|
|
|
# unknown exit code: just the number
|
2020-12-16 12:16:05 +08:00
|
|
|
r = pytester_mod.RunResult(99, outlines, errlines, duration=0.5)
|
2019-10-23 06:33:54 +08:00
|
|
|
assert (
|
|
|
|
repr(r) == "<RunResult ret=99 len(stdout.lines)=3"
|
|
|
|
" len(stderr.lines)=4 duration=0.50s>"
|
|
|
|
)
|
2019-12-19 02:15:53 +08:00
|
|
|
|
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_pytester_outcomes_with_multiple_errors(pytester: Pytester) -> None:
|
|
|
|
p1 = pytester.makepyfile(
|
2019-12-31 00:08:52 +08:00
|
|
|
"""
|
2019-12-19 02:15:53 +08:00
|
|
|
import pytest
|
|
|
|
|
|
|
|
@pytest.fixture
|
|
|
|
def bad_fixture():
|
|
|
|
raise Exception("bad")
|
|
|
|
|
|
|
|
def test_error1(bad_fixture):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def test_error2(bad_fixture):
|
|
|
|
pass
|
|
|
|
"""
|
2019-12-31 00:08:52 +08:00
|
|
|
)
|
2020-12-16 12:16:05 +08:00
|
|
|
result = pytester.runpytest(str(p1))
|
2020-06-13 21:24:44 +08:00
|
|
|
result.assert_outcomes(errors=2)
|
2019-12-31 00:08:52 +08:00
|
|
|
|
2020-06-13 21:24:44 +08:00
|
|
|
assert result.parseoutcomes() == {"errors": 2}
|
|
|
|
|
|
|
|
|
2020-12-19 04:36:20 +08:00
|
|
|
def test_parse_summary_line_always_plural() -> None:
|
2020-06-13 21:24:44 +08:00
|
|
|
"""Parsing summaries always returns plural nouns (#6505)"""
|
|
|
|
lines = [
|
|
|
|
"some output 1",
|
|
|
|
"some output 2",
|
|
|
|
"======= 1 failed, 1 passed, 1 warning, 1 error in 0.13s ====",
|
|
|
|
"done.",
|
|
|
|
]
|
2020-12-16 12:16:05 +08:00
|
|
|
assert pytester_mod.RunResult.parse_summary_nouns(lines) == {
|
2020-06-13 21:24:44 +08:00
|
|
|
"errors": 1,
|
|
|
|
"failed": 1,
|
|
|
|
"passed": 1,
|
|
|
|
"warnings": 1,
|
|
|
|
}
|
|
|
|
|
|
|
|
lines = [
|
|
|
|
"some output 1",
|
|
|
|
"some output 2",
|
|
|
|
"======= 1 failed, 1 passed, 2 warnings, 2 errors in 0.13s ====",
|
|
|
|
"done.",
|
|
|
|
]
|
2020-12-16 12:16:05 +08:00
|
|
|
assert pytester_mod.RunResult.parse_summary_nouns(lines) == {
|
2020-06-13 21:24:44 +08:00
|
|
|
"errors": 2,
|
|
|
|
"failed": 1,
|
|
|
|
"passed": 1,
|
|
|
|
"warnings": 2,
|
|
|
|
}
|
2020-01-27 06:36:28 +08:00
|
|
|
|
|
|
|
|
2020-12-16 12:16:05 +08:00
|
|
|
def test_makefile_joins_absolute_path(pytester: Pytester) -> None:
|
|
|
|
absfile = pytester.path / "absfile"
|
|
|
|
p1 = pytester.makepyfile(**{str(absfile): ""})
|
|
|
|
assert str(p1) == str(pytester.path / "absfile.py")
|
2020-10-12 23:13:06 +08:00
|
|
|
|
|
|
|
|
2020-12-19 04:36:20 +08:00
|
|
|
def test_testtmproot(testdir) -> None:
|
2020-10-12 23:13:06 +08:00
|
|
|
"""Check test_tmproot is a py.path attribute for backward compatibility."""
|
|
|
|
assert testdir.test_tmproot.check(dir=1)
|
2021-01-04 21:58:11 +08:00
|
|
|
|
|
|
|
|
|
|
|
def test_testdir_makefile_dot_prefixes_extension_silently(
|
|
|
|
testdir: Testdir,
|
|
|
|
) -> None:
|
|
|
|
"""For backwards compat #8192"""
|
|
|
|
p1 = testdir.makefile("foo.bar", "")
|
|
|
|
assert ".foo.bar" in str(p1)
|
|
|
|
|
|
|
|
|
|
|
|
def test_pytester_makefile_dot_prefixes_extension_with_warning(
|
|
|
|
pytester: Pytester,
|
|
|
|
) -> None:
|
|
|
|
with pytest.raises(
|
|
|
|
ValueError,
|
|
|
|
match="pytester.makefile expects a file extension, try .foo.bar instead of foo.bar",
|
|
|
|
):
|
|
|
|
pytester.makefile("foo.bar", "")
|
|
|
|
|
|
|
|
|
|
|
|
def test_testdir_makefile_ext_none_raises_type_error(testdir) -> None:
|
|
|
|
"""For backwards compat #8192"""
|
|
|
|
with pytest.raises(TypeError):
|
|
|
|
testdir.makefile(None, "")
|
|
|
|
|
|
|
|
|
|
|
|
def test_testdir_makefile_ext_empty_string_makes_file(testdir) -> None:
|
|
|
|
"""For backwards compat #8192"""
|
|
|
|
p1 = testdir.makefile("", "")
|
|
|
|
assert "test_testdir_makefile" in str(p1)
|