Harbor format: 871 coding_baseline tasks (part 56)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/issue88_initial_file_multinodes/test_hello.pyAdded+6
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/issue_519.pyAdded+54
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/junit-10.xsdAdded+147
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/marks/marks_considered_keywords/__init__.pyiAdded
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/marks/marks_considered_keywords/conftest.pyAdded
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/marks/marks_considered_keywords/test_marks_as_keywords.pyAdded+9
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/perf_examples/collect_stats/.gitignoreAdded+1
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/perf_examples/collect_stats/generate_folders.pyAdded+31
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/perf_examples/collect_stats/template_test.pyAdded+6
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/pytest.iniAdded+2
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/tmpdir/tmp_path_fixture.pyAdded+10
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_parametrized_fixture_error_message.pyAdded+17
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_setup_skip.pyAdded+17
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_setup_skip_class.pyAdded+18
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_setup_skip_module.pyAdded+16
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_unittest_asyncio.pyAdded+27
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_unittest_asynctest.pyAdded+26
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_unittest_plain_async.pyAdded+9
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/warnings/test_group_warnings_by_message.pyAdded+24
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/warnings/test_group_warnings_by_message_summary/test_1.pyAdded+24
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/warnings/test_group_warnings_by_message_summary/test_2.pyAdded+8
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/examples/test_issue519.pyAdded+9
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/.gitignoreAdded+3
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/create_executable.pyAdded+16
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/runtests_script.pyAdded+14
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/tests/test_doctest.txtAdded+6
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/tests/test_trivial.pyAdded+10
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/tox_run.pyAdded+16
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/io/test_pprint.pyAdded+408
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/io/test_saferepr.pyAdded+231
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/io/test_terminalwriter.pyAdded+325
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/io/test_wcwidth.pyAdded+40
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/logging/test_fixture.pyAdded+483
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/logging/test_formatter.pyAdded+175
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/logging/test_reporting.pyAdded+1549
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/.gitignoreAdded+2
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/README.rstAdded+13
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/bdd_wallet.featureAdded+9
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/bdd_wallet.pyAdded+42
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/django_settings.pyAdded+4
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest.iniAdded+7
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_anyio_integration.pyAdded+11
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_asyncio_integration.pyAdded+11
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_mock_integration.pyAdded+6
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_rerunfailures_integration.pyAdded+13
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_trio_integration.pyAdded+11
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_twisted_integration.pyAdded+21
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/requirements.txtAdded+15
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/simple_integration.pyAdded+13
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/python/approx.pyAdded+1162
123456# mypy: allow-untyped-defsfrom __future__ import annotations
def test_hello(): pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354# mypy: allow-untyped-defsfrom __future__ import annotations
import pprint
import pytest
def pytest_generate_tests(metafunc): if "arg1" in metafunc.fixturenames: metafunc.parametrize("arg1", ["arg1v1", "arg1v2"], scope="module")
if "arg2" in metafunc.fixturenames: metafunc.parametrize("arg2", ["arg2v1", "arg2v2"], scope="function")
@pytest.fixture(scope="session")def checked_order(): order: list[tuple[str, str, str]] = []
yield order pprint.pprint(order) assert order == [ ("issue_519.py", "fix1", "arg1v1"), ("test_one[arg1v1-arg2v1]", "fix2", "arg2v1"), ("test_two[arg1v1-arg2v1]", "fix2", "arg2v1"), ("test_one[arg1v1-arg2v2]", "fix2", "arg2v2"), ("test_two[arg1v1-arg2v2]", "fix2", "arg2v2"), ("issue_519.py", "fix1", "arg1v2"), ("test_one[arg1v2-arg2v1]", "fix2", "arg2v1"), ("test_two[arg1v2-arg2v1]", "fix2", "arg2v1"), ("test_one[arg1v2-arg2v2]", "fix2", "arg2v2"), ("test_two[arg1v2-arg2v2]", "fix2", "arg2v2"), ]
@pytest.fixture(scope="module")def fix1(request, arg1, checked_order): checked_order.append((request.node.name, "fix1", arg1)) yield "fix1-" + arg1
@pytest.fixture(scope="function")def fix2(request, fix1, arg2, checked_order): checked_order.append((request.node.name, "fix2", arg2)) yield "fix2-" + arg2 + fix1
def test_one(fix2): pass
def test_two(fix2): pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147<?xml version="1.0" encoding="UTF-8" ?><!--The MIT License (MIT)
Copyright (c) 2014, Gregory Boissinot
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included inall copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS INTHE SOFTWARE.--><xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="SUREFIRE_TIME"> <xs:restriction base="xs:string"> <xs:pattern value="(([0-9]{0,3},)*[0-9]{3}|[0-9]{0,3})*(\.[0-9]{0,3})?"/> </xs:restriction> </xs:simpleType>
<xs:complexType name="rerunType" mixed="true"> <!-- mixed (XML contains text) to be compatible with version previous than 2.22.1 --> <xs:sequence> <xs:element name="stackTrace" type="xs:string" minOccurs="0" /> <!-- optional to be compatible with version previous than 2.22.1 --> <xs:element name="system-out" type="xs:string" minOccurs="0" /> <xs:element name="system-err" type="xs:string" minOccurs="0" /> </xs:sequence> <xs:attribute name="message" type="xs:string" /> <xs:attribute name="type" type="xs:string" use="required" /> </xs:complexType>
<xs:element name="failure"> <xs:complexType mixed="true"> <xs:attribute name="type" type="xs:string"/> <xs:attribute name="message" type="xs:string"/> </xs:complexType> </xs:element>
<xs:element name="error"> <xs:complexType mixed="true"> <xs:attribute name="type" type="xs:string"/> <xs:attribute name="message" type="xs:string"/> </xs:complexType> </xs:element>
<xs:element name="skipped"> <xs:complexType mixed="true"> <xs:attribute name="type" type="xs:string"/> <xs:attribute name="message" type="xs:string"/> </xs:complexType> </xs:element>
<xs:element name="properties"> <xs:complexType> <xs:sequence> <xs:element ref="property" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> </xs:element>
<xs:element name="property"> <xs:complexType> <xs:attribute name="name" type="xs:string" use="required"/> <xs:attribute name="value" type="xs:string" use="required"/> </xs:complexType> </xs:element>
<xs:element name="system-err" type="xs:string"/> <xs:element name="system-out" type="xs:string"/> <xs:element name="rerunFailure" type="rerunType"/> <xs:element name="rerunError" type="rerunType"/> <xs:element name="flakyFailure" type="rerunType"/> <xs:element name="flakyError" type="rerunType"/>
<xs:element name="testcase"> <xs:complexType> <xs:sequence> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element ref="skipped"/> <xs:element ref="error"/> <xs:element ref="failure"/> <xs:element ref="rerunFailure" minOccurs="0" maxOccurs="unbounded"/> <xs:element ref="rerunError" minOccurs="0" maxOccurs="unbounded"/> <xs:element ref="flakyFailure" minOccurs="0" maxOccurs="unbounded"/> <xs:element ref="flakyError" minOccurs="0" maxOccurs="unbounded"/> <xs:element ref="system-out"/> <xs:element ref="system-err"/> </xs:choice> </xs:sequence> <xs:attribute name="name" type="xs:string" use="required"/> <xs:attribute name="time" type="xs:string"/> <xs:attribute name="classname" type="xs:string"/> <xs:attribute name="group" type="xs:string"/> </xs:complexType> </xs:element>
<xs:element name="testsuite"> <xs:complexType> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element ref="testsuite"/> <xs:element ref="properties"/> <xs:element ref="testcase"/> <xs:element ref="system-out"/> <xs:element ref="system-err"/> </xs:choice> <xs:attribute name="name" type="xs:string" use="required"/> <xs:attribute name="tests" type="xs:string" use="required"/> <xs:attribute name="failures" type="xs:string" use="required"/> <xs:attribute name="errors" type="xs:string" use="required"/> <xs:attribute name="group" type="xs:string" /> <xs:attribute name="time" type="SUREFIRE_TIME"/> <xs:attribute name="skipped" type="xs:string" /> <xs:attribute name="timestamp" type="xs:string" /> <xs:attribute name="hostname" type="xs:string" /> <xs:attribute name="id" type="xs:string" /> <xs:attribute name="package" type="xs:string" /> <xs:attribute name="file" type="xs:string"/> <xs:attribute name="log" type="xs:string"/> <xs:attribute name="url" type="xs:string"/> <xs:attribute name="version" type="xs:string"/> </xs:complexType> </xs:element>
<xs:element name="testsuites"> <xs:complexType> <xs:sequence> <xs:element ref="testsuite" minOccurs="0" maxOccurs="unbounded" /> </xs:sequence> <xs:attribute name="name" type="xs:string" /> <xs:attribute name="time" type="SUREFIRE_TIME"/> <xs:attribute name="tests" type="xs:string" /> <xs:attribute name="failures" type="xs:string" /> <xs:attribute name="errors" type="xs:string" /> </xs:complexType> </xs:element>
</xs:schema>123456789# mypy: allow-untyped-defsfrom __future__ import annotations
import pytest
@pytest.mark.foodef test_mark(): pass1foo_*12345678910111213141516171819202122232425262728293031# mypy: allow-untyped-defsfrom __future__ import annotations
import argparseimport pathlib
HERE = pathlib.Path(__file__).parentTEST_CONTENT = (HERE / "template_test.py").read_bytes()
parser = argparse.ArgumentParser()parser.add_argument("numbers", nargs="*", type=int)
def generate_folders(root, elements, *more_numbers): fill_len = len(str(elements)) if more_numbers: for i in range(elements): new_folder = root.joinpath(f"foo_{i:0>{fill_len}}") new_folder.mkdir() new_folder.joinpath("__init__.py").write_bytes(TEST_CONTENT) generate_folders(new_folder, *more_numbers) else: for i in range(elements): new_test = root.joinpath(f"test_{i:0<{fill_len}}.py") new_test.write_bytes(TEST_CONTENT)
if __name__ == "__main__": args = parser.parse_args() generate_folders(HERE, *(args.numbers or (10, 100)))123456# mypy: allow-untyped-defsfrom __future__ import annotations
def test_x(): pass12[pytest]# dummy pytest.ini to ease direct running of example scripts12345678910# mypy: allow-untyped-defsfrom __future__ import annotations
import pytest
@pytest.mark.parametrize("a", [r"qwe/\abc"])def test_fixture(tmp_path, a): assert tmp_path.is_dir() assert list(tmp_path.iterdir()) == []1234567891011121314151617# mypy: allow-untyped-defsfrom __future__ import annotations
import unittest
import pytest
@pytest.fixture(params=[1, 2])def two(request): return request.param
@pytest.mark.usefixtures("two")class TestSomethingElse(unittest.TestCase): def test_two(self): pass1234567891011121314151617# mypy: allow-untyped-defs"""Skipping an entire subclass with unittest.skip() should *not* call setUp from a base class."""
from __future__ import annotations
import unittest
class Base(unittest.TestCase): def setUp(self): assert 0
@unittest.skip("skip all tests")class Test(Base): def test_foo(self): assert 0123456789101112131415161718# mypy: allow-untyped-defs"""Skipping an entire subclass with unittest.skip() should *not* call setUpClass from a base class."""
from __future__ import annotations
import unittest
class Base(unittest.TestCase): @classmethod def setUpClass(cls): assert 0
@unittest.skip("skip all tests")class Test(Base): def test_foo(self): assert 012345678910111213141516# mypy: allow-untyped-defs"""setUpModule is always called, even if all tests in the module are skipped"""
from __future__ import annotations
import unittest
def setUpModule(): assert 0
@unittest.skip("skip all tests")class Base(unittest.TestCase): def test(self): assert 0123456789101112131415161718192021222324252627# mypy: allow-untyped-defsfrom __future__ import annotations
from unittest import IsolatedAsyncioTestCase
teardowns: list[None] = []
class AsyncArguments(IsolatedAsyncioTestCase): async def asyncTearDown(self): teardowns.append(None)
async def test_something_async(self): async def addition(x, y): return x + y
self.assertEqual(await addition(2, 2), 4)
async def test_something_async_fails(self): async def addition(x, y): return x + y
self.assertEqual(await addition(2, 2), 3)
def test_teardowns(self): assert len(teardowns) == 21234567891011121314151617181920212223242526# mypy: allow-untyped-defs"""Issue #7110"""
from __future__ import annotations
import asyncio
import asynctest
teardowns: list[None] = []
class Test(asynctest.TestCase): async def tearDown(self): teardowns.append(None)
async def test_error(self): await asyncio.sleep(0) self.fail("failing on purpose")
async def test_ok(self): await asyncio.sleep(0)
def test_teardowns(self): assert len(teardowns) == 2123456789# mypy: allow-untyped-defsfrom __future__ import annotations
import unittest
class Test(unittest.TestCase): async def test_foo(self): assert False123456789101112131415161718192021222324# mypy: allow-untyped-defsfrom __future__ import annotations
import warnings
import pytest
def func(msg): warnings.warn(UserWarning(msg))
@pytest.mark.parametrize("i", range(5))def test_foo(i): func("foo")
def test_foo_1(): func("foo")
@pytest.mark.parametrize("i", range(5))def test_bar(i): func("bar")123456789101112131415161718192021222324# mypy: allow-untyped-defsfrom __future__ import annotations
import warnings
import pytest
def func(msg): warnings.warn(UserWarning(msg))
@pytest.mark.parametrize("i", range(20))def test_foo(i): func("foo")
def test_foo_1(): func("foo")
@pytest.mark.parametrize("i", range(20))def test_bar(i): func("bar")12345678# mypy: allow-untyped-defsfrom __future__ import annotations
from test_1 import func
def test_2(): func("foo")123456789from __future__ import annotations
from _pytest.pytester import Pytester
def test_519(pytester: Pytester) -> None: pytester.copy_example("issue_519.py") res = pytester.runpytest("issue_519.py") res.assert_outcomes(passed=8)123build/dist/*.spec12345678910111213141516"""Generate an executable with pytest runner embedded using PyInstaller."""
from __future__ import annotations
if __name__ == "__main__": import subprocess
import pytest
hidden = [] for x in pytest.freeze_includes(): hidden.extend(["--hidden-import", x]) hidden.extend(["--hidden-import", "distutils"]) args = ["pyinstaller", "--noconfirm", *hidden, "runtests_script.py"] subprocess.check_call(" ".join(args), shell=True)1234567891011121314"""This is the script that is actually frozen into an executable: simply executespytest main()."""
from __future__ import annotations
if __name__ == "__main__": import sys
import pytest
sys.exit(pytest.main())123456
Testing doctest::
>>> 1 + 1 212345678910# mypy: allow-untyped-defsfrom __future__ import annotations
def test_upper(): assert "foo".upper() == "FOO"
def test_lower(): assert "FOO".lower() == "foo"12345678910111213141516"""Called by tox.ini: uses the generated executable to run the tests in ./tests/directory."""
from __future__ import annotations
if __name__ == "__main__": import os import sys
executable = os.path.join(os.getcwd(), "dist", "runtests_script", "runtests_script") if sys.platform.startswith("win"): executable += ".exe" sys.exit(os.system(f"{executable} tests"))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408from __future__ import annotations
from collections import ChainMapfrom collections import Counterfrom collections import defaultdictfrom collections import dequefrom collections import OrderedDictfrom dataclasses import dataclassimport textwrapfrom types import MappingProxyTypefrom types import SimpleNamespacefrom typing import Any
from _pytest._io.pprint import PrettyPrinterimport pytest
@dataclassclass EmptyDataclass: pass
@dataclassclass DataclassWithOneItem: foo: str
@dataclassclass DataclassWithTwoItems: foo: str bar: str
@pytest.mark.parametrize( ("data", "expected"), ( pytest.param( EmptyDataclass(), "EmptyDataclass()", id="dataclass-empty", ), pytest.param( DataclassWithOneItem(foo="bar"), """ DataclassWithOneItem( foo='bar', ) """, id="dataclass-one-item", ), pytest.param( DataclassWithTwoItems(foo="foo", bar="bar"), """ DataclassWithTwoItems( foo='foo', bar='bar', ) """, id="dataclass-two-items", ), pytest.param( {}, "{}", id="dict-empty", ), pytest.param( {"one": 1}, """ { 'one': 1, } """, id="dict-one-item", ), pytest.param( {"one": 1, "two": 2}, """ { 'one': 1, 'two': 2, } """, id="dict-two-items", ), pytest.param(OrderedDict(), "OrderedDict()", id="ordereddict-empty"), pytest.param( OrderedDict({"one": 1}), """ OrderedDict({ 'one': 1, }) """, id="ordereddict-one-item", ), pytest.param( OrderedDict({"one": 1, "two": 2}), """ OrderedDict({ 'one': 1, 'two': 2, }) """, id="ordereddict-two-items", ), pytest.param( [], "[]", id="list-empty", ), pytest.param( [1], """ [ 1, ] """, id="list-one-item", ), pytest.param( [1, 2], """ [ 1, 2, ] """, id="list-two-items", ), pytest.param( tuple(), "()", id="tuple-empty", ), pytest.param( (1,), """ ( 1, ) """, id="tuple-one-item", ), pytest.param( (1, 2), """ ( 1, 2, ) """, id="tuple-two-items", ), pytest.param( set(), "set()", id="set-empty", ), pytest.param( {1}, """ { 1, } """, id="set-one-item", ), pytest.param( {1, 2}, """ { 1, 2, } """, id="set-two-items", ), pytest.param( MappingProxyType({}), "mappingproxy({})", id="mappingproxy-empty", ), pytest.param( MappingProxyType({"one": 1}), """ mappingproxy({ 'one': 1, }) """, id="mappingproxy-one-item", ), pytest.param( MappingProxyType({"one": 1, "two": 2}), """ mappingproxy({ 'one': 1, 'two': 2, }) """, id="mappingproxy-two-items", ), pytest.param( SimpleNamespace(), "namespace()", id="simplenamespace-empty", ), pytest.param( SimpleNamespace(one=1), """ namespace( one=1, ) """, id="simplenamespace-one-item", ), pytest.param( SimpleNamespace(one=1, two=2), """ namespace( one=1, two=2, ) """, id="simplenamespace-two-items", ), pytest.param( defaultdict(str), "defaultdict(<class 'str'>, {})", id="defaultdict-empty" ), pytest.param( defaultdict(str, {"one": "1"}), """ defaultdict(<class 'str'>, { 'one': '1', }) """, id="defaultdict-one-item", ), pytest.param( defaultdict(str, {"one": "1", "two": "2"}), """ defaultdict(<class 'str'>, { 'one': '1', 'two': '2', }) """, id="defaultdict-two-items", ), pytest.param( Counter(), "Counter()", id="counter-empty", ), pytest.param( Counter("1"), """ Counter({ '1': 1, }) """, id="counter-one-item", ), pytest.param( Counter("121"), """ Counter({ '1': 2, '2': 1, }) """, id="counter-two-items", ), pytest.param(ChainMap(), "ChainMap({})", id="chainmap-empty"), pytest.param( ChainMap({"one": 1, "two": 2}), """ ChainMap( { 'one': 1, 'two': 2, }, ) """, id="chainmap-one-item", ), pytest.param( ChainMap({"one": 1}, {"two": 2}), """ ChainMap( { 'one': 1, }, { 'two': 2, }, ) """, id="chainmap-two-items", ), pytest.param( deque(), "deque([])", id="deque-empty", ), pytest.param( deque([1]), """ deque([ 1, ]) """, id="deque-one-item", ), pytest.param( deque([1, 2]), """ deque([ 1, 2, ]) """, id="deque-two-items", ), pytest.param( deque([1, 2], maxlen=3), """ deque(maxlen=3, [ 1, 2, ]) """, id="deque-maxlen", ), pytest.param( { "chainmap": ChainMap({"one": 1}, {"two": 2}), "counter": Counter("122"), "dataclass": DataclassWithTwoItems(foo="foo", bar="bar"), "defaultdict": defaultdict(str, {"one": "1", "two": "2"}), "deque": deque([1, 2], maxlen=3), "dict": {"one": 1, "two": 2}, "list": [1, 2], "mappingproxy": MappingProxyType({"one": 1, "two": 2}), "ordereddict": OrderedDict({"one": 1, "two": 2}), "set": {1, 2}, "simplenamespace": SimpleNamespace(one=1, two=2), "tuple": (1, 2), }, """ { 'chainmap': ChainMap( { 'one': 1, }, { 'two': 2, }, ), 'counter': Counter({ '2': 2, '1': 1, }), 'dataclass': DataclassWithTwoItems( foo='foo', bar='bar', ), 'defaultdict': defaultdict(<class 'str'>, { 'one': '1', 'two': '2', }), 'deque': deque(maxlen=3, [ 1, 2, ]), 'dict': { 'one': 1, 'two': 2, }, 'list': [ 1, 2, ], 'mappingproxy': mappingproxy({ 'one': 1, 'two': 2, }), 'ordereddict': OrderedDict({ 'one': 1, 'two': 2, }), 'set': { 1, 2, }, 'simplenamespace': namespace( one=1, two=2, ), 'tuple': ( 1, 2, ), } """, id="deep-example", ), ),)def test_consistent_pretty_printer(data: Any, expected: str) -> None: assert PrettyPrinter().pformat(data) == textwrap.dedent(expected).strip()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231# mypy: allow-untyped-defsfrom __future__ import annotations
from _pytest._io.saferepr import DEFAULT_REPR_MAX_SIZEfrom _pytest._io.saferepr import SafeReprfrom _pytest._io.saferepr import safereprfrom _pytest._io.saferepr import saferepr_unlimitedimport pytest
def test_simple_repr(): assert saferepr(1) == "1" assert saferepr(None) == "None"
def test_maxsize(): s = saferepr("x" * 50, maxsize=25) assert len(s) == 25 expected = repr("x" * 10 + "..." + "x" * 10) assert s == expected
def test_no_maxsize(): text = "x" * DEFAULT_REPR_MAX_SIZE * 10 s = saferepr(text, maxsize=None) expected = repr(text) assert s == expected
def test_maxsize_error_on_instance(): class A: def __repr__(self): raise ValueError("...")
s = saferepr(("*" * 50, A()), maxsize=25) assert len(s) == 25 assert s[0] == "(" and s[-1] == ")"
def test_exceptions() -> None: class BrokenRepr: def __init__(self, ex): self.ex = ex
def __repr__(self): raise self.ex
class BrokenReprException(Exception): __str__ = None # type: ignore[assignment] __repr__ = None # type: ignore[assignment]
assert "Exception" in saferepr(BrokenRepr(Exception("broken"))) s = saferepr(BrokenReprException("really broken")) assert "TypeError" in s assert "TypeError" in saferepr(BrokenRepr("string"))
none = None try: none() # type: ignore[misc] except BaseException as exc: exp_exc = repr(exc) obj = BrokenRepr(BrokenReprException("omg even worse")) s2 = saferepr(obj) assert s2 == ( f"<[unpresentable exception ({exp_exc!s}) raised in repr()] BrokenRepr object at 0x{id(obj):x}>" )
def test_baseexception(): """Test saferepr() with BaseExceptions, which includes pytest outcomes."""
class RaisingOnStrRepr(BaseException): def __init__(self, exc_types): self.exc_types = exc_types
def raise_exc(self, *args): try: self.exc_type = self.exc_types.pop(0) except IndexError: pass if hasattr(self.exc_type, "__call__"): raise self.exc_type(*args) raise self.exc_type
def __str__(self): # noqa: PLE0307 self.raise_exc("__str__")
def __repr__(self): self.raise_exc("__repr__")
class BrokenObj: def __init__(self, exc): self.exc = exc
def __repr__(self): raise self.exc
__str__ = __repr__
baseexc_str = BaseException("__str__") obj = BrokenObj(RaisingOnStrRepr([BaseException])) assert saferepr(obj) == ( f"<[unpresentable exception ({baseexc_str!r}) " f"raised in repr()] BrokenObj object at 0x{id(obj):x}>" ) obj = BrokenObj(RaisingOnStrRepr([RaisingOnStrRepr([BaseException])])) assert saferepr(obj) == ( f"<[{baseexc_str!r} raised in repr()] BrokenObj object at 0x{id(obj):x}>" )
with pytest.raises(KeyboardInterrupt): saferepr(BrokenObj(KeyboardInterrupt()))
with pytest.raises(SystemExit): saferepr(BrokenObj(SystemExit()))
with pytest.raises(KeyboardInterrupt): saferepr(BrokenObj(RaisingOnStrRepr([KeyboardInterrupt])))
with pytest.raises(SystemExit): saferepr(BrokenObj(RaisingOnStrRepr([SystemExit])))
with pytest.raises(KeyboardInterrupt): print(saferepr(BrokenObj(RaisingOnStrRepr([BaseException, KeyboardInterrupt]))))
with pytest.raises(SystemExit): saferepr(BrokenObj(RaisingOnStrRepr([BaseException, SystemExit])))
def test_buggy_builtin_repr(): # Simulate a case where a repr for a builtin raises. # reprlib dispatches by type name, so use "int".
class int: def __repr__(self): raise ValueError("Buggy repr!")
assert "Buggy" in saferepr(int())
def test_big_repr(): from _pytest._io.saferepr import SafeRepr
assert len(saferepr(range(1000))) <= len("[" + SafeRepr(0).maxlist * "1000" + "]")
def test_repr_on_newstyle() -> None: class Function: def __repr__(self): return f"<{self.name}>" # type: ignore[attr-defined]
assert saferepr(Function())
def test_unicode(): val = "£€" reprval = "'£€'" assert saferepr(val) == reprval
def test_broken_getattribute(): """saferepr() can create proper representations of classes with broken __getattribute__ (#7145) """
class SomeClass: def __getattribute__(self, attr): raise RuntimeError
def __repr__(self): raise RuntimeError
assert saferepr(SomeClass()).startswith( "<[RuntimeError() raised in repr()] SomeClass object at 0x" )
def test_saferepr_unlimited(): dict5 = {f"v{i}": i for i in range(5)} assert saferepr_unlimited(dict5) == "{'v0': 0, 'v1': 1, 'v2': 2, 'v3': 3, 'v4': 4}"
dict_long = {f"v{i}": i for i in range(1_000)} r = saferepr_unlimited(dict_long) assert "..." not in r assert "\n" not in r
def test_saferepr_unlimited_exc(): class A: def __repr__(self): raise ValueError(42)
assert saferepr_unlimited(A()).startswith( "<[ValueError(42) raised in repr()] A object at 0x" )
def test_saferepr_dict_preserves_insertion_order() -> None: d = { "b": 2, "a": 1, "d": 4, "e": 5, "c": 3, } s = SafeRepr(maxsize=None) s.maxdict = 10 assert s.repr(d) == "{'b': 2, 'a': 1, 'd': 4, 'e': 5, 'c': 3}"
def test_saferepr_dict_truncation_preserves_insertion_order() -> None: d = { "b": 2, "a": 1, "d": 4, "e": 5, "c": 3, } s = SafeRepr(maxsize=None) s.maxdict = 1 assert s.repr(d) == "{'b': 2, ...}"
def test_saferepr_dict_fillvalue_when_level_is_zero() -> None: s = SafeRepr(maxsize=None) assert s.repr_dict({"a": 1}, level=0) == "{...}"
def test_saferepr_dict_empty() -> None: s = SafeRepr(maxsize=None) assert s.repr_dict({}, level=1) == "{}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325# mypy: allow-untyped-defsfrom __future__ import annotations
from collections.abc import Generatorimport iofrom io import StringIOimport osfrom pathlib import Pathimport reimport shutilimport sysfrom unittest import mock
from _pytest._io import terminalwriterfrom _pytest.monkeypatch import MonkeyPatchimport pytest
# These tests were initially copied from py 1.8.1.
def test_terminal_width_COLUMNS(monkeypatch: MonkeyPatch) -> None: monkeypatch.setenv("COLUMNS", "42") assert terminalwriter.get_terminal_width() == 42 monkeypatch.delenv("COLUMNS", raising=False)
def test_terminalwriter_width_bogus(monkeypatch: MonkeyPatch) -> None: monkeypatch.setattr(shutil, "get_terminal_size", mock.Mock(return_value=(10, 10))) monkeypatch.delenv("COLUMNS", raising=False) tw = terminalwriter.TerminalWriter() assert tw.fullwidth == 80
def test_terminalwriter_computes_width(monkeypatch: MonkeyPatch) -> None: monkeypatch.setattr(terminalwriter, "get_terminal_width", lambda: 42) tw = terminalwriter.TerminalWriter() assert tw.fullwidth == 42
def test_terminalwriter_dumb_term_no_markup(monkeypatch: MonkeyPatch) -> None: monkeypatch.setattr(os, "environ", {"TERM": "dumb", "PATH": ""})
class MyFile: closed = False
def isatty(self): return True
with monkeypatch.context() as m: m.setattr(sys, "stdout", MyFile()) assert sys.stdout.isatty() tw = terminalwriter.TerminalWriter() assert not tw.hasmarkup
def test_terminalwriter_not_unicode() -> None: """If the file doesn't support Unicode, the string is unicode-escaped (#7475).""" buffer = io.BytesIO() file = io.TextIOWrapper(buffer, encoding="cp1252") tw = terminalwriter.TerminalWriter(file) tw.write("hello 🌀 wôrld אבג", flush=True) assert buffer.getvalue() == rb"hello \U0001f300 w\xf4rld \u05d0\u05d1\u05d2"
win32 = int(sys.platform == "win32")
class TestTerminalWriter: @pytest.fixture(params=["path", "stringio"]) def tw(self, request, tmp_path: Path) -> Generator[terminalwriter.TerminalWriter]: f: io.TextIOWrapper | StringIO if request.param == "path": p = tmp_path.joinpath("tmpfile") f = open(str(p), "w+", encoding="utf8") tw = terminalwriter.TerminalWriter(f)
def getlines(): f.flush() with open(str(p), encoding="utf8") as fp: return fp.readlines()
elif request.param == "stringio": f = io.StringIO() tw = terminalwriter.TerminalWriter(f)
def getlines(): f.seek(0) return f.readlines()
tw.getlines = getlines # type: ignore tw.getvalue = lambda: "".join(getlines()) # type: ignore
with f: yield tw
def test_line(self, tw) -> None: tw.line("hello") lines = tw.getlines() assert len(lines) == 1 assert lines[0] == "hello\n"
def test_line_unicode(self, tw) -> None: msg = "b\u00f6y" tw.line(msg) lines = tw.getlines() assert lines[0] == msg + "\n"
def test_sep_no_title(self, tw) -> None: tw.sep("-", fullwidth=60) lines = tw.getlines() assert len(lines) == 1 assert lines[0] == "-" * (60 - win32) + "\n"
def test_sep_with_title(self, tw) -> None: tw.sep("-", "hello", fullwidth=60) lines = tw.getlines() assert len(lines) == 1 assert lines[0] == "-" * 26 + " hello " + "-" * (27 - win32) + "\n"
def test_sep_longer_than_width(self, tw) -> None: tw.sep("-", "a" * 10, fullwidth=5) (line,) = tw.getlines() # even though the string is wider than the line, still have a separator assert line == "- aaaaaaaaaa -\n"
@pytest.mark.skipif(sys.platform == "win32", reason="win32 has no native ansi") @pytest.mark.parametrize("bold", (True, False)) @pytest.mark.parametrize("color", ("red", "green")) def test_markup(self, tw, bold: bool, color: str) -> None: text = tw.markup("hello", **{color: True, "bold": bold}) assert "hello" in text
def test_markup_bad(self, tw) -> None: with pytest.raises(ValueError): tw.markup("x", wronkw=3) with pytest.raises(ValueError): tw.markup("x", wronkw=0)
def test_line_write_markup(self, tw) -> None: tw.hasmarkup = True tw.line("x", bold=True) tw.write("x\n", red=True) lines = tw.getlines() if sys.platform != "win32": assert len(lines[0]) >= 2, lines assert len(lines[1]) >= 2, lines
def test_attr_fullwidth(self, tw) -> None: tw.sep("-", "hello", fullwidth=70) tw.fullwidth = 70 tw.sep("-", "hello") lines = tw.getlines() assert len(lines[0]) == len(lines[1])
@pytest.mark.skipif(sys.platform == "win32", reason="win32 has no native ansi")def test_attr_hasmarkup() -> None: file = io.StringIO() tw = terminalwriter.TerminalWriter(file) assert not tw.hasmarkup tw.hasmarkup = True tw.line("hello", bold=True) s = file.getvalue() assert len(s) > len("hello\n") assert "\x1b[1m" in s assert "\x1b[0m" in s
def assert_color(expected: bool, default: bool | None = None) -> None: file = io.StringIO() if default is None: default = not expected file.isatty = lambda: default # type: ignore tw = terminalwriter.TerminalWriter(file=file) assert tw.hasmarkup is expected tw.line("hello", bold=True) s = file.getvalue() if expected: assert len(s) > len("hello\n") assert "\x1b[1m" in s assert "\x1b[0m" in s else: assert s == "hello\n"
def test_should_do_markup_PY_COLORS_eq_1(monkeypatch: MonkeyPatch) -> None: monkeypatch.setitem(os.environ, "PY_COLORS", "1") assert_color(True)
def test_should_not_do_markup_PY_COLORS_eq_0(monkeypatch: MonkeyPatch) -> None: monkeypatch.setitem(os.environ, "PY_COLORS", "0") assert_color(False)
def test_should_not_do_markup_NO_COLOR(monkeypatch: MonkeyPatch) -> None: monkeypatch.setitem(os.environ, "NO_COLOR", "1") assert_color(False)
def test_should_do_markup_FORCE_COLOR(monkeypatch: MonkeyPatch) -> None: monkeypatch.setitem(os.environ, "FORCE_COLOR", "1") assert_color(True)
@pytest.mark.parametrize( ["NO_COLOR", "FORCE_COLOR", "expected"], [ ("1", "1", False), ("", "1", True), ("1", "", False), ],)def test_NO_COLOR_and_FORCE_COLOR( monkeypatch: MonkeyPatch, NO_COLOR: str, FORCE_COLOR: str, expected: bool,) -> None: monkeypatch.setitem(os.environ, "NO_COLOR", NO_COLOR) monkeypatch.setitem(os.environ, "FORCE_COLOR", FORCE_COLOR) assert_color(expected)
def test_empty_NO_COLOR_and_FORCE_COLOR_ignored(monkeypatch: MonkeyPatch) -> None: monkeypatch.setenv("TERM", "xterm-256color") monkeypatch.setitem(os.environ, "NO_COLOR", "") monkeypatch.setitem(os.environ, "FORCE_COLOR", "") assert_color(True, True) assert_color(False, False)
class TestTerminalWriterLineWidth: def test_init(self) -> None: tw = terminalwriter.TerminalWriter() assert tw.width_of_current_line == 0
def test_update(self) -> None: tw = terminalwriter.TerminalWriter() tw.write("hello world") assert tw.width_of_current_line == 11
def test_update_with_newline(self) -> None: tw = terminalwriter.TerminalWriter() tw.write("hello\nworld") assert tw.width_of_current_line == 5
def test_update_with_wide_text(self) -> None: tw = terminalwriter.TerminalWriter() tw.write("乇乂ㄒ尺卂 ㄒ卄丨匚匚") assert tw.width_of_current_line == 21 # 5*2 + 1 + 5*2
def test_composed(self) -> None: tw = terminalwriter.TerminalWriter() text = "café food" assert len(text) == 9 tw.write(text) assert tw.width_of_current_line == 9
def test_combining(self) -> None: tw = terminalwriter.TerminalWriter() text = "café food" assert len(text) == 10 tw.write(text) assert tw.width_of_current_line == 9
@pytest.mark.parametrize( ("has_markup", "code_highlight", "expected"), [ pytest.param( True, True, "{reset}{kw}assert{hl-reset} {number}0{hl-reset}{endline}\n", id="with markup and code_highlight", ), pytest.param( True, False, "assert 0\n", id="with markup but no code_highlight", ), pytest.param( False, True, "assert 0\n", id="without markup but with code_highlight", ), pytest.param( False, False, "assert 0\n", id="neither markup nor code_highlight", ), ],)def test_code_highlight(has_markup, code_highlight, expected, color_mapping): f = io.StringIO() tw = terminalwriter.TerminalWriter(f) tw.hasmarkup = has_markup tw.code_highlight = code_highlight tw._write_source(["assert 0"])
assert f.getvalue().splitlines(keepends=True) == color_mapping.format([expected])
with pytest.raises( ValueError, match=re.escape("indents size (2) should have same size as lines (1)"), ): tw._write_source(["assert 0"], [" ", " "])
def test_highlight_empty_source() -> None: """Don't crash trying to highlight empty source code.
Issue #11758. """ f = io.StringIO() tw = terminalwriter.TerminalWriter(f) tw.hasmarkup = True tw.code_highlight = True tw._write_source([])
assert f.getvalue() == ""12345678910111213141516171819202122232425262728293031323334353637383940from __future__ import annotations
from _pytest._io.wcwidth import wcswidthfrom _pytest._io.wcwidth import wcwidthimport pytest
@pytest.mark.parametrize( ("c", "expected"), [ ("\0", 0), ("\n", -1), ("a", 1), ("1", 1), ("א", 1), ("\u200b", 0), ("\u1abe", 0), ("\u0591", 0), ("🉐", 2), ("$", 2), # noqa: RUF001 ],)def test_wcwidth(c: str, expected: int) -> None: assert wcwidth(c) == expected
@pytest.mark.parametrize( ("s", "expected"), [ ("", 0), ("hello, world!", 13), ("hello, world!\n", -1), ("0123456789", 10), ("שלום, עולם!", 11), ("שְבֻעָיים", 6), ("🉐🉐🉐", 6), ],)def test_wcswidth(s: str, expected: int) -> None: assert wcswidth(s) == expected123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483# mypy: disable-error-code="attr-defined"# mypy: disallow-untyped-defsfrom __future__ import annotations
from collections.abc import Iteratorimport logging
from _pytest.logging import caplog_records_keyfrom _pytest.pytester import Pytesterimport pytest
logger = logging.getLogger(__name__)sublogger = logging.getLogger(__name__ + ".baz")
@pytest.fixture(autouse=True)def cleanup_disabled_logging() -> Iterator[None]: """Simple fixture that ensures that a test doesn't disable logging.
This is necessary because ``logging.disable()`` is global, so a test disabling logging and not cleaning up after will break every test that runs after it.
This behavior was moved to a fixture so that logging will be un-disabled even if the test fails an assertion. """ yield logging.disable(logging.NOTSET)
def test_fixture_help(pytester: Pytester) -> None: result = pytester.runpytest("--fixtures") result.stdout.fnmatch_lines(["*caplog*"])
def test_change_level(caplog: pytest.LogCaptureFixture) -> None: caplog.set_level(logging.INFO) logger.debug("handler DEBUG level") logger.info("handler INFO level")
caplog.set_level(logging.CRITICAL, logger=sublogger.name) sublogger.warning("logger WARNING level") sublogger.critical("logger CRITICAL level")
assert "DEBUG" not in caplog.text assert "INFO" in caplog.text assert "WARNING" not in caplog.text assert "CRITICAL" in caplog.text
def test_change_level_logging_disabled(caplog: pytest.LogCaptureFixture) -> None: logging.disable(logging.CRITICAL) assert logging.root.manager.disable == logging.CRITICAL caplog.set_level(logging.WARNING) logger.info("handler INFO level") logger.warning("handler WARNING level")
caplog.set_level(logging.CRITICAL, logger=sublogger.name) sublogger.warning("logger SUB_WARNING level") sublogger.critical("logger SUB_CRITICAL level")
assert "INFO" not in caplog.text assert "WARNING" in caplog.text assert "SUB_WARNING" not in caplog.text assert "SUB_CRITICAL" in caplog.text
def test_change_level_undo(pytester: Pytester) -> None: """Ensure that 'set_level' is undone after the end of the test.
Tests the logging output themselves (affected both by logger and handler levels). """ pytester.makepyfile( """ import logging
def test1(caplog): caplog.set_level(logging.INFO) # using + operator here so fnmatch_lines doesn't match the code in the traceback logging.info('log from ' + 'test1') assert 0
def test2(caplog): # using + operator here so fnmatch_lines doesn't match the code in the traceback logging.info('log from ' + 'test2') assert 0 """ ) result = pytester.runpytest() result.stdout.fnmatch_lines(["*log from test1*", "*2 failed in *"]) result.stdout.no_fnmatch_line("*log from test2*")
def test_change_disabled_level_undo(pytester: Pytester) -> None: """Ensure that '_force_enable_logging' in 'set_level' is undone after the end of the test.
Tests the logging output themselves (affected by disabled logging level). """ pytester.makepyfile( """ import logging
def test1(caplog): logging.disable(logging.CRITICAL) caplog.set_level(logging.INFO) # using + operator here so fnmatch_lines doesn't match the code in the traceback logging.info('log from ' + 'test1') assert 0
def test2(caplog): # using + operator here so fnmatch_lines doesn't match the code in the traceback # use logging.warning because we need a level that will show up if logging.disabled # isn't reset to ``CRITICAL`` after test1. logging.warning('log from ' + 'test2') assert 0 """ ) result = pytester.runpytest() result.stdout.fnmatch_lines(["*log from test1*", "*2 failed in *"]) result.stdout.no_fnmatch_line("*log from test2*")
def test_change_level_undoes_handler_level(pytester: Pytester) -> None: """Ensure that 'set_level' is undone after the end of the test (handler).
Issue #7569. Tests the handler level specifically. """ pytester.makepyfile( """ import logging
def test1(caplog): assert caplog.handler.level == 0 caplog.set_level(9999) caplog.set_level(41) assert caplog.handler.level == 41
def test2(caplog): assert caplog.handler.level == 0
def test3(caplog): assert caplog.handler.level == 0 caplog.set_level(43) assert caplog.handler.level == 43 """ ) result = pytester.runpytest() result.assert_outcomes(passed=3)
def test_with_statement_at_level(caplog: pytest.LogCaptureFixture) -> None: with caplog.at_level(logging.INFO): logger.debug("handler DEBUG level") logger.info("handler INFO level")
with caplog.at_level(logging.CRITICAL, logger=sublogger.name): sublogger.warning("logger WARNING level") sublogger.critical("logger CRITICAL level")
assert "DEBUG" not in caplog.text assert "INFO" in caplog.text assert "WARNING" not in caplog.text assert "CRITICAL" in caplog.text
def test_with_statement_at_level_logging_disabled( caplog: pytest.LogCaptureFixture,) -> None: logging.disable(logging.CRITICAL) assert logging.root.manager.disable == logging.CRITICAL with caplog.at_level(logging.WARNING): logger.debug("handler DEBUG level") logger.info("handler INFO level") logger.warning("handler WARNING level") logger.error("handler ERROR level") logger.critical("handler CRITICAL level")
assert logging.root.manager.disable == logging.INFO
with caplog.at_level(logging.CRITICAL, logger=sublogger.name): sublogger.warning("logger SUB_WARNING level") sublogger.critical("logger SUB_CRITICAL level")
assert "DEBUG" not in caplog.text assert "INFO" not in caplog.text assert "WARNING" in caplog.text assert "ERROR" in caplog.text assert " CRITICAL" in caplog.text assert "SUB_WARNING" not in caplog.text assert "SUB_CRITICAL" in caplog.text assert logging.root.manager.disable == logging.CRITICAL
def test_with_statement_filtering(caplog: pytest.LogCaptureFixture) -> None: class TestFilter(logging.Filter): def filter(self, record: logging.LogRecord) -> bool: record.msg = "filtered handler call" return True
with caplog.at_level(logging.INFO): with caplog.filtering(TestFilter()): logger.info("handler call") logger.info("handler call")
filtered_tuple, unfiltered_tuple = caplog.record_tuples assert filtered_tuple == ("test_fixture", 20, "filtered handler call") assert unfiltered_tuple == ("test_fixture", 20, "handler call")
@pytest.mark.parametrize( "level_str,expected_disable_level", [ ("CRITICAL", logging.ERROR), ("ERROR", logging.WARNING), ("WARNING", logging.INFO), ("INFO", logging.DEBUG), ("DEBUG", logging.NOTSET), ("NOTSET", logging.NOTSET), ("NOTVALIDLEVEL", logging.NOTSET), ],)def test_force_enable_logging_level_string( caplog: pytest.LogCaptureFixture, level_str: str, expected_disable_level: int) -> None: """Test _force_enable_logging using a level string.
``expected_disable_level`` is one level below ``level_str`` because the disabled log level always needs to be *at least* one level lower than the level that caplog is trying to capture. """ test_logger = logging.getLogger("test_str_level_force_enable") # Emulate a testing environment where all logging is disabled. logging.disable(logging.CRITICAL) # Make sure all logging is disabled. assert not test_logger.isEnabledFor(logging.CRITICAL) # Un-disable logging for `level_str`. caplog._force_enable_logging(level_str, test_logger) # Make sure that the disabled level is now one below the requested logging level. # We don't use `isEnabledFor` here because that also checks the level set by # `logging.setLevel()` which is irrelevant to `logging.disable()`. assert test_logger.manager.disable == expected_disable_level
def test_log_access(caplog: pytest.LogCaptureFixture) -> None: caplog.set_level(logging.INFO) logger.info("boo %s", "arg") assert caplog.records[0].levelname == "INFO" assert caplog.records[0].msg == "boo %s" assert "boo arg" in caplog.text
def test_messages(caplog: pytest.LogCaptureFixture) -> None: caplog.set_level(logging.INFO) logger.info("boo %s", "arg") logger.info("bar %s\nbaz %s", "arg1", "arg2") assert "boo arg" == caplog.messages[0] assert "bar arg1\nbaz arg2" == caplog.messages[1] assert caplog.text.count("\n") > len(caplog.messages) assert len(caplog.text.splitlines()) > len(caplog.messages)
try: raise Exception("test") except Exception: logger.exception("oops")
assert "oops" in caplog.text assert "oops" in caplog.messages[-1] # Tracebacks are stored in the record and not added until the formatter or handler. assert "Exception" in caplog.text assert "Exception" not in caplog.messages[-1]
def test_record_tuples(caplog: pytest.LogCaptureFixture) -> None: caplog.set_level(logging.INFO) logger.info("boo %s", "arg")
assert caplog.record_tuples == [(__name__, logging.INFO, "boo arg")]
def test_unicode(caplog: pytest.LogCaptureFixture) -> None: caplog.set_level(logging.INFO) logger.info("bū") assert caplog.records[0].levelname == "INFO" assert caplog.records[0].msg == "bū" assert "bū" in caplog.text
def test_clear(caplog: pytest.LogCaptureFixture) -> None: caplog.set_level(logging.INFO) logger.info("bū") assert len(caplog.records) assert caplog.text caplog.clear() assert not len(caplog.records) assert not caplog.text
@pytest.fixturedef logging_during_setup_and_teardown( caplog: pytest.LogCaptureFixture,) -> Iterator[None]: caplog.set_level("INFO") logger.info("a_setup_log") yield logger.info("a_teardown_log") assert [x.message for x in caplog.get_records("teardown")] == ["a_teardown_log"]
def private_assert_caplog_records_is_setup_call( caplog: pytest.LogCaptureFixture,) -> None: # This reaches into private API, don't use this type of thing in real tests! caplog_records = caplog._item.stash[caplog_records_key] assert set(caplog_records) == {"setup", "call"}
def test_captures_for_all_stages( caplog: pytest.LogCaptureFixture, logging_during_setup_and_teardown: None) -> None: assert not caplog.records assert not caplog.get_records("call") logger.info("a_call_log") assert [x.message for x in caplog.get_records("call")] == ["a_call_log"]
assert [x.message for x in caplog.get_records("setup")] == ["a_setup_log"]
private_assert_caplog_records_is_setup_call(caplog)
def test_clear_for_call_stage( caplog: pytest.LogCaptureFixture, logging_during_setup_and_teardown: None) -> None: logger.info("a_call_log") assert [x.message for x in caplog.get_records("call")] == ["a_call_log"] assert [x.message for x in caplog.get_records("setup")] == ["a_setup_log"] private_assert_caplog_records_is_setup_call(caplog)
caplog.clear()
assert caplog.get_records("call") == [] assert [x.message for x in caplog.get_records("setup")] == ["a_setup_log"] private_assert_caplog_records_is_setup_call(caplog)
logging.info("a_call_log_after_clear") assert [x.message for x in caplog.get_records("call")] == ["a_call_log_after_clear"] assert [x.message for x in caplog.get_records("setup")] == ["a_setup_log"] private_assert_caplog_records_is_setup_call(caplog)
def test_ini_controls_global_log_level(pytester: Pytester) -> None: pytester.makepyfile( """ import pytest import logging def test_log_level_override(request, caplog): plugin = request.config.pluginmanager.getplugin('logging-plugin') assert plugin.log_level == logging.ERROR logger = logging.getLogger('catchlog') logger.warning("WARNING message won't be shown") logger.error("ERROR message will be shown") assert 'WARNING' not in caplog.text assert 'ERROR' in caplog.text """ ) pytester.makeini( """ [pytest] log_level=ERROR """ )
result = pytester.runpytest() # make sure that we get a '0' exit code for the testsuite assert result.ret == 0
def test_can_override_global_log_level(pytester: Pytester) -> None: pytester.makepyfile( """ import pytest import logging def test_log_level_override(request, caplog): logger = logging.getLogger('catchlog') plugin = request.config.pluginmanager.getplugin('logging-plugin') assert plugin.log_level == logging.WARNING
logger.info("INFO message won't be shown")
caplog.set_level(logging.INFO, logger.name)
with caplog.at_level(logging.DEBUG, logger.name): logger.debug("DEBUG message will be shown")
logger.debug("DEBUG message won't be shown")
with caplog.at_level(logging.CRITICAL, logger.name): logger.warning("WARNING message won't be shown")
logger.debug("DEBUG message won't be shown") logger.info("INFO message will be shown")
assert "message won't be shown" not in caplog.text """ ) pytester.makeini( """ [pytest] log_level=WARNING """ )
result = pytester.runpytest() assert result.ret == 0
def test_captures_despite_exception(pytester: Pytester) -> None: pytester.makepyfile( """ import pytest import logging def test_log_level_override(request, caplog): logger = logging.getLogger('catchlog') plugin = request.config.pluginmanager.getplugin('logging-plugin') assert plugin.log_level == logging.WARNING
logger.error("ERROR message " + "will be shown")
with caplog.at_level(logging.DEBUG, logger.name): logger.debug("DEBUG message " + "won't be shown") raise Exception() """ ) pytester.makeini( """ [pytest] log_level=WARNING """ )
result = pytester.runpytest() result.stdout.fnmatch_lines(["*ERROR message will be shown*"]) result.stdout.no_fnmatch_line("*DEBUG message won't be shown*") assert result.ret == 1
def test_log_report_captures_according_to_config_option_upon_failure( pytester: Pytester,) -> None: """Test that upon failure: (1) `caplog` succeeded to capture the DEBUG message and assert on it => No `Exception` is raised. (2) The `DEBUG` message does NOT appear in the `Captured log call` report. (3) The stdout, `INFO`, and `WARNING` messages DO appear in the test reports due to `--log-level=INFO`. """ pytester.makepyfile( """ import pytest import logging
def function_that_logs(): logging.debug('DEBUG log ' + 'message') logging.info('INFO log ' + 'message') logging.warning('WARNING log ' + 'message') print('Print ' + 'message')
def test_that_fails(request, caplog): plugin = request.config.pluginmanager.getplugin('logging-plugin') assert plugin.log_level == logging.INFO
with caplog.at_level(logging.DEBUG): function_that_logs()
if 'DEBUG log ' + 'message' not in caplog.text: raise Exception('caplog failed to ' + 'capture DEBUG')
assert False """ )
result = pytester.runpytest("--log-level=INFO") result.stdout.no_fnmatch_line("*Exception: caplog failed to capture DEBUG*") result.stdout.no_fnmatch_line("*DEBUG log message*") result.stdout.fnmatch_lines( ["*Print message*", "*INFO log message*", "*WARNING log message*"] ) assert result.ret == 1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175from __future__ import annotations
import loggingfrom typing import Any
from _pytest._io import TerminalWriterfrom _pytest.logging import ColoredLevelFormatter
def test_coloredlogformatter() -> None: logfmt = "%(filename)-25s %(lineno)4d %(levelname)-8s %(message)s"
record = logging.LogRecord( name="dummy", level=logging.INFO, pathname="dummypath", lineno=10, msg="Test Message", args=(), exc_info=None, )
tw = TerminalWriter() tw.hasmarkup = True formatter = ColoredLevelFormatter(tw, logfmt) output = formatter.format(record) assert output == ( "dummypath 10 \x1b[32mINFO \x1b[0m Test Message" )
tw.hasmarkup = False formatter = ColoredLevelFormatter(tw, logfmt) output = formatter.format(record) assert output == ("dummypath 10 INFO Test Message")
def test_coloredlogformatter_with_width_precision() -> None: logfmt = "%(filename)-25s %(lineno)4d %(levelname)-8.8s %(message)s"
record = logging.LogRecord( name="dummy", level=logging.INFO, pathname="dummypath", lineno=10, msg="Test Message", args=(), exc_info=None, )
tw = TerminalWriter() tw.hasmarkup = True formatter = ColoredLevelFormatter(tw, logfmt) output = formatter.format(record) assert output == ( "dummypath 10 \x1b[32mINFO \x1b[0m Test Message" )
tw.hasmarkup = False formatter = ColoredLevelFormatter(tw, logfmt) output = formatter.format(record) assert output == ("dummypath 10 INFO Test Message")
def test_multiline_message() -> None: from _pytest.logging import PercentStyleMultiline
logfmt = "%(filename)-25s %(lineno)4d %(levelname)-8s %(message)s"
record: Any = logging.LogRecord( name="dummy", level=logging.INFO, pathname="dummypath", lineno=10, msg="Test Message line1\nline2", args=(), exc_info=None, ) # this is called by logging.Formatter.format record.message = record.getMessage()
ai_on_style = PercentStyleMultiline(logfmt, True) output = ai_on_style.format(record) assert output == ( "dummypath 10 INFO Test Message line1\n" " line2" )
ai_off_style = PercentStyleMultiline(logfmt, False) output = ai_off_style.format(record) assert output == ( "dummypath 10 INFO Test Message line1\nline2" )
ai_none_style = PercentStyleMultiline(logfmt, None) output = ai_none_style.format(record) assert output == ( "dummypath 10 INFO Test Message line1\nline2" )
record.auto_indent = False output = ai_on_style.format(record) assert output == ( "dummypath 10 INFO Test Message line1\nline2" )
record.auto_indent = True output = ai_off_style.format(record) assert output == ( "dummypath 10 INFO Test Message line1\n" " line2" )
record.auto_indent = "False" output = ai_on_style.format(record) assert output == ( "dummypath 10 INFO Test Message line1\nline2" )
record.auto_indent = "True" output = ai_off_style.format(record) assert output == ( "dummypath 10 INFO Test Message line1\n" " line2" )
# bad string values default to False record.auto_indent = "junk" output = ai_off_style.format(record) assert output == ( "dummypath 10 INFO Test Message line1\nline2" )
# anything other than string or int will default to False record.auto_indent = dict() output = ai_off_style.format(record) assert output == ( "dummypath 10 INFO Test Message line1\nline2" )
record.auto_indent = "5" output = ai_off_style.format(record) assert output == ( "dummypath 10 INFO Test Message line1\n line2" )
record.auto_indent = 5 output = ai_off_style.format(record) assert output == ( "dummypath 10 INFO Test Message line1\n line2" )
def test_colored_short_level() -> None: logfmt = "%(levelname).1s %(message)s"
record = logging.LogRecord( name="dummy", level=logging.INFO, pathname="dummypath", lineno=10, msg="Test Message", args=(), exc_info=None, )
class ColorConfig: class option: pass
tw = TerminalWriter() tw.hasmarkup = True formatter = ColoredLevelFormatter(tw, logfmt) output = formatter.format(record) # the I (of INFO) is colored assert output == ("\x1b[32mI\x1b[0m Test Message")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549# mypy: allow-untyped-defsfrom __future__ import annotations
import ioimport osimport refrom typing import cast
from _pytest.capture import CaptureManagerfrom _pytest.config import ExitCodefrom _pytest.fixtures import FixtureRequestfrom _pytest.pytester import Pytesterfrom _pytest.terminal import TerminalReporterimport pytest
def test_nothing_logged(pytester: Pytester) -> None: pytester.makepyfile( """ import sys
def test_foo(): sys.stdout.write('text going to stdout') sys.stderr.write('text going to stderr') assert False """ ) result = pytester.runpytest() assert result.ret == 1 result.stdout.fnmatch_lines(["*- Captured stdout call -*", "text going to stdout"]) result.stdout.fnmatch_lines(["*- Captured stderr call -*", "text going to stderr"]) with pytest.raises(pytest.fail.Exception): result.stdout.fnmatch_lines(["*- Captured *log call -*"])
def test_messages_logged(pytester: Pytester) -> None: pytester.makepyfile( """ import sys import logging
logger = logging.getLogger(__name__)
def test_foo(): sys.stdout.write('text going to stdout') sys.stderr.write('text going to stderr') logger.info('text going to logger') assert False """ ) result = pytester.runpytest("--log-level=INFO") assert result.ret == 1 result.stdout.fnmatch_lines(["*- Captured *log call -*", "*text going to logger*"]) result.stdout.fnmatch_lines(["*- Captured stdout call -*", "text going to stdout"]) result.stdout.fnmatch_lines(["*- Captured stderr call -*", "text going to stderr"])
def test_root_logger_affected(pytester: Pytester) -> None: pytester.makepyfile( """ import logging logger = logging.getLogger()
def test_foo(): logger.info('info text ' + 'going to logger') logger.warning('warning text ' + 'going to logger') logger.error('error text ' + 'going to logger')
assert 0 """ ) log_file = str(pytester.path.joinpath("pytest.log")) result = pytester.runpytest("--log-level=ERROR", "--log-file=pytest.log") assert result.ret == 1
# The capture log calls in the stdout section only contain the # logger.error msg, because of --log-level=ERROR. result.stdout.fnmatch_lines(["*error text going to logger*"]) stdout = result.stdout.str() assert "warning text going to logger" not in stdout assert "info text going to logger" not in stdout
# The log file should only contain the error log messages and # not the warning or info ones, because the root logger is set to # ERROR using --log-level=ERROR. assert os.path.isfile(log_file) with open(log_file, encoding="utf-8") as rfh: contents = rfh.read() assert "info text going to logger" not in contents assert "warning text going to logger" not in contents assert "error text going to logger" in contents
def test_log_cli_level_log_level_interaction(pytester: Pytester) -> None: pytester.makepyfile( """ import logging logger = logging.getLogger()
def test_foo(): logger.debug('debug text ' + 'going to logger') logger.info('info text ' + 'going to logger') logger.warning('warning text ' + 'going to logger') logger.error('error text ' + 'going to logger') assert 0 """ )
result = pytester.runpytest("--log-cli-level=INFO", "--log-level=ERROR") assert result.ret == 1
result.stdout.fnmatch_lines( [ "*-- live log call --*", "*INFO*info text going to logger", "*WARNING*warning text going to logger", "*ERROR*error text going to logger", "=* 1 failed in *=", ] ) result.stdout.no_re_match_line("DEBUG")
def test_setup_logging(pytester: Pytester) -> None: pytester.makepyfile( """ import logging
logger = logging.getLogger(__name__)
def setup_function(function): logger.info('text going to logger from setup')
def test_foo(): logger.info('text going to logger from call') assert False """ ) result = pytester.runpytest("--log-level=INFO") assert result.ret == 1 result.stdout.fnmatch_lines( [ "*- Captured *log setup -*", "*text going to logger from setup*", "*- Captured *log call -*", "*text going to logger from call*", ] )
def test_teardown_logging(pytester: Pytester) -> None: pytester.makepyfile( """ import logging
logger = logging.getLogger(__name__)
def test_foo(): logger.info('text going to logger from call')
def teardown_function(function): logger.info('text going to logger from teardown') assert False """ ) result = pytester.runpytest("--log-level=INFO") assert result.ret == 1 result.stdout.fnmatch_lines( [ "*- Captured *log call -*", "*text going to logger from call*", "*- Captured *log teardown -*", "*text going to logger from teardown*", ] )
@pytest.mark.parametrize("enabled", [True, False])def test_log_cli_enabled_disabled(pytester: Pytester, enabled: bool) -> None: msg = "critical message logged by test" pytester.makepyfile( f""" import logging def test_log_cli(): logging.critical("{msg}") """ ) if enabled: pytester.makeini( """ [pytest] log_cli=true """ ) result = pytester.runpytest() if enabled: result.stdout.fnmatch_lines( [ "test_log_cli_enabled_disabled.py::test_log_cli ", "*-- live log call --*", "CRITICAL *test_log_cli_enabled_disabled.py* critical message logged by test", "PASSED*", ] ) else: assert msg not in result.stdout.str()
def test_log_cli_default_level(pytester: Pytester) -> None: # Default log file level pytester.makepyfile( """ import pytest import logging def test_log_cli(request): plugin = request.config.pluginmanager.getplugin('logging-plugin') assert plugin.log_cli_handler.level == logging.NOTSET logging.getLogger('catchlog').info("INFO message won't be shown") logging.getLogger('catchlog').warning("WARNING message will be shown") """ ) pytester.makeini( """ [pytest] log_cli=true """ )
result = pytester.runpytest()
# fnmatch_lines does an assertion internally result.stdout.fnmatch_lines( [ "test_log_cli_default_level.py::test_log_cli ", "WARNING*test_log_cli_default_level.py* message will be shown*", ] ) result.stdout.no_fnmatch_line("*INFO message won't be shown*") # make sure that we get a '0' exit code for the testsuite assert result.ret == 0
def test_log_cli_default_level_multiple_tests( pytester: Pytester, request: FixtureRequest) -> None: """Ensure we reset the first newline added by the live logger between tests""" filename = request.node.name + ".py" pytester.makepyfile( """ import logging
def test_log_1(): logging.warning("log message from test_log_1")
def test_log_2(): logging.warning("log message from test_log_2") """ ) pytester.makeini( """ [pytest] log_cli=true """ )
result = pytester.runpytest() result.stdout.fnmatch_lines( [ f"{filename}::test_log_1 ", "*WARNING*log message from test_log_1*", "PASSED *50%*", f"{filename}::test_log_2 ", "*WARNING*log message from test_log_2*", "PASSED *100%*", "=* 2 passed in *=", ] )
def test_log_cli_default_level_sections( pytester: Pytester, request: FixtureRequest) -> None: """Check that with live logging enable we are printing the correct headers during start/setup/call/teardown/finish.""" filename = request.node.name + ".py" pytester.makeconftest( """ import pytest import logging
def pytest_runtest_logstart(): logging.warning('>>>>> START >>>>>')
def pytest_runtest_logfinish(): logging.warning('<<<<< END <<<<<<<') """ )
pytester.makepyfile( """ import pytest import logging
@pytest.fixture def fix(request): logging.warning("log message from setup of {}".format(request.node.name)) yield logging.warning("log message from teardown of {}".format(request.node.name))
def test_log_1(fix): logging.warning("log message from test_log_1")
def test_log_2(fix): logging.warning("log message from test_log_2") """ ) pytester.makeini( """ [pytest] log_cli=true """ )
result = pytester.runpytest() result.stdout.fnmatch_lines( [ f"{filename}::test_log_1 ", "*-- live log start --*", "*WARNING* >>>>> START >>>>>*", "*-- live log setup --*", "*WARNING*log message from setup of test_log_1*", "*-- live log call --*", "*WARNING*log message from test_log_1*", "PASSED *50%*", "*-- live log teardown --*", "*WARNING*log message from teardown of test_log_1*", "*-- live log finish --*", "*WARNING* <<<<< END <<<<<<<*", f"{filename}::test_log_2 ", "*-- live log start --*", "*WARNING* >>>>> START >>>>>*", "*-- live log setup --*", "*WARNING*log message from setup of test_log_2*", "*-- live log call --*", "*WARNING*log message from test_log_2*", "PASSED *100%*", "*-- live log teardown --*", "*WARNING*log message from teardown of test_log_2*", "*-- live log finish --*", "*WARNING* <<<<< END <<<<<<<*", "=* 2 passed in *=", ] )
def test_live_logs_unknown_sections( pytester: Pytester, request: FixtureRequest) -> None: """Check that with live logging enable we are printing the correct headers during start/setup/call/teardown/finish.""" filename = request.node.name + ".py" pytester.makeconftest( """ import pytest import logging
def pytest_runtest_protocol(item, nextitem): logging.warning('Unknown Section!')
def pytest_runtest_logstart(): logging.warning('>>>>> START >>>>>')
def pytest_runtest_logfinish(): logging.warning('<<<<< END <<<<<<<') """ )
pytester.makepyfile( """ import pytest import logging
@pytest.fixture def fix(request): logging.warning("log message from setup of {}".format(request.node.name)) yield logging.warning("log message from teardown of {}".format(request.node.name))
def test_log_1(fix): logging.warning("log message from test_log_1")
""" ) pytester.makeini( """ [pytest] log_cli=true """ )
result = pytester.runpytest() result.stdout.fnmatch_lines( [ "*WARNING*Unknown Section*", f"{filename}::test_log_1 ", "*WARNING* >>>>> START >>>>>*", "*-- live log setup --*", "*WARNING*log message from setup of test_log_1*", "*-- live log call --*", "*WARNING*log message from test_log_1*", "PASSED *100%*", "*-- live log teardown --*", "*WARNING*log message from teardown of test_log_1*", "*WARNING* <<<<< END <<<<<<<*", "=* 1 passed in *=", ] )
def test_sections_single_new_line_after_test_outcome( pytester: Pytester, request: FixtureRequest) -> None: """Check that only a single new line is written between log messages during teardown/finish.""" filename = request.node.name + ".py" pytester.makeconftest( """ import pytest import logging
def pytest_runtest_logstart(): logging.warning('>>>>> START >>>>>')
def pytest_runtest_logfinish(): logging.warning('<<<<< END <<<<<<<') logging.warning('<<<<< END <<<<<<<') """ )
pytester.makepyfile( """ import pytest import logging
@pytest.fixture def fix(request): logging.warning("log message from setup of {}".format(request.node.name)) yield logging.warning("log message from teardown of {}".format(request.node.name)) logging.warning("log message from teardown of {}".format(request.node.name))
def test_log_1(fix): logging.warning("log message from test_log_1") """ ) pytester.makeini( """ [pytest] log_cli=true """ )
result = pytester.runpytest() result.stdout.fnmatch_lines( [ f"{filename}::test_log_1 ", "*-- live log start --*", "*WARNING* >>>>> START >>>>>*", "*-- live log setup --*", "*WARNING*log message from setup of test_log_1*", "*-- live log call --*", "*WARNING*log message from test_log_1*", "PASSED *100%*", "*-- live log teardown --*", "*WARNING*log message from teardown of test_log_1*", "*-- live log finish --*", "*WARNING* <<<<< END <<<<<<<*", "*WARNING* <<<<< END <<<<<<<*", "=* 1 passed in *=", ] ) assert ( re.search( r"(.+)live log teardown(.+)\nWARNING(.+)\nWARNING(.+)", result.stdout.str(), re.MULTILINE, ) is not None ) assert ( re.search( r"(.+)live log finish(.+)\nWARNING(.+)\nWARNING(.+)", result.stdout.str(), re.MULTILINE, ) is not None )
def test_log_cli_level(pytester: Pytester) -> None: # Default log file level pytester.makepyfile( """ import pytest import logging def test_log_cli(request): plugin = request.config.pluginmanager.getplugin('logging-plugin') assert plugin.log_cli_handler.level == logging.INFO logging.getLogger('catchlog').debug("This log message won't be shown") logging.getLogger('catchlog').info("This log message will be shown") print('PASSED') """ ) pytester.makeini( """ [pytest] log_cli=true """ )
result = pytester.runpytest("-s", "--log-cli-level=INFO")
# fnmatch_lines does an assertion internally result.stdout.fnmatch_lines( [ "*test_log_cli_level.py*This log message will be shown", "PASSED", # 'PASSED' on its own line because the log message prints a new line ] ) result.stdout.no_fnmatch_line("*This log message won't be shown*")
# make sure that we get a '0' exit code for the testsuite assert result.ret == 0
result = pytester.runpytest("-s", "--log-level=INFO")
# fnmatch_lines does an assertion internally result.stdout.fnmatch_lines( [ "*test_log_cli_level.py* This log message will be shown", "PASSED", # 'PASSED' on its own line because the log message prints a new line ] ) result.stdout.no_fnmatch_line("*This log message won't be shown*")
# make sure that we get a '0' exit code for the testsuite assert result.ret == 0
def test_log_cli_ini_level(pytester: Pytester) -> None: pytester.makeini( """ [pytest] log_cli=true log_cli_level = INFO """ ) pytester.makepyfile( """ import pytest import logging def test_log_cli(request): plugin = request.config.pluginmanager.getplugin('logging-plugin') assert plugin.log_cli_handler.level == logging.INFO logging.getLogger('catchlog').debug("This log message won't be shown") logging.getLogger('catchlog').info("This log message will be shown") print('PASSED') """ )
result = pytester.runpytest("-s")
# fnmatch_lines does an assertion internally result.stdout.fnmatch_lines( [ "*test_log_cli_ini_level.py* This log message will be shown", "PASSED", # 'PASSED' on its own line because the log message prints a new line ] ) result.stdout.no_fnmatch_line("*This log message won't be shown*")
# make sure that we get a '0' exit code for the testsuite assert result.ret == 0
@pytest.mark.parametrize( "cli_args", ["", "--log-level=WARNING", "--log-file-level=WARNING", "--log-cli-level=WARNING"],)def test_log_cli_auto_enable(pytester: Pytester, cli_args: str) -> None: """Check that live logs are enabled if --log-level or --log-cli-level is passed on the CLI.
It should not be auto enabled if the same configs are set on the configuration file. """ pytester.makepyfile( """ import logging
def test_log_1(): logging.info("log message from test_log_1 not to be shown") logging.warning("log message from test_log_1")
""" ) pytester.makeini( """ [pytest] log_level=INFO log_cli_level=INFO """ )
result = pytester.runpytest(cli_args) stdout = result.stdout.str() if cli_args == "--log-cli-level=WARNING": result.stdout.fnmatch_lines( [ "*::test_log_1 ", "*-- live log call --*", "*WARNING*log message from test_log_1*", "PASSED *100%*", "=* 1 passed in *=", ] ) assert "INFO" not in stdout else: result.stdout.fnmatch_lines( ["*test_log_cli_auto_enable*100%*", "=* 1 passed in *="] ) assert "INFO" not in stdout assert "WARNING" not in stdout
def test_log_file_cli(pytester: Pytester) -> None: # Default log file level pytester.makepyfile( """ import pytest import logging def test_log_file(request): plugin = request.config.pluginmanager.getplugin('logging-plugin') assert plugin.log_file_handler.level == logging.WARNING logging.getLogger('catchlog').info("This log message won't be shown") logging.getLogger('catchlog').warning("This log message will be shown") print('PASSED') """ )
log_file = str(pytester.path.joinpath("pytest.log"))
result = pytester.runpytest( "-s", f"--log-file={log_file}", "--log-file-level=WARNING" )
# fnmatch_lines does an assertion internally result.stdout.fnmatch_lines(["test_log_file_cli.py PASSED"])
# make sure that we get a '0' exit code for the testsuite assert result.ret == 0 assert os.path.isfile(log_file) with open(log_file, encoding="utf-8") as rfh: contents = rfh.read() assert "This log message will be shown" in contents assert "This log message won't be shown" not in contents
def test_log_file_mode_cli(pytester: Pytester) -> None: # Default log file level pytester.makepyfile( """ import pytest import logging def test_log_file(request): plugin = request.config.pluginmanager.getplugin('logging-plugin') assert plugin.log_file_handler.level == logging.WARNING logging.getLogger('catchlog').info("This log message won't be shown") logging.getLogger('catchlog').warning("This log message will be shown") print('PASSED') """ )
log_file = str(pytester.path.joinpath("pytest.log"))
with open(log_file, mode="w", encoding="utf-8") as wfh: wfh.write("A custom header\n")
result = pytester.runpytest( "-s", f"--log-file={log_file}", "--log-file-mode=a", "--log-file-level=WARNING", )
# fnmatch_lines does an assertion internally result.stdout.fnmatch_lines(["test_log_file_mode_cli.py PASSED"])
# make sure that we get a '0' exit code for the testsuite assert result.ret == 0 assert os.path.isfile(log_file) with open(log_file, encoding="utf-8") as rfh: contents = rfh.read() assert "A custom header" in contents assert "This log message will be shown" in contents assert "This log message won't be shown" not in contents
def test_log_file_mode_cli_invalid(pytester: Pytester) -> None: # Default log file level pytester.makepyfile( """ import pytest import logging def test_log_file(request): plugin = request.config.pluginmanager.getplugin('logging-plugin') assert plugin.log_file_handler.level == logging.WARNING logging.getLogger('catchlog').info("This log message won't be shown") logging.getLogger('catchlog').warning("This log message will be shown") """ )
log_file = str(pytester.path.joinpath("pytest.log"))
result = pytester.runpytest( "-s", f"--log-file={log_file}", "--log-file-mode=b", "--log-file-level=WARNING", )
# make sure that we get a '4' exit code for the testsuite assert result.ret == ExitCode.USAGE_ERROR
def test_log_file_cli_level(pytester: Pytester) -> None: # Default log file level pytester.makepyfile( """ import pytest import logging def test_log_file(request): plugin = request.config.pluginmanager.getplugin('logging-plugin') assert plugin.log_file_handler.level == logging.INFO logging.getLogger('catchlog').debug("This log message won't be shown") logging.getLogger('catchlog').info("This log message will be shown") print('PASSED') """ )
log_file = str(pytester.path.joinpath("pytest.log"))
result = pytester.runpytest("-s", f"--log-file={log_file}", "--log-file-level=INFO")
# fnmatch_lines does an assertion internally result.stdout.fnmatch_lines(["test_log_file_cli_level.py PASSED"])
# make sure that we get a '0' exit code for the testsuite assert result.ret == 0 assert os.path.isfile(log_file) with open(log_file, encoding="utf-8") as rfh: contents = rfh.read() assert "This log message will be shown" in contents assert "This log message won't be shown" not in contents
def test_log_level_not_changed_by_default(pytester: Pytester) -> None: pytester.makepyfile( """ import logging def test_log_file(): assert logging.getLogger().level == logging.WARNING """ ) result = pytester.runpytest("-s") result.stdout.fnmatch_lines(["* 1 passed in *"])
def test_log_file_ini(pytester: Pytester) -> None: log_file = str(pytester.path.joinpath("pytest.log"))
pytester.makeini( f""" [pytest] log_file={log_file} log_file_level=WARNING """ ) pytester.makepyfile( """ import pytest import logging def test_log_file(request): plugin = request.config.pluginmanager.getplugin('logging-plugin') assert plugin.log_file_handler.level == logging.WARNING logging.getLogger('catchlog').info("This log message won't be shown") logging.getLogger('catchlog').warning("This log message will be shown") print('PASSED') """ )
result = pytester.runpytest("-s")
# fnmatch_lines does an assertion internally result.stdout.fnmatch_lines(["test_log_file_ini.py PASSED"])
# make sure that we get a '0' exit code for the testsuite assert result.ret == 0 assert os.path.isfile(log_file) with open(log_file, encoding="utf-8") as rfh: contents = rfh.read() assert "This log message will be shown" in contents assert "This log message won't be shown" not in contents
def test_log_file_mode_ini(pytester: Pytester) -> None: log_file = str(pytester.path.joinpath("pytest.log"))
pytester.makeini( f""" [pytest] log_file={log_file} log_file_mode=a log_file_level=WARNING """ ) pytester.makepyfile( """ import pytest import logging def test_log_file(request): plugin = request.config.pluginmanager.getplugin('logging-plugin') assert plugin.log_file_handler.level == logging.WARNING logging.getLogger('catchlog').info("This log message won't be shown") logging.getLogger('catchlog').warning("This log message will be shown") print('PASSED') """ )
with open(log_file, mode="w", encoding="utf-8") as wfh: wfh.write("A custom header\n")
result = pytester.runpytest("-s")
# fnmatch_lines does an assertion internally result.stdout.fnmatch_lines(["test_log_file_mode_ini.py PASSED"])
assert result.ret == ExitCode.OK assert os.path.isfile(log_file) with open(log_file, encoding="utf-8") as rfh: contents = rfh.read() assert "A custom header" in contents assert "This log message will be shown" in contents assert "This log message won't be shown" not in contents
def test_log_file_ini_level(pytester: Pytester) -> None: log_file = str(pytester.path.joinpath("pytest.log"))
pytester.makeini( f""" [pytest] log_file={log_file} log_file_level = INFO """ ) pytester.makepyfile( """ import pytest import logging def test_log_file(request): plugin = request.config.pluginmanager.getplugin('logging-plugin') assert plugin.log_file_handler.level == logging.INFO logging.getLogger('catchlog').debug("This log message won't be shown") logging.getLogger('catchlog').info("This log message will be shown") print('PASSED') """ )
result = pytester.runpytest("-s")
# fnmatch_lines does an assertion internally result.stdout.fnmatch_lines(["test_log_file_ini_level.py PASSED"])
# make sure that we get a '0' exit code for the testsuite assert result.ret == 0 assert os.path.isfile(log_file) with open(log_file, encoding="utf-8") as rfh: contents = rfh.read() assert "This log message will be shown" in contents assert "This log message won't be shown" not in contents
def test_log_file_unicode(pytester: Pytester) -> None: log_file = str(pytester.path.joinpath("pytest.log"))
pytester.makeini( f""" [pytest] log_file={log_file} log_file_level = INFO """ ) pytester.makepyfile( """\ import logging
def test_log_file(): logging.getLogger('catchlog').info("Normal message") logging.getLogger('catchlog').info("├") logging.getLogger('catchlog').info("Another normal message") """ )
result = pytester.runpytest()
# make sure that we get a '0' exit code for the testsuite assert result.ret == 0 assert os.path.isfile(log_file) with open(log_file, encoding="utf-8") as rfh: contents = rfh.read() assert "Normal message" in contents assert "├" in contents assert "Another normal message" in contents
@pytest.mark.parametrize("has_capture_manager", [True, False])def test_live_logging_suspends_capture( has_capture_manager: bool, request: FixtureRequest) -> None: """Test that capture manager is suspended when we emitting messages for live logging.
This tests the implementation calls instead of behavior because it is difficult/impossible to do it using ``pytester`` facilities because they do their own capturing.
We parametrize the test to also make sure _LiveLoggingStreamHandler works correctly if no capture manager plugin is installed. """ import contextlib from functools import partial import logging
from _pytest.logging import _LiveLoggingStreamHandler
class MockCaptureManager: calls = []
@contextlib.contextmanager def global_and_fixture_disabled(self): self.calls.append("enter disabled") yield self.calls.append("exit disabled")
class DummyTerminal(io.StringIO): def section(self, *args, **kwargs): pass
out_file = cast(TerminalReporter, DummyTerminal()) capture_manager = ( cast(CaptureManager, MockCaptureManager()) if has_capture_manager else None ) handler = _LiveLoggingStreamHandler(out_file, capture_manager) handler.set_when("call")
logger = logging.getLogger(__name__ + ".test_live_logging_suspends_capture") logger.addHandler(handler) request.addfinalizer(partial(logger.removeHandler, handler))
logger.critical("some message") if has_capture_manager: assert MockCaptureManager.calls == ["enter disabled", "exit disabled"] else: assert MockCaptureManager.calls == [] assert cast(io.StringIO, out_file).getvalue() == "\nsome message\n"
def test_collection_live_logging(pytester: Pytester) -> None: pytester.makepyfile( """ import logging
logging.getLogger().info("Normal message") """ )
result = pytester.runpytest("--log-cli-level=INFO") result.stdout.fnmatch_lines( ["*--- live log collection ---*", "*Normal message*", "collected 0 items"] )
@pytest.mark.parametrize("verbose", ["", "-q", "-qq"])def test_collection_collect_only_live_logging(pytester: Pytester, verbose: str) -> None: pytester.makepyfile( """ def test_simple(): pass """ )
result = pytester.runpytest("--collect-only", "--log-cli-level=INFO", verbose)
expected_lines = []
if not verbose: expected_lines.extend( [ "*collected 1 item*", "*<Module test_collection_collect_only_live_logging.py>*", "*1 test collected*", ] ) elif verbose == "-q": result.stdout.no_fnmatch_line("*collected 1 item**") expected_lines.extend( [ "*test_collection_collect_only_live_logging.py::test_simple*", "1 test collected in [0-9].[0-9][0-9]s", ] ) elif verbose == "-qq": result.stdout.no_fnmatch_line("*collected 1 item**") expected_lines.extend(["*test_collection_collect_only_live_logging.py: 1*"])
result.stdout.fnmatch_lines(expected_lines)
def test_collection_logging_to_file(pytester: Pytester) -> None: log_file = str(pytester.path.joinpath("pytest.log"))
pytester.makeini( f""" [pytest] log_file={log_file} log_file_level = INFO """ )
pytester.makepyfile( """ import logging
logging.getLogger().info("Normal message")
def test_simple(): logging.getLogger().debug("debug message in test_simple") logging.getLogger().info("info message in test_simple") """ )
result = pytester.runpytest()
result.stdout.no_fnmatch_line("*--- live log collection ---*")
assert result.ret == 0 assert os.path.isfile(log_file) with open(log_file, encoding="utf-8") as rfh: contents = rfh.read() assert "Normal message" in contents assert "debug message in test_simple" not in contents assert "info message in test_simple" in contents
def test_log_in_hooks(pytester: Pytester) -> None: log_file = str(pytester.path.joinpath("pytest.log"))
pytester.makeini( f""" [pytest] log_file={log_file} log_file_level = INFO log_cli=true """ ) pytester.makeconftest( """ import logging
def pytest_runtestloop(session): logging.info('runtestloop')
def pytest_sessionstart(session): logging.info('sessionstart')
def pytest_sessionfinish(session, exitstatus): logging.info('sessionfinish') """ ) result = pytester.runpytest() result.stdout.fnmatch_lines(["*sessionstart*", "*runtestloop*", "*sessionfinish*"]) with open(log_file, encoding="utf-8") as rfh: contents = rfh.read() assert "sessionstart" in contents assert "runtestloop" in contents assert "sessionfinish" in contents
def test_log_in_runtest_logreport(pytester: Pytester) -> None: log_file = str(pytester.path.joinpath("pytest.log"))
pytester.makeini( f""" [pytest] log_file={log_file} log_file_level = INFO log_cli=true """ ) pytester.makeconftest( """ import logging logger = logging.getLogger(__name__)
def pytest_runtest_logreport(report): logger.info("logreport") """ ) pytester.makepyfile( """ def test_first(): assert True """ ) pytester.runpytest() with open(log_file, encoding="utf-8") as rfh: contents = rfh.read() assert contents.count("logreport") == 3
def test_log_set_path(pytester: Pytester) -> None: report_dir_base = str(pytester.path)
pytester.makeini( """ [pytest] log_file_level = DEBUG log_cli=true """ ) pytester.makeconftest( f""" import os import pytest @pytest.hookimpl(wrapper=True, tryfirst=True) def pytest_runtest_setup(item): config = item.config logging_plugin = config.pluginmanager.get_plugin("logging-plugin") report_file = os.path.join({report_dir_base!r}, item._request.node.name) logging_plugin.set_log_path(report_file) return (yield) """ ) pytester.makepyfile( """ import logging logger = logging.getLogger("testcase-logger") def test_first(): logger.info("message from test 1") assert True
def test_second(): logger.debug("message from test 2") assert True """ ) pytester.runpytest() with open(os.path.join(report_dir_base, "test_first"), encoding="utf-8") as rfh: content = rfh.read() assert "message from test 1" in content
with open(os.path.join(report_dir_base, "test_second"), encoding="utf-8") as rfh: content = rfh.read() assert "message from test 2" in content
def test_log_set_path_with_log_file_mode(pytester: Pytester) -> None: report_dir_base = str(pytester.path)
pytester.makeini( """ [pytest] log_file_level = DEBUG log_cli=true log_file_mode=a """ ) pytester.makeconftest( f""" import os import pytest @pytest.hookimpl(wrapper=True, tryfirst=True) def pytest_runtest_setup(item): config = item.config logging_plugin = config.pluginmanager.get_plugin("logging-plugin") report_file = os.path.join({report_dir_base!r}, item._request.node.name) logging_plugin.set_log_path(report_file) return (yield) """ ) pytester.makepyfile( """ import logging logger = logging.getLogger("testcase-logger") def test_first(): logger.info("message from test 1") assert True
def test_second(): logger.debug("message from test 2") assert True """ )
test_first_log_file = os.path.join(report_dir_base, "test_first") test_second_log_file = os.path.join(report_dir_base, "test_second") with open(test_first_log_file, mode="w", encoding="utf-8") as wfh: wfh.write("A custom header for test 1\n")
with open(test_second_log_file, mode="w", encoding="utf-8") as wfh: wfh.write("A custom header for test 2\n")
result = pytester.runpytest() assert result.ret == ExitCode.OK
with open(test_first_log_file, encoding="utf-8") as rfh: content = rfh.read() assert "A custom header for test 1" in content assert "message from test 1" in content
with open(test_second_log_file, encoding="utf-8") as rfh: content = rfh.read() assert "A custom header for test 2" in content assert "message from test 2" in content
def test_colored_captured_log(pytester: Pytester) -> None: """Test that the level names of captured log messages of a failing test are colored.""" pytester.makepyfile( """ import logging
logger = logging.getLogger(__name__)
def test_foo(): logger.info('text going to logger from call') assert False """ ) result = pytester.runpytest("--log-level=INFO", "--color=yes") assert result.ret == 1 result.stdout.fnmatch_lines( [ "*-- Captured log call --*", "\x1b[32mINFO \x1b[0m*text going to logger from call", ] )
def test_colored_ansi_esc_caplogtext(pytester: Pytester) -> None: """Make sure that caplog.text does not contain ANSI escape sequences.""" pytester.makepyfile( """ import logging
logger = logging.getLogger(__name__)
def test_foo(caplog): logger.info('text going to logger from call') assert '\x1b' not in caplog.text """ ) result = pytester.runpytest("--log-level=INFO", "--color=yes") assert result.ret == 0
def test_logging_emit_error(pytester: Pytester) -> None: """An exception raised during emit() should fail the test.
The default behavior of logging is to print "Logging error" to stderr with the call stack and some extra details.
pytest overrides this behavior to propagate the exception. """ pytester.makepyfile( """ import logging
def test_bad_log(): logging.warning('oops', 'first', 2) """ ) result = pytester.runpytest() result.assert_outcomes(failed=1) result.stdout.fnmatch_lines( [ "====* FAILURES *====", "*not all arguments converted during string formatting*", ] )
def test_logging_emit_error_supressed(pytester: Pytester) -> None: """If logging is configured to silently ignore errors, pytest doesn't propagate errors either.""" pytester.makepyfile( """ import logging
def test_bad_log(monkeypatch): monkeypatch.setattr(logging, 'raiseExceptions', False) logging.warning('oops', 'first', 2) """ ) result = pytester.runpytest() result.assert_outcomes(passed=1)
def test_log_file_cli_subdirectories_are_successfully_created( pytester: Pytester,) -> None: path = pytester.makepyfile(""" def test_logger(): pass """) expected = os.path.join(os.path.dirname(str(path)), "foo", "bar") result = pytester.runpytest("--log-file=foo/bar/logf.log") assert "logf.log" in os.listdir(expected) assert result.ret == ExitCode.OK
def test_disable_loggers(pytester: Pytester) -> None: pytester.makepyfile( """ import logging import os disabled_log = logging.getLogger('disabled') test_log = logging.getLogger('test') def test_logger_propagation(caplog): with caplog.at_level(logging.DEBUG): disabled_log.warning("no log; no stderr") test_log.debug("Visible text!") assert caplog.record_tuples == [('test', 10, 'Visible text!')] """ ) result = pytester.runpytest("--log-disable=disabled", "-s") assert result.ret == ExitCode.OK assert not result.stderr.lines
def test_disable_loggers_does_not_propagate(pytester: Pytester) -> None: pytester.makepyfile( """ import logging import os
parent_logger = logging.getLogger("parent") child_logger = parent_logger.getChild("child")
def test_logger_propagation_to_parent(caplog): with caplog.at_level(logging.DEBUG): parent_logger.warning("some parent logger message") child_logger.warning("some child logger message") assert len(caplog.record_tuples) == 1 assert caplog.record_tuples[0][0] == "parent" assert caplog.record_tuples[0][2] == "some parent logger message" """ )
result = pytester.runpytest("--log-disable=parent.child", "-s") assert result.ret == ExitCode.OK assert not result.stderr.lines
def test_log_disabling_works_with_log_cli(pytester: Pytester) -> None: pytester.makepyfile( """ import logging disabled_log = logging.getLogger('disabled') test_log = logging.getLogger('test')
def test_log_cli_works(caplog): test_log.info("Visible text!") disabled_log.warning("This string will be suppressed.") """ ) result = pytester.runpytest( "--log-cli-level=DEBUG", "--log-disable=disabled", ) assert result.ret == ExitCode.OK result.stdout.fnmatch_lines( "INFO test:test_log_disabling_works_with_log_cli.py:6 Visible text!" ) result.stdout.no_fnmatch_line( "WARNING disabled:test_log_disabling_works_with_log_cli.py:7 This string will be suppressed." ) assert not result.stderr.lines
def test_without_date_format_log(pytester: Pytester) -> None: """Check that date is not printed by default.""" pytester.makepyfile( """ import logging
logger = logging.getLogger(__name__)
def test_foo(): logger.warning('text') assert False """ ) result = pytester.runpytest() assert result.ret == 1 result.stdout.fnmatch_lines( ["WARNING test_without_date_format_log:test_without_date_format_log.py:6 text"] )
def test_date_format_log(pytester: Pytester) -> None: """Check that log_date_format affects output.""" pytester.makepyfile( """ import logging
logger = logging.getLogger(__name__)
def test_foo(): logger.warning('text') assert False """ ) pytester.makeini( """ [pytest] log_format=%(asctime)s; %(levelname)s; %(message)s log_date_format=%Y-%m-%d %H:%M:%S """ ) result = pytester.runpytest() assert result.ret == 1 result.stdout.re_match_lines([r"^[0-9-]{10} [0-9:]{8}; WARNING; text"])
def test_date_format_percentf_log(pytester: Pytester) -> None: """Make sure that microseconds are printed in log.""" pytester.makepyfile( """ import logging
logger = logging.getLogger(__name__)
def test_foo(): logger.warning('text') assert False """ ) pytester.makeini( """ [pytest] log_format=%(asctime)s; %(levelname)s; %(message)s log_date_format=%Y-%m-%d %H:%M:%S.%f """ ) result = pytester.runpytest() assert result.ret == 1 result.stdout.re_match_lines([r"^[0-9-]{10} [0-9:]{8}.[0-9]{6}; WARNING; text"])
def test_date_format_percentf_tz_log(pytester: Pytester) -> None: """Make sure that timezone and microseconds are properly formatted together.""" pytester.makepyfile( """ import logging
logger = logging.getLogger(__name__)
def test_foo(): logger.warning('text') assert False """ ) pytester.makeini( """ [pytest] log_format=%(asctime)s; %(levelname)s; %(message)s log_date_format=%Y-%m-%d %H:%M:%S.%f%z """ ) result = pytester.runpytest() assert result.ret == 1 result.stdout.re_match_lines( [r"^[0-9-]{10} [0-9:]{8}.[0-9]{6}[+-][0-9\.]+; WARNING; text"] )
def test_log_file_cli_fallback_options(pytester: Pytester) -> None: """Make sure that fallback values for log-file formats and level works.""" pytester.makepyfile( """ import logging logger = logging.getLogger()
def test_foo(): logger.info('info text going to logger') logger.warning('warning text going to logger') logger.error('error text going to logger')
assert 0 """ ) log_file = str(pytester.path.joinpath("pytest.log")) result = pytester.runpytest( "--log-level=ERROR", "--log-format=%(asctime)s %(message)s", "--log-date-format=%H:%M", "--log-file=pytest.log", ) assert result.ret == 1
# The log file should only contain the error log messages # not the warning or info ones and the format and date format # should match the formats provided using --log-format and --log-date-format assert os.path.isfile(log_file) with open(log_file, encoding="utf-8") as rfh: contents = rfh.read() assert re.match(r"[0-9]{2}:[0-9]{2} error text going to logger\s*", contents) assert "info text going to logger" not in contents assert "warning text going to logger" not in contents assert "error text going to logger" in contents
# Try with a different format and date format to make sure that the formats # are being used result = pytester.runpytest( "--log-level=ERROR", "--log-format=%(asctime)s : %(message)s", "--log-date-format=%H:%M:%S", "--log-file=pytest.log", ) assert result.ret == 1
# The log file should only contain the error log messages # not the warning or info ones and the format and date format # should match the formats provided using --log-format and --log-date-format assert os.path.isfile(log_file) with open(log_file, encoding="utf-8") as rfh: contents = rfh.read() assert re.match( r"[0-9]{2}:[0-9]{2}:[0-9]{2} : error text going to logger\s*", contents ) assert "info text going to logger" not in contents assert "warning text going to logger" not in contents assert "error text going to logger" in contents12*.htmlassets/12345678910111213This directory contains tests and support files for smoke testing popular plugins against the current pytest version.
The objective is to gauge if any intentional or unintentional changes in pytest break plugins.
As a rule of thumb, we should add plugins here:
1. That are used at large. This might be subjective in some cases, but if answer is yes to the question: *if a new release of pytest causes pytest-X to break, will this break a ton of test suites out there?*.2. That don't have large external dependencies: such as external services.
Besides adding the plugin as dependency, we should also add a quick test which uses someminimal part of the plugin, a smoke test. Also consider reusing one of the existing tests if that'spossible.123456789Feature: Buy things with apple
Scenario: Buy fruits Given A wallet with 50
When I buy some apples for 1 And I buy some bananas for 2
Then I have 47 left123456789101112131415161718192021222324252627282930313233343536373839404142# mypy: allow-untyped-defsfrom __future__ import annotations
from pytest_bdd import givenfrom pytest_bdd import scenariofrom pytest_bdd import thenfrom pytest_bdd import when
import pytest
@scenario("bdd_wallet.feature", "Buy fruits")def test_publish(): pass
@pytest.fixturedef wallet(): class Wallet: amount = 0
return Wallet()
@given("A wallet with 50")def fill_wallet(wallet): wallet.amount = 50
@when("I buy some apples for 1")def buy_apples(wallet): wallet.amount -= 1
@when("I buy some bananas for 2")def buy_bananas(wallet): wallet.amount -= 2
@then("I have 47 left")def check(wallet): assert wallet.amount == 471234from __future__ import annotations
SECRET_KEY = "mysecret"1234567[pytest]strict_markers = Trueasyncio_mode = strictfilterwarnings = error::pytest.PytestWarning ignore:usefixtures.* without arguments has no effect:pytest.PytestWarning ignore:.*.fspath is deprecated and will be replaced by .*.path.*:pytest.PytestDeprecationWarning1234567891011# mypy: allow-untyped-defsfrom __future__ import annotations
import anyio
import pytest
@pytest.mark.anyioasync def test_sleep(): await anyio.sleep(0)1234567891011# mypy: allow-untyped-defsfrom __future__ import annotations
import asyncio
import pytest
@pytest.mark.asyncioasync def test_sleep(): await asyncio.sleep(0)123456# mypy: allow-untyped-defsfrom __future__ import annotations
def test_mocker(mocker): mocker.MagicMock()12345678910111213from __future__ import annotations
import unittest
class MyTestCase(unittest.TestCase): first_time = True
def test_fail_the_first_time(self) -> None: """Regression test for issue #12424.""" if self.first_time: type(self).first_time = False self.fail()1234567891011# mypy: allow-untyped-defsfrom __future__ import annotations
import trio
import pytest
@pytest.mark.trioasync def test_sleep(): await trio.sleep(0)123456789101112131415161718192021# mypy: allow-untyped-defsfrom __future__ import annotations
import pytest_twistedfrom twisted.internet.task import deferLater
def sleep(): import twisted.internet.reactor
return deferLater(clock=twisted.internet.reactor, delay=0)
@pytest_twisted.inlineCallbacksdef test_inlineCallbacks(): yield sleep()
@pytest_twisted.ensureDeferredasync def test_inlineCallbacks_async(): await sleep()123456789101112131415anyio[trio]==4.13.0django==6.0.4pytest-asyncio==1.3.0pytest-bdd==8.1.0pytest-cov==7.1.0pytest-django==4.12.0pytest-flakes==4.0.5pytest-html==4.2.0pytest-mock==3.15.1pytest-rerunfailures==16.1pytest-sugar==1.1.1pytest-trio==0.8.0pytest-twisted==1.14.3twisted==25.5.0pytest-xvfb==3.1.112345678910111213# mypy: allow-untyped-defsfrom __future__ import annotations
import pytest
def test_foo(): assert True
@pytest.mark.parametrize("i", range(3))def test_bar(i): assert True1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162# mypy: allow-untyped-defsfrom __future__ import annotations
from contextlib import contextmanagerimport decimalfrom decimal import Decimalfrom fractions import Fractionfrom math import inffrom math import nanfrom math import sqrtimport operatorfrom operator import eqfrom operator import neimport re
from _pytest.pytester import Pytesterfrom _pytest.python_api import _recursive_sequence_mapimport pytestfrom pytest import approx
@pytest.fixturedef mocked_doctest_runner(monkeypatch): import doctest
class MockedPdb: def __init__(self, out): pass
def set_trace(self): raise NotImplementedError("not used")
def reset(self): pass
def set_continue(self): pass
monkeypatch.setattr("doctest._OutputRedirectingPdb", MockedPdb)
class MyDocTestRunner(doctest.DocTestRunner): def report_failure(self, out, test, example, got): raise AssertionError( f"'{example.source.strip()}' evaluates to '{got.strip()}', not '{example.want.strip()}'" )
return MyDocTestRunner()
@contextmanagerdef temporary_verbosity(config, verbosity=0): original_verbosity = config.getoption("verbose") config.option.verbose = verbosity try: yield finally: config.option.verbose = original_verbosity
@pytest.fixturedef assert_approx_raises_regex(pytestconfig): def do_assert(lhs, rhs, expected_message, verbosity_level=0): import re
with temporary_verbosity(pytestconfig, verbosity_level): with pytest.raises(AssertionError) as e: assert lhs == approx(rhs)
nl = "\n" obtained_message = str(e.value).splitlines()[1:] assert len(obtained_message) == len(expected_message), ( "Regex message length doesn't match obtained.\n" "Obtained:\n" f"{nl.join(obtained_message)}\n\n" "Expected regex:\n" f"{nl.join(expected_message)}\n\n" )
for i, (obtained_line, expected_line) in enumerate( zip(obtained_message, expected_message, strict=True) ): regex = re.compile(expected_line) assert regex.match(obtained_line) is not None, ( "Unexpected error message:\n" f"{nl.join(obtained_message)}\n\n" "Did not match regex:\n" f"{nl.join(expected_message)}\n\n" f"With verbosity level = {verbosity_level}, on line {i}" )
return do_assert
SOME_FLOAT = r"[+-]?((?:([0-9]*[.])?[0-9]+(e-?[0-9]+)?)|inf|nan)\s*"SOME_INT = r"[0-9]+\s*"SOME_TOLERANCE = rf"({SOME_FLOAT}|[+-]?[0-9]+(\.[0-9]+)?[eE][+-]?[0-9]+\s*)"
class TestApprox: def test_error_messages_native_dtypes(self, assert_approx_raises_regex): # Treat bool exactly. assert_approx_raises_regex( {"a": 1.0, "b": True}, {"a": 1.0, "b": False}, [ "", " comparison failed. Mismatched elements: 1 / 2:", f" Max absolute difference: {SOME_FLOAT}", f" Max relative difference: {SOME_FLOAT}", r" Index\s+\| Obtained\s+\| Expected", r".*(True|False)\s+", ], ) assert_approx_raises_regex( 2.0, 1.0, [ "", " comparison failed", f" Obtained: {SOME_FLOAT}", f" Expected: {SOME_FLOAT} ± {SOME_TOLERANCE}", ], )
assert_approx_raises_regex( {"a": 1.0, "b": 1000.0, "c": 1000000.0}, { "a": 2.0, "b": 1000.0, "c": 3000000.0, }, [ r"", r" comparison failed. Mismatched elements: 2 / 3:", rf" Max absolute difference: {SOME_FLOAT}", rf" Max relative difference: {SOME_FLOAT}", r" Index \| Obtained\s+\| Expected\s+", rf" a \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_TOLERANCE}", rf" c \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_TOLERANCE}", ], )
assert_approx_raises_regex( {"a": 1.0, "b": None, "c": None}, { "a": None, "b": 1000.0, "c": None, }, [ r"", r" comparison failed. Mismatched elements: 2 / 3:", r" Max absolute difference: -inf", r" Max relative difference: -inf", r" Index \| Obtained\s+\| Expected\s+", rf" a \| {SOME_FLOAT} \| None", rf" b \| None\s+\| {SOME_FLOAT} ± {SOME_FLOAT}", ], )
assert_approx_raises_regex( [1.0, 2.0, 3.0, 4.0], [1.0, 3.0, 3.0, 5.0], [ r"", r" comparison failed. Mismatched elements: 2 / 4:", rf" Max absolute difference: {SOME_FLOAT}", rf" Max relative difference: {SOME_FLOAT}", r" Index \| Obtained\s+\| Expected ", rf" 1 \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}", rf" 3 \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}", ], )
assert_approx_raises_regex( (1, 2.2, 4), (1, 3.2, 4), [ r"", r" comparison failed. Mismatched elements: 1 / 3:", rf" Max absolute difference: {SOME_FLOAT}", rf" Max relative difference: {SOME_FLOAT}", r" Index \| Obtained\s+\| Expected ", rf" 1 \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}", ], )
# Specific test for comparison with 0.0 (relative diff will be 'inf') assert_approx_raises_regex( [0.0], [1.0], [ r"", r" comparison failed. Mismatched elements: 1 / 1:", rf" Max absolute difference: {SOME_FLOAT}", r" Max relative difference: inf", r" Index \| Obtained\s+\| Expected ", rf"\s*0\s*\| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}", ], )
def test_error_messages_numpy_dtypes(self, assert_approx_raises_regex): np = pytest.importorskip("numpy")
a = np.linspace(0, 100, 20) b = np.linspace(0, 100, 20) a[10] += 0.5 assert_approx_raises_regex( a, b, [ r"", r" comparison failed. Mismatched elements: 1 / 20:", rf" Max absolute difference: {SOME_FLOAT}", rf" Max relative difference: {SOME_FLOAT}", r" Index \| Obtained\s+\| Expected", rf" \(10,\) \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}", ], )
assert_approx_raises_regex( np.array( [ [[1.1987311, 12412342.3], [3.214143244, 1423412423415.677]], [[1, 2], [3, 219371297321973]], ] ), np.array( [ [[1.12313, 12412342.3], [3.214143244, 534523542345.677]], [[1, 2], [3, 7]], ] ), [ r"", r" comparison failed. Mismatched elements: 3 / 8:", rf" Max absolute difference: {SOME_FLOAT}", rf" Max relative difference: {SOME_FLOAT}", r" Index\s+\| Obtained\s+\| Expected\s+", rf" \(0, 0, 0\) \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}", rf" \(0, 1, 1\) \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}", rf" \(1, 1, 1\) \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}", ], )
# Specific test for comparison with 0.0 (relative diff will be 'inf') assert_approx_raises_regex( np.array([0.0]), np.array([1.0]), [ r"", r" comparison failed. Mismatched elements: 1 / 1:", rf" Max absolute difference: {SOME_FLOAT}", r" Max relative difference: inf", r" Index \| Obtained\s+\| Expected ", rf"\s*\(0,\)\s*\| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}", ], )
def test_error_messages_invalid_args(self, assert_approx_raises_regex): np = pytest.importorskip("numpy") with pytest.raises(AssertionError) as e: assert np.array([[1.2, 3.4], [4.0, 5.0]]) == pytest.approx( np.array([[4.0], [5.0]]) ) message = "\n".join(str(e.value).split("\n")[1:]) assert message == "\n".join( [ " ", " Impossible to compare arrays with different shapes.", " Shapes: (2, 1) and (2, 2)", ] )
with pytest.raises(AssertionError) as e: assert [1.0, 2.0, 3.0] == pytest.approx([4.0, 5.0]) message = "\n".join(str(e.value).split("\n")[1:]) assert message == "\n".join( [ " ", " Impossible to compare lists with different sizes.", " Lengths: 2 and 3", ] )
def test_error_messages_with_different_verbosity(self, assert_approx_raises_regex): np = pytest.importorskip("numpy") for v in [0, 1, 2]: # Verbosity level doesn't affect the error message for scalars assert_approx_raises_regex( 2.0, 1.0, [ "", " comparison failed", f" Obtained: {SOME_FLOAT}", f" Expected: {SOME_FLOAT} ± {SOME_FLOAT}", ], verbosity_level=v, )
a = np.linspace(1, 101, 20) b = np.linspace(2, 102, 20) assert_approx_raises_regex( a, b, [ r"^ $", r"^ comparison failed. Mismatched elements: 20 / 20:$", rf"^ Max absolute difference: {SOME_FLOAT}$", rf"^ Max relative difference: {SOME_FLOAT}$", r"^ Index \| Obtained\s+\| Expected\s+$", rf"^ \(0,\)\s+\| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}e-{SOME_INT}$", rf"^ \(1,\)\s+\| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}e-{SOME_INT}\.\.\.$", "^ $", rf"^ ...Full output truncated \({SOME_INT} lines hidden\), use '-vv' to show$", ], verbosity_level=0, )
assert_approx_raises_regex( a, b, [ r" ", r" comparison failed. Mismatched elements: 20 / 20:", rf" Max absolute difference: {SOME_FLOAT}", rf" Max relative difference: {SOME_FLOAT}", r" Index \| Obtained\s+\| Expected", ] + [ rf" \({i},\)\s+\| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}" for i in range(20) ], verbosity_level=2, )
def test_repr_string(self): assert repr(approx(1.0)) == "1.0 ± 1.0e-06" assert repr(approx([1.0, 2.0])) == "approx([1.0 ± 1.0e-06, 2.0 ± 2.0e-06])" assert repr(approx((1.0, 2.0))) == "approx((1.0 ± 1.0e-06, 2.0 ± 2.0e-06))" assert repr(approx(inf)) == "inf" assert repr(approx(1.0, rel=nan)) == "1.0 ± ???" assert repr(approx(1.0, rel=inf)) == "1.0 ± inf"
# Dictionaries aren't ordered, so we need to check both orders. assert repr(approx({"a": 1.0, "b": 2.0})) in ( "approx({'a': 1.0 ± 1.0e-06, 'b': 2.0 ± 2.0e-06})", "approx({'b': 2.0 ± 2.0e-06, 'a': 1.0 ± 1.0e-06})", )
assert repr(approx(42, abs=1)) == "42 ± 1" assert repr(approx(5, rel=0.01)) == "5 ± 0.05" assert repr(approx(24000, abs=500)) == "24000 ± 500" assert repr(approx(1500, abs=555)) == "1500 ± 555"
def test_repr_complex_numbers(self): assert repr(approx(inf + 1j)) == "(inf+1j)" assert repr(approx(1.0j, rel=inf)) == "1j ± inf"
# can't compute a sensible tolerance assert repr(approx(nan + 1j)) == "(nan+1j) ± ???"
assert repr(approx(1.0j)) == "1j ± 1.0e-06 ∠ ±180°"
# relative tolerance is scaled to |3+4j| = 5 assert repr(approx(3 + 4 * 1j)) == "(3+4j) ± 5.0e-06 ∠ ±180°"
# absolute tolerance is not scaled assert repr(approx(3.3 + 4.4 * 1j, abs=0.02)) == "(3.3+4.4j) ± 0.02 ∠ ±180°"
@pytest.mark.parametrize( "value, expected_repr_string", [ (5.0, "approx(5.0 ± 5.0e-06)"), ([5.0], "approx([5.0 ± 5.0e-06])"), ([[5.0]], "approx([[5.0 ± 5.0e-06]])"), ([[5.0, 6.0]], "approx([[5.0 ± 5.0e-06, 6.0 ± 6.0e-06]])"), ([[5.0], [6.0]], "approx([[5.0 ± 5.0e-06], [6.0 ± 6.0e-06]])"), ], ) def test_repr_nd_array(self, value, expected_repr_string): """Make sure that arrays of all different dimensions are repr'd correctly.""" np = pytest.importorskip("numpy") np_array = np.array(value) assert repr(approx(np_array)) == expected_repr_string
def test_bool(self): with pytest.raises(AssertionError) as err: assert approx(1)
assert err.match(r"approx\(\) is not supported in a boolean context")
def test_mixed_sequence(self, assert_approx_raises_regex) -> None: """Approx should work on sequences that also contain non-numbers (#13010).""" assert_approx_raises_regex( [1.1, 2, "word"], [1.0, 2, "different"], [ "", r" comparison failed. Mismatched elements: 2 / 3:", rf" Max absolute difference: {SOME_FLOAT}", rf" Max relative difference: {SOME_FLOAT}", r" Index \| Obtained\s+\| Expected\s+", r"\s*0\s*\|\s*1\.1\s*\|\s*1\.0\s*±\s*1\.0e\-06\s*", r"\s*2\s*\|\s*word\s*\|\s*different\s*", ], verbosity_level=2, ) assert_approx_raises_regex( [1.1, 2, "word"], [1.0, 2, "word"], [ "", r" comparison failed. Mismatched elements: 1 / 3:", rf" Max absolute difference: {SOME_FLOAT}", rf" Max relative difference: {SOME_FLOAT}", r" Index \| Obtained\s+\| Expected\s+", r"\s*0\s*\|\s*1\.1\s*\|\s*1\.0\s*±\s*1\.0e\-06\s*", ], verbosity_level=2, ) assert [1.1, 2, "word"] == pytest.approx([1.1, 2, "word"])
def test_operator_overloading(self): assert 1 == approx(1, rel=1e-6, abs=1e-12) assert not (1 != approx(1, rel=1e-6, abs=1e-12)) assert 10 != approx(1, rel=1e-6, abs=1e-12) assert not (10 == approx(1, rel=1e-6, abs=1e-12))
def test_exactly_equal(self): examples = [ (2.0, 2.0), (0.1e200, 0.1e200), (1.123e-300, 1.123e-300), (12345, 12345.0), (0.0, -0.0), (345678, 345678), (Decimal("1.0001"), Decimal("1.0001")), (Fraction(1, 3), Fraction(-1, -3)), ] for a, x in examples: assert a == approx(x)
def test_opposite_sign(self): examples = [(eq, 1e-100, -1e-100), (ne, 1e100, -1e100)] for op, a, x in examples: assert op(a, approx(x))
def test_zero_tolerance(self): within_1e10 = [(1.1e-100, 1e-100), (-1.1e-100, -1e-100)] for a, x in within_1e10: assert x == approx(x, rel=0.0, abs=0.0) assert a != approx(x, rel=0.0, abs=0.0) assert a == approx(x, rel=0.0, abs=5e-101) assert a != approx(x, rel=0.0, abs=5e-102) assert a == approx(x, rel=5e-1, abs=0.0) assert a != approx(x, rel=5e-2, abs=0.0)
@pytest.mark.parametrize( ("rel", "abs"), [ (-1e100, None), (None, -1e100), (1e100, -1e100), (-1e100, 1e100), (-1e100, -1e100), ], ) def test_negative_tolerance(self, rel: float | None, abs: float | None) -> None: # Negative tolerances are not allowed. with pytest.raises(ValueError): 1.1 == approx(1, rel, abs)
def test_negative_tolerance_message(self): # Error message for negative tolerance should include the value. with pytest.raises(ValueError, match="-3"): 0 == approx(1, abs=-3) with pytest.raises(ValueError, match="-3"): 0 == approx(1, rel=-3)
def test_inf_tolerance(self): # Everything should be equal if the tolerance is infinite. large_diffs = [(1, 1000), (1e-50, 1e50), (-1.0, -1e300), (0.0, 10)] for a, x in large_diffs: assert a != approx(x, rel=0.0, abs=0.0) assert a == approx(x, rel=inf, abs=0.0) assert a == approx(x, rel=0.0, abs=inf) assert a == approx(x, rel=inf, abs=inf)
def test_inf_tolerance_expecting_zero(self) -> None: # If the relative tolerance is zero but the expected value is infinite, # the actual tolerance is a NaN, which should be an error. with pytest.raises(ValueError): 1 == approx(0, rel=inf, abs=0.0) with pytest.raises(ValueError): 1 == approx(0, rel=inf, abs=inf)
def test_nan_tolerance(self) -> None: with pytest.raises(ValueError): 1.1 == approx(1, rel=nan) with pytest.raises(ValueError): 1.1 == approx(1, abs=nan) with pytest.raises(ValueError): 1.1 == approx(1, rel=nan, abs=nan)
def test_reasonable_defaults(self): # Whatever the defaults are, they should work for numbers close to 1 # than have a small amount of floating-point error. assert 0.1 + 0.2 == approx(0.3)
def test_default_tolerances(self): # This tests the defaults as they are currently set. If you change the # defaults, this test will fail but you should feel free to change it. # None of the other tests (except the doctests) should be affected by # the choice of defaults. examples = [ # Relative tolerance used. (eq, 1e100 + 1e94, 1e100), (ne, 1e100 + 2e94, 1e100), (eq, 1e0 + 1e-6, 1e0), (ne, 1e0 + 2e-6, 1e0), # Absolute tolerance used. (eq, 1e-100, +1e-106), (eq, 1e-100, +2e-106), (eq, 1e-100, 0), ] for op, a, x in examples: assert op(a, approx(x))
def test_custom_tolerances(self): assert 1e8 + 1e0 == approx(1e8, rel=5e-8, abs=5e0) assert 1e8 + 1e0 == approx(1e8, rel=5e-9, abs=5e0) assert 1e8 + 1e0 == approx(1e8, rel=5e-8, abs=5e-1) assert 1e8 + 1e0 != approx(1e8, rel=5e-9, abs=5e-1)
assert 1e0 + 1e-8 == approx(1e0, rel=5e-8, abs=5e-8) assert 1e0 + 1e-8 == approx(1e0, rel=5e-9, abs=5e-8) assert 1e0 + 1e-8 == approx(1e0, rel=5e-8, abs=5e-9) assert 1e0 + 1e-8 != approx(1e0, rel=5e-9, abs=5e-9)
assert 1e-8 + 1e-16 == approx(1e-8, rel=5e-8, abs=5e-16) assert 1e-8 + 1e-16 == approx(1e-8, rel=5e-9, abs=5e-16) assert 1e-8 + 1e-16 == approx(1e-8, rel=5e-8, abs=5e-17) assert 1e-8 + 1e-16 != approx(1e-8, rel=5e-9, abs=5e-17)
def test_relative_tolerance(self): within_1e8_rel = [(1e8 + 1e0, 1e8), (1e0 + 1e-8, 1e0), (1e-8 + 1e-16, 1e-8)] for a, x in within_1e8_rel: assert a == approx(x, rel=5e-8, abs=0.0) assert a != approx(x, rel=5e-9, abs=0.0)
def test_absolute_tolerance(self): within_1e8_abs = [(1e8 + 9e-9, 1e8), (1e0 + 9e-9, 1e0), (1e-8 + 9e-9, 1e-8)] for a, x in within_1e8_abs: assert a == approx(x, rel=0, abs=5e-8) assert a != approx(x, rel=0, abs=5e-9)
def test_expecting_zero(self): examples = [ (ne, 1e-6, 0.0), (ne, -1e-6, 0.0), (eq, 1e-12, 0.0), (eq, -1e-12, 0.0), (ne, 2e-12, 0.0), (ne, -2e-12, 0.0), (ne, inf, 0.0), (ne, nan, 0.0), ] for op, a, x in examples: assert op(a, approx(x, rel=0.0, abs=1e-12)) assert op(a, approx(x, rel=1e-6, abs=1e-12))
def test_expecting_inf(self): examples = [ (eq, inf, inf), (eq, -inf, -inf), (ne, inf, -inf), (ne, 0.0, inf), (ne, nan, inf), ] for op, a, x in examples: assert op(a, approx(x))
def test_expecting_nan(self): examples = [ (eq, nan, nan), (eq, -nan, -nan), (eq, nan, -nan), (ne, 0.0, nan), (ne, inf, nan), ] for op, a, x in examples: # Nothing is equal to NaN by default. assert a != approx(x)
# If ``nan_ok=True``, then NaN is equal to NaN. assert op(a, approx(x, nan_ok=True))
def test_int(self): within_1e6 = [(1000001, 1000000), (-1000001, -1000000)] for a, x in within_1e6: assert a == approx(x, rel=5e-6, abs=0) assert a != approx(x, rel=5e-7, abs=0) assert approx(x, rel=5e-6, abs=0) == a assert approx(x, rel=5e-7, abs=0) != a
def test_decimal(self): within_1e6 = [ (Decimal("1.000001"), Decimal("1.0")), (Decimal("-1.000001"), Decimal("-1.0")), ] for a, x in within_1e6: assert a == approx(x) assert a == approx(x, rel=Decimal("5e-6"), abs=0) assert a != approx(x, rel=Decimal("5e-7"), abs=0) assert approx(x, rel=Decimal("5e-6"), abs=0) == a assert approx(x, rel=Decimal("5e-7"), abs=0) != a assert approx(x, rel=0, abs=Decimal("5e-3")) == a assert approx(x, rel=0, abs=Decimal("5e-7")) != a
def test_fraction(self): within_1e6 = [ (1 + Fraction(1, 1000000), Fraction(1)), (-1 - Fraction(-1, 1000000), Fraction(-1)), ] for a, x in within_1e6: assert a == approx(x, rel=5e-6, abs=0) assert a != approx(x, rel=5e-7, abs=0) assert approx(x, rel=5e-6, abs=0) == a assert approx(x, rel=5e-7, abs=0) != a
def test_complex(self): within_1e6 = [ (1.000001 + 1.0j, 1.0 + 1.0j), (1.0 + 1.000001j, 1.0 + 1.0j), (-1.000001 + 1.0j, -1.0 + 1.0j), (1.0 - 1.000001j, 1.0 - 1.0j), ] for a, x in within_1e6: assert a == approx(x, rel=5e-6, abs=0) assert a != approx(x, rel=5e-7, abs=0) assert approx(x, rel=5e-6, abs=0) == a assert approx(x, rel=5e-7, abs=0) != a
def test_expecting_bool(self) -> None: assert True == approx(True) # noqa: E712 assert False == approx(False) # noqa: E712 assert True != approx(False) # noqa: E712 assert True != approx(False, abs=2) # noqa: E712 assert 1 != approx(True)
def test_expecting_bool_numpy(self) -> None: """Check approx comparing with numpy.bool (#13047).""" np = pytest.importorskip("numpy") assert np.False_ != approx(True) assert np.True_ != approx(False) assert np.True_ == approx(True) assert np.False_ == approx(False) assert np.True_ != approx(False, abs=2)
def test_list(self): actual = [1 + 1e-7, 2 + 1e-8] expected = [1, 2]
# Return false if any element is outside the tolerance. assert actual == approx(expected, rel=5e-7, abs=0) assert actual != approx(expected, rel=5e-8, abs=0) assert approx(expected, rel=5e-7, abs=0) == actual assert approx(expected, rel=5e-8, abs=0) != actual
def test_list_decimal(self): actual = [Decimal("1.000001"), Decimal("2.000001")] expected = [Decimal("1"), Decimal("2")]
assert actual == approx(expected)
def test_list_wrong_len(self): assert [1, 2] != approx([1]) assert [1, 2] != approx([1, 2, 3])
def test_tuple(self): actual = (1 + 1e-7, 2 + 1e-8) expected = (1, 2)
# Return false if any element is outside the tolerance. assert actual == approx(expected, rel=5e-7, abs=0) assert actual != approx(expected, rel=5e-8, abs=0) assert approx(expected, rel=5e-7, abs=0) == actual assert approx(expected, rel=5e-8, abs=0) != actual
def test_tuple_wrong_len(self): assert (1, 2) != approx((1,)) assert (1, 2) != approx((1, 2, 3))
def test_tuple_vs_other(self): assert 1 != approx((1,))
def test_dict(self): actual = {"a": 1 + 1e-7, "b": 2 + 1e-8} # Dictionaries became ordered in python3.6, so switch up the order here # to make sure it doesn't matter. expected = {"b": 2, "a": 1}
# Return false if any element is outside the tolerance. assert actual == approx(expected, rel=5e-7, abs=0) assert actual != approx(expected, rel=5e-8, abs=0) assert approx(expected, rel=5e-7, abs=0) == actual assert approx(expected, rel=5e-8, abs=0) != actual
def test_dict_decimal(self): actual = {"a": Decimal("1.000001"), "b": Decimal("2.000001")} # Dictionaries became ordered in python3.6, so switch up the order here # to make sure it doesn't matter. expected = {"b": Decimal("2"), "a": Decimal("1")}
assert actual == approx(expected)
def test_dict_wrong_len(self): assert {"a": 1, "b": 2} != approx({"a": 1}) assert {"a": 1, "b": 2} != approx({"a": 1, "c": 2}) assert {"a": 1, "b": 2} != approx({"a": 1, "b": 2, "c": 3})
def test_dict_nonnumeric(self): assert {"a": 1.0, "b": None} == pytest.approx({"a": 1.0, "b": None}) assert {"a": 1.0, "b": 1} != pytest.approx({"a": 1.0, "b": None}) assert {"a": 1.0, "b": True} != pytest.approx({"a": 1.0, "b": False}, abs=2)
def test_dict_vs_other(self): assert 1 != approx({"a": 0})
def test_dict_for_div_by_zero(self, assert_approx_raises_regex): assert_approx_raises_regex( {"foo": 42.0}, {"foo": 0.0}, [ r"", r" comparison failed. Mismatched elements: 1 / 1:", rf" Max absolute difference: {SOME_FLOAT}", r" Max relative difference: inf", r" Index \| Obtained\s+\| Expected ", rf" foo | {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}", ], )
def test_dict_differing_lengths(self, assert_approx_raises_regex): assert_approx_raises_regex( {"a": 0}, {"a": 0, "b": 1}, [ " ", r" Impossible to compare mappings with different sizes\.", r" Lengths: 2 and 1", ], )
def test_numpy_array(self): np = pytest.importorskip("numpy")
actual = np.array([1 + 1e-7, 2 + 1e-8]) expected = np.array([1, 2])
# Return false if any element is outside the tolerance. assert actual == approx(expected, rel=5e-7, abs=0) assert actual != approx(expected, rel=5e-8, abs=0) assert approx(expected, rel=5e-7, abs=0) == expected assert approx(expected, rel=5e-8, abs=0) != actual
# Should be able to compare lists with numpy arrays. assert list(actual) == approx(expected, rel=5e-7, abs=0) assert list(actual) != approx(expected, rel=5e-8, abs=0) assert actual == approx(list(expected), rel=5e-7, abs=0) assert actual != approx(list(expected), rel=5e-8, abs=0)
def test_numpy_tolerance_args(self): """ Check that numpy rel/abs args are handled correctly for comparison against an np.array Check both sides of the operator, hopefully it doesn't impact things. Test all permutations of where the approx and np.array() can show up """ np = pytest.importorskip("numpy") expected = 100.0 actual = 99.0 abs_diff = expected - actual rel_diff = (expected - actual) / expected
tests = [ (eq, abs_diff, 0), (eq, 0, rel_diff), (ne, 0, rel_diff / 2.0), # rel diff fail (ne, abs_diff / 2.0, 0), # abs diff fail ]
for op, _abs, _rel in tests: assert op(np.array(actual), approx(expected, abs=_abs, rel=_rel)) # a, b assert op(approx(expected, abs=_abs, rel=_rel), np.array(actual)) # b, a
assert op(actual, approx(np.array(expected), abs=_abs, rel=_rel)) # a, b assert op(approx(np.array(expected), abs=_abs, rel=_rel), actual) # b, a
assert op(np.array(actual), approx(np.array(expected), abs=_abs, rel=_rel)) assert op(approx(np.array(expected), abs=_abs, rel=_rel), np.array(actual))
def test_numpy_expecting_nan(self): np = pytest.importorskip("numpy") examples = [ (eq, nan, nan), (eq, -nan, -nan), (eq, nan, -nan), (ne, 0.0, nan), (ne, inf, nan), ] for op, a, x in examples: # Nothing is equal to NaN by default. assert np.array(a) != approx(x) assert a != approx(np.array(x))
# If ``nan_ok=True``, then NaN is equal to NaN. assert op(np.array(a), approx(x, nan_ok=True)) assert op(a, approx(np.array(x), nan_ok=True))
def test_numpy_expecting_inf(self): np = pytest.importorskip("numpy") examples = [ (eq, inf, inf), (eq, -inf, -inf), (ne, inf, -inf), (ne, 0.0, inf), (ne, nan, inf), ] for op, a, x in examples: assert op(np.array(a), approx(x)) assert op(a, approx(np.array(x))) assert op(np.array(a), approx(np.array(x)))
def test_numpy_array_wrong_shape(self): np = pytest.importorskip("numpy")
a12 = np.array([[1, 2]]) a21 = np.array([[1], [2]])
assert a12 != approx(a21) assert a21 != approx(a12)
def test_numpy_array_implicit_conversion(self): np = pytest.importorskip("numpy")
class ImplicitArray: """Type which is implicitly convertible to a numpy array."""
def __init__(self, vals): self.vals = vals
def __array__(self, dtype=None, copy=None): return np.array(self.vals)
vec1 = ImplicitArray([1.0, 2.0, 3.0]) vec2 = ImplicitArray([1.0, 2.0, 4.0]) # see issue #12114 for test case assert vec1 != approx(vec2)
def test_numpy_array_protocol(self): """ array-like objects such as tensorflow's DeviceArray are handled like ndarray. See issue #8132 """ np = pytest.importorskip("numpy")
class DeviceArray: def __init__(self, value, size): self.value = value self.size = size
def __array__(self): return self.value * np.ones(self.size)
class DeviceScalar: def __init__(self, value): self.value = value
def __array__(self): return np.array(self.value)
expected = 1 actual = 1 + 1e-6 assert approx(expected) == DeviceArray(actual, size=1) assert approx(expected) == DeviceArray(actual, size=2) assert approx(expected) == DeviceScalar(actual) assert approx(DeviceScalar(expected)) == actual assert approx(DeviceScalar(expected)) == DeviceScalar(actual)
def test_doctests(self, mocked_doctest_runner) -> None: import doctest
parser = doctest.DocTestParser() assert approx.__doc__ is not None test = parser.get_doctest( approx.__doc__, {"approx": approx}, approx.__name__, None, None ) mocked_doctest_runner.run(test)
def test_unicode_plus_minus(self, pytester: Pytester) -> None: """ Comparing approx instances inside lists should not produce an error in the detailed diff. Integration test for issue #2111. """ pytester.makepyfile( """ import pytest def test_foo(): assert [3] == [pytest.approx(4)] """ ) expected = "4.0e-06" result = pytester.runpytest() result.stdout.fnmatch_lines( [f"*At index 0 diff: 3 != 4 ± {expected}", "=* 1 failed in *="] )
@pytest.mark.parametrize( "x, name", [ pytest.param([[1]], "data structures", id="nested-list"), pytest.param({"key": {"key": 1}}, "dictionaries", id="nested-dict"), ], ) def test_expected_value_type_error(self, x, name): with pytest.raises( TypeError, match=rf"pytest.approx\(\) does not support nested {name}:", ): approx(x)
@pytest.mark.parametrize( "x", [ pytest.param(None), pytest.param("string"), pytest.param(["string"], id="nested-str"), pytest.param({"key": "string"}, id="dict-with-string"), ], ) def test_nonnumeric_okay_if_equal(self, x): assert x == approx(x)
@pytest.mark.parametrize( "x", [ pytest.param("string"), pytest.param(["string"], id="nested-str"), pytest.param({"key": "string"}, id="dict-with-string"), ], ) def test_nonnumeric_false_if_unequal(self, x): """For non-numeric types, x != pytest.approx(y) reduces to x != y""" assert "ab" != approx("abc") assert ["ab"] != approx(["abc"]) # in particular, both of these should return False assert {"a": 1.0} != approx({"a": None}) assert {"a": None} != approx({"a": 1.0})
assert 1.0 != approx(None) assert None != approx(1.0) # noqa: E711
assert 1.0 != approx([None]) assert None != approx([1.0]) # noqa: E711
def test_nonnumeric_dict_repr(self): """Dicts with non-numerics and infinites have no tolerances""" x1 = {"foo": 1.0000005, "bar": None, "foobar": inf} assert ( repr(approx(x1)) == "approx({'foo': 1.0000005 ± 1.0e-06, 'bar': None, 'foobar': inf})" )
def test_nonnumeric_list_repr(self): """Lists with non-numerics and infinites have no tolerances""" x1 = [1.0000005, None, inf] assert repr(approx(x1)) == "approx([1.0000005 ± 1.0e-06, None, inf])"
@pytest.mark.parametrize( "op", [ pytest.param(operator.le, id="<="), pytest.param(operator.lt, id="<"), pytest.param(operator.ge, id=">="), pytest.param(operator.gt, id=">"), ], ) def test_comparison_operator_type_error(self, op): """pytest.approx should raise TypeError for operators other than == and != (#2003).""" with pytest.raises(TypeError): op(1, approx(1, rel=1e-6, abs=1e-12))
def test_numpy_array_with_scalar(self): np = pytest.importorskip("numpy")
actual = np.array([1 + 1e-7, 1 - 1e-8]) expected = 1.0
assert actual == approx(expected, rel=5e-7, abs=0) assert actual != approx(expected, rel=5e-8, abs=0) assert approx(expected, rel=5e-7, abs=0) == actual assert approx(expected, rel=5e-8, abs=0) != actual
def test_numpy_scalar_with_array(self): np = pytest.importorskip("numpy")
actual = 1.0 expected = np.array([1 + 1e-7, 1 - 1e-8])
assert actual == approx(expected, rel=5e-7, abs=0) assert actual != approx(expected, rel=5e-8, abs=0) assert approx(expected, rel=5e-7, abs=0) == actual assert approx(expected, rel=5e-8, abs=0) != actual
def test_generic_ordered_sequence(self): class MySequence: def __getitem__(self, i): return [1, 2, 3, 4][i]
def __len__(self): return 4
expected = MySequence() assert [1, 2, 3, 4] == approx(expected, abs=1e-4)
expected_repr = "approx([1 ± 1.0e-06, 2 ± 2.0e-06, 3 ± 3.0e-06, 4 ± 4.0e-06])" assert repr(approx(expected)) == expected_repr
def test_decimal_approx_repr(self, monkeypatch) -> None: monkeypatch.setitem(decimal.getcontext().traps, decimal.FloatOperation, True) approx_obj = pytest.approx(decimal.Decimal("2.60")) assert decimal.Decimal("2.600001") == approx_obj
def test_allow_ordered_sequences_only(self) -> None: """pytest.approx() should raise an error on unordered sequences (#9692).""" with pytest.raises(TypeError, match="only supports ordered sequences"): assert {1, 2, 3} == approx({1, 2, 3})
def test_strange_sequence(self): """https://github.com/pytest-dev/pytest/issues/11797""" a = MyVec3(1, 2, 3) b = MyVec3(0, 1, 2)
# this would trigger the error inside the test pytest.approx(a, abs=0.5)._repr_compare(b)
assert b == pytest.approx(a, abs=2) assert b != pytest.approx(a, abs=0.5)
def test_approx_dicts_with_mismatch_on_keys(self) -> None: """https://github.com/pytest-dev/pytest/issues/13816""" expected = {"a": 1, "b": 3} actual = {"a": 1, "c": 3}
with pytest.raises( AssertionError, match=re.escape( "comparison failed.\n Mappings has different keys: " "expected dict_keys(['a', 'b']) but got dict_keys(['a', 'c'])" ), ): assert actual == approx(expected)
def test_approx_on_unordered_mapping_with_mismatch( self, pytester: Pytester ) -> None: """https://github.com/pytest-dev/pytest/issues/12444""" pytester.makepyfile( """ import pytest
def test_approx_on_unordered_mapping_with_mismatch(): expected = {"a": 1, "b": 2, "c": 3, "d": 4} actual = {"d": 4, "c": 5, "a": 8, "b": 2} assert actual == pytest.approx(expected) """ ) result = pytester.runpytest() result.assert_outcomes(failed=1) result.stdout.fnmatch_lines( [ "*comparison failed.**Mismatched elements: 2 / 4:*", "*Max absolute difference: 7*", "*Index | Obtained | Expected *", "* a * | 8 * | 1 *", "* c * | 5 * | 3 *", ] )
def test_approx_on_unordered_mapping_matching(self, pytester: Pytester) -> None: """https://github.com/pytest-dev/pytest/issues/12444""" pytester.makepyfile( """ import pytest def test_approx_on_unordered_mapping_matching(): expected = {"a": 1, "b": 2, "c": 3, "d": 4} actual = {"d": 4, "c": 3, "a": 1, "b": 2} assert actual == pytest.approx(expected) """ ) result = pytester.runpytest() result.assert_outcomes(passed=1)
class MyVec3: # incomplete """sequence like"""
_x: int _y: int _z: int
def __init__(self, x: int, y: int, z: int): self._x, self._y, self._z = x, y, z
def __repr__(self) -> str: return f"<MyVec3 {self._x} {self._y} {self._z}>"
def __len__(self) -> int: return 3
def __getitem__(self, key: int) -> int: if key == 0: return self._x if key == 1: return self._y if key == 2: return self._z raise IndexError(key)
class TestRecursiveSequenceMap: def test_map_over_scalar(self): assert _recursive_sequence_map(sqrt, 16) == 4
def test_map_over_empty_list(self): assert _recursive_sequence_map(sqrt, []) == []
def test_map_over_list(self): assert _recursive_sequence_map(sqrt, [4, 16, 25, 676]) == [2, 4, 5, 26]
def test_map_over_tuple(self): assert _recursive_sequence_map(sqrt, (4, 16, 25, 676)) == (2, 4, 5, 26)
def test_map_over_nested_lists(self): assert _recursive_sequence_map(sqrt, [4, [25, 64], [[49]]]) == [ 2, [5, 8], [[7]], ]
def test_map_over_mixed_sequence(self): assert _recursive_sequence_map(sqrt, [4, (25, 64), [49]]) == [ 2, (5, 8), [7], ]
def test_map_over_sequence_like(self): assert _recursive_sequence_map(int, MyVec3(1, 2, 3)) == [1, 2, 3]tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/issue88_initial_file_multinodes/test_hello.pyAdded+6
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/issue_519.pyAdded+54
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/junit-10.xsdAdded+147
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/marks/marks_considered_keywords/__init__.pyiAdded
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/marks/marks_considered_keywords/conftest.pyAdded
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/marks/marks_considered_keywords/test_marks_as_keywords.pyAdded+9
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/perf_examples/collect_stats/.gitignoreAdded+1
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/perf_examples/collect_stats/generate_folders.pyAdded+31
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/perf_examples/collect_stats/template_test.pyAdded+6
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/pytest.iniAdded+2
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/tmpdir/tmp_path_fixture.pyAdded+10
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_parametrized_fixture_error_message.pyAdded+17
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_setup_skip.pyAdded+17
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_setup_skip_class.pyAdded+18
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_setup_skip_module.pyAdded+16
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_unittest_asyncio.pyAdded+27
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_unittest_asynctest.pyAdded+26
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_unittest_plain_async.pyAdded+9
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/warnings/test_group_warnings_by_message.pyAdded+24
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/warnings/test_group_warnings_by_message_summary/test_1.pyAdded+24
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/warnings/test_group_warnings_by_message_summary/test_2.pyAdded+8
tasks/tasksmith-5e916b3f6da1/tests/source/testing/examples/test_issue519.pyAdded+9
tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/.gitignoreAdded+3
tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/create_executable.pyAdded+16
tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/runtests_script.pyAdded+14
tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/tests/test_doctest.txtAdded+6
tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/tests/test_trivial.pyAdded+10
tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/tox_run.pyAdded+16
tasks/tasksmith-5e916b3f6da1/tests/source/testing/io/test_pprint.pyAdded+408
tasks/tasksmith-5e916b3f6da1/tests/source/testing/io/test_saferepr.pyAdded+231
tasks/tasksmith-5e916b3f6da1/tests/source/testing/io/test_terminalwriter.pyAdded+325
tasks/tasksmith-5e916b3f6da1/tests/source/testing/io/test_wcwidth.pyAdded+40
tasks/tasksmith-5e916b3f6da1/tests/source/testing/logging/test_fixture.pyAdded+483
tasks/tasksmith-5e916b3f6da1/tests/source/testing/logging/test_formatter.pyAdded+175
tasks/tasksmith-5e916b3f6da1/tests/source/testing/logging/test_reporting.pyAdded+1549
tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/.gitignoreAdded+2
tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/README.rstAdded+13
tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/bdd_wallet.featureAdded+9
tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/bdd_wallet.pyAdded+42
tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/django_settings.pyAdded+4
tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest.iniAdded+7
tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_anyio_integration.pyAdded+11
tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_asyncio_integration.pyAdded+11
tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_mock_integration.pyAdded+6
tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_rerunfailures_integration.pyAdded+13
tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_trio_integration.pyAdded+11
tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_twisted_integration.pyAdded+21
tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/requirements.txtAdded+15
tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/simple_integration.pyAdded+13
tasks/tasksmith-5e916b3f6da1/tests/source/testing/python/approx.pyAdded+1162