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
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/issue88_initial_file_multinodes/test_hello.py +6 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/issue_519.py +54 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/junit-10.xsd +147 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/marks/marks_considered_keywords/__init__.pyi +0 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/marks/marks_considered_keywords/conftest.py +0 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/marks/marks_considered_keywords/test_marks_as_keywords.py +9 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/perf_examples/collect_stats/.gitignore +1 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/perf_examples/collect_stats/generate_folders.py +31 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/perf_examples/collect_stats/template_test.py +6 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/pytest.ini +2 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/tmpdir/tmp_path_fixture.py +10 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_parametrized_fixture_error_message.py +17 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_setup_skip.py +17 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_setup_skip_class.py +18 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_setup_skip_module.py +16 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_unittest_asyncio.py +27 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_unittest_asynctest.py +26 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_unittest_plain_async.py +9 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/warnings/test_group_warnings_by_message.py +24 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/warnings/test_group_warnings_by_message_summary/test_1.py +24 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/warnings/test_group_warnings_by_message_summary/test_2.py +8 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/examples/test_issue519.py +9 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/.gitignore +3 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/create_executable.py +16 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/runtests_script.py +14 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/tests/test_doctest.txt +6 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/tests/test_trivial.py +10 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/tox_run.py +16 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/io/test_pprint.py +408 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/io/test_saferepr.py +231 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/io/test_terminalwriter.py +325 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/io/test_wcwidth.py +40 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/logging/test_fixture.py +483 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/logging/test_formatter.py +175 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/logging/test_reporting.py +1549 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/.gitignore +2 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/README.rst +13 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/bdd_wallet.feature +9 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/bdd_wallet.py +42 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/django_settings.py +4 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest.ini +7 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_anyio_integration.py +11 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_asyncio_integration.py +11 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_mock_integration.py +6 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_rerunfailures_integration.py +13 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_trio_integration.py +11 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_twisted_integration.py +21 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/requirements.txt +15 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/simple_integration.py +13 -0
- tasks/tasksmith-5e916b3f6da1/tests/source/testing/python/approx.py +1162 -0
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/issue88_initial_file_multinodes/test_hello.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def test_hello():
|
| 6 |
+
pass
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/issue_519.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import pprint
|
| 5 |
+
|
| 6 |
+
import pytest
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def pytest_generate_tests(metafunc):
|
| 10 |
+
if "arg1" in metafunc.fixturenames:
|
| 11 |
+
metafunc.parametrize("arg1", ["arg1v1", "arg1v2"], scope="module")
|
| 12 |
+
|
| 13 |
+
if "arg2" in metafunc.fixturenames:
|
| 14 |
+
metafunc.parametrize("arg2", ["arg2v1", "arg2v2"], scope="function")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@pytest.fixture(scope="session")
|
| 18 |
+
def checked_order():
|
| 19 |
+
order: list[tuple[str, str, str]] = []
|
| 20 |
+
|
| 21 |
+
yield order
|
| 22 |
+
pprint.pprint(order)
|
| 23 |
+
assert order == [
|
| 24 |
+
("issue_519.py", "fix1", "arg1v1"),
|
| 25 |
+
("test_one[arg1v1-arg2v1]", "fix2", "arg2v1"),
|
| 26 |
+
("test_two[arg1v1-arg2v1]", "fix2", "arg2v1"),
|
| 27 |
+
("test_one[arg1v1-arg2v2]", "fix2", "arg2v2"),
|
| 28 |
+
("test_two[arg1v1-arg2v2]", "fix2", "arg2v2"),
|
| 29 |
+
("issue_519.py", "fix1", "arg1v2"),
|
| 30 |
+
("test_one[arg1v2-arg2v1]", "fix2", "arg2v1"),
|
| 31 |
+
("test_two[arg1v2-arg2v1]", "fix2", "arg2v1"),
|
| 32 |
+
("test_one[arg1v2-arg2v2]", "fix2", "arg2v2"),
|
| 33 |
+
("test_two[arg1v2-arg2v2]", "fix2", "arg2v2"),
|
| 34 |
+
]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@pytest.fixture(scope="module")
|
| 38 |
+
def fix1(request, arg1, checked_order):
|
| 39 |
+
checked_order.append((request.node.name, "fix1", arg1))
|
| 40 |
+
yield "fix1-" + arg1
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@pytest.fixture(scope="function")
|
| 44 |
+
def fix2(request, fix1, arg2, checked_order):
|
| 45 |
+
checked_order.append((request.node.name, "fix2", arg2))
|
| 46 |
+
yield "fix2-" + arg2 + fix1
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def test_one(fix2):
|
| 50 |
+
pass
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def test_two(fix2):
|
| 54 |
+
pass
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/junit-10.xsd
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<?xml version="1.0" encoding="UTF-8" ?>
|
| 2 |
+
<!--
|
| 3 |
+
The MIT License (MIT)
|
| 4 |
+
|
| 5 |
+
Copyright (c) 2014, Gregory Boissinot
|
| 6 |
+
|
| 7 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 8 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 9 |
+
in the Software without restriction, including without limitation the rights
|
| 10 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 11 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 12 |
+
furnished to do so, subject to the following conditions:
|
| 13 |
+
|
| 14 |
+
The above copyright notice and this permission notice shall be included in
|
| 15 |
+
all copies or substantial portions of the Software.
|
| 16 |
+
|
| 17 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 18 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 19 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 20 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 21 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 22 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
| 23 |
+
THE SOFTWARE.
|
| 24 |
+
-->
|
| 25 |
+
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
|
| 26 |
+
<xs:simpleType name="SUREFIRE_TIME">
|
| 27 |
+
<xs:restriction base="xs:string">
|
| 28 |
+
<xs:pattern value="(([0-9]{0,3},)*[0-9]{3}|[0-9]{0,3})*(\.[0-9]{0,3})?"/>
|
| 29 |
+
</xs:restriction>
|
| 30 |
+
</xs:simpleType>
|
| 31 |
+
|
| 32 |
+
<xs:complexType name="rerunType" mixed="true"> <!-- mixed (XML contains text) to be compatible with version previous than 2.22.1 -->
|
| 33 |
+
<xs:sequence>
|
| 34 |
+
<xs:element name="stackTrace" type="xs:string" minOccurs="0" /> <!-- optional to be compatible with version previous than 2.22.1 -->
|
| 35 |
+
<xs:element name="system-out" type="xs:string" minOccurs="0" />
|
| 36 |
+
<xs:element name="system-err" type="xs:string" minOccurs="0" />
|
| 37 |
+
</xs:sequence>
|
| 38 |
+
<xs:attribute name="message" type="xs:string" />
|
| 39 |
+
<xs:attribute name="type" type="xs:string" use="required" />
|
| 40 |
+
</xs:complexType>
|
| 41 |
+
|
| 42 |
+
<xs:element name="failure">
|
| 43 |
+
<xs:complexType mixed="true">
|
| 44 |
+
<xs:attribute name="type" type="xs:string"/>
|
| 45 |
+
<xs:attribute name="message" type="xs:string"/>
|
| 46 |
+
</xs:complexType>
|
| 47 |
+
</xs:element>
|
| 48 |
+
|
| 49 |
+
<xs:element name="error">
|
| 50 |
+
<xs:complexType mixed="true">
|
| 51 |
+
<xs:attribute name="type" type="xs:string"/>
|
| 52 |
+
<xs:attribute name="message" type="xs:string"/>
|
| 53 |
+
</xs:complexType>
|
| 54 |
+
</xs:element>
|
| 55 |
+
|
| 56 |
+
<xs:element name="skipped">
|
| 57 |
+
<xs:complexType mixed="true">
|
| 58 |
+
<xs:attribute name="type" type="xs:string"/>
|
| 59 |
+
<xs:attribute name="message" type="xs:string"/>
|
| 60 |
+
</xs:complexType>
|
| 61 |
+
</xs:element>
|
| 62 |
+
|
| 63 |
+
<xs:element name="properties">
|
| 64 |
+
<xs:complexType>
|
| 65 |
+
<xs:sequence>
|
| 66 |
+
<xs:element ref="property" minOccurs="0" maxOccurs="unbounded"/>
|
| 67 |
+
</xs:sequence>
|
| 68 |
+
</xs:complexType>
|
| 69 |
+
</xs:element>
|
| 70 |
+
|
| 71 |
+
<xs:element name="property">
|
| 72 |
+
<xs:complexType>
|
| 73 |
+
<xs:attribute name="name" type="xs:string" use="required"/>
|
| 74 |
+
<xs:attribute name="value" type="xs:string" use="required"/>
|
| 75 |
+
</xs:complexType>
|
| 76 |
+
</xs:element>
|
| 77 |
+
|
| 78 |
+
<xs:element name="system-err" type="xs:string"/>
|
| 79 |
+
<xs:element name="system-out" type="xs:string"/>
|
| 80 |
+
<xs:element name="rerunFailure" type="rerunType"/>
|
| 81 |
+
<xs:element name="rerunError" type="rerunType"/>
|
| 82 |
+
<xs:element name="flakyFailure" type="rerunType"/>
|
| 83 |
+
<xs:element name="flakyError" type="rerunType"/>
|
| 84 |
+
|
| 85 |
+
<xs:element name="testcase">
|
| 86 |
+
<xs:complexType>
|
| 87 |
+
<xs:sequence>
|
| 88 |
+
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
| 89 |
+
<xs:element ref="skipped"/>
|
| 90 |
+
<xs:element ref="error"/>
|
| 91 |
+
<xs:element ref="failure"/>
|
| 92 |
+
<xs:element ref="rerunFailure" minOccurs="0" maxOccurs="unbounded"/>
|
| 93 |
+
<xs:element ref="rerunError" minOccurs="0" maxOccurs="unbounded"/>
|
| 94 |
+
<xs:element ref="flakyFailure" minOccurs="0" maxOccurs="unbounded"/>
|
| 95 |
+
<xs:element ref="flakyError" minOccurs="0" maxOccurs="unbounded"/>
|
| 96 |
+
<xs:element ref="system-out"/>
|
| 97 |
+
<xs:element ref="system-err"/>
|
| 98 |
+
</xs:choice>
|
| 99 |
+
</xs:sequence>
|
| 100 |
+
<xs:attribute name="name" type="xs:string" use="required"/>
|
| 101 |
+
<xs:attribute name="time" type="xs:string"/>
|
| 102 |
+
<xs:attribute name="classname" type="xs:string"/>
|
| 103 |
+
<xs:attribute name="group" type="xs:string"/>
|
| 104 |
+
</xs:complexType>
|
| 105 |
+
</xs:element>
|
| 106 |
+
|
| 107 |
+
<xs:element name="testsuite">
|
| 108 |
+
<xs:complexType>
|
| 109 |
+
<xs:choice minOccurs="0" maxOccurs="unbounded">
|
| 110 |
+
<xs:element ref="testsuite"/>
|
| 111 |
+
<xs:element ref="properties"/>
|
| 112 |
+
<xs:element ref="testcase"/>
|
| 113 |
+
<xs:element ref="system-out"/>
|
| 114 |
+
<xs:element ref="system-err"/>
|
| 115 |
+
</xs:choice>
|
| 116 |
+
<xs:attribute name="name" type="xs:string" use="required"/>
|
| 117 |
+
<xs:attribute name="tests" type="xs:string" use="required"/>
|
| 118 |
+
<xs:attribute name="failures" type="xs:string" use="required"/>
|
| 119 |
+
<xs:attribute name="errors" type="xs:string" use="required"/>
|
| 120 |
+
<xs:attribute name="group" type="xs:string" />
|
| 121 |
+
<xs:attribute name="time" type="SUREFIRE_TIME"/>
|
| 122 |
+
<xs:attribute name="skipped" type="xs:string" />
|
| 123 |
+
<xs:attribute name="timestamp" type="xs:string" />
|
| 124 |
+
<xs:attribute name="hostname" type="xs:string" />
|
| 125 |
+
<xs:attribute name="id" type="xs:string" />
|
| 126 |
+
<xs:attribute name="package" type="xs:string" />
|
| 127 |
+
<xs:attribute name="file" type="xs:string"/>
|
| 128 |
+
<xs:attribute name="log" type="xs:string"/>
|
| 129 |
+
<xs:attribute name="url" type="xs:string"/>
|
| 130 |
+
<xs:attribute name="version" type="xs:string"/>
|
| 131 |
+
</xs:complexType>
|
| 132 |
+
</xs:element>
|
| 133 |
+
|
| 134 |
+
<xs:element name="testsuites">
|
| 135 |
+
<xs:complexType>
|
| 136 |
+
<xs:sequence>
|
| 137 |
+
<xs:element ref="testsuite" minOccurs="0" maxOccurs="unbounded" />
|
| 138 |
+
</xs:sequence>
|
| 139 |
+
<xs:attribute name="name" type="xs:string" />
|
| 140 |
+
<xs:attribute name="time" type="SUREFIRE_TIME"/>
|
| 141 |
+
<xs:attribute name="tests" type="xs:string" />
|
| 142 |
+
<xs:attribute name="failures" type="xs:string" />
|
| 143 |
+
<xs:attribute name="errors" type="xs:string" />
|
| 144 |
+
</xs:complexType>
|
| 145 |
+
</xs:element>
|
| 146 |
+
|
| 147 |
+
</xs:schema>
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/marks/marks_considered_keywords/__init__.pyi
ADDED
|
File without changes
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/marks/marks_considered_keywords/conftest.py
ADDED
|
File without changes
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/marks/marks_considered_keywords/test_marks_as_keywords.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
@pytest.mark.foo
|
| 8 |
+
def test_mark():
|
| 9 |
+
pass
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/perf_examples/collect_stats/.gitignore
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
foo_*
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/perf_examples/collect_stats/generate_folders.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import pathlib
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
HERE = pathlib.Path(__file__).parent
|
| 9 |
+
TEST_CONTENT = (HERE / "template_test.py").read_bytes()
|
| 10 |
+
|
| 11 |
+
parser = argparse.ArgumentParser()
|
| 12 |
+
parser.add_argument("numbers", nargs="*", type=int)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def generate_folders(root, elements, *more_numbers):
|
| 16 |
+
fill_len = len(str(elements))
|
| 17 |
+
if more_numbers:
|
| 18 |
+
for i in range(elements):
|
| 19 |
+
new_folder = root.joinpath(f"foo_{i:0>{fill_len}}")
|
| 20 |
+
new_folder.mkdir()
|
| 21 |
+
new_folder.joinpath("__init__.py").write_bytes(TEST_CONTENT)
|
| 22 |
+
generate_folders(new_folder, *more_numbers)
|
| 23 |
+
else:
|
| 24 |
+
for i in range(elements):
|
| 25 |
+
new_test = root.joinpath(f"test_{i:0<{fill_len}}.py")
|
| 26 |
+
new_test.write_bytes(TEST_CONTENT)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if __name__ == "__main__":
|
| 30 |
+
args = parser.parse_args()
|
| 31 |
+
generate_folders(HERE, *(args.numbers or (10, 100)))
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/perf_examples/collect_stats/template_test.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def test_x():
|
| 6 |
+
pass
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/pytest.ini
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[pytest]
|
| 2 |
+
# dummy pytest.ini to ease direct running of example scripts
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/tmpdir/tmp_path_fixture.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
@pytest.mark.parametrize("a", [r"qwe/\abc"])
|
| 8 |
+
def test_fixture(tmp_path, a):
|
| 9 |
+
assert tmp_path.is_dir()
|
| 10 |
+
assert list(tmp_path.iterdir()) == []
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_parametrized_fixture_error_message.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import unittest
|
| 5 |
+
|
| 6 |
+
import pytest
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@pytest.fixture(params=[1, 2])
|
| 10 |
+
def two(request):
|
| 11 |
+
return request.param
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@pytest.mark.usefixtures("two")
|
| 15 |
+
class TestSomethingElse(unittest.TestCase):
|
| 16 |
+
def test_two(self):
|
| 17 |
+
pass
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_setup_skip.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
"""Skipping an entire subclass with unittest.skip() should *not* call setUp from a base class."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import unittest
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class Base(unittest.TestCase):
|
| 10 |
+
def setUp(self):
|
| 11 |
+
assert 0
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@unittest.skip("skip all tests")
|
| 15 |
+
class Test(Base):
|
| 16 |
+
def test_foo(self):
|
| 17 |
+
assert 0
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_setup_skip_class.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
"""Skipping an entire subclass with unittest.skip() should *not* call setUpClass from a base class."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import unittest
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class Base(unittest.TestCase):
|
| 10 |
+
@classmethod
|
| 11 |
+
def setUpClass(cls):
|
| 12 |
+
assert 0
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@unittest.skip("skip all tests")
|
| 16 |
+
class Test(Base):
|
| 17 |
+
def test_foo(self):
|
| 18 |
+
assert 0
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_setup_skip_module.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
"""setUpModule is always called, even if all tests in the module are skipped"""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import unittest
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def setUpModule():
|
| 10 |
+
assert 0
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@unittest.skip("skip all tests")
|
| 14 |
+
class Base(unittest.TestCase):
|
| 15 |
+
def test(self):
|
| 16 |
+
assert 0
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_unittest_asyncio.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from unittest import IsolatedAsyncioTestCase
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
teardowns: list[None] = []
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class AsyncArguments(IsolatedAsyncioTestCase):
|
| 11 |
+
async def asyncTearDown(self):
|
| 12 |
+
teardowns.append(None)
|
| 13 |
+
|
| 14 |
+
async def test_something_async(self):
|
| 15 |
+
async def addition(x, y):
|
| 16 |
+
return x + y
|
| 17 |
+
|
| 18 |
+
self.assertEqual(await addition(2, 2), 4)
|
| 19 |
+
|
| 20 |
+
async def test_something_async_fails(self):
|
| 21 |
+
async def addition(x, y):
|
| 22 |
+
return x + y
|
| 23 |
+
|
| 24 |
+
self.assertEqual(await addition(2, 2), 3)
|
| 25 |
+
|
| 26 |
+
def test_teardowns(self):
|
| 27 |
+
assert len(teardowns) == 2
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_unittest_asynctest.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
"""Issue #7110"""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import asyncio
|
| 7 |
+
|
| 8 |
+
import asynctest
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
teardowns: list[None] = []
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class Test(asynctest.TestCase):
|
| 15 |
+
async def tearDown(self):
|
| 16 |
+
teardowns.append(None)
|
| 17 |
+
|
| 18 |
+
async def test_error(self):
|
| 19 |
+
await asyncio.sleep(0)
|
| 20 |
+
self.fail("failing on purpose")
|
| 21 |
+
|
| 22 |
+
async def test_ok(self):
|
| 23 |
+
await asyncio.sleep(0)
|
| 24 |
+
|
| 25 |
+
def test_teardowns(self):
|
| 26 |
+
assert len(teardowns) == 2
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/unittest/test_unittest_plain_async.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import unittest
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class Test(unittest.TestCase):
|
| 8 |
+
async def test_foo(self):
|
| 9 |
+
assert False
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/warnings/test_group_warnings_by_message.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import warnings
|
| 5 |
+
|
| 6 |
+
import pytest
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def func(msg):
|
| 10 |
+
warnings.warn(UserWarning(msg))
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@pytest.mark.parametrize("i", range(5))
|
| 14 |
+
def test_foo(i):
|
| 15 |
+
func("foo")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def test_foo_1():
|
| 19 |
+
func("foo")
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@pytest.mark.parametrize("i", range(5))
|
| 23 |
+
def test_bar(i):
|
| 24 |
+
func("bar")
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/warnings/test_group_warnings_by_message_summary/test_1.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import warnings
|
| 5 |
+
|
| 6 |
+
import pytest
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def func(msg):
|
| 10 |
+
warnings.warn(UserWarning(msg))
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@pytest.mark.parametrize("i", range(20))
|
| 14 |
+
def test_foo(i):
|
| 15 |
+
func("foo")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def test_foo_1():
|
| 19 |
+
func("foo")
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@pytest.mark.parametrize("i", range(20))
|
| 23 |
+
def test_bar(i):
|
| 24 |
+
func("bar")
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/example_scripts/warnings/test_group_warnings_by_message_summary/test_2.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from test_1 import func
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def test_2():
|
| 8 |
+
func("foo")
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/examples/test_issue519.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from _pytest.pytester import Pytester
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def test_519(pytester: Pytester) -> None:
|
| 7 |
+
pytester.copy_example("issue_519.py")
|
| 8 |
+
res = pytester.runpytest("issue_519.py")
|
| 9 |
+
res.assert_outcomes(passed=8)
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/.gitignore
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
build/
|
| 2 |
+
dist/
|
| 3 |
+
*.spec
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/create_executable.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Generate an executable with pytest runner embedded using PyInstaller."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
if __name__ == "__main__":
|
| 7 |
+
import subprocess
|
| 8 |
+
|
| 9 |
+
import pytest
|
| 10 |
+
|
| 11 |
+
hidden = []
|
| 12 |
+
for x in pytest.freeze_includes():
|
| 13 |
+
hidden.extend(["--hidden-import", x])
|
| 14 |
+
hidden.extend(["--hidden-import", "distutils"])
|
| 15 |
+
args = ["pyinstaller", "--noconfirm", *hidden, "runtests_script.py"]
|
| 16 |
+
subprocess.check_call(" ".join(args), shell=True)
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/runtests_script.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This is the script that is actually frozen into an executable: simply executes
|
| 3 |
+
pytest main().
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
if __name__ == "__main__":
|
| 10 |
+
import sys
|
| 11 |
+
|
| 12 |
+
import pytest
|
| 13 |
+
|
| 14 |
+
sys.exit(pytest.main())
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/tests/test_doctest.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
|
| 3 |
+
Testing doctest::
|
| 4 |
+
|
| 5 |
+
>>> 1 + 1
|
| 6 |
+
2
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/tests/test_trivial.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def test_upper():
|
| 6 |
+
assert "foo".upper() == "FOO"
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def test_lower():
|
| 10 |
+
assert "FOO".lower() == "foo"
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/freeze/tox_run.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Called by tox.ini: uses the generated executable to run the tests in ./tests/
|
| 3 |
+
directory.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
if __name__ == "__main__":
|
| 10 |
+
import os
|
| 11 |
+
import sys
|
| 12 |
+
|
| 13 |
+
executable = os.path.join(os.getcwd(), "dist", "runtests_script", "runtests_script")
|
| 14 |
+
if sys.platform.startswith("win"):
|
| 15 |
+
executable += ".exe"
|
| 16 |
+
sys.exit(os.system(f"{executable} tests"))
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/io/test_pprint.py
ADDED
|
@@ -0,0 +1,408 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from collections import ChainMap
|
| 4 |
+
from collections import Counter
|
| 5 |
+
from collections import defaultdict
|
| 6 |
+
from collections import deque
|
| 7 |
+
from collections import OrderedDict
|
| 8 |
+
from dataclasses import dataclass
|
| 9 |
+
import textwrap
|
| 10 |
+
from types import MappingProxyType
|
| 11 |
+
from types import SimpleNamespace
|
| 12 |
+
from typing import Any
|
| 13 |
+
|
| 14 |
+
from _pytest._io.pprint import PrettyPrinter
|
| 15 |
+
import pytest
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@dataclass
|
| 19 |
+
class EmptyDataclass:
|
| 20 |
+
pass
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@dataclass
|
| 24 |
+
class DataclassWithOneItem:
|
| 25 |
+
foo: str
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@dataclass
|
| 29 |
+
class DataclassWithTwoItems:
|
| 30 |
+
foo: str
|
| 31 |
+
bar: str
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@pytest.mark.parametrize(
|
| 35 |
+
("data", "expected"),
|
| 36 |
+
(
|
| 37 |
+
pytest.param(
|
| 38 |
+
EmptyDataclass(),
|
| 39 |
+
"EmptyDataclass()",
|
| 40 |
+
id="dataclass-empty",
|
| 41 |
+
),
|
| 42 |
+
pytest.param(
|
| 43 |
+
DataclassWithOneItem(foo="bar"),
|
| 44 |
+
"""
|
| 45 |
+
DataclassWithOneItem(
|
| 46 |
+
foo='bar',
|
| 47 |
+
)
|
| 48 |
+
""",
|
| 49 |
+
id="dataclass-one-item",
|
| 50 |
+
),
|
| 51 |
+
pytest.param(
|
| 52 |
+
DataclassWithTwoItems(foo="foo", bar="bar"),
|
| 53 |
+
"""
|
| 54 |
+
DataclassWithTwoItems(
|
| 55 |
+
foo='foo',
|
| 56 |
+
bar='bar',
|
| 57 |
+
)
|
| 58 |
+
""",
|
| 59 |
+
id="dataclass-two-items",
|
| 60 |
+
),
|
| 61 |
+
pytest.param(
|
| 62 |
+
{},
|
| 63 |
+
"{}",
|
| 64 |
+
id="dict-empty",
|
| 65 |
+
),
|
| 66 |
+
pytest.param(
|
| 67 |
+
{"one": 1},
|
| 68 |
+
"""
|
| 69 |
+
{
|
| 70 |
+
'one': 1,
|
| 71 |
+
}
|
| 72 |
+
""",
|
| 73 |
+
id="dict-one-item",
|
| 74 |
+
),
|
| 75 |
+
pytest.param(
|
| 76 |
+
{"one": 1, "two": 2},
|
| 77 |
+
"""
|
| 78 |
+
{
|
| 79 |
+
'one': 1,
|
| 80 |
+
'two': 2,
|
| 81 |
+
}
|
| 82 |
+
""",
|
| 83 |
+
id="dict-two-items",
|
| 84 |
+
),
|
| 85 |
+
pytest.param(OrderedDict(), "OrderedDict()", id="ordereddict-empty"),
|
| 86 |
+
pytest.param(
|
| 87 |
+
OrderedDict({"one": 1}),
|
| 88 |
+
"""
|
| 89 |
+
OrderedDict({
|
| 90 |
+
'one': 1,
|
| 91 |
+
})
|
| 92 |
+
""",
|
| 93 |
+
id="ordereddict-one-item",
|
| 94 |
+
),
|
| 95 |
+
pytest.param(
|
| 96 |
+
OrderedDict({"one": 1, "two": 2}),
|
| 97 |
+
"""
|
| 98 |
+
OrderedDict({
|
| 99 |
+
'one': 1,
|
| 100 |
+
'two': 2,
|
| 101 |
+
})
|
| 102 |
+
""",
|
| 103 |
+
id="ordereddict-two-items",
|
| 104 |
+
),
|
| 105 |
+
pytest.param(
|
| 106 |
+
[],
|
| 107 |
+
"[]",
|
| 108 |
+
id="list-empty",
|
| 109 |
+
),
|
| 110 |
+
pytest.param(
|
| 111 |
+
[1],
|
| 112 |
+
"""
|
| 113 |
+
[
|
| 114 |
+
1,
|
| 115 |
+
]
|
| 116 |
+
""",
|
| 117 |
+
id="list-one-item",
|
| 118 |
+
),
|
| 119 |
+
pytest.param(
|
| 120 |
+
[1, 2],
|
| 121 |
+
"""
|
| 122 |
+
[
|
| 123 |
+
1,
|
| 124 |
+
2,
|
| 125 |
+
]
|
| 126 |
+
""",
|
| 127 |
+
id="list-two-items",
|
| 128 |
+
),
|
| 129 |
+
pytest.param(
|
| 130 |
+
tuple(),
|
| 131 |
+
"()",
|
| 132 |
+
id="tuple-empty",
|
| 133 |
+
),
|
| 134 |
+
pytest.param(
|
| 135 |
+
(1,),
|
| 136 |
+
"""
|
| 137 |
+
(
|
| 138 |
+
1,
|
| 139 |
+
)
|
| 140 |
+
""",
|
| 141 |
+
id="tuple-one-item",
|
| 142 |
+
),
|
| 143 |
+
pytest.param(
|
| 144 |
+
(1, 2),
|
| 145 |
+
"""
|
| 146 |
+
(
|
| 147 |
+
1,
|
| 148 |
+
2,
|
| 149 |
+
)
|
| 150 |
+
""",
|
| 151 |
+
id="tuple-two-items",
|
| 152 |
+
),
|
| 153 |
+
pytest.param(
|
| 154 |
+
set(),
|
| 155 |
+
"set()",
|
| 156 |
+
id="set-empty",
|
| 157 |
+
),
|
| 158 |
+
pytest.param(
|
| 159 |
+
{1},
|
| 160 |
+
"""
|
| 161 |
+
{
|
| 162 |
+
1,
|
| 163 |
+
}
|
| 164 |
+
""",
|
| 165 |
+
id="set-one-item",
|
| 166 |
+
),
|
| 167 |
+
pytest.param(
|
| 168 |
+
{1, 2},
|
| 169 |
+
"""
|
| 170 |
+
{
|
| 171 |
+
1,
|
| 172 |
+
2,
|
| 173 |
+
}
|
| 174 |
+
""",
|
| 175 |
+
id="set-two-items",
|
| 176 |
+
),
|
| 177 |
+
pytest.param(
|
| 178 |
+
MappingProxyType({}),
|
| 179 |
+
"mappingproxy({})",
|
| 180 |
+
id="mappingproxy-empty",
|
| 181 |
+
),
|
| 182 |
+
pytest.param(
|
| 183 |
+
MappingProxyType({"one": 1}),
|
| 184 |
+
"""
|
| 185 |
+
mappingproxy({
|
| 186 |
+
'one': 1,
|
| 187 |
+
})
|
| 188 |
+
""",
|
| 189 |
+
id="mappingproxy-one-item",
|
| 190 |
+
),
|
| 191 |
+
pytest.param(
|
| 192 |
+
MappingProxyType({"one": 1, "two": 2}),
|
| 193 |
+
"""
|
| 194 |
+
mappingproxy({
|
| 195 |
+
'one': 1,
|
| 196 |
+
'two': 2,
|
| 197 |
+
})
|
| 198 |
+
""",
|
| 199 |
+
id="mappingproxy-two-items",
|
| 200 |
+
),
|
| 201 |
+
pytest.param(
|
| 202 |
+
SimpleNamespace(),
|
| 203 |
+
"namespace()",
|
| 204 |
+
id="simplenamespace-empty",
|
| 205 |
+
),
|
| 206 |
+
pytest.param(
|
| 207 |
+
SimpleNamespace(one=1),
|
| 208 |
+
"""
|
| 209 |
+
namespace(
|
| 210 |
+
one=1,
|
| 211 |
+
)
|
| 212 |
+
""",
|
| 213 |
+
id="simplenamespace-one-item",
|
| 214 |
+
),
|
| 215 |
+
pytest.param(
|
| 216 |
+
SimpleNamespace(one=1, two=2),
|
| 217 |
+
"""
|
| 218 |
+
namespace(
|
| 219 |
+
one=1,
|
| 220 |
+
two=2,
|
| 221 |
+
)
|
| 222 |
+
""",
|
| 223 |
+
id="simplenamespace-two-items",
|
| 224 |
+
),
|
| 225 |
+
pytest.param(
|
| 226 |
+
defaultdict(str), "defaultdict(<class 'str'>, {})", id="defaultdict-empty"
|
| 227 |
+
),
|
| 228 |
+
pytest.param(
|
| 229 |
+
defaultdict(str, {"one": "1"}),
|
| 230 |
+
"""
|
| 231 |
+
defaultdict(<class 'str'>, {
|
| 232 |
+
'one': '1',
|
| 233 |
+
})
|
| 234 |
+
""",
|
| 235 |
+
id="defaultdict-one-item",
|
| 236 |
+
),
|
| 237 |
+
pytest.param(
|
| 238 |
+
defaultdict(str, {"one": "1", "two": "2"}),
|
| 239 |
+
"""
|
| 240 |
+
defaultdict(<class 'str'>, {
|
| 241 |
+
'one': '1',
|
| 242 |
+
'two': '2',
|
| 243 |
+
})
|
| 244 |
+
""",
|
| 245 |
+
id="defaultdict-two-items",
|
| 246 |
+
),
|
| 247 |
+
pytest.param(
|
| 248 |
+
Counter(),
|
| 249 |
+
"Counter()",
|
| 250 |
+
id="counter-empty",
|
| 251 |
+
),
|
| 252 |
+
pytest.param(
|
| 253 |
+
Counter("1"),
|
| 254 |
+
"""
|
| 255 |
+
Counter({
|
| 256 |
+
'1': 1,
|
| 257 |
+
})
|
| 258 |
+
""",
|
| 259 |
+
id="counter-one-item",
|
| 260 |
+
),
|
| 261 |
+
pytest.param(
|
| 262 |
+
Counter("121"),
|
| 263 |
+
"""
|
| 264 |
+
Counter({
|
| 265 |
+
'1': 2,
|
| 266 |
+
'2': 1,
|
| 267 |
+
})
|
| 268 |
+
""",
|
| 269 |
+
id="counter-two-items",
|
| 270 |
+
),
|
| 271 |
+
pytest.param(ChainMap(), "ChainMap({})", id="chainmap-empty"),
|
| 272 |
+
pytest.param(
|
| 273 |
+
ChainMap({"one": 1, "two": 2}),
|
| 274 |
+
"""
|
| 275 |
+
ChainMap(
|
| 276 |
+
{
|
| 277 |
+
'one': 1,
|
| 278 |
+
'two': 2,
|
| 279 |
+
},
|
| 280 |
+
)
|
| 281 |
+
""",
|
| 282 |
+
id="chainmap-one-item",
|
| 283 |
+
),
|
| 284 |
+
pytest.param(
|
| 285 |
+
ChainMap({"one": 1}, {"two": 2}),
|
| 286 |
+
"""
|
| 287 |
+
ChainMap(
|
| 288 |
+
{
|
| 289 |
+
'one': 1,
|
| 290 |
+
},
|
| 291 |
+
{
|
| 292 |
+
'two': 2,
|
| 293 |
+
},
|
| 294 |
+
)
|
| 295 |
+
""",
|
| 296 |
+
id="chainmap-two-items",
|
| 297 |
+
),
|
| 298 |
+
pytest.param(
|
| 299 |
+
deque(),
|
| 300 |
+
"deque([])",
|
| 301 |
+
id="deque-empty",
|
| 302 |
+
),
|
| 303 |
+
pytest.param(
|
| 304 |
+
deque([1]),
|
| 305 |
+
"""
|
| 306 |
+
deque([
|
| 307 |
+
1,
|
| 308 |
+
])
|
| 309 |
+
""",
|
| 310 |
+
id="deque-one-item",
|
| 311 |
+
),
|
| 312 |
+
pytest.param(
|
| 313 |
+
deque([1, 2]),
|
| 314 |
+
"""
|
| 315 |
+
deque([
|
| 316 |
+
1,
|
| 317 |
+
2,
|
| 318 |
+
])
|
| 319 |
+
""",
|
| 320 |
+
id="deque-two-items",
|
| 321 |
+
),
|
| 322 |
+
pytest.param(
|
| 323 |
+
deque([1, 2], maxlen=3),
|
| 324 |
+
"""
|
| 325 |
+
deque(maxlen=3, [
|
| 326 |
+
1,
|
| 327 |
+
2,
|
| 328 |
+
])
|
| 329 |
+
""",
|
| 330 |
+
id="deque-maxlen",
|
| 331 |
+
),
|
| 332 |
+
pytest.param(
|
| 333 |
+
{
|
| 334 |
+
"chainmap": ChainMap({"one": 1}, {"two": 2}),
|
| 335 |
+
"counter": Counter("122"),
|
| 336 |
+
"dataclass": DataclassWithTwoItems(foo="foo", bar="bar"),
|
| 337 |
+
"defaultdict": defaultdict(str, {"one": "1", "two": "2"}),
|
| 338 |
+
"deque": deque([1, 2], maxlen=3),
|
| 339 |
+
"dict": {"one": 1, "two": 2},
|
| 340 |
+
"list": [1, 2],
|
| 341 |
+
"mappingproxy": MappingProxyType({"one": 1, "two": 2}),
|
| 342 |
+
"ordereddict": OrderedDict({"one": 1, "two": 2}),
|
| 343 |
+
"set": {1, 2},
|
| 344 |
+
"simplenamespace": SimpleNamespace(one=1, two=2),
|
| 345 |
+
"tuple": (1, 2),
|
| 346 |
+
},
|
| 347 |
+
"""
|
| 348 |
+
{
|
| 349 |
+
'chainmap': ChainMap(
|
| 350 |
+
{
|
| 351 |
+
'one': 1,
|
| 352 |
+
},
|
| 353 |
+
{
|
| 354 |
+
'two': 2,
|
| 355 |
+
},
|
| 356 |
+
),
|
| 357 |
+
'counter': Counter({
|
| 358 |
+
'2': 2,
|
| 359 |
+
'1': 1,
|
| 360 |
+
}),
|
| 361 |
+
'dataclass': DataclassWithTwoItems(
|
| 362 |
+
foo='foo',
|
| 363 |
+
bar='bar',
|
| 364 |
+
),
|
| 365 |
+
'defaultdict': defaultdict(<class 'str'>, {
|
| 366 |
+
'one': '1',
|
| 367 |
+
'two': '2',
|
| 368 |
+
}),
|
| 369 |
+
'deque': deque(maxlen=3, [
|
| 370 |
+
1,
|
| 371 |
+
2,
|
| 372 |
+
]),
|
| 373 |
+
'dict': {
|
| 374 |
+
'one': 1,
|
| 375 |
+
'two': 2,
|
| 376 |
+
},
|
| 377 |
+
'list': [
|
| 378 |
+
1,
|
| 379 |
+
2,
|
| 380 |
+
],
|
| 381 |
+
'mappingproxy': mappingproxy({
|
| 382 |
+
'one': 1,
|
| 383 |
+
'two': 2,
|
| 384 |
+
}),
|
| 385 |
+
'ordereddict': OrderedDict({
|
| 386 |
+
'one': 1,
|
| 387 |
+
'two': 2,
|
| 388 |
+
}),
|
| 389 |
+
'set': {
|
| 390 |
+
1,
|
| 391 |
+
2,
|
| 392 |
+
},
|
| 393 |
+
'simplenamespace': namespace(
|
| 394 |
+
one=1,
|
| 395 |
+
two=2,
|
| 396 |
+
),
|
| 397 |
+
'tuple': (
|
| 398 |
+
1,
|
| 399 |
+
2,
|
| 400 |
+
),
|
| 401 |
+
}
|
| 402 |
+
""",
|
| 403 |
+
id="deep-example",
|
| 404 |
+
),
|
| 405 |
+
),
|
| 406 |
+
)
|
| 407 |
+
def test_consistent_pretty_printer(data: Any, expected: str) -> None:
|
| 408 |
+
assert PrettyPrinter().pformat(data) == textwrap.dedent(expected).strip()
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/io/test_saferepr.py
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from _pytest._io.saferepr import DEFAULT_REPR_MAX_SIZE
|
| 5 |
+
from _pytest._io.saferepr import SafeRepr
|
| 6 |
+
from _pytest._io.saferepr import saferepr
|
| 7 |
+
from _pytest._io.saferepr import saferepr_unlimited
|
| 8 |
+
import pytest
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def test_simple_repr():
|
| 12 |
+
assert saferepr(1) == "1"
|
| 13 |
+
assert saferepr(None) == "None"
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def test_maxsize():
|
| 17 |
+
s = saferepr("x" * 50, maxsize=25)
|
| 18 |
+
assert len(s) == 25
|
| 19 |
+
expected = repr("x" * 10 + "..." + "x" * 10)
|
| 20 |
+
assert s == expected
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_no_maxsize():
|
| 24 |
+
text = "x" * DEFAULT_REPR_MAX_SIZE * 10
|
| 25 |
+
s = saferepr(text, maxsize=None)
|
| 26 |
+
expected = repr(text)
|
| 27 |
+
assert s == expected
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def test_maxsize_error_on_instance():
|
| 31 |
+
class A:
|
| 32 |
+
def __repr__(self):
|
| 33 |
+
raise ValueError("...")
|
| 34 |
+
|
| 35 |
+
s = saferepr(("*" * 50, A()), maxsize=25)
|
| 36 |
+
assert len(s) == 25
|
| 37 |
+
assert s[0] == "(" and s[-1] == ")"
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def test_exceptions() -> None:
|
| 41 |
+
class BrokenRepr:
|
| 42 |
+
def __init__(self, ex):
|
| 43 |
+
self.ex = ex
|
| 44 |
+
|
| 45 |
+
def __repr__(self):
|
| 46 |
+
raise self.ex
|
| 47 |
+
|
| 48 |
+
class BrokenReprException(Exception):
|
| 49 |
+
__str__ = None # type: ignore[assignment]
|
| 50 |
+
__repr__ = None # type: ignore[assignment]
|
| 51 |
+
|
| 52 |
+
assert "Exception" in saferepr(BrokenRepr(Exception("broken")))
|
| 53 |
+
s = saferepr(BrokenReprException("really broken"))
|
| 54 |
+
assert "TypeError" in s
|
| 55 |
+
assert "TypeError" in saferepr(BrokenRepr("string"))
|
| 56 |
+
|
| 57 |
+
none = None
|
| 58 |
+
try:
|
| 59 |
+
none() # type: ignore[misc]
|
| 60 |
+
except BaseException as exc:
|
| 61 |
+
exp_exc = repr(exc)
|
| 62 |
+
obj = BrokenRepr(BrokenReprException("omg even worse"))
|
| 63 |
+
s2 = saferepr(obj)
|
| 64 |
+
assert s2 == (
|
| 65 |
+
f"<[unpresentable exception ({exp_exc!s}) raised in repr()] BrokenRepr object at 0x{id(obj):x}>"
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def test_baseexception():
|
| 70 |
+
"""Test saferepr() with BaseExceptions, which includes pytest outcomes."""
|
| 71 |
+
|
| 72 |
+
class RaisingOnStrRepr(BaseException):
|
| 73 |
+
def __init__(self, exc_types):
|
| 74 |
+
self.exc_types = exc_types
|
| 75 |
+
|
| 76 |
+
def raise_exc(self, *args):
|
| 77 |
+
try:
|
| 78 |
+
self.exc_type = self.exc_types.pop(0)
|
| 79 |
+
except IndexError:
|
| 80 |
+
pass
|
| 81 |
+
if hasattr(self.exc_type, "__call__"):
|
| 82 |
+
raise self.exc_type(*args)
|
| 83 |
+
raise self.exc_type
|
| 84 |
+
|
| 85 |
+
def __str__(self): # noqa: PLE0307
|
| 86 |
+
self.raise_exc("__str__")
|
| 87 |
+
|
| 88 |
+
def __repr__(self):
|
| 89 |
+
self.raise_exc("__repr__")
|
| 90 |
+
|
| 91 |
+
class BrokenObj:
|
| 92 |
+
def __init__(self, exc):
|
| 93 |
+
self.exc = exc
|
| 94 |
+
|
| 95 |
+
def __repr__(self):
|
| 96 |
+
raise self.exc
|
| 97 |
+
|
| 98 |
+
__str__ = __repr__
|
| 99 |
+
|
| 100 |
+
baseexc_str = BaseException("__str__")
|
| 101 |
+
obj = BrokenObj(RaisingOnStrRepr([BaseException]))
|
| 102 |
+
assert saferepr(obj) == (
|
| 103 |
+
f"<[unpresentable exception ({baseexc_str!r}) "
|
| 104 |
+
f"raised in repr()] BrokenObj object at 0x{id(obj):x}>"
|
| 105 |
+
)
|
| 106 |
+
obj = BrokenObj(RaisingOnStrRepr([RaisingOnStrRepr([BaseException])]))
|
| 107 |
+
assert saferepr(obj) == (
|
| 108 |
+
f"<[{baseexc_str!r} raised in repr()] BrokenObj object at 0x{id(obj):x}>"
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
with pytest.raises(KeyboardInterrupt):
|
| 112 |
+
saferepr(BrokenObj(KeyboardInterrupt()))
|
| 113 |
+
|
| 114 |
+
with pytest.raises(SystemExit):
|
| 115 |
+
saferepr(BrokenObj(SystemExit()))
|
| 116 |
+
|
| 117 |
+
with pytest.raises(KeyboardInterrupt):
|
| 118 |
+
saferepr(BrokenObj(RaisingOnStrRepr([KeyboardInterrupt])))
|
| 119 |
+
|
| 120 |
+
with pytest.raises(SystemExit):
|
| 121 |
+
saferepr(BrokenObj(RaisingOnStrRepr([SystemExit])))
|
| 122 |
+
|
| 123 |
+
with pytest.raises(KeyboardInterrupt):
|
| 124 |
+
print(saferepr(BrokenObj(RaisingOnStrRepr([BaseException, KeyboardInterrupt]))))
|
| 125 |
+
|
| 126 |
+
with pytest.raises(SystemExit):
|
| 127 |
+
saferepr(BrokenObj(RaisingOnStrRepr([BaseException, SystemExit])))
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def test_buggy_builtin_repr():
|
| 131 |
+
# Simulate a case where a repr for a builtin raises.
|
| 132 |
+
# reprlib dispatches by type name, so use "int".
|
| 133 |
+
|
| 134 |
+
class int:
|
| 135 |
+
def __repr__(self):
|
| 136 |
+
raise ValueError("Buggy repr!")
|
| 137 |
+
|
| 138 |
+
assert "Buggy" in saferepr(int())
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def test_big_repr():
|
| 142 |
+
from _pytest._io.saferepr import SafeRepr
|
| 143 |
+
|
| 144 |
+
assert len(saferepr(range(1000))) <= len("[" + SafeRepr(0).maxlist * "1000" + "]")
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def test_repr_on_newstyle() -> None:
|
| 148 |
+
class Function:
|
| 149 |
+
def __repr__(self):
|
| 150 |
+
return f"<{self.name}>" # type: ignore[attr-defined]
|
| 151 |
+
|
| 152 |
+
assert saferepr(Function())
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def test_unicode():
|
| 156 |
+
val = "£€"
|
| 157 |
+
reprval = "'£€'"
|
| 158 |
+
assert saferepr(val) == reprval
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def test_broken_getattribute():
|
| 162 |
+
"""saferepr() can create proper representations of classes with
|
| 163 |
+
broken __getattribute__ (#7145)
|
| 164 |
+
"""
|
| 165 |
+
|
| 166 |
+
class SomeClass:
|
| 167 |
+
def __getattribute__(self, attr):
|
| 168 |
+
raise RuntimeError
|
| 169 |
+
|
| 170 |
+
def __repr__(self):
|
| 171 |
+
raise RuntimeError
|
| 172 |
+
|
| 173 |
+
assert saferepr(SomeClass()).startswith(
|
| 174 |
+
"<[RuntimeError() raised in repr()] SomeClass object at 0x"
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def test_saferepr_unlimited():
|
| 179 |
+
dict5 = {f"v{i}": i for i in range(5)}
|
| 180 |
+
assert saferepr_unlimited(dict5) == "{'v0': 0, 'v1': 1, 'v2': 2, 'v3': 3, 'v4': 4}"
|
| 181 |
+
|
| 182 |
+
dict_long = {f"v{i}": i for i in range(1_000)}
|
| 183 |
+
r = saferepr_unlimited(dict_long)
|
| 184 |
+
assert "..." not in r
|
| 185 |
+
assert "\n" not in r
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def test_saferepr_unlimited_exc():
|
| 189 |
+
class A:
|
| 190 |
+
def __repr__(self):
|
| 191 |
+
raise ValueError(42)
|
| 192 |
+
|
| 193 |
+
assert saferepr_unlimited(A()).startswith(
|
| 194 |
+
"<[ValueError(42) raised in repr()] A object at 0x"
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def test_saferepr_dict_preserves_insertion_order() -> None:
|
| 199 |
+
d = {
|
| 200 |
+
"b": 2,
|
| 201 |
+
"a": 1,
|
| 202 |
+
"d": 4,
|
| 203 |
+
"e": 5,
|
| 204 |
+
"c": 3,
|
| 205 |
+
}
|
| 206 |
+
s = SafeRepr(maxsize=None)
|
| 207 |
+
s.maxdict = 10
|
| 208 |
+
assert s.repr(d) == "{'b': 2, 'a': 1, 'd': 4, 'e': 5, 'c': 3}"
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def test_saferepr_dict_truncation_preserves_insertion_order() -> None:
|
| 212 |
+
d = {
|
| 213 |
+
"b": 2,
|
| 214 |
+
"a": 1,
|
| 215 |
+
"d": 4,
|
| 216 |
+
"e": 5,
|
| 217 |
+
"c": 3,
|
| 218 |
+
}
|
| 219 |
+
s = SafeRepr(maxsize=None)
|
| 220 |
+
s.maxdict = 1
|
| 221 |
+
assert s.repr(d) == "{'b': 2, ...}"
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def test_saferepr_dict_fillvalue_when_level_is_zero() -> None:
|
| 225 |
+
s = SafeRepr(maxsize=None)
|
| 226 |
+
assert s.repr_dict({"a": 1}, level=0) == "{...}"
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def test_saferepr_dict_empty() -> None:
|
| 230 |
+
s = SafeRepr(maxsize=None)
|
| 231 |
+
assert s.repr_dict({}, level=1) == "{}"
|
tasks/tas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
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from collections.abc import Generator
|
| 5 |
+
import io
|
| 6 |
+
from io import StringIO
|
| 7 |
+
import os
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
import re
|
| 10 |
+
import shutil
|
| 11 |
+
import sys
|
| 12 |
+
from unittest import mock
|
| 13 |
+
|
| 14 |
+
from _pytest._io import terminalwriter
|
| 15 |
+
from _pytest.monkeypatch import MonkeyPatch
|
| 16 |
+
import pytest
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
# These tests were initially copied from py 1.8.1.
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def test_terminal_width_COLUMNS(monkeypatch: MonkeyPatch) -> None:
|
| 23 |
+
monkeypatch.setenv("COLUMNS", "42")
|
| 24 |
+
assert terminalwriter.get_terminal_width() == 42
|
| 25 |
+
monkeypatch.delenv("COLUMNS", raising=False)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def test_terminalwriter_width_bogus(monkeypatch: MonkeyPatch) -> None:
|
| 29 |
+
monkeypatch.setattr(shutil, "get_terminal_size", mock.Mock(return_value=(10, 10)))
|
| 30 |
+
monkeypatch.delenv("COLUMNS", raising=False)
|
| 31 |
+
tw = terminalwriter.TerminalWriter()
|
| 32 |
+
assert tw.fullwidth == 80
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def test_terminalwriter_computes_width(monkeypatch: MonkeyPatch) -> None:
|
| 36 |
+
monkeypatch.setattr(terminalwriter, "get_terminal_width", lambda: 42)
|
| 37 |
+
tw = terminalwriter.TerminalWriter()
|
| 38 |
+
assert tw.fullwidth == 42
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def test_terminalwriter_dumb_term_no_markup(monkeypatch: MonkeyPatch) -> None:
|
| 42 |
+
monkeypatch.setattr(os, "environ", {"TERM": "dumb", "PATH": ""})
|
| 43 |
+
|
| 44 |
+
class MyFile:
|
| 45 |
+
closed = False
|
| 46 |
+
|
| 47 |
+
def isatty(self):
|
| 48 |
+
return True
|
| 49 |
+
|
| 50 |
+
with monkeypatch.context() as m:
|
| 51 |
+
m.setattr(sys, "stdout", MyFile())
|
| 52 |
+
assert sys.stdout.isatty()
|
| 53 |
+
tw = terminalwriter.TerminalWriter()
|
| 54 |
+
assert not tw.hasmarkup
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def test_terminalwriter_not_unicode() -> None:
|
| 58 |
+
"""If the file doesn't support Unicode, the string is unicode-escaped (#7475)."""
|
| 59 |
+
buffer = io.BytesIO()
|
| 60 |
+
file = io.TextIOWrapper(buffer, encoding="cp1252")
|
| 61 |
+
tw = terminalwriter.TerminalWriter(file)
|
| 62 |
+
tw.write("hello 🌀 wôrld אבג", flush=True)
|
| 63 |
+
assert buffer.getvalue() == rb"hello \U0001f300 w\xf4rld \u05d0\u05d1\u05d2"
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
win32 = int(sys.platform == "win32")
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class TestTerminalWriter:
|
| 70 |
+
@pytest.fixture(params=["path", "stringio"])
|
| 71 |
+
def tw(self, request, tmp_path: Path) -> Generator[terminalwriter.TerminalWriter]:
|
| 72 |
+
f: io.TextIOWrapper | StringIO
|
| 73 |
+
if request.param == "path":
|
| 74 |
+
p = tmp_path.joinpath("tmpfile")
|
| 75 |
+
f = open(str(p), "w+", encoding="utf8")
|
| 76 |
+
tw = terminalwriter.TerminalWriter(f)
|
| 77 |
+
|
| 78 |
+
def getlines():
|
| 79 |
+
f.flush()
|
| 80 |
+
with open(str(p), encoding="utf8") as fp:
|
| 81 |
+
return fp.readlines()
|
| 82 |
+
|
| 83 |
+
elif request.param == "stringio":
|
| 84 |
+
f = io.StringIO()
|
| 85 |
+
tw = terminalwriter.TerminalWriter(f)
|
| 86 |
+
|
| 87 |
+
def getlines():
|
| 88 |
+
f.seek(0)
|
| 89 |
+
return f.readlines()
|
| 90 |
+
|
| 91 |
+
tw.getlines = getlines # type: ignore
|
| 92 |
+
tw.getvalue = lambda: "".join(getlines()) # type: ignore
|
| 93 |
+
|
| 94 |
+
with f:
|
| 95 |
+
yield tw
|
| 96 |
+
|
| 97 |
+
def test_line(self, tw) -> None:
|
| 98 |
+
tw.line("hello")
|
| 99 |
+
lines = tw.getlines()
|
| 100 |
+
assert len(lines) == 1
|
| 101 |
+
assert lines[0] == "hello\n"
|
| 102 |
+
|
| 103 |
+
def test_line_unicode(self, tw) -> None:
|
| 104 |
+
msg = "b\u00f6y"
|
| 105 |
+
tw.line(msg)
|
| 106 |
+
lines = tw.getlines()
|
| 107 |
+
assert lines[0] == msg + "\n"
|
| 108 |
+
|
| 109 |
+
def test_sep_no_title(self, tw) -> None:
|
| 110 |
+
tw.sep("-", fullwidth=60)
|
| 111 |
+
lines = tw.getlines()
|
| 112 |
+
assert len(lines) == 1
|
| 113 |
+
assert lines[0] == "-" * (60 - win32) + "\n"
|
| 114 |
+
|
| 115 |
+
def test_sep_with_title(self, tw) -> None:
|
| 116 |
+
tw.sep("-", "hello", fullwidth=60)
|
| 117 |
+
lines = tw.getlines()
|
| 118 |
+
assert len(lines) == 1
|
| 119 |
+
assert lines[0] == "-" * 26 + " hello " + "-" * (27 - win32) + "\n"
|
| 120 |
+
|
| 121 |
+
def test_sep_longer_than_width(self, tw) -> None:
|
| 122 |
+
tw.sep("-", "a" * 10, fullwidth=5)
|
| 123 |
+
(line,) = tw.getlines()
|
| 124 |
+
# even though the string is wider than the line, still have a separator
|
| 125 |
+
assert line == "- aaaaaaaaaa -\n"
|
| 126 |
+
|
| 127 |
+
@pytest.mark.skipif(sys.platform == "win32", reason="win32 has no native ansi")
|
| 128 |
+
@pytest.mark.parametrize("bold", (True, False))
|
| 129 |
+
@pytest.mark.parametrize("color", ("red", "green"))
|
| 130 |
+
def test_markup(self, tw, bold: bool, color: str) -> None:
|
| 131 |
+
text = tw.markup("hello", **{color: True, "bold": bold})
|
| 132 |
+
assert "hello" in text
|
| 133 |
+
|
| 134 |
+
def test_markup_bad(self, tw) -> None:
|
| 135 |
+
with pytest.raises(ValueError):
|
| 136 |
+
tw.markup("x", wronkw=3)
|
| 137 |
+
with pytest.raises(ValueError):
|
| 138 |
+
tw.markup("x", wronkw=0)
|
| 139 |
+
|
| 140 |
+
def test_line_write_markup(self, tw) -> None:
|
| 141 |
+
tw.hasmarkup = True
|
| 142 |
+
tw.line("x", bold=True)
|
| 143 |
+
tw.write("x\n", red=True)
|
| 144 |
+
lines = tw.getlines()
|
| 145 |
+
if sys.platform != "win32":
|
| 146 |
+
assert len(lines[0]) >= 2, lines
|
| 147 |
+
assert len(lines[1]) >= 2, lines
|
| 148 |
+
|
| 149 |
+
def test_attr_fullwidth(self, tw) -> None:
|
| 150 |
+
tw.sep("-", "hello", fullwidth=70)
|
| 151 |
+
tw.fullwidth = 70
|
| 152 |
+
tw.sep("-", "hello")
|
| 153 |
+
lines = tw.getlines()
|
| 154 |
+
assert len(lines[0]) == len(lines[1])
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
@pytest.mark.skipif(sys.platform == "win32", reason="win32 has no native ansi")
|
| 158 |
+
def test_attr_hasmarkup() -> None:
|
| 159 |
+
file = io.StringIO()
|
| 160 |
+
tw = terminalwriter.TerminalWriter(file)
|
| 161 |
+
assert not tw.hasmarkup
|
| 162 |
+
tw.hasmarkup = True
|
| 163 |
+
tw.line("hello", bold=True)
|
| 164 |
+
s = file.getvalue()
|
| 165 |
+
assert len(s) > len("hello\n")
|
| 166 |
+
assert "\x1b[1m" in s
|
| 167 |
+
assert "\x1b[0m" in s
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def assert_color(expected: bool, default: bool | None = None) -> None:
|
| 171 |
+
file = io.StringIO()
|
| 172 |
+
if default is None:
|
| 173 |
+
default = not expected
|
| 174 |
+
file.isatty = lambda: default # type: ignore
|
| 175 |
+
tw = terminalwriter.TerminalWriter(file=file)
|
| 176 |
+
assert tw.hasmarkup is expected
|
| 177 |
+
tw.line("hello", bold=True)
|
| 178 |
+
s = file.getvalue()
|
| 179 |
+
if expected:
|
| 180 |
+
assert len(s) > len("hello\n")
|
| 181 |
+
assert "\x1b[1m" in s
|
| 182 |
+
assert "\x1b[0m" in s
|
| 183 |
+
else:
|
| 184 |
+
assert s == "hello\n"
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def test_should_do_markup_PY_COLORS_eq_1(monkeypatch: MonkeyPatch) -> None:
|
| 188 |
+
monkeypatch.setitem(os.environ, "PY_COLORS", "1")
|
| 189 |
+
assert_color(True)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def test_should_not_do_markup_PY_COLORS_eq_0(monkeypatch: MonkeyPatch) -> None:
|
| 193 |
+
monkeypatch.setitem(os.environ, "PY_COLORS", "0")
|
| 194 |
+
assert_color(False)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def test_should_not_do_markup_NO_COLOR(monkeypatch: MonkeyPatch) -> None:
|
| 198 |
+
monkeypatch.setitem(os.environ, "NO_COLOR", "1")
|
| 199 |
+
assert_color(False)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def test_should_do_markup_FORCE_COLOR(monkeypatch: MonkeyPatch) -> None:
|
| 203 |
+
monkeypatch.setitem(os.environ, "FORCE_COLOR", "1")
|
| 204 |
+
assert_color(True)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
@pytest.mark.parametrize(
|
| 208 |
+
["NO_COLOR", "FORCE_COLOR", "expected"],
|
| 209 |
+
[
|
| 210 |
+
("1", "1", False),
|
| 211 |
+
("", "1", True),
|
| 212 |
+
("1", "", False),
|
| 213 |
+
],
|
| 214 |
+
)
|
| 215 |
+
def test_NO_COLOR_and_FORCE_COLOR(
|
| 216 |
+
monkeypatch: MonkeyPatch,
|
| 217 |
+
NO_COLOR: str,
|
| 218 |
+
FORCE_COLOR: str,
|
| 219 |
+
expected: bool,
|
| 220 |
+
) -> None:
|
| 221 |
+
monkeypatch.setitem(os.environ, "NO_COLOR", NO_COLOR)
|
| 222 |
+
monkeypatch.setitem(os.environ, "FORCE_COLOR", FORCE_COLOR)
|
| 223 |
+
assert_color(expected)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def test_empty_NO_COLOR_and_FORCE_COLOR_ignored(monkeypatch: MonkeyPatch) -> None:
|
| 227 |
+
monkeypatch.setenv("TERM", "xterm-256color")
|
| 228 |
+
monkeypatch.setitem(os.environ, "NO_COLOR", "")
|
| 229 |
+
monkeypatch.setitem(os.environ, "FORCE_COLOR", "")
|
| 230 |
+
assert_color(True, True)
|
| 231 |
+
assert_color(False, False)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
class TestTerminalWriterLineWidth:
|
| 235 |
+
def test_init(self) -> None:
|
| 236 |
+
tw = terminalwriter.TerminalWriter()
|
| 237 |
+
assert tw.width_of_current_line == 0
|
| 238 |
+
|
| 239 |
+
def test_update(self) -> None:
|
| 240 |
+
tw = terminalwriter.TerminalWriter()
|
| 241 |
+
tw.write("hello world")
|
| 242 |
+
assert tw.width_of_current_line == 11
|
| 243 |
+
|
| 244 |
+
def test_update_with_newline(self) -> None:
|
| 245 |
+
tw = terminalwriter.TerminalWriter()
|
| 246 |
+
tw.write("hello\nworld")
|
| 247 |
+
assert tw.width_of_current_line == 5
|
| 248 |
+
|
| 249 |
+
def test_update_with_wide_text(self) -> None:
|
| 250 |
+
tw = terminalwriter.TerminalWriter()
|
| 251 |
+
tw.write("乇乂ㄒ尺卂 ㄒ卄丨匚匚")
|
| 252 |
+
assert tw.width_of_current_line == 21 # 5*2 + 1 + 5*2
|
| 253 |
+
|
| 254 |
+
def test_composed(self) -> None:
|
| 255 |
+
tw = terminalwriter.TerminalWriter()
|
| 256 |
+
text = "café food"
|
| 257 |
+
assert len(text) == 9
|
| 258 |
+
tw.write(text)
|
| 259 |
+
assert tw.width_of_current_line == 9
|
| 260 |
+
|
| 261 |
+
def test_combining(self) -> None:
|
| 262 |
+
tw = terminalwriter.TerminalWriter()
|
| 263 |
+
text = "café food"
|
| 264 |
+
assert len(text) == 10
|
| 265 |
+
tw.write(text)
|
| 266 |
+
assert tw.width_of_current_line == 9
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
@pytest.mark.parametrize(
|
| 270 |
+
("has_markup", "code_highlight", "expected"),
|
| 271 |
+
[
|
| 272 |
+
pytest.param(
|
| 273 |
+
True,
|
| 274 |
+
True,
|
| 275 |
+
"{reset}{kw}assert{hl-reset} {number}0{hl-reset}{endline}\n",
|
| 276 |
+
id="with markup and code_highlight",
|
| 277 |
+
),
|
| 278 |
+
pytest.param(
|
| 279 |
+
True,
|
| 280 |
+
False,
|
| 281 |
+
"assert 0\n",
|
| 282 |
+
id="with markup but no code_highlight",
|
| 283 |
+
),
|
| 284 |
+
pytest.param(
|
| 285 |
+
False,
|
| 286 |
+
True,
|
| 287 |
+
"assert 0\n",
|
| 288 |
+
id="without markup but with code_highlight",
|
| 289 |
+
),
|
| 290 |
+
pytest.param(
|
| 291 |
+
False,
|
| 292 |
+
False,
|
| 293 |
+
"assert 0\n",
|
| 294 |
+
id="neither markup nor code_highlight",
|
| 295 |
+
),
|
| 296 |
+
],
|
| 297 |
+
)
|
| 298 |
+
def test_code_highlight(has_markup, code_highlight, expected, color_mapping):
|
| 299 |
+
f = io.StringIO()
|
| 300 |
+
tw = terminalwriter.TerminalWriter(f)
|
| 301 |
+
tw.hasmarkup = has_markup
|
| 302 |
+
tw.code_highlight = code_highlight
|
| 303 |
+
tw._write_source(["assert 0"])
|
| 304 |
+
|
| 305 |
+
assert f.getvalue().splitlines(keepends=True) == color_mapping.format([expected])
|
| 306 |
+
|
| 307 |
+
with pytest.raises(
|
| 308 |
+
ValueError,
|
| 309 |
+
match=re.escape("indents size (2) should have same size as lines (1)"),
|
| 310 |
+
):
|
| 311 |
+
tw._write_source(["assert 0"], [" ", " "])
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def test_highlight_empty_source() -> None:
|
| 315 |
+
"""Don't crash trying to highlight empty source code.
|
| 316 |
+
|
| 317 |
+
Issue #11758.
|
| 318 |
+
"""
|
| 319 |
+
f = io.StringIO()
|
| 320 |
+
tw = terminalwriter.TerminalWriter(f)
|
| 321 |
+
tw.hasmarkup = True
|
| 322 |
+
tw.code_highlight = True
|
| 323 |
+
tw._write_source([])
|
| 324 |
+
|
| 325 |
+
assert f.getvalue() == ""
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/io/test_wcwidth.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from _pytest._io.wcwidth import wcswidth
|
| 4 |
+
from _pytest._io.wcwidth import wcwidth
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@pytest.mark.parametrize(
|
| 9 |
+
("c", "expected"),
|
| 10 |
+
[
|
| 11 |
+
("\0", 0),
|
| 12 |
+
("\n", -1),
|
| 13 |
+
("a", 1),
|
| 14 |
+
("1", 1),
|
| 15 |
+
("א", 1),
|
| 16 |
+
("\u200b", 0),
|
| 17 |
+
("\u1abe", 0),
|
| 18 |
+
("\u0591", 0),
|
| 19 |
+
("🉐", 2),
|
| 20 |
+
("$", 2), # noqa: RUF001
|
| 21 |
+
],
|
| 22 |
+
)
|
| 23 |
+
def test_wcwidth(c: str, expected: int) -> None:
|
| 24 |
+
assert wcwidth(c) == expected
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@pytest.mark.parametrize(
|
| 28 |
+
("s", "expected"),
|
| 29 |
+
[
|
| 30 |
+
("", 0),
|
| 31 |
+
("hello, world!", 13),
|
| 32 |
+
("hello, world!\n", -1),
|
| 33 |
+
("0123456789", 10),
|
| 34 |
+
("שלום, עולם!", 11),
|
| 35 |
+
("שְבֻעָיים", 6),
|
| 36 |
+
("🉐🉐🉐", 6),
|
| 37 |
+
],
|
| 38 |
+
)
|
| 39 |
+
def test_wcswidth(s: str, expected: int) -> None:
|
| 40 |
+
assert wcswidth(s) == expected
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/logging/test_fixture.py
ADDED
|
@@ -0,0 +1,483 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: disable-error-code="attr-defined"
|
| 2 |
+
# mypy: disallow-untyped-defs
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from collections.abc import Iterator
|
| 6 |
+
import logging
|
| 7 |
+
|
| 8 |
+
from _pytest.logging import caplog_records_key
|
| 9 |
+
from _pytest.pytester import Pytester
|
| 10 |
+
import pytest
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
sublogger = logging.getLogger(__name__ + ".baz")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@pytest.fixture(autouse=True)
|
| 18 |
+
def cleanup_disabled_logging() -> Iterator[None]:
|
| 19 |
+
"""Simple fixture that ensures that a test doesn't disable logging.
|
| 20 |
+
|
| 21 |
+
This is necessary because ``logging.disable()`` is global, so a test disabling logging
|
| 22 |
+
and not cleaning up after will break every test that runs after it.
|
| 23 |
+
|
| 24 |
+
This behavior was moved to a fixture so that logging will be un-disabled even if the test fails an assertion.
|
| 25 |
+
"""
|
| 26 |
+
yield
|
| 27 |
+
logging.disable(logging.NOTSET)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def test_fixture_help(pytester: Pytester) -> None:
|
| 31 |
+
result = pytester.runpytest("--fixtures")
|
| 32 |
+
result.stdout.fnmatch_lines(["*caplog*"])
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def test_change_level(caplog: pytest.LogCaptureFixture) -> None:
|
| 36 |
+
caplog.set_level(logging.INFO)
|
| 37 |
+
logger.debug("handler DEBUG level")
|
| 38 |
+
logger.info("handler INFO level")
|
| 39 |
+
|
| 40 |
+
caplog.set_level(logging.CRITICAL, logger=sublogger.name)
|
| 41 |
+
sublogger.warning("logger WARNING level")
|
| 42 |
+
sublogger.critical("logger CRITICAL level")
|
| 43 |
+
|
| 44 |
+
assert "DEBUG" not in caplog.text
|
| 45 |
+
assert "INFO" in caplog.text
|
| 46 |
+
assert "WARNING" not in caplog.text
|
| 47 |
+
assert "CRITICAL" in caplog.text
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def test_change_level_logging_disabled(caplog: pytest.LogCaptureFixture) -> None:
|
| 51 |
+
logging.disable(logging.CRITICAL)
|
| 52 |
+
assert logging.root.manager.disable == logging.CRITICAL
|
| 53 |
+
caplog.set_level(logging.WARNING)
|
| 54 |
+
logger.info("handler INFO level")
|
| 55 |
+
logger.warning("handler WARNING level")
|
| 56 |
+
|
| 57 |
+
caplog.set_level(logging.CRITICAL, logger=sublogger.name)
|
| 58 |
+
sublogger.warning("logger SUB_WARNING level")
|
| 59 |
+
sublogger.critical("logger SUB_CRITICAL level")
|
| 60 |
+
|
| 61 |
+
assert "INFO" not in caplog.text
|
| 62 |
+
assert "WARNING" in caplog.text
|
| 63 |
+
assert "SUB_WARNING" not in caplog.text
|
| 64 |
+
assert "SUB_CRITICAL" in caplog.text
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def test_change_level_undo(pytester: Pytester) -> None:
|
| 68 |
+
"""Ensure that 'set_level' is undone after the end of the test.
|
| 69 |
+
|
| 70 |
+
Tests the logging output themselves (affected both by logger and handler levels).
|
| 71 |
+
"""
|
| 72 |
+
pytester.makepyfile(
|
| 73 |
+
"""
|
| 74 |
+
import logging
|
| 75 |
+
|
| 76 |
+
def test1(caplog):
|
| 77 |
+
caplog.set_level(logging.INFO)
|
| 78 |
+
# using + operator here so fnmatch_lines doesn't match the code in the traceback
|
| 79 |
+
logging.info('log from ' + 'test1')
|
| 80 |
+
assert 0
|
| 81 |
+
|
| 82 |
+
def test2(caplog):
|
| 83 |
+
# using + operator here so fnmatch_lines doesn't match the code in the traceback
|
| 84 |
+
logging.info('log from ' + 'test2')
|
| 85 |
+
assert 0
|
| 86 |
+
"""
|
| 87 |
+
)
|
| 88 |
+
result = pytester.runpytest()
|
| 89 |
+
result.stdout.fnmatch_lines(["*log from test1*", "*2 failed in *"])
|
| 90 |
+
result.stdout.no_fnmatch_line("*log from test2*")
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def test_change_disabled_level_undo(pytester: Pytester) -> None:
|
| 94 |
+
"""Ensure that '_force_enable_logging' in 'set_level' is undone after the end of the test.
|
| 95 |
+
|
| 96 |
+
Tests the logging output themselves (affected by disabled logging level).
|
| 97 |
+
"""
|
| 98 |
+
pytester.makepyfile(
|
| 99 |
+
"""
|
| 100 |
+
import logging
|
| 101 |
+
|
| 102 |
+
def test1(caplog):
|
| 103 |
+
logging.disable(logging.CRITICAL)
|
| 104 |
+
caplog.set_level(logging.INFO)
|
| 105 |
+
# using + operator here so fnmatch_lines doesn't match the code in the traceback
|
| 106 |
+
logging.info('log from ' + 'test1')
|
| 107 |
+
assert 0
|
| 108 |
+
|
| 109 |
+
def test2(caplog):
|
| 110 |
+
# using + operator here so fnmatch_lines doesn't match the code in the traceback
|
| 111 |
+
# use logging.warning because we need a level that will show up if logging.disabled
|
| 112 |
+
# isn't reset to ``CRITICAL`` after test1.
|
| 113 |
+
logging.warning('log from ' + 'test2')
|
| 114 |
+
assert 0
|
| 115 |
+
"""
|
| 116 |
+
)
|
| 117 |
+
result = pytester.runpytest()
|
| 118 |
+
result.stdout.fnmatch_lines(["*log from test1*", "*2 failed in *"])
|
| 119 |
+
result.stdout.no_fnmatch_line("*log from test2*")
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def test_change_level_undoes_handler_level(pytester: Pytester) -> None:
|
| 123 |
+
"""Ensure that 'set_level' is undone after the end of the test (handler).
|
| 124 |
+
|
| 125 |
+
Issue #7569. Tests the handler level specifically.
|
| 126 |
+
"""
|
| 127 |
+
pytester.makepyfile(
|
| 128 |
+
"""
|
| 129 |
+
import logging
|
| 130 |
+
|
| 131 |
+
def test1(caplog):
|
| 132 |
+
assert caplog.handler.level == 0
|
| 133 |
+
caplog.set_level(9999)
|
| 134 |
+
caplog.set_level(41)
|
| 135 |
+
assert caplog.handler.level == 41
|
| 136 |
+
|
| 137 |
+
def test2(caplog):
|
| 138 |
+
assert caplog.handler.level == 0
|
| 139 |
+
|
| 140 |
+
def test3(caplog):
|
| 141 |
+
assert caplog.handler.level == 0
|
| 142 |
+
caplog.set_level(43)
|
| 143 |
+
assert caplog.handler.level == 43
|
| 144 |
+
"""
|
| 145 |
+
)
|
| 146 |
+
result = pytester.runpytest()
|
| 147 |
+
result.assert_outcomes(passed=3)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def test_with_statement_at_level(caplog: pytest.LogCaptureFixture) -> None:
|
| 151 |
+
with caplog.at_level(logging.INFO):
|
| 152 |
+
logger.debug("handler DEBUG level")
|
| 153 |
+
logger.info("handler INFO level")
|
| 154 |
+
|
| 155 |
+
with caplog.at_level(logging.CRITICAL, logger=sublogger.name):
|
| 156 |
+
sublogger.warning("logger WARNING level")
|
| 157 |
+
sublogger.critical("logger CRITICAL level")
|
| 158 |
+
|
| 159 |
+
assert "DEBUG" not in caplog.text
|
| 160 |
+
assert "INFO" in caplog.text
|
| 161 |
+
assert "WARNING" not in caplog.text
|
| 162 |
+
assert "CRITICAL" in caplog.text
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def test_with_statement_at_level_logging_disabled(
|
| 166 |
+
caplog: pytest.LogCaptureFixture,
|
| 167 |
+
) -> None:
|
| 168 |
+
logging.disable(logging.CRITICAL)
|
| 169 |
+
assert logging.root.manager.disable == logging.CRITICAL
|
| 170 |
+
with caplog.at_level(logging.WARNING):
|
| 171 |
+
logger.debug("handler DEBUG level")
|
| 172 |
+
logger.info("handler INFO level")
|
| 173 |
+
logger.warning("handler WARNING level")
|
| 174 |
+
logger.error("handler ERROR level")
|
| 175 |
+
logger.critical("handler CRITICAL level")
|
| 176 |
+
|
| 177 |
+
assert logging.root.manager.disable == logging.INFO
|
| 178 |
+
|
| 179 |
+
with caplog.at_level(logging.CRITICAL, logger=sublogger.name):
|
| 180 |
+
sublogger.warning("logger SUB_WARNING level")
|
| 181 |
+
sublogger.critical("logger SUB_CRITICAL level")
|
| 182 |
+
|
| 183 |
+
assert "DEBUG" not in caplog.text
|
| 184 |
+
assert "INFO" not in caplog.text
|
| 185 |
+
assert "WARNING" in caplog.text
|
| 186 |
+
assert "ERROR" in caplog.text
|
| 187 |
+
assert " CRITICAL" in caplog.text
|
| 188 |
+
assert "SUB_WARNING" not in caplog.text
|
| 189 |
+
assert "SUB_CRITICAL" in caplog.text
|
| 190 |
+
assert logging.root.manager.disable == logging.CRITICAL
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def test_with_statement_filtering(caplog: pytest.LogCaptureFixture) -> None:
|
| 194 |
+
class TestFilter(logging.Filter):
|
| 195 |
+
def filter(self, record: logging.LogRecord) -> bool:
|
| 196 |
+
record.msg = "filtered handler call"
|
| 197 |
+
return True
|
| 198 |
+
|
| 199 |
+
with caplog.at_level(logging.INFO):
|
| 200 |
+
with caplog.filtering(TestFilter()):
|
| 201 |
+
logger.info("handler call")
|
| 202 |
+
logger.info("handler call")
|
| 203 |
+
|
| 204 |
+
filtered_tuple, unfiltered_tuple = caplog.record_tuples
|
| 205 |
+
assert filtered_tuple == ("test_fixture", 20, "filtered handler call")
|
| 206 |
+
assert unfiltered_tuple == ("test_fixture", 20, "handler call")
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
@pytest.mark.parametrize(
|
| 210 |
+
"level_str,expected_disable_level",
|
| 211 |
+
[
|
| 212 |
+
("CRITICAL", logging.ERROR),
|
| 213 |
+
("ERROR", logging.WARNING),
|
| 214 |
+
("WARNING", logging.INFO),
|
| 215 |
+
("INFO", logging.DEBUG),
|
| 216 |
+
("DEBUG", logging.NOTSET),
|
| 217 |
+
("NOTSET", logging.NOTSET),
|
| 218 |
+
("NOTVALIDLEVEL", logging.NOTSET),
|
| 219 |
+
],
|
| 220 |
+
)
|
| 221 |
+
def test_force_enable_logging_level_string(
|
| 222 |
+
caplog: pytest.LogCaptureFixture, level_str: str, expected_disable_level: int
|
| 223 |
+
) -> None:
|
| 224 |
+
"""Test _force_enable_logging using a level string.
|
| 225 |
+
|
| 226 |
+
``expected_disable_level`` is one level below ``level_str`` because the disabled log level
|
| 227 |
+
always needs to be *at least* one level lower than the level that caplog is trying to capture.
|
| 228 |
+
"""
|
| 229 |
+
test_logger = logging.getLogger("test_str_level_force_enable")
|
| 230 |
+
# Emulate a testing environment where all logging is disabled.
|
| 231 |
+
logging.disable(logging.CRITICAL)
|
| 232 |
+
# Make sure all logging is disabled.
|
| 233 |
+
assert not test_logger.isEnabledFor(logging.CRITICAL)
|
| 234 |
+
# Un-disable logging for `level_str`.
|
| 235 |
+
caplog._force_enable_logging(level_str, test_logger)
|
| 236 |
+
# Make sure that the disabled level is now one below the requested logging level.
|
| 237 |
+
# We don't use `isEnabledFor` here because that also checks the level set by
|
| 238 |
+
# `logging.setLevel()` which is irrelevant to `logging.disable()`.
|
| 239 |
+
assert test_logger.manager.disable == expected_disable_level
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def test_log_access(caplog: pytest.LogCaptureFixture) -> None:
|
| 243 |
+
caplog.set_level(logging.INFO)
|
| 244 |
+
logger.info("boo %s", "arg")
|
| 245 |
+
assert caplog.records[0].levelname == "INFO"
|
| 246 |
+
assert caplog.records[0].msg == "boo %s"
|
| 247 |
+
assert "boo arg" in caplog.text
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def test_messages(caplog: pytest.LogCaptureFixture) -> None:
|
| 251 |
+
caplog.set_level(logging.INFO)
|
| 252 |
+
logger.info("boo %s", "arg")
|
| 253 |
+
logger.info("bar %s\nbaz %s", "arg1", "arg2")
|
| 254 |
+
assert "boo arg" == caplog.messages[0]
|
| 255 |
+
assert "bar arg1\nbaz arg2" == caplog.messages[1]
|
| 256 |
+
assert caplog.text.count("\n") > len(caplog.messages)
|
| 257 |
+
assert len(caplog.text.splitlines()) > len(caplog.messages)
|
| 258 |
+
|
| 259 |
+
try:
|
| 260 |
+
raise Exception("test")
|
| 261 |
+
except Exception:
|
| 262 |
+
logger.exception("oops")
|
| 263 |
+
|
| 264 |
+
assert "oops" in caplog.text
|
| 265 |
+
assert "oops" in caplog.messages[-1]
|
| 266 |
+
# Tracebacks are stored in the record and not added until the formatter or handler.
|
| 267 |
+
assert "Exception" in caplog.text
|
| 268 |
+
assert "Exception" not in caplog.messages[-1]
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def test_record_tuples(caplog: pytest.LogCaptureFixture) -> None:
|
| 272 |
+
caplog.set_level(logging.INFO)
|
| 273 |
+
logger.info("boo %s", "arg")
|
| 274 |
+
|
| 275 |
+
assert caplog.record_tuples == [(__name__, logging.INFO, "boo arg")]
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def test_unicode(caplog: pytest.LogCaptureFixture) -> None:
|
| 279 |
+
caplog.set_level(logging.INFO)
|
| 280 |
+
logger.info("bū")
|
| 281 |
+
assert caplog.records[0].levelname == "INFO"
|
| 282 |
+
assert caplog.records[0].msg == "bū"
|
| 283 |
+
assert "bū" in caplog.text
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def test_clear(caplog: pytest.LogCaptureFixture) -> None:
|
| 287 |
+
caplog.set_level(logging.INFO)
|
| 288 |
+
logger.info("bū")
|
| 289 |
+
assert len(caplog.records)
|
| 290 |
+
assert caplog.text
|
| 291 |
+
caplog.clear()
|
| 292 |
+
assert not len(caplog.records)
|
| 293 |
+
assert not caplog.text
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
@pytest.fixture
|
| 297 |
+
def logging_during_setup_and_teardown(
|
| 298 |
+
caplog: pytest.LogCaptureFixture,
|
| 299 |
+
) -> Iterator[None]:
|
| 300 |
+
caplog.set_level("INFO")
|
| 301 |
+
logger.info("a_setup_log")
|
| 302 |
+
yield
|
| 303 |
+
logger.info("a_teardown_log")
|
| 304 |
+
assert [x.message for x in caplog.get_records("teardown")] == ["a_teardown_log"]
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def private_assert_caplog_records_is_setup_call(
|
| 308 |
+
caplog: pytest.LogCaptureFixture,
|
| 309 |
+
) -> None:
|
| 310 |
+
# This reaches into private API, don't use this type of thing in real tests!
|
| 311 |
+
caplog_records = caplog._item.stash[caplog_records_key]
|
| 312 |
+
assert set(caplog_records) == {"setup", "call"}
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def test_captures_for_all_stages(
|
| 316 |
+
caplog: pytest.LogCaptureFixture, logging_during_setup_and_teardown: None
|
| 317 |
+
) -> None:
|
| 318 |
+
assert not caplog.records
|
| 319 |
+
assert not caplog.get_records("call")
|
| 320 |
+
logger.info("a_call_log")
|
| 321 |
+
assert [x.message for x in caplog.get_records("call")] == ["a_call_log"]
|
| 322 |
+
|
| 323 |
+
assert [x.message for x in caplog.get_records("setup")] == ["a_setup_log"]
|
| 324 |
+
|
| 325 |
+
private_assert_caplog_records_is_setup_call(caplog)
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def test_clear_for_call_stage(
|
| 329 |
+
caplog: pytest.LogCaptureFixture, logging_during_setup_and_teardown: None
|
| 330 |
+
) -> None:
|
| 331 |
+
logger.info("a_call_log")
|
| 332 |
+
assert [x.message for x in caplog.get_records("call")] == ["a_call_log"]
|
| 333 |
+
assert [x.message for x in caplog.get_records("setup")] == ["a_setup_log"]
|
| 334 |
+
private_assert_caplog_records_is_setup_call(caplog)
|
| 335 |
+
|
| 336 |
+
caplog.clear()
|
| 337 |
+
|
| 338 |
+
assert caplog.get_records("call") == []
|
| 339 |
+
assert [x.message for x in caplog.get_records("setup")] == ["a_setup_log"]
|
| 340 |
+
private_assert_caplog_records_is_setup_call(caplog)
|
| 341 |
+
|
| 342 |
+
logging.info("a_call_log_after_clear")
|
| 343 |
+
assert [x.message for x in caplog.get_records("call")] == ["a_call_log_after_clear"]
|
| 344 |
+
assert [x.message for x in caplog.get_records("setup")] == ["a_setup_log"]
|
| 345 |
+
private_assert_caplog_records_is_setup_call(caplog)
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def test_ini_controls_global_log_level(pytester: Pytester) -> None:
|
| 349 |
+
pytester.makepyfile(
|
| 350 |
+
"""
|
| 351 |
+
import pytest
|
| 352 |
+
import logging
|
| 353 |
+
def test_log_level_override(request, caplog):
|
| 354 |
+
plugin = request.config.pluginmanager.getplugin('logging-plugin')
|
| 355 |
+
assert plugin.log_level == logging.ERROR
|
| 356 |
+
logger = logging.getLogger('catchlog')
|
| 357 |
+
logger.warning("WARNING message won't be shown")
|
| 358 |
+
logger.error("ERROR message will be shown")
|
| 359 |
+
assert 'WARNING' not in caplog.text
|
| 360 |
+
assert 'ERROR' in caplog.text
|
| 361 |
+
"""
|
| 362 |
+
)
|
| 363 |
+
pytester.makeini(
|
| 364 |
+
"""
|
| 365 |
+
[pytest]
|
| 366 |
+
log_level=ERROR
|
| 367 |
+
"""
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
result = pytester.runpytest()
|
| 371 |
+
# make sure that we get a '0' exit code for the testsuite
|
| 372 |
+
assert result.ret == 0
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def test_can_override_global_log_level(pytester: Pytester) -> None:
|
| 376 |
+
pytester.makepyfile(
|
| 377 |
+
"""
|
| 378 |
+
import pytest
|
| 379 |
+
import logging
|
| 380 |
+
def test_log_level_override(request, caplog):
|
| 381 |
+
logger = logging.getLogger('catchlog')
|
| 382 |
+
plugin = request.config.pluginmanager.getplugin('logging-plugin')
|
| 383 |
+
assert plugin.log_level == logging.WARNING
|
| 384 |
+
|
| 385 |
+
logger.info("INFO message won't be shown")
|
| 386 |
+
|
| 387 |
+
caplog.set_level(logging.INFO, logger.name)
|
| 388 |
+
|
| 389 |
+
with caplog.at_level(logging.DEBUG, logger.name):
|
| 390 |
+
logger.debug("DEBUG message will be shown")
|
| 391 |
+
|
| 392 |
+
logger.debug("DEBUG message won't be shown")
|
| 393 |
+
|
| 394 |
+
with caplog.at_level(logging.CRITICAL, logger.name):
|
| 395 |
+
logger.warning("WARNING message won't be shown")
|
| 396 |
+
|
| 397 |
+
logger.debug("DEBUG message won't be shown")
|
| 398 |
+
logger.info("INFO message will be shown")
|
| 399 |
+
|
| 400 |
+
assert "message won't be shown" not in caplog.text
|
| 401 |
+
"""
|
| 402 |
+
)
|
| 403 |
+
pytester.makeini(
|
| 404 |
+
"""
|
| 405 |
+
[pytest]
|
| 406 |
+
log_level=WARNING
|
| 407 |
+
"""
|
| 408 |
+
)
|
| 409 |
+
|
| 410 |
+
result = pytester.runpytest()
|
| 411 |
+
assert result.ret == 0
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
def test_captures_despite_exception(pytester: Pytester) -> None:
|
| 415 |
+
pytester.makepyfile(
|
| 416 |
+
"""
|
| 417 |
+
import pytest
|
| 418 |
+
import logging
|
| 419 |
+
def test_log_level_override(request, caplog):
|
| 420 |
+
logger = logging.getLogger('catchlog')
|
| 421 |
+
plugin = request.config.pluginmanager.getplugin('logging-plugin')
|
| 422 |
+
assert plugin.log_level == logging.WARNING
|
| 423 |
+
|
| 424 |
+
logger.error("ERROR message " + "will be shown")
|
| 425 |
+
|
| 426 |
+
with caplog.at_level(logging.DEBUG, logger.name):
|
| 427 |
+
logger.debug("DEBUG message " + "won't be shown")
|
| 428 |
+
raise Exception()
|
| 429 |
+
"""
|
| 430 |
+
)
|
| 431 |
+
pytester.makeini(
|
| 432 |
+
"""
|
| 433 |
+
[pytest]
|
| 434 |
+
log_level=WARNING
|
| 435 |
+
"""
|
| 436 |
+
)
|
| 437 |
+
|
| 438 |
+
result = pytester.runpytest()
|
| 439 |
+
result.stdout.fnmatch_lines(["*ERROR message will be shown*"])
|
| 440 |
+
result.stdout.no_fnmatch_line("*DEBUG message won't be shown*")
|
| 441 |
+
assert result.ret == 1
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
def test_log_report_captures_according_to_config_option_upon_failure(
|
| 445 |
+
pytester: Pytester,
|
| 446 |
+
) -> None:
|
| 447 |
+
"""Test that upon failure:
|
| 448 |
+
(1) `caplog` succeeded to capture the DEBUG message and assert on it => No `Exception` is raised.
|
| 449 |
+
(2) The `DEBUG` message does NOT appear in the `Captured log call` report.
|
| 450 |
+
(3) The stdout, `INFO`, and `WARNING` messages DO appear in the test reports due to `--log-level=INFO`.
|
| 451 |
+
"""
|
| 452 |
+
pytester.makepyfile(
|
| 453 |
+
"""
|
| 454 |
+
import pytest
|
| 455 |
+
import logging
|
| 456 |
+
|
| 457 |
+
def function_that_logs():
|
| 458 |
+
logging.debug('DEBUG log ' + 'message')
|
| 459 |
+
logging.info('INFO log ' + 'message')
|
| 460 |
+
logging.warning('WARNING log ' + 'message')
|
| 461 |
+
print('Print ' + 'message')
|
| 462 |
+
|
| 463 |
+
def test_that_fails(request, caplog):
|
| 464 |
+
plugin = request.config.pluginmanager.getplugin('logging-plugin')
|
| 465 |
+
assert plugin.log_level == logging.INFO
|
| 466 |
+
|
| 467 |
+
with caplog.at_level(logging.DEBUG):
|
| 468 |
+
function_that_logs()
|
| 469 |
+
|
| 470 |
+
if 'DEBUG log ' + 'message' not in caplog.text:
|
| 471 |
+
raise Exception('caplog failed to ' + 'capture DEBUG')
|
| 472 |
+
|
| 473 |
+
assert False
|
| 474 |
+
"""
|
| 475 |
+
)
|
| 476 |
+
|
| 477 |
+
result = pytester.runpytest("--log-level=INFO")
|
| 478 |
+
result.stdout.no_fnmatch_line("*Exception: caplog failed to capture DEBUG*")
|
| 479 |
+
result.stdout.no_fnmatch_line("*DEBUG log message*")
|
| 480 |
+
result.stdout.fnmatch_lines(
|
| 481 |
+
["*Print message*", "*INFO log message*", "*WARNING log message*"]
|
| 482 |
+
)
|
| 483 |
+
assert result.ret == 1
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/logging/test_formatter.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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typing import Any
|
| 5 |
+
|
| 6 |
+
from _pytest._io import TerminalWriter
|
| 7 |
+
from _pytest.logging import ColoredLevelFormatter
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def test_coloredlogformatter() -> None:
|
| 11 |
+
logfmt = "%(filename)-25s %(lineno)4d %(levelname)-8s %(message)s"
|
| 12 |
+
|
| 13 |
+
record = logging.LogRecord(
|
| 14 |
+
name="dummy",
|
| 15 |
+
level=logging.INFO,
|
| 16 |
+
pathname="dummypath",
|
| 17 |
+
lineno=10,
|
| 18 |
+
msg="Test Message",
|
| 19 |
+
args=(),
|
| 20 |
+
exc_info=None,
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
tw = TerminalWriter()
|
| 24 |
+
tw.hasmarkup = True
|
| 25 |
+
formatter = ColoredLevelFormatter(tw, logfmt)
|
| 26 |
+
output = formatter.format(record)
|
| 27 |
+
assert output == (
|
| 28 |
+
"dummypath 10 \x1b[32mINFO \x1b[0m Test Message"
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
tw.hasmarkup = False
|
| 32 |
+
formatter = ColoredLevelFormatter(tw, logfmt)
|
| 33 |
+
output = formatter.format(record)
|
| 34 |
+
assert output == ("dummypath 10 INFO Test Message")
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def test_coloredlogformatter_with_width_precision() -> None:
|
| 38 |
+
logfmt = "%(filename)-25s %(lineno)4d %(levelname)-8.8s %(message)s"
|
| 39 |
+
|
| 40 |
+
record = logging.LogRecord(
|
| 41 |
+
name="dummy",
|
| 42 |
+
level=logging.INFO,
|
| 43 |
+
pathname="dummypath",
|
| 44 |
+
lineno=10,
|
| 45 |
+
msg="Test Message",
|
| 46 |
+
args=(),
|
| 47 |
+
exc_info=None,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
tw = TerminalWriter()
|
| 51 |
+
tw.hasmarkup = True
|
| 52 |
+
formatter = ColoredLevelFormatter(tw, logfmt)
|
| 53 |
+
output = formatter.format(record)
|
| 54 |
+
assert output == (
|
| 55 |
+
"dummypath 10 \x1b[32mINFO \x1b[0m Test Message"
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
tw.hasmarkup = False
|
| 59 |
+
formatter = ColoredLevelFormatter(tw, logfmt)
|
| 60 |
+
output = formatter.format(record)
|
| 61 |
+
assert output == ("dummypath 10 INFO Test Message")
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def test_multiline_message() -> None:
|
| 65 |
+
from _pytest.logging import PercentStyleMultiline
|
| 66 |
+
|
| 67 |
+
logfmt = "%(filename)-25s %(lineno)4d %(levelname)-8s %(message)s"
|
| 68 |
+
|
| 69 |
+
record: Any = logging.LogRecord(
|
| 70 |
+
name="dummy",
|
| 71 |
+
level=logging.INFO,
|
| 72 |
+
pathname="dummypath",
|
| 73 |
+
lineno=10,
|
| 74 |
+
msg="Test Message line1\nline2",
|
| 75 |
+
args=(),
|
| 76 |
+
exc_info=None,
|
| 77 |
+
)
|
| 78 |
+
# this is called by logging.Formatter.format
|
| 79 |
+
record.message = record.getMessage()
|
| 80 |
+
|
| 81 |
+
ai_on_style = PercentStyleMultiline(logfmt, True)
|
| 82 |
+
output = ai_on_style.format(record)
|
| 83 |
+
assert output == (
|
| 84 |
+
"dummypath 10 INFO Test Message line1\n"
|
| 85 |
+
" line2"
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
ai_off_style = PercentStyleMultiline(logfmt, False)
|
| 89 |
+
output = ai_off_style.format(record)
|
| 90 |
+
assert output == (
|
| 91 |
+
"dummypath 10 INFO Test Message line1\nline2"
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
ai_none_style = PercentStyleMultiline(logfmt, None)
|
| 95 |
+
output = ai_none_style.format(record)
|
| 96 |
+
assert output == (
|
| 97 |
+
"dummypath 10 INFO Test Message line1\nline2"
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
record.auto_indent = False
|
| 101 |
+
output = ai_on_style.format(record)
|
| 102 |
+
assert output == (
|
| 103 |
+
"dummypath 10 INFO Test Message line1\nline2"
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
record.auto_indent = True
|
| 107 |
+
output = ai_off_style.format(record)
|
| 108 |
+
assert output == (
|
| 109 |
+
"dummypath 10 INFO Test Message line1\n"
|
| 110 |
+
" line2"
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
record.auto_indent = "False"
|
| 114 |
+
output = ai_on_style.format(record)
|
| 115 |
+
assert output == (
|
| 116 |
+
"dummypath 10 INFO Test Message line1\nline2"
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
record.auto_indent = "True"
|
| 120 |
+
output = ai_off_style.format(record)
|
| 121 |
+
assert output == (
|
| 122 |
+
"dummypath 10 INFO Test Message line1\n"
|
| 123 |
+
" line2"
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
# bad string values default to False
|
| 127 |
+
record.auto_indent = "junk"
|
| 128 |
+
output = ai_off_style.format(record)
|
| 129 |
+
assert output == (
|
| 130 |
+
"dummypath 10 INFO Test Message line1\nline2"
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
# anything other than string or int will default to False
|
| 134 |
+
record.auto_indent = dict()
|
| 135 |
+
output = ai_off_style.format(record)
|
| 136 |
+
assert output == (
|
| 137 |
+
"dummypath 10 INFO Test Message line1\nline2"
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
record.auto_indent = "5"
|
| 141 |
+
output = ai_off_style.format(record)
|
| 142 |
+
assert output == (
|
| 143 |
+
"dummypath 10 INFO Test Message line1\n line2"
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
record.auto_indent = 5
|
| 147 |
+
output = ai_off_style.format(record)
|
| 148 |
+
assert output == (
|
| 149 |
+
"dummypath 10 INFO Test Message line1\n line2"
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def test_colored_short_level() -> None:
|
| 154 |
+
logfmt = "%(levelname).1s %(message)s"
|
| 155 |
+
|
| 156 |
+
record = logging.LogRecord(
|
| 157 |
+
name="dummy",
|
| 158 |
+
level=logging.INFO,
|
| 159 |
+
pathname="dummypath",
|
| 160 |
+
lineno=10,
|
| 161 |
+
msg="Test Message",
|
| 162 |
+
args=(),
|
| 163 |
+
exc_info=None,
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
class ColorConfig:
|
| 167 |
+
class option:
|
| 168 |
+
pass
|
| 169 |
+
|
| 170 |
+
tw = TerminalWriter()
|
| 171 |
+
tw.hasmarkup = True
|
| 172 |
+
formatter = ColoredLevelFormatter(tw, logfmt)
|
| 173 |
+
output = formatter.format(record)
|
| 174 |
+
# the I (of INFO) is colored
|
| 175 |
+
assert output == ("\x1b[32mI\x1b[0m Test Message")
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/logging/test_reporting.py
ADDED
|
@@ -0,0 +1,1549 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import io
|
| 5 |
+
import os
|
| 6 |
+
import re
|
| 7 |
+
from typing import cast
|
| 8 |
+
|
| 9 |
+
from _pytest.capture import CaptureManager
|
| 10 |
+
from _pytest.config import ExitCode
|
| 11 |
+
from _pytest.fixtures import FixtureRequest
|
| 12 |
+
from _pytest.pytester import Pytester
|
| 13 |
+
from _pytest.terminal import TerminalReporter
|
| 14 |
+
import pytest
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def test_nothing_logged(pytester: Pytester) -> None:
|
| 18 |
+
pytester.makepyfile(
|
| 19 |
+
"""
|
| 20 |
+
import sys
|
| 21 |
+
|
| 22 |
+
def test_foo():
|
| 23 |
+
sys.stdout.write('text going to stdout')
|
| 24 |
+
sys.stderr.write('text going to stderr')
|
| 25 |
+
assert False
|
| 26 |
+
"""
|
| 27 |
+
)
|
| 28 |
+
result = pytester.runpytest()
|
| 29 |
+
assert result.ret == 1
|
| 30 |
+
result.stdout.fnmatch_lines(["*- Captured stdout call -*", "text going to stdout"])
|
| 31 |
+
result.stdout.fnmatch_lines(["*- Captured stderr call -*", "text going to stderr"])
|
| 32 |
+
with pytest.raises(pytest.fail.Exception):
|
| 33 |
+
result.stdout.fnmatch_lines(["*- Captured *log call -*"])
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def test_messages_logged(pytester: Pytester) -> None:
|
| 37 |
+
pytester.makepyfile(
|
| 38 |
+
"""
|
| 39 |
+
import sys
|
| 40 |
+
import logging
|
| 41 |
+
|
| 42 |
+
logger = logging.getLogger(__name__)
|
| 43 |
+
|
| 44 |
+
def test_foo():
|
| 45 |
+
sys.stdout.write('text going to stdout')
|
| 46 |
+
sys.stderr.write('text going to stderr')
|
| 47 |
+
logger.info('text going to logger')
|
| 48 |
+
assert False
|
| 49 |
+
"""
|
| 50 |
+
)
|
| 51 |
+
result = pytester.runpytest("--log-level=INFO")
|
| 52 |
+
assert result.ret == 1
|
| 53 |
+
result.stdout.fnmatch_lines(["*- Captured *log call -*", "*text going to logger*"])
|
| 54 |
+
result.stdout.fnmatch_lines(["*- Captured stdout call -*", "text going to stdout"])
|
| 55 |
+
result.stdout.fnmatch_lines(["*- Captured stderr call -*", "text going to stderr"])
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def test_root_logger_affected(pytester: Pytester) -> None:
|
| 59 |
+
pytester.makepyfile(
|
| 60 |
+
"""
|
| 61 |
+
import logging
|
| 62 |
+
logger = logging.getLogger()
|
| 63 |
+
|
| 64 |
+
def test_foo():
|
| 65 |
+
logger.info('info text ' + 'going to logger')
|
| 66 |
+
logger.warning('warning text ' + 'going to logger')
|
| 67 |
+
logger.error('error text ' + 'going to logger')
|
| 68 |
+
|
| 69 |
+
assert 0
|
| 70 |
+
"""
|
| 71 |
+
)
|
| 72 |
+
log_file = str(pytester.path.joinpath("pytest.log"))
|
| 73 |
+
result = pytester.runpytest("--log-level=ERROR", "--log-file=pytest.log")
|
| 74 |
+
assert result.ret == 1
|
| 75 |
+
|
| 76 |
+
# The capture log calls in the stdout section only contain the
|
| 77 |
+
# logger.error msg, because of --log-level=ERROR.
|
| 78 |
+
result.stdout.fnmatch_lines(["*error text going to logger*"])
|
| 79 |
+
stdout = result.stdout.str()
|
| 80 |
+
assert "warning text going to logger" not in stdout
|
| 81 |
+
assert "info text going to logger" not in stdout
|
| 82 |
+
|
| 83 |
+
# The log file should only contain the error log messages and
|
| 84 |
+
# not the warning or info ones, because the root logger is set to
|
| 85 |
+
# ERROR using --log-level=ERROR.
|
| 86 |
+
assert os.path.isfile(log_file)
|
| 87 |
+
with open(log_file, encoding="utf-8") as rfh:
|
| 88 |
+
contents = rfh.read()
|
| 89 |
+
assert "info text going to logger" not in contents
|
| 90 |
+
assert "warning text going to logger" not in contents
|
| 91 |
+
assert "error text going to logger" in contents
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def test_log_cli_level_log_level_interaction(pytester: Pytester) -> None:
|
| 95 |
+
pytester.makepyfile(
|
| 96 |
+
"""
|
| 97 |
+
import logging
|
| 98 |
+
logger = logging.getLogger()
|
| 99 |
+
|
| 100 |
+
def test_foo():
|
| 101 |
+
logger.debug('debug text ' + 'going to logger')
|
| 102 |
+
logger.info('info text ' + 'going to logger')
|
| 103 |
+
logger.warning('warning text ' + 'going to logger')
|
| 104 |
+
logger.error('error text ' + 'going to logger')
|
| 105 |
+
assert 0
|
| 106 |
+
"""
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
result = pytester.runpytest("--log-cli-level=INFO", "--log-level=ERROR")
|
| 110 |
+
assert result.ret == 1
|
| 111 |
+
|
| 112 |
+
result.stdout.fnmatch_lines(
|
| 113 |
+
[
|
| 114 |
+
"*-- live log call --*",
|
| 115 |
+
"*INFO*info text going to logger",
|
| 116 |
+
"*WARNING*warning text going to logger",
|
| 117 |
+
"*ERROR*error text going to logger",
|
| 118 |
+
"=* 1 failed in *=",
|
| 119 |
+
]
|
| 120 |
+
)
|
| 121 |
+
result.stdout.no_re_match_line("DEBUG")
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def test_setup_logging(pytester: Pytester) -> None:
|
| 125 |
+
pytester.makepyfile(
|
| 126 |
+
"""
|
| 127 |
+
import logging
|
| 128 |
+
|
| 129 |
+
logger = logging.getLogger(__name__)
|
| 130 |
+
|
| 131 |
+
def setup_function(function):
|
| 132 |
+
logger.info('text going to logger from setup')
|
| 133 |
+
|
| 134 |
+
def test_foo():
|
| 135 |
+
logger.info('text going to logger from call')
|
| 136 |
+
assert False
|
| 137 |
+
"""
|
| 138 |
+
)
|
| 139 |
+
result = pytester.runpytest("--log-level=INFO")
|
| 140 |
+
assert result.ret == 1
|
| 141 |
+
result.stdout.fnmatch_lines(
|
| 142 |
+
[
|
| 143 |
+
"*- Captured *log setup -*",
|
| 144 |
+
"*text going to logger from setup*",
|
| 145 |
+
"*- Captured *log call -*",
|
| 146 |
+
"*text going to logger from call*",
|
| 147 |
+
]
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def test_teardown_logging(pytester: Pytester) -> None:
|
| 152 |
+
pytester.makepyfile(
|
| 153 |
+
"""
|
| 154 |
+
import logging
|
| 155 |
+
|
| 156 |
+
logger = logging.getLogger(__name__)
|
| 157 |
+
|
| 158 |
+
def test_foo():
|
| 159 |
+
logger.info('text going to logger from call')
|
| 160 |
+
|
| 161 |
+
def teardown_function(function):
|
| 162 |
+
logger.info('text going to logger from teardown')
|
| 163 |
+
assert False
|
| 164 |
+
"""
|
| 165 |
+
)
|
| 166 |
+
result = pytester.runpytest("--log-level=INFO")
|
| 167 |
+
assert result.ret == 1
|
| 168 |
+
result.stdout.fnmatch_lines(
|
| 169 |
+
[
|
| 170 |
+
"*- Captured *log call -*",
|
| 171 |
+
"*text going to logger from call*",
|
| 172 |
+
"*- Captured *log teardown -*",
|
| 173 |
+
"*text going to logger from teardown*",
|
| 174 |
+
]
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
@pytest.mark.parametrize("enabled", [True, False])
|
| 179 |
+
def test_log_cli_enabled_disabled(pytester: Pytester, enabled: bool) -> None:
|
| 180 |
+
msg = "critical message logged by test"
|
| 181 |
+
pytester.makepyfile(
|
| 182 |
+
f"""
|
| 183 |
+
import logging
|
| 184 |
+
def test_log_cli():
|
| 185 |
+
logging.critical("{msg}")
|
| 186 |
+
"""
|
| 187 |
+
)
|
| 188 |
+
if enabled:
|
| 189 |
+
pytester.makeini(
|
| 190 |
+
"""
|
| 191 |
+
[pytest]
|
| 192 |
+
log_cli=true
|
| 193 |
+
"""
|
| 194 |
+
)
|
| 195 |
+
result = pytester.runpytest()
|
| 196 |
+
if enabled:
|
| 197 |
+
result.stdout.fnmatch_lines(
|
| 198 |
+
[
|
| 199 |
+
"test_log_cli_enabled_disabled.py::test_log_cli ",
|
| 200 |
+
"*-- live log call --*",
|
| 201 |
+
"CRITICAL *test_log_cli_enabled_disabled.py* critical message logged by test",
|
| 202 |
+
"PASSED*",
|
| 203 |
+
]
|
| 204 |
+
)
|
| 205 |
+
else:
|
| 206 |
+
assert msg not in result.stdout.str()
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def test_log_cli_default_level(pytester: Pytester) -> None:
|
| 210 |
+
# Default log file level
|
| 211 |
+
pytester.makepyfile(
|
| 212 |
+
"""
|
| 213 |
+
import pytest
|
| 214 |
+
import logging
|
| 215 |
+
def test_log_cli(request):
|
| 216 |
+
plugin = request.config.pluginmanager.getplugin('logging-plugin')
|
| 217 |
+
assert plugin.log_cli_handler.level == logging.NOTSET
|
| 218 |
+
logging.getLogger('catchlog').info("INFO message won't be shown")
|
| 219 |
+
logging.getLogger('catchlog').warning("WARNING message will be shown")
|
| 220 |
+
"""
|
| 221 |
+
)
|
| 222 |
+
pytester.makeini(
|
| 223 |
+
"""
|
| 224 |
+
[pytest]
|
| 225 |
+
log_cli=true
|
| 226 |
+
"""
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
result = pytester.runpytest()
|
| 230 |
+
|
| 231 |
+
# fnmatch_lines does an assertion internally
|
| 232 |
+
result.stdout.fnmatch_lines(
|
| 233 |
+
[
|
| 234 |
+
"test_log_cli_default_level.py::test_log_cli ",
|
| 235 |
+
"WARNING*test_log_cli_default_level.py* message will be shown*",
|
| 236 |
+
]
|
| 237 |
+
)
|
| 238 |
+
result.stdout.no_fnmatch_line("*INFO message won't be shown*")
|
| 239 |
+
# make sure that we get a '0' exit code for the testsuite
|
| 240 |
+
assert result.ret == 0
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def test_log_cli_default_level_multiple_tests(
|
| 244 |
+
pytester: Pytester, request: FixtureRequest
|
| 245 |
+
) -> None:
|
| 246 |
+
"""Ensure we reset the first newline added by the live logger between tests"""
|
| 247 |
+
filename = request.node.name + ".py"
|
| 248 |
+
pytester.makepyfile(
|
| 249 |
+
"""
|
| 250 |
+
import logging
|
| 251 |
+
|
| 252 |
+
def test_log_1():
|
| 253 |
+
logging.warning("log message from test_log_1")
|
| 254 |
+
|
| 255 |
+
def test_log_2():
|
| 256 |
+
logging.warning("log message from test_log_2")
|
| 257 |
+
"""
|
| 258 |
+
)
|
| 259 |
+
pytester.makeini(
|
| 260 |
+
"""
|
| 261 |
+
[pytest]
|
| 262 |
+
log_cli=true
|
| 263 |
+
"""
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
result = pytester.runpytest()
|
| 267 |
+
result.stdout.fnmatch_lines(
|
| 268 |
+
[
|
| 269 |
+
f"{filename}::test_log_1 ",
|
| 270 |
+
"*WARNING*log message from test_log_1*",
|
| 271 |
+
"PASSED *50%*",
|
| 272 |
+
f"{filename}::test_log_2 ",
|
| 273 |
+
"*WARNING*log message from test_log_2*",
|
| 274 |
+
"PASSED *100%*",
|
| 275 |
+
"=* 2 passed in *=",
|
| 276 |
+
]
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def test_log_cli_default_level_sections(
|
| 281 |
+
pytester: Pytester, request: FixtureRequest
|
| 282 |
+
) -> None:
|
| 283 |
+
"""Check that with live logging enable we are printing the correct headers during
|
| 284 |
+
start/setup/call/teardown/finish."""
|
| 285 |
+
filename = request.node.name + ".py"
|
| 286 |
+
pytester.makeconftest(
|
| 287 |
+
"""
|
| 288 |
+
import pytest
|
| 289 |
+
import logging
|
| 290 |
+
|
| 291 |
+
def pytest_runtest_logstart():
|
| 292 |
+
logging.warning('>>>>> START >>>>>')
|
| 293 |
+
|
| 294 |
+
def pytest_runtest_logfinish():
|
| 295 |
+
logging.warning('<<<<< END <<<<<<<')
|
| 296 |
+
"""
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
pytester.makepyfile(
|
| 300 |
+
"""
|
| 301 |
+
import pytest
|
| 302 |
+
import logging
|
| 303 |
+
|
| 304 |
+
@pytest.fixture
|
| 305 |
+
def fix(request):
|
| 306 |
+
logging.warning("log message from setup of {}".format(request.node.name))
|
| 307 |
+
yield
|
| 308 |
+
logging.warning("log message from teardown of {}".format(request.node.name))
|
| 309 |
+
|
| 310 |
+
def test_log_1(fix):
|
| 311 |
+
logging.warning("log message from test_log_1")
|
| 312 |
+
|
| 313 |
+
def test_log_2(fix):
|
| 314 |
+
logging.warning("log message from test_log_2")
|
| 315 |
+
"""
|
| 316 |
+
)
|
| 317 |
+
pytester.makeini(
|
| 318 |
+
"""
|
| 319 |
+
[pytest]
|
| 320 |
+
log_cli=true
|
| 321 |
+
"""
|
| 322 |
+
)
|
| 323 |
+
|
| 324 |
+
result = pytester.runpytest()
|
| 325 |
+
result.stdout.fnmatch_lines(
|
| 326 |
+
[
|
| 327 |
+
f"{filename}::test_log_1 ",
|
| 328 |
+
"*-- live log start --*",
|
| 329 |
+
"*WARNING* >>>>> START >>>>>*",
|
| 330 |
+
"*-- live log setup --*",
|
| 331 |
+
"*WARNING*log message from setup of test_log_1*",
|
| 332 |
+
"*-- live log call --*",
|
| 333 |
+
"*WARNING*log message from test_log_1*",
|
| 334 |
+
"PASSED *50%*",
|
| 335 |
+
"*-- live log teardown --*",
|
| 336 |
+
"*WARNING*log message from teardown of test_log_1*",
|
| 337 |
+
"*-- live log finish --*",
|
| 338 |
+
"*WARNING* <<<<< END <<<<<<<*",
|
| 339 |
+
f"{filename}::test_log_2 ",
|
| 340 |
+
"*-- live log start --*",
|
| 341 |
+
"*WARNING* >>>>> START >>>>>*",
|
| 342 |
+
"*-- live log setup --*",
|
| 343 |
+
"*WARNING*log message from setup of test_log_2*",
|
| 344 |
+
"*-- live log call --*",
|
| 345 |
+
"*WARNING*log message from test_log_2*",
|
| 346 |
+
"PASSED *100%*",
|
| 347 |
+
"*-- live log teardown --*",
|
| 348 |
+
"*WARNING*log message from teardown of test_log_2*",
|
| 349 |
+
"*-- live log finish --*",
|
| 350 |
+
"*WARNING* <<<<< END <<<<<<<*",
|
| 351 |
+
"=* 2 passed in *=",
|
| 352 |
+
]
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
def test_live_logs_unknown_sections(
|
| 357 |
+
pytester: Pytester, request: FixtureRequest
|
| 358 |
+
) -> None:
|
| 359 |
+
"""Check that with live logging enable we are printing the correct headers during
|
| 360 |
+
start/setup/call/teardown/finish."""
|
| 361 |
+
filename = request.node.name + ".py"
|
| 362 |
+
pytester.makeconftest(
|
| 363 |
+
"""
|
| 364 |
+
import pytest
|
| 365 |
+
import logging
|
| 366 |
+
|
| 367 |
+
def pytest_runtest_protocol(item, nextitem):
|
| 368 |
+
logging.warning('Unknown Section!')
|
| 369 |
+
|
| 370 |
+
def pytest_runtest_logstart():
|
| 371 |
+
logging.warning('>>>>> START >>>>>')
|
| 372 |
+
|
| 373 |
+
def pytest_runtest_logfinish():
|
| 374 |
+
logging.warning('<<<<< END <<<<<<<')
|
| 375 |
+
"""
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
pytester.makepyfile(
|
| 379 |
+
"""
|
| 380 |
+
import pytest
|
| 381 |
+
import logging
|
| 382 |
+
|
| 383 |
+
@pytest.fixture
|
| 384 |
+
def fix(request):
|
| 385 |
+
logging.warning("log message from setup of {}".format(request.node.name))
|
| 386 |
+
yield
|
| 387 |
+
logging.warning("log message from teardown of {}".format(request.node.name))
|
| 388 |
+
|
| 389 |
+
def test_log_1(fix):
|
| 390 |
+
logging.warning("log message from test_log_1")
|
| 391 |
+
|
| 392 |
+
"""
|
| 393 |
+
)
|
| 394 |
+
pytester.makeini(
|
| 395 |
+
"""
|
| 396 |
+
[pytest]
|
| 397 |
+
log_cli=true
|
| 398 |
+
"""
|
| 399 |
+
)
|
| 400 |
+
|
| 401 |
+
result = pytester.runpytest()
|
| 402 |
+
result.stdout.fnmatch_lines(
|
| 403 |
+
[
|
| 404 |
+
"*WARNING*Unknown Section*",
|
| 405 |
+
f"{filename}::test_log_1 ",
|
| 406 |
+
"*WARNING* >>>>> START >>>>>*",
|
| 407 |
+
"*-- live log setup --*",
|
| 408 |
+
"*WARNING*log message from setup of test_log_1*",
|
| 409 |
+
"*-- live log call --*",
|
| 410 |
+
"*WARNING*log message from test_log_1*",
|
| 411 |
+
"PASSED *100%*",
|
| 412 |
+
"*-- live log teardown --*",
|
| 413 |
+
"*WARNING*log message from teardown of test_log_1*",
|
| 414 |
+
"*WARNING* <<<<< END <<<<<<<*",
|
| 415 |
+
"=* 1 passed in *=",
|
| 416 |
+
]
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
def test_sections_single_new_line_after_test_outcome(
|
| 421 |
+
pytester: Pytester, request: FixtureRequest
|
| 422 |
+
) -> None:
|
| 423 |
+
"""Check that only a single new line is written between log messages during
|
| 424 |
+
teardown/finish."""
|
| 425 |
+
filename = request.node.name + ".py"
|
| 426 |
+
pytester.makeconftest(
|
| 427 |
+
"""
|
| 428 |
+
import pytest
|
| 429 |
+
import logging
|
| 430 |
+
|
| 431 |
+
def pytest_runtest_logstart():
|
| 432 |
+
logging.warning('>>>>> START >>>>>')
|
| 433 |
+
|
| 434 |
+
def pytest_runtest_logfinish():
|
| 435 |
+
logging.warning('<<<<< END <<<<<<<')
|
| 436 |
+
logging.warning('<<<<< END <<<<<<<')
|
| 437 |
+
"""
|
| 438 |
+
)
|
| 439 |
+
|
| 440 |
+
pytester.makepyfile(
|
| 441 |
+
"""
|
| 442 |
+
import pytest
|
| 443 |
+
import logging
|
| 444 |
+
|
| 445 |
+
@pytest.fixture
|
| 446 |
+
def fix(request):
|
| 447 |
+
logging.warning("log message from setup of {}".format(request.node.name))
|
| 448 |
+
yield
|
| 449 |
+
logging.warning("log message from teardown of {}".format(request.node.name))
|
| 450 |
+
logging.warning("log message from teardown of {}".format(request.node.name))
|
| 451 |
+
|
| 452 |
+
def test_log_1(fix):
|
| 453 |
+
logging.warning("log message from test_log_1")
|
| 454 |
+
"""
|
| 455 |
+
)
|
| 456 |
+
pytester.makeini(
|
| 457 |
+
"""
|
| 458 |
+
[pytest]
|
| 459 |
+
log_cli=true
|
| 460 |
+
"""
|
| 461 |
+
)
|
| 462 |
+
|
| 463 |
+
result = pytester.runpytest()
|
| 464 |
+
result.stdout.fnmatch_lines(
|
| 465 |
+
[
|
| 466 |
+
f"{filename}::test_log_1 ",
|
| 467 |
+
"*-- live log start --*",
|
| 468 |
+
"*WARNING* >>>>> START >>>>>*",
|
| 469 |
+
"*-- live log setup --*",
|
| 470 |
+
"*WARNING*log message from setup of test_log_1*",
|
| 471 |
+
"*-- live log call --*",
|
| 472 |
+
"*WARNING*log message from test_log_1*",
|
| 473 |
+
"PASSED *100%*",
|
| 474 |
+
"*-- live log teardown --*",
|
| 475 |
+
"*WARNING*log message from teardown of test_log_1*",
|
| 476 |
+
"*-- live log finish --*",
|
| 477 |
+
"*WARNING* <<<<< END <<<<<<<*",
|
| 478 |
+
"*WARNING* <<<<< END <<<<<<<*",
|
| 479 |
+
"=* 1 passed in *=",
|
| 480 |
+
]
|
| 481 |
+
)
|
| 482 |
+
assert (
|
| 483 |
+
re.search(
|
| 484 |
+
r"(.+)live log teardown(.+)\nWARNING(.+)\nWARNING(.+)",
|
| 485 |
+
result.stdout.str(),
|
| 486 |
+
re.MULTILINE,
|
| 487 |
+
)
|
| 488 |
+
is not None
|
| 489 |
+
)
|
| 490 |
+
assert (
|
| 491 |
+
re.search(
|
| 492 |
+
r"(.+)live log finish(.+)\nWARNING(.+)\nWARNING(.+)",
|
| 493 |
+
result.stdout.str(),
|
| 494 |
+
re.MULTILINE,
|
| 495 |
+
)
|
| 496 |
+
is not None
|
| 497 |
+
)
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
def test_log_cli_level(pytester: Pytester) -> None:
|
| 501 |
+
# Default log file level
|
| 502 |
+
pytester.makepyfile(
|
| 503 |
+
"""
|
| 504 |
+
import pytest
|
| 505 |
+
import logging
|
| 506 |
+
def test_log_cli(request):
|
| 507 |
+
plugin = request.config.pluginmanager.getplugin('logging-plugin')
|
| 508 |
+
assert plugin.log_cli_handler.level == logging.INFO
|
| 509 |
+
logging.getLogger('catchlog').debug("This log message won't be shown")
|
| 510 |
+
logging.getLogger('catchlog').info("This log message will be shown")
|
| 511 |
+
print('PASSED')
|
| 512 |
+
"""
|
| 513 |
+
)
|
| 514 |
+
pytester.makeini(
|
| 515 |
+
"""
|
| 516 |
+
[pytest]
|
| 517 |
+
log_cli=true
|
| 518 |
+
"""
|
| 519 |
+
)
|
| 520 |
+
|
| 521 |
+
result = pytester.runpytest("-s", "--log-cli-level=INFO")
|
| 522 |
+
|
| 523 |
+
# fnmatch_lines does an assertion internally
|
| 524 |
+
result.stdout.fnmatch_lines(
|
| 525 |
+
[
|
| 526 |
+
"*test_log_cli_level.py*This log message will be shown",
|
| 527 |
+
"PASSED", # 'PASSED' on its own line because the log message prints a new line
|
| 528 |
+
]
|
| 529 |
+
)
|
| 530 |
+
result.stdout.no_fnmatch_line("*This log message won't be shown*")
|
| 531 |
+
|
| 532 |
+
# make sure that we get a '0' exit code for the testsuite
|
| 533 |
+
assert result.ret == 0
|
| 534 |
+
|
| 535 |
+
result = pytester.runpytest("-s", "--log-level=INFO")
|
| 536 |
+
|
| 537 |
+
# fnmatch_lines does an assertion internally
|
| 538 |
+
result.stdout.fnmatch_lines(
|
| 539 |
+
[
|
| 540 |
+
"*test_log_cli_level.py* This log message will be shown",
|
| 541 |
+
"PASSED", # 'PASSED' on its own line because the log message prints a new line
|
| 542 |
+
]
|
| 543 |
+
)
|
| 544 |
+
result.stdout.no_fnmatch_line("*This log message won't be shown*")
|
| 545 |
+
|
| 546 |
+
# make sure that we get a '0' exit code for the testsuite
|
| 547 |
+
assert result.ret == 0
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
def test_log_cli_ini_level(pytester: Pytester) -> None:
|
| 551 |
+
pytester.makeini(
|
| 552 |
+
"""
|
| 553 |
+
[pytest]
|
| 554 |
+
log_cli=true
|
| 555 |
+
log_cli_level = INFO
|
| 556 |
+
"""
|
| 557 |
+
)
|
| 558 |
+
pytester.makepyfile(
|
| 559 |
+
"""
|
| 560 |
+
import pytest
|
| 561 |
+
import logging
|
| 562 |
+
def test_log_cli(request):
|
| 563 |
+
plugin = request.config.pluginmanager.getplugin('logging-plugin')
|
| 564 |
+
assert plugin.log_cli_handler.level == logging.INFO
|
| 565 |
+
logging.getLogger('catchlog').debug("This log message won't be shown")
|
| 566 |
+
logging.getLogger('catchlog').info("This log message will be shown")
|
| 567 |
+
print('PASSED')
|
| 568 |
+
"""
|
| 569 |
+
)
|
| 570 |
+
|
| 571 |
+
result = pytester.runpytest("-s")
|
| 572 |
+
|
| 573 |
+
# fnmatch_lines does an assertion internally
|
| 574 |
+
result.stdout.fnmatch_lines(
|
| 575 |
+
[
|
| 576 |
+
"*test_log_cli_ini_level.py* This log message will be shown",
|
| 577 |
+
"PASSED", # 'PASSED' on its own line because the log message prints a new line
|
| 578 |
+
]
|
| 579 |
+
)
|
| 580 |
+
result.stdout.no_fnmatch_line("*This log message won't be shown*")
|
| 581 |
+
|
| 582 |
+
# make sure that we get a '0' exit code for the testsuite
|
| 583 |
+
assert result.ret == 0
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
@pytest.mark.parametrize(
|
| 587 |
+
"cli_args",
|
| 588 |
+
["", "--log-level=WARNING", "--log-file-level=WARNING", "--log-cli-level=WARNING"],
|
| 589 |
+
)
|
| 590 |
+
def test_log_cli_auto_enable(pytester: Pytester, cli_args: str) -> None:
|
| 591 |
+
"""Check that live logs are enabled if --log-level or --log-cli-level is passed on the CLI.
|
| 592 |
+
|
| 593 |
+
It should not be auto enabled if the same configs are set on the configuration file.
|
| 594 |
+
"""
|
| 595 |
+
pytester.makepyfile(
|
| 596 |
+
"""
|
| 597 |
+
import logging
|
| 598 |
+
|
| 599 |
+
def test_log_1():
|
| 600 |
+
logging.info("log message from test_log_1 not to be shown")
|
| 601 |
+
logging.warning("log message from test_log_1")
|
| 602 |
+
|
| 603 |
+
"""
|
| 604 |
+
)
|
| 605 |
+
pytester.makeini(
|
| 606 |
+
"""
|
| 607 |
+
[pytest]
|
| 608 |
+
log_level=INFO
|
| 609 |
+
log_cli_level=INFO
|
| 610 |
+
"""
|
| 611 |
+
)
|
| 612 |
+
|
| 613 |
+
result = pytester.runpytest(cli_args)
|
| 614 |
+
stdout = result.stdout.str()
|
| 615 |
+
if cli_args == "--log-cli-level=WARNING":
|
| 616 |
+
result.stdout.fnmatch_lines(
|
| 617 |
+
[
|
| 618 |
+
"*::test_log_1 ",
|
| 619 |
+
"*-- live log call --*",
|
| 620 |
+
"*WARNING*log message from test_log_1*",
|
| 621 |
+
"PASSED *100%*",
|
| 622 |
+
"=* 1 passed in *=",
|
| 623 |
+
]
|
| 624 |
+
)
|
| 625 |
+
assert "INFO" not in stdout
|
| 626 |
+
else:
|
| 627 |
+
result.stdout.fnmatch_lines(
|
| 628 |
+
["*test_log_cli_auto_enable*100%*", "=* 1 passed in *="]
|
| 629 |
+
)
|
| 630 |
+
assert "INFO" not in stdout
|
| 631 |
+
assert "WARNING" not in stdout
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
def test_log_file_cli(pytester: Pytester) -> None:
|
| 635 |
+
# Default log file level
|
| 636 |
+
pytester.makepyfile(
|
| 637 |
+
"""
|
| 638 |
+
import pytest
|
| 639 |
+
import logging
|
| 640 |
+
def test_log_file(request):
|
| 641 |
+
plugin = request.config.pluginmanager.getplugin('logging-plugin')
|
| 642 |
+
assert plugin.log_file_handler.level == logging.WARNING
|
| 643 |
+
logging.getLogger('catchlog').info("This log message won't be shown")
|
| 644 |
+
logging.getLogger('catchlog').warning("This log message will be shown")
|
| 645 |
+
print('PASSED')
|
| 646 |
+
"""
|
| 647 |
+
)
|
| 648 |
+
|
| 649 |
+
log_file = str(pytester.path.joinpath("pytest.log"))
|
| 650 |
+
|
| 651 |
+
result = pytester.runpytest(
|
| 652 |
+
"-s", f"--log-file={log_file}", "--log-file-level=WARNING"
|
| 653 |
+
)
|
| 654 |
+
|
| 655 |
+
# fnmatch_lines does an assertion internally
|
| 656 |
+
result.stdout.fnmatch_lines(["test_log_file_cli.py PASSED"])
|
| 657 |
+
|
| 658 |
+
# make sure that we get a '0' exit code for the testsuite
|
| 659 |
+
assert result.ret == 0
|
| 660 |
+
assert os.path.isfile(log_file)
|
| 661 |
+
with open(log_file, encoding="utf-8") as rfh:
|
| 662 |
+
contents = rfh.read()
|
| 663 |
+
assert "This log message will be shown" in contents
|
| 664 |
+
assert "This log message won't be shown" not in contents
|
| 665 |
+
|
| 666 |
+
|
| 667 |
+
def test_log_file_mode_cli(pytester: Pytester) -> None:
|
| 668 |
+
# Default log file level
|
| 669 |
+
pytester.makepyfile(
|
| 670 |
+
"""
|
| 671 |
+
import pytest
|
| 672 |
+
import logging
|
| 673 |
+
def test_log_file(request):
|
| 674 |
+
plugin = request.config.pluginmanager.getplugin('logging-plugin')
|
| 675 |
+
assert plugin.log_file_handler.level == logging.WARNING
|
| 676 |
+
logging.getLogger('catchlog').info("This log message won't be shown")
|
| 677 |
+
logging.getLogger('catchlog').warning("This log message will be shown")
|
| 678 |
+
print('PASSED')
|
| 679 |
+
"""
|
| 680 |
+
)
|
| 681 |
+
|
| 682 |
+
log_file = str(pytester.path.joinpath("pytest.log"))
|
| 683 |
+
|
| 684 |
+
with open(log_file, mode="w", encoding="utf-8") as wfh:
|
| 685 |
+
wfh.write("A custom header\n")
|
| 686 |
+
|
| 687 |
+
result = pytester.runpytest(
|
| 688 |
+
"-s",
|
| 689 |
+
f"--log-file={log_file}",
|
| 690 |
+
"--log-file-mode=a",
|
| 691 |
+
"--log-file-level=WARNING",
|
| 692 |
+
)
|
| 693 |
+
|
| 694 |
+
# fnmatch_lines does an assertion internally
|
| 695 |
+
result.stdout.fnmatch_lines(["test_log_file_mode_cli.py PASSED"])
|
| 696 |
+
|
| 697 |
+
# make sure that we get a '0' exit code for the testsuite
|
| 698 |
+
assert result.ret == 0
|
| 699 |
+
assert os.path.isfile(log_file)
|
| 700 |
+
with open(log_file, encoding="utf-8") as rfh:
|
| 701 |
+
contents = rfh.read()
|
| 702 |
+
assert "A custom header" in contents
|
| 703 |
+
assert "This log message will be shown" in contents
|
| 704 |
+
assert "This log message won't be shown" not in contents
|
| 705 |
+
|
| 706 |
+
|
| 707 |
+
def test_log_file_mode_cli_invalid(pytester: Pytester) -> None:
|
| 708 |
+
# Default log file level
|
| 709 |
+
pytester.makepyfile(
|
| 710 |
+
"""
|
| 711 |
+
import pytest
|
| 712 |
+
import logging
|
| 713 |
+
def test_log_file(request):
|
| 714 |
+
plugin = request.config.pluginmanager.getplugin('logging-plugin')
|
| 715 |
+
assert plugin.log_file_handler.level == logging.WARNING
|
| 716 |
+
logging.getLogger('catchlog').info("This log message won't be shown")
|
| 717 |
+
logging.getLogger('catchlog').warning("This log message will be shown")
|
| 718 |
+
"""
|
| 719 |
+
)
|
| 720 |
+
|
| 721 |
+
log_file = str(pytester.path.joinpath("pytest.log"))
|
| 722 |
+
|
| 723 |
+
result = pytester.runpytest(
|
| 724 |
+
"-s",
|
| 725 |
+
f"--log-file={log_file}",
|
| 726 |
+
"--log-file-mode=b",
|
| 727 |
+
"--log-file-level=WARNING",
|
| 728 |
+
)
|
| 729 |
+
|
| 730 |
+
# make sure that we get a '4' exit code for the testsuite
|
| 731 |
+
assert result.ret == ExitCode.USAGE_ERROR
|
| 732 |
+
|
| 733 |
+
|
| 734 |
+
def test_log_file_cli_level(pytester: Pytester) -> None:
|
| 735 |
+
# Default log file level
|
| 736 |
+
pytester.makepyfile(
|
| 737 |
+
"""
|
| 738 |
+
import pytest
|
| 739 |
+
import logging
|
| 740 |
+
def test_log_file(request):
|
| 741 |
+
plugin = request.config.pluginmanager.getplugin('logging-plugin')
|
| 742 |
+
assert plugin.log_file_handler.level == logging.INFO
|
| 743 |
+
logging.getLogger('catchlog').debug("This log message won't be shown")
|
| 744 |
+
logging.getLogger('catchlog').info("This log message will be shown")
|
| 745 |
+
print('PASSED')
|
| 746 |
+
"""
|
| 747 |
+
)
|
| 748 |
+
|
| 749 |
+
log_file = str(pytester.path.joinpath("pytest.log"))
|
| 750 |
+
|
| 751 |
+
result = pytester.runpytest("-s", f"--log-file={log_file}", "--log-file-level=INFO")
|
| 752 |
+
|
| 753 |
+
# fnmatch_lines does an assertion internally
|
| 754 |
+
result.stdout.fnmatch_lines(["test_log_file_cli_level.py PASSED"])
|
| 755 |
+
|
| 756 |
+
# make sure that we get a '0' exit code for the testsuite
|
| 757 |
+
assert result.ret == 0
|
| 758 |
+
assert os.path.isfile(log_file)
|
| 759 |
+
with open(log_file, encoding="utf-8") as rfh:
|
| 760 |
+
contents = rfh.read()
|
| 761 |
+
assert "This log message will be shown" in contents
|
| 762 |
+
assert "This log message won't be shown" not in contents
|
| 763 |
+
|
| 764 |
+
|
| 765 |
+
def test_log_level_not_changed_by_default(pytester: Pytester) -> None:
|
| 766 |
+
pytester.makepyfile(
|
| 767 |
+
"""
|
| 768 |
+
import logging
|
| 769 |
+
def test_log_file():
|
| 770 |
+
assert logging.getLogger().level == logging.WARNING
|
| 771 |
+
"""
|
| 772 |
+
)
|
| 773 |
+
result = pytester.runpytest("-s")
|
| 774 |
+
result.stdout.fnmatch_lines(["* 1 passed in *"])
|
| 775 |
+
|
| 776 |
+
|
| 777 |
+
def test_log_file_ini(pytester: Pytester) -> None:
|
| 778 |
+
log_file = str(pytester.path.joinpath("pytest.log"))
|
| 779 |
+
|
| 780 |
+
pytester.makeini(
|
| 781 |
+
f"""
|
| 782 |
+
[pytest]
|
| 783 |
+
log_file={log_file}
|
| 784 |
+
log_file_level=WARNING
|
| 785 |
+
"""
|
| 786 |
+
)
|
| 787 |
+
pytester.makepyfile(
|
| 788 |
+
"""
|
| 789 |
+
import pytest
|
| 790 |
+
import logging
|
| 791 |
+
def test_log_file(request):
|
| 792 |
+
plugin = request.config.pluginmanager.getplugin('logging-plugin')
|
| 793 |
+
assert plugin.log_file_handler.level == logging.WARNING
|
| 794 |
+
logging.getLogger('catchlog').info("This log message won't be shown")
|
| 795 |
+
logging.getLogger('catchlog').warning("This log message will be shown")
|
| 796 |
+
print('PASSED')
|
| 797 |
+
"""
|
| 798 |
+
)
|
| 799 |
+
|
| 800 |
+
result = pytester.runpytest("-s")
|
| 801 |
+
|
| 802 |
+
# fnmatch_lines does an assertion internally
|
| 803 |
+
result.stdout.fnmatch_lines(["test_log_file_ini.py PASSED"])
|
| 804 |
+
|
| 805 |
+
# make sure that we get a '0' exit code for the testsuite
|
| 806 |
+
assert result.ret == 0
|
| 807 |
+
assert os.path.isfile(log_file)
|
| 808 |
+
with open(log_file, encoding="utf-8") as rfh:
|
| 809 |
+
contents = rfh.read()
|
| 810 |
+
assert "This log message will be shown" in contents
|
| 811 |
+
assert "This log message won't be shown" not in contents
|
| 812 |
+
|
| 813 |
+
|
| 814 |
+
def test_log_file_mode_ini(pytester: Pytester) -> None:
|
| 815 |
+
log_file = str(pytester.path.joinpath("pytest.log"))
|
| 816 |
+
|
| 817 |
+
pytester.makeini(
|
| 818 |
+
f"""
|
| 819 |
+
[pytest]
|
| 820 |
+
log_file={log_file}
|
| 821 |
+
log_file_mode=a
|
| 822 |
+
log_file_level=WARNING
|
| 823 |
+
"""
|
| 824 |
+
)
|
| 825 |
+
pytester.makepyfile(
|
| 826 |
+
"""
|
| 827 |
+
import pytest
|
| 828 |
+
import logging
|
| 829 |
+
def test_log_file(request):
|
| 830 |
+
plugin = request.config.pluginmanager.getplugin('logging-plugin')
|
| 831 |
+
assert plugin.log_file_handler.level == logging.WARNING
|
| 832 |
+
logging.getLogger('catchlog').info("This log message won't be shown")
|
| 833 |
+
logging.getLogger('catchlog').warning("This log message will be shown")
|
| 834 |
+
print('PASSED')
|
| 835 |
+
"""
|
| 836 |
+
)
|
| 837 |
+
|
| 838 |
+
with open(log_file, mode="w", encoding="utf-8") as wfh:
|
| 839 |
+
wfh.write("A custom header\n")
|
| 840 |
+
|
| 841 |
+
result = pytester.runpytest("-s")
|
| 842 |
+
|
| 843 |
+
# fnmatch_lines does an assertion internally
|
| 844 |
+
result.stdout.fnmatch_lines(["test_log_file_mode_ini.py PASSED"])
|
| 845 |
+
|
| 846 |
+
assert result.ret == ExitCode.OK
|
| 847 |
+
assert os.path.isfile(log_file)
|
| 848 |
+
with open(log_file, encoding="utf-8") as rfh:
|
| 849 |
+
contents = rfh.read()
|
| 850 |
+
assert "A custom header" in contents
|
| 851 |
+
assert "This log message will be shown" in contents
|
| 852 |
+
assert "This log message won't be shown" not in contents
|
| 853 |
+
|
| 854 |
+
|
| 855 |
+
def test_log_file_ini_level(pytester: Pytester) -> None:
|
| 856 |
+
log_file = str(pytester.path.joinpath("pytest.log"))
|
| 857 |
+
|
| 858 |
+
pytester.makeini(
|
| 859 |
+
f"""
|
| 860 |
+
[pytest]
|
| 861 |
+
log_file={log_file}
|
| 862 |
+
log_file_level = INFO
|
| 863 |
+
"""
|
| 864 |
+
)
|
| 865 |
+
pytester.makepyfile(
|
| 866 |
+
"""
|
| 867 |
+
import pytest
|
| 868 |
+
import logging
|
| 869 |
+
def test_log_file(request):
|
| 870 |
+
plugin = request.config.pluginmanager.getplugin('logging-plugin')
|
| 871 |
+
assert plugin.log_file_handler.level == logging.INFO
|
| 872 |
+
logging.getLogger('catchlog').debug("This log message won't be shown")
|
| 873 |
+
logging.getLogger('catchlog').info("This log message will be shown")
|
| 874 |
+
print('PASSED')
|
| 875 |
+
"""
|
| 876 |
+
)
|
| 877 |
+
|
| 878 |
+
result = pytester.runpytest("-s")
|
| 879 |
+
|
| 880 |
+
# fnmatch_lines does an assertion internally
|
| 881 |
+
result.stdout.fnmatch_lines(["test_log_file_ini_level.py PASSED"])
|
| 882 |
+
|
| 883 |
+
# make sure that we get a '0' exit code for the testsuite
|
| 884 |
+
assert result.ret == 0
|
| 885 |
+
assert os.path.isfile(log_file)
|
| 886 |
+
with open(log_file, encoding="utf-8") as rfh:
|
| 887 |
+
contents = rfh.read()
|
| 888 |
+
assert "This log message will be shown" in contents
|
| 889 |
+
assert "This log message won't be shown" not in contents
|
| 890 |
+
|
| 891 |
+
|
| 892 |
+
def test_log_file_unicode(pytester: Pytester) -> None:
|
| 893 |
+
log_file = str(pytester.path.joinpath("pytest.log"))
|
| 894 |
+
|
| 895 |
+
pytester.makeini(
|
| 896 |
+
f"""
|
| 897 |
+
[pytest]
|
| 898 |
+
log_file={log_file}
|
| 899 |
+
log_file_level = INFO
|
| 900 |
+
"""
|
| 901 |
+
)
|
| 902 |
+
pytester.makepyfile(
|
| 903 |
+
"""\
|
| 904 |
+
import logging
|
| 905 |
+
|
| 906 |
+
def test_log_file():
|
| 907 |
+
logging.getLogger('catchlog').info("Normal message")
|
| 908 |
+
logging.getLogger('catchlog').info("├")
|
| 909 |
+
logging.getLogger('catchlog').info("Another normal message")
|
| 910 |
+
"""
|
| 911 |
+
)
|
| 912 |
+
|
| 913 |
+
result = pytester.runpytest()
|
| 914 |
+
|
| 915 |
+
# make sure that we get a '0' exit code for the testsuite
|
| 916 |
+
assert result.ret == 0
|
| 917 |
+
assert os.path.isfile(log_file)
|
| 918 |
+
with open(log_file, encoding="utf-8") as rfh:
|
| 919 |
+
contents = rfh.read()
|
| 920 |
+
assert "Normal message" in contents
|
| 921 |
+
assert "├" in contents
|
| 922 |
+
assert "Another normal message" in contents
|
| 923 |
+
|
| 924 |
+
|
| 925 |
+
@pytest.mark.parametrize("has_capture_manager", [True, False])
|
| 926 |
+
def test_live_logging_suspends_capture(
|
| 927 |
+
has_capture_manager: bool, request: FixtureRequest
|
| 928 |
+
) -> None:
|
| 929 |
+
"""Test that capture manager is suspended when we emitting messages for live logging.
|
| 930 |
+
|
| 931 |
+
This tests the implementation calls instead of behavior because it is difficult/impossible to do it using
|
| 932 |
+
``pytester`` facilities because they do their own capturing.
|
| 933 |
+
|
| 934 |
+
We parametrize the test to also make sure _LiveLoggingStreamHandler works correctly if no capture manager plugin
|
| 935 |
+
is installed.
|
| 936 |
+
"""
|
| 937 |
+
import contextlib
|
| 938 |
+
from functools import partial
|
| 939 |
+
import logging
|
| 940 |
+
|
| 941 |
+
from _pytest.logging import _LiveLoggingStreamHandler
|
| 942 |
+
|
| 943 |
+
class MockCaptureManager:
|
| 944 |
+
calls = []
|
| 945 |
+
|
| 946 |
+
@contextlib.contextmanager
|
| 947 |
+
def global_and_fixture_disabled(self):
|
| 948 |
+
self.calls.append("enter disabled")
|
| 949 |
+
yield
|
| 950 |
+
self.calls.append("exit disabled")
|
| 951 |
+
|
| 952 |
+
class DummyTerminal(io.StringIO):
|
| 953 |
+
def section(self, *args, **kwargs):
|
| 954 |
+
pass
|
| 955 |
+
|
| 956 |
+
out_file = cast(TerminalReporter, DummyTerminal())
|
| 957 |
+
capture_manager = (
|
| 958 |
+
cast(CaptureManager, MockCaptureManager()) if has_capture_manager else None
|
| 959 |
+
)
|
| 960 |
+
handler = _LiveLoggingStreamHandler(out_file, capture_manager)
|
| 961 |
+
handler.set_when("call")
|
| 962 |
+
|
| 963 |
+
logger = logging.getLogger(__name__ + ".test_live_logging_suspends_capture")
|
| 964 |
+
logger.addHandler(handler)
|
| 965 |
+
request.addfinalizer(partial(logger.removeHandler, handler))
|
| 966 |
+
|
| 967 |
+
logger.critical("some message")
|
| 968 |
+
if has_capture_manager:
|
| 969 |
+
assert MockCaptureManager.calls == ["enter disabled", "exit disabled"]
|
| 970 |
+
else:
|
| 971 |
+
assert MockCaptureManager.calls == []
|
| 972 |
+
assert cast(io.StringIO, out_file).getvalue() == "\nsome message\n"
|
| 973 |
+
|
| 974 |
+
|
| 975 |
+
def test_collection_live_logging(pytester: Pytester) -> None:
|
| 976 |
+
pytester.makepyfile(
|
| 977 |
+
"""
|
| 978 |
+
import logging
|
| 979 |
+
|
| 980 |
+
logging.getLogger().info("Normal message")
|
| 981 |
+
"""
|
| 982 |
+
)
|
| 983 |
+
|
| 984 |
+
result = pytester.runpytest("--log-cli-level=INFO")
|
| 985 |
+
result.stdout.fnmatch_lines(
|
| 986 |
+
["*--- live log collection ---*", "*Normal message*", "collected 0 items"]
|
| 987 |
+
)
|
| 988 |
+
|
| 989 |
+
|
| 990 |
+
@pytest.mark.parametrize("verbose", ["", "-q", "-qq"])
|
| 991 |
+
def test_collection_collect_only_live_logging(pytester: Pytester, verbose: str) -> None:
|
| 992 |
+
pytester.makepyfile(
|
| 993 |
+
"""
|
| 994 |
+
def test_simple():
|
| 995 |
+
pass
|
| 996 |
+
"""
|
| 997 |
+
)
|
| 998 |
+
|
| 999 |
+
result = pytester.runpytest("--collect-only", "--log-cli-level=INFO", verbose)
|
| 1000 |
+
|
| 1001 |
+
expected_lines = []
|
| 1002 |
+
|
| 1003 |
+
if not verbose:
|
| 1004 |
+
expected_lines.extend(
|
| 1005 |
+
[
|
| 1006 |
+
"*collected 1 item*",
|
| 1007 |
+
"*<Module test_collection_collect_only_live_logging.py>*",
|
| 1008 |
+
"*1 test collected*",
|
| 1009 |
+
]
|
| 1010 |
+
)
|
| 1011 |
+
elif verbose == "-q":
|
| 1012 |
+
result.stdout.no_fnmatch_line("*collected 1 item**")
|
| 1013 |
+
expected_lines.extend(
|
| 1014 |
+
[
|
| 1015 |
+
"*test_collection_collect_only_live_logging.py::test_simple*",
|
| 1016 |
+
"1 test collected in [0-9].[0-9][0-9]s",
|
| 1017 |
+
]
|
| 1018 |
+
)
|
| 1019 |
+
elif verbose == "-qq":
|
| 1020 |
+
result.stdout.no_fnmatch_line("*collected 1 item**")
|
| 1021 |
+
expected_lines.extend(["*test_collection_collect_only_live_logging.py: 1*"])
|
| 1022 |
+
|
| 1023 |
+
result.stdout.fnmatch_lines(expected_lines)
|
| 1024 |
+
|
| 1025 |
+
|
| 1026 |
+
def test_collection_logging_to_file(pytester: Pytester) -> None:
|
| 1027 |
+
log_file = str(pytester.path.joinpath("pytest.log"))
|
| 1028 |
+
|
| 1029 |
+
pytester.makeini(
|
| 1030 |
+
f"""
|
| 1031 |
+
[pytest]
|
| 1032 |
+
log_file={log_file}
|
| 1033 |
+
log_file_level = INFO
|
| 1034 |
+
"""
|
| 1035 |
+
)
|
| 1036 |
+
|
| 1037 |
+
pytester.makepyfile(
|
| 1038 |
+
"""
|
| 1039 |
+
import logging
|
| 1040 |
+
|
| 1041 |
+
logging.getLogger().info("Normal message")
|
| 1042 |
+
|
| 1043 |
+
def test_simple():
|
| 1044 |
+
logging.getLogger().debug("debug message in test_simple")
|
| 1045 |
+
logging.getLogger().info("info message in test_simple")
|
| 1046 |
+
"""
|
| 1047 |
+
)
|
| 1048 |
+
|
| 1049 |
+
result = pytester.runpytest()
|
| 1050 |
+
|
| 1051 |
+
result.stdout.no_fnmatch_line("*--- live log collection ---*")
|
| 1052 |
+
|
| 1053 |
+
assert result.ret == 0
|
| 1054 |
+
assert os.path.isfile(log_file)
|
| 1055 |
+
with open(log_file, encoding="utf-8") as rfh:
|
| 1056 |
+
contents = rfh.read()
|
| 1057 |
+
assert "Normal message" in contents
|
| 1058 |
+
assert "debug message in test_simple" not in contents
|
| 1059 |
+
assert "info message in test_simple" in contents
|
| 1060 |
+
|
| 1061 |
+
|
| 1062 |
+
def test_log_in_hooks(pytester: Pytester) -> None:
|
| 1063 |
+
log_file = str(pytester.path.joinpath("pytest.log"))
|
| 1064 |
+
|
| 1065 |
+
pytester.makeini(
|
| 1066 |
+
f"""
|
| 1067 |
+
[pytest]
|
| 1068 |
+
log_file={log_file}
|
| 1069 |
+
log_file_level = INFO
|
| 1070 |
+
log_cli=true
|
| 1071 |
+
"""
|
| 1072 |
+
)
|
| 1073 |
+
pytester.makeconftest(
|
| 1074 |
+
"""
|
| 1075 |
+
import logging
|
| 1076 |
+
|
| 1077 |
+
def pytest_runtestloop(session):
|
| 1078 |
+
logging.info('runtestloop')
|
| 1079 |
+
|
| 1080 |
+
def pytest_sessionstart(session):
|
| 1081 |
+
logging.info('sessionstart')
|
| 1082 |
+
|
| 1083 |
+
def pytest_sessionfinish(session, exitstatus):
|
| 1084 |
+
logging.info('sessionfinish')
|
| 1085 |
+
"""
|
| 1086 |
+
)
|
| 1087 |
+
result = pytester.runpytest()
|
| 1088 |
+
result.stdout.fnmatch_lines(["*sessionstart*", "*runtestloop*", "*sessionfinish*"])
|
| 1089 |
+
with open(log_file, encoding="utf-8") as rfh:
|
| 1090 |
+
contents = rfh.read()
|
| 1091 |
+
assert "sessionstart" in contents
|
| 1092 |
+
assert "runtestloop" in contents
|
| 1093 |
+
assert "sessionfinish" in contents
|
| 1094 |
+
|
| 1095 |
+
|
| 1096 |
+
def test_log_in_runtest_logreport(pytester: Pytester) -> None:
|
| 1097 |
+
log_file = str(pytester.path.joinpath("pytest.log"))
|
| 1098 |
+
|
| 1099 |
+
pytester.makeini(
|
| 1100 |
+
f"""
|
| 1101 |
+
[pytest]
|
| 1102 |
+
log_file={log_file}
|
| 1103 |
+
log_file_level = INFO
|
| 1104 |
+
log_cli=true
|
| 1105 |
+
"""
|
| 1106 |
+
)
|
| 1107 |
+
pytester.makeconftest(
|
| 1108 |
+
"""
|
| 1109 |
+
import logging
|
| 1110 |
+
logger = logging.getLogger(__name__)
|
| 1111 |
+
|
| 1112 |
+
def pytest_runtest_logreport(report):
|
| 1113 |
+
logger.info("logreport")
|
| 1114 |
+
"""
|
| 1115 |
+
)
|
| 1116 |
+
pytester.makepyfile(
|
| 1117 |
+
"""
|
| 1118 |
+
def test_first():
|
| 1119 |
+
assert True
|
| 1120 |
+
"""
|
| 1121 |
+
)
|
| 1122 |
+
pytester.runpytest()
|
| 1123 |
+
with open(log_file, encoding="utf-8") as rfh:
|
| 1124 |
+
contents = rfh.read()
|
| 1125 |
+
assert contents.count("logreport") == 3
|
| 1126 |
+
|
| 1127 |
+
|
| 1128 |
+
def test_log_set_path(pytester: Pytester) -> None:
|
| 1129 |
+
report_dir_base = str(pytester.path)
|
| 1130 |
+
|
| 1131 |
+
pytester.makeini(
|
| 1132 |
+
"""
|
| 1133 |
+
[pytest]
|
| 1134 |
+
log_file_level = DEBUG
|
| 1135 |
+
log_cli=true
|
| 1136 |
+
"""
|
| 1137 |
+
)
|
| 1138 |
+
pytester.makeconftest(
|
| 1139 |
+
f"""
|
| 1140 |
+
import os
|
| 1141 |
+
import pytest
|
| 1142 |
+
@pytest.hookimpl(wrapper=True, tryfirst=True)
|
| 1143 |
+
def pytest_runtest_setup(item):
|
| 1144 |
+
config = item.config
|
| 1145 |
+
logging_plugin = config.pluginmanager.get_plugin("logging-plugin")
|
| 1146 |
+
report_file = os.path.join({report_dir_base!r}, item._request.node.name)
|
| 1147 |
+
logging_plugin.set_log_path(report_file)
|
| 1148 |
+
return (yield)
|
| 1149 |
+
"""
|
| 1150 |
+
)
|
| 1151 |
+
pytester.makepyfile(
|
| 1152 |
+
"""
|
| 1153 |
+
import logging
|
| 1154 |
+
logger = logging.getLogger("testcase-logger")
|
| 1155 |
+
def test_first():
|
| 1156 |
+
logger.info("message from test 1")
|
| 1157 |
+
assert True
|
| 1158 |
+
|
| 1159 |
+
def test_second():
|
| 1160 |
+
logger.debug("message from test 2")
|
| 1161 |
+
assert True
|
| 1162 |
+
"""
|
| 1163 |
+
)
|
| 1164 |
+
pytester.runpytest()
|
| 1165 |
+
with open(os.path.join(report_dir_base, "test_first"), encoding="utf-8") as rfh:
|
| 1166 |
+
content = rfh.read()
|
| 1167 |
+
assert "message from test 1" in content
|
| 1168 |
+
|
| 1169 |
+
with open(os.path.join(report_dir_base, "test_second"), encoding="utf-8") as rfh:
|
| 1170 |
+
content = rfh.read()
|
| 1171 |
+
assert "message from test 2" in content
|
| 1172 |
+
|
| 1173 |
+
|
| 1174 |
+
def test_log_set_path_with_log_file_mode(pytester: Pytester) -> None:
|
| 1175 |
+
report_dir_base = str(pytester.path)
|
| 1176 |
+
|
| 1177 |
+
pytester.makeini(
|
| 1178 |
+
"""
|
| 1179 |
+
[pytest]
|
| 1180 |
+
log_file_level = DEBUG
|
| 1181 |
+
log_cli=true
|
| 1182 |
+
log_file_mode=a
|
| 1183 |
+
"""
|
| 1184 |
+
)
|
| 1185 |
+
pytester.makeconftest(
|
| 1186 |
+
f"""
|
| 1187 |
+
import os
|
| 1188 |
+
import pytest
|
| 1189 |
+
@pytest.hookimpl(wrapper=True, tryfirst=True)
|
| 1190 |
+
def pytest_runtest_setup(item):
|
| 1191 |
+
config = item.config
|
| 1192 |
+
logging_plugin = config.pluginmanager.get_plugin("logging-plugin")
|
| 1193 |
+
report_file = os.path.join({report_dir_base!r}, item._request.node.name)
|
| 1194 |
+
logging_plugin.set_log_path(report_file)
|
| 1195 |
+
return (yield)
|
| 1196 |
+
"""
|
| 1197 |
+
)
|
| 1198 |
+
pytester.makepyfile(
|
| 1199 |
+
"""
|
| 1200 |
+
import logging
|
| 1201 |
+
logger = logging.getLogger("testcase-logger")
|
| 1202 |
+
def test_first():
|
| 1203 |
+
logger.info("message from test 1")
|
| 1204 |
+
assert True
|
| 1205 |
+
|
| 1206 |
+
def test_second():
|
| 1207 |
+
logger.debug("message from test 2")
|
| 1208 |
+
assert True
|
| 1209 |
+
"""
|
| 1210 |
+
)
|
| 1211 |
+
|
| 1212 |
+
test_first_log_file = os.path.join(report_dir_base, "test_first")
|
| 1213 |
+
test_second_log_file = os.path.join(report_dir_base, "test_second")
|
| 1214 |
+
with open(test_first_log_file, mode="w", encoding="utf-8") as wfh:
|
| 1215 |
+
wfh.write("A custom header for test 1\n")
|
| 1216 |
+
|
| 1217 |
+
with open(test_second_log_file, mode="w", encoding="utf-8") as wfh:
|
| 1218 |
+
wfh.write("A custom header for test 2\n")
|
| 1219 |
+
|
| 1220 |
+
result = pytester.runpytest()
|
| 1221 |
+
assert result.ret == ExitCode.OK
|
| 1222 |
+
|
| 1223 |
+
with open(test_first_log_file, encoding="utf-8") as rfh:
|
| 1224 |
+
content = rfh.read()
|
| 1225 |
+
assert "A custom header for test 1" in content
|
| 1226 |
+
assert "message from test 1" in content
|
| 1227 |
+
|
| 1228 |
+
with open(test_second_log_file, encoding="utf-8") as rfh:
|
| 1229 |
+
content = rfh.read()
|
| 1230 |
+
assert "A custom header for test 2" in content
|
| 1231 |
+
assert "message from test 2" in content
|
| 1232 |
+
|
| 1233 |
+
|
| 1234 |
+
def test_colored_captured_log(pytester: Pytester) -> None:
|
| 1235 |
+
"""Test that the level names of captured log messages of a failing test
|
| 1236 |
+
are colored."""
|
| 1237 |
+
pytester.makepyfile(
|
| 1238 |
+
"""
|
| 1239 |
+
import logging
|
| 1240 |
+
|
| 1241 |
+
logger = logging.getLogger(__name__)
|
| 1242 |
+
|
| 1243 |
+
def test_foo():
|
| 1244 |
+
logger.info('text going to logger from call')
|
| 1245 |
+
assert False
|
| 1246 |
+
"""
|
| 1247 |
+
)
|
| 1248 |
+
result = pytester.runpytest("--log-level=INFO", "--color=yes")
|
| 1249 |
+
assert result.ret == 1
|
| 1250 |
+
result.stdout.fnmatch_lines(
|
| 1251 |
+
[
|
| 1252 |
+
"*-- Captured log call --*",
|
| 1253 |
+
"\x1b[32mINFO \x1b[0m*text going to logger from call",
|
| 1254 |
+
]
|
| 1255 |
+
)
|
| 1256 |
+
|
| 1257 |
+
|
| 1258 |
+
def test_colored_ansi_esc_caplogtext(pytester: Pytester) -> None:
|
| 1259 |
+
"""Make sure that caplog.text does not contain ANSI escape sequences."""
|
| 1260 |
+
pytester.makepyfile(
|
| 1261 |
+
"""
|
| 1262 |
+
import logging
|
| 1263 |
+
|
| 1264 |
+
logger = logging.getLogger(__name__)
|
| 1265 |
+
|
| 1266 |
+
def test_foo(caplog):
|
| 1267 |
+
logger.info('text going to logger from call')
|
| 1268 |
+
assert '\x1b' not in caplog.text
|
| 1269 |
+
"""
|
| 1270 |
+
)
|
| 1271 |
+
result = pytester.runpytest("--log-level=INFO", "--color=yes")
|
| 1272 |
+
assert result.ret == 0
|
| 1273 |
+
|
| 1274 |
+
|
| 1275 |
+
def test_logging_emit_error(pytester: Pytester) -> None:
|
| 1276 |
+
"""An exception raised during emit() should fail the test.
|
| 1277 |
+
|
| 1278 |
+
The default behavior of logging is to print "Logging error"
|
| 1279 |
+
to stderr with the call stack and some extra details.
|
| 1280 |
+
|
| 1281 |
+
pytest overrides this behavior to propagate the exception.
|
| 1282 |
+
"""
|
| 1283 |
+
pytester.makepyfile(
|
| 1284 |
+
"""
|
| 1285 |
+
import logging
|
| 1286 |
+
|
| 1287 |
+
def test_bad_log():
|
| 1288 |
+
logging.warning('oops', 'first', 2)
|
| 1289 |
+
"""
|
| 1290 |
+
)
|
| 1291 |
+
result = pytester.runpytest()
|
| 1292 |
+
result.assert_outcomes(failed=1)
|
| 1293 |
+
result.stdout.fnmatch_lines(
|
| 1294 |
+
[
|
| 1295 |
+
"====* FAILURES *====",
|
| 1296 |
+
"*not all arguments converted during string formatting*",
|
| 1297 |
+
]
|
| 1298 |
+
)
|
| 1299 |
+
|
| 1300 |
+
|
| 1301 |
+
def test_logging_emit_error_supressed(pytester: Pytester) -> None:
|
| 1302 |
+
"""If logging is configured to silently ignore errors, pytest
|
| 1303 |
+
doesn't propagate errors either."""
|
| 1304 |
+
pytester.makepyfile(
|
| 1305 |
+
"""
|
| 1306 |
+
import logging
|
| 1307 |
+
|
| 1308 |
+
def test_bad_log(monkeypatch):
|
| 1309 |
+
monkeypatch.setattr(logging, 'raiseExceptions', False)
|
| 1310 |
+
logging.warning('oops', 'first', 2)
|
| 1311 |
+
"""
|
| 1312 |
+
)
|
| 1313 |
+
result = pytester.runpytest()
|
| 1314 |
+
result.assert_outcomes(passed=1)
|
| 1315 |
+
|
| 1316 |
+
|
| 1317 |
+
def test_log_file_cli_subdirectories_are_successfully_created(
|
| 1318 |
+
pytester: Pytester,
|
| 1319 |
+
) -> None:
|
| 1320 |
+
path = pytester.makepyfile(""" def test_logger(): pass """)
|
| 1321 |
+
expected = os.path.join(os.path.dirname(str(path)), "foo", "bar")
|
| 1322 |
+
result = pytester.runpytest("--log-file=foo/bar/logf.log")
|
| 1323 |
+
assert "logf.log" in os.listdir(expected)
|
| 1324 |
+
assert result.ret == ExitCode.OK
|
| 1325 |
+
|
| 1326 |
+
|
| 1327 |
+
def test_disable_loggers(pytester: Pytester) -> None:
|
| 1328 |
+
pytester.makepyfile(
|
| 1329 |
+
"""
|
| 1330 |
+
import logging
|
| 1331 |
+
import os
|
| 1332 |
+
disabled_log = logging.getLogger('disabled')
|
| 1333 |
+
test_log = logging.getLogger('test')
|
| 1334 |
+
def test_logger_propagation(caplog):
|
| 1335 |
+
with caplog.at_level(logging.DEBUG):
|
| 1336 |
+
disabled_log.warning("no log; no stderr")
|
| 1337 |
+
test_log.debug("Visible text!")
|
| 1338 |
+
assert caplog.record_tuples == [('test', 10, 'Visible text!')]
|
| 1339 |
+
"""
|
| 1340 |
+
)
|
| 1341 |
+
result = pytester.runpytest("--log-disable=disabled", "-s")
|
| 1342 |
+
assert result.ret == ExitCode.OK
|
| 1343 |
+
assert not result.stderr.lines
|
| 1344 |
+
|
| 1345 |
+
|
| 1346 |
+
def test_disable_loggers_does_not_propagate(pytester: Pytester) -> None:
|
| 1347 |
+
pytester.makepyfile(
|
| 1348 |
+
"""
|
| 1349 |
+
import logging
|
| 1350 |
+
import os
|
| 1351 |
+
|
| 1352 |
+
parent_logger = logging.getLogger("parent")
|
| 1353 |
+
child_logger = parent_logger.getChild("child")
|
| 1354 |
+
|
| 1355 |
+
def test_logger_propagation_to_parent(caplog):
|
| 1356 |
+
with caplog.at_level(logging.DEBUG):
|
| 1357 |
+
parent_logger.warning("some parent logger message")
|
| 1358 |
+
child_logger.warning("some child logger message")
|
| 1359 |
+
assert len(caplog.record_tuples) == 1
|
| 1360 |
+
assert caplog.record_tuples[0][0] == "parent"
|
| 1361 |
+
assert caplog.record_tuples[0][2] == "some parent logger message"
|
| 1362 |
+
"""
|
| 1363 |
+
)
|
| 1364 |
+
|
| 1365 |
+
result = pytester.runpytest("--log-disable=parent.child", "-s")
|
| 1366 |
+
assert result.ret == ExitCode.OK
|
| 1367 |
+
assert not result.stderr.lines
|
| 1368 |
+
|
| 1369 |
+
|
| 1370 |
+
def test_log_disabling_works_with_log_cli(pytester: Pytester) -> None:
|
| 1371 |
+
pytester.makepyfile(
|
| 1372 |
+
"""
|
| 1373 |
+
import logging
|
| 1374 |
+
disabled_log = logging.getLogger('disabled')
|
| 1375 |
+
test_log = logging.getLogger('test')
|
| 1376 |
+
|
| 1377 |
+
def test_log_cli_works(caplog):
|
| 1378 |
+
test_log.info("Visible text!")
|
| 1379 |
+
disabled_log.warning("This string will be suppressed.")
|
| 1380 |
+
"""
|
| 1381 |
+
)
|
| 1382 |
+
result = pytester.runpytest(
|
| 1383 |
+
"--log-cli-level=DEBUG",
|
| 1384 |
+
"--log-disable=disabled",
|
| 1385 |
+
)
|
| 1386 |
+
assert result.ret == ExitCode.OK
|
| 1387 |
+
result.stdout.fnmatch_lines(
|
| 1388 |
+
"INFO test:test_log_disabling_works_with_log_cli.py:6 Visible text!"
|
| 1389 |
+
)
|
| 1390 |
+
result.stdout.no_fnmatch_line(
|
| 1391 |
+
"WARNING disabled:test_log_disabling_works_with_log_cli.py:7 This string will be suppressed."
|
| 1392 |
+
)
|
| 1393 |
+
assert not result.stderr.lines
|
| 1394 |
+
|
| 1395 |
+
|
| 1396 |
+
def test_without_date_format_log(pytester: Pytester) -> None:
|
| 1397 |
+
"""Check that date is not printed by default."""
|
| 1398 |
+
pytester.makepyfile(
|
| 1399 |
+
"""
|
| 1400 |
+
import logging
|
| 1401 |
+
|
| 1402 |
+
logger = logging.getLogger(__name__)
|
| 1403 |
+
|
| 1404 |
+
def test_foo():
|
| 1405 |
+
logger.warning('text')
|
| 1406 |
+
assert False
|
| 1407 |
+
"""
|
| 1408 |
+
)
|
| 1409 |
+
result = pytester.runpytest()
|
| 1410 |
+
assert result.ret == 1
|
| 1411 |
+
result.stdout.fnmatch_lines(
|
| 1412 |
+
["WARNING test_without_date_format_log:test_without_date_format_log.py:6 text"]
|
| 1413 |
+
)
|
| 1414 |
+
|
| 1415 |
+
|
| 1416 |
+
def test_date_format_log(pytester: Pytester) -> None:
|
| 1417 |
+
"""Check that log_date_format affects output."""
|
| 1418 |
+
pytester.makepyfile(
|
| 1419 |
+
"""
|
| 1420 |
+
import logging
|
| 1421 |
+
|
| 1422 |
+
logger = logging.getLogger(__name__)
|
| 1423 |
+
|
| 1424 |
+
def test_foo():
|
| 1425 |
+
logger.warning('text')
|
| 1426 |
+
assert False
|
| 1427 |
+
"""
|
| 1428 |
+
)
|
| 1429 |
+
pytester.makeini(
|
| 1430 |
+
"""
|
| 1431 |
+
[pytest]
|
| 1432 |
+
log_format=%(asctime)s; %(levelname)s; %(message)s
|
| 1433 |
+
log_date_format=%Y-%m-%d %H:%M:%S
|
| 1434 |
+
"""
|
| 1435 |
+
)
|
| 1436 |
+
result = pytester.runpytest()
|
| 1437 |
+
assert result.ret == 1
|
| 1438 |
+
result.stdout.re_match_lines([r"^[0-9-]{10} [0-9:]{8}; WARNING; text"])
|
| 1439 |
+
|
| 1440 |
+
|
| 1441 |
+
def test_date_format_percentf_log(pytester: Pytester) -> None:
|
| 1442 |
+
"""Make sure that microseconds are printed in log."""
|
| 1443 |
+
pytester.makepyfile(
|
| 1444 |
+
"""
|
| 1445 |
+
import logging
|
| 1446 |
+
|
| 1447 |
+
logger = logging.getLogger(__name__)
|
| 1448 |
+
|
| 1449 |
+
def test_foo():
|
| 1450 |
+
logger.warning('text')
|
| 1451 |
+
assert False
|
| 1452 |
+
"""
|
| 1453 |
+
)
|
| 1454 |
+
pytester.makeini(
|
| 1455 |
+
"""
|
| 1456 |
+
[pytest]
|
| 1457 |
+
log_format=%(asctime)s; %(levelname)s; %(message)s
|
| 1458 |
+
log_date_format=%Y-%m-%d %H:%M:%S.%f
|
| 1459 |
+
"""
|
| 1460 |
+
)
|
| 1461 |
+
result = pytester.runpytest()
|
| 1462 |
+
assert result.ret == 1
|
| 1463 |
+
result.stdout.re_match_lines([r"^[0-9-]{10} [0-9:]{8}.[0-9]{6}; WARNING; text"])
|
| 1464 |
+
|
| 1465 |
+
|
| 1466 |
+
def test_date_format_percentf_tz_log(pytester: Pytester) -> None:
|
| 1467 |
+
"""Make sure that timezone and microseconds are properly formatted together."""
|
| 1468 |
+
pytester.makepyfile(
|
| 1469 |
+
"""
|
| 1470 |
+
import logging
|
| 1471 |
+
|
| 1472 |
+
logger = logging.getLogger(__name__)
|
| 1473 |
+
|
| 1474 |
+
def test_foo():
|
| 1475 |
+
logger.warning('text')
|
| 1476 |
+
assert False
|
| 1477 |
+
"""
|
| 1478 |
+
)
|
| 1479 |
+
pytester.makeini(
|
| 1480 |
+
"""
|
| 1481 |
+
[pytest]
|
| 1482 |
+
log_format=%(asctime)s; %(levelname)s; %(message)s
|
| 1483 |
+
log_date_format=%Y-%m-%d %H:%M:%S.%f%z
|
| 1484 |
+
"""
|
| 1485 |
+
)
|
| 1486 |
+
result = pytester.runpytest()
|
| 1487 |
+
assert result.ret == 1
|
| 1488 |
+
result.stdout.re_match_lines(
|
| 1489 |
+
[r"^[0-9-]{10} [0-9:]{8}.[0-9]{6}[+-][0-9\.]+; WARNING; text"]
|
| 1490 |
+
)
|
| 1491 |
+
|
| 1492 |
+
|
| 1493 |
+
def test_log_file_cli_fallback_options(pytester: Pytester) -> None:
|
| 1494 |
+
"""Make sure that fallback values for log-file formats and level works."""
|
| 1495 |
+
pytester.makepyfile(
|
| 1496 |
+
"""
|
| 1497 |
+
import logging
|
| 1498 |
+
logger = logging.getLogger()
|
| 1499 |
+
|
| 1500 |
+
def test_foo():
|
| 1501 |
+
logger.info('info text going to logger')
|
| 1502 |
+
logger.warning('warning text going to logger')
|
| 1503 |
+
logger.error('error text going to logger')
|
| 1504 |
+
|
| 1505 |
+
assert 0
|
| 1506 |
+
"""
|
| 1507 |
+
)
|
| 1508 |
+
log_file = str(pytester.path.joinpath("pytest.log"))
|
| 1509 |
+
result = pytester.runpytest(
|
| 1510 |
+
"--log-level=ERROR",
|
| 1511 |
+
"--log-format=%(asctime)s %(message)s",
|
| 1512 |
+
"--log-date-format=%H:%M",
|
| 1513 |
+
"--log-file=pytest.log",
|
| 1514 |
+
)
|
| 1515 |
+
assert result.ret == 1
|
| 1516 |
+
|
| 1517 |
+
# The log file should only contain the error log messages
|
| 1518 |
+
# not the warning or info ones and the format and date format
|
| 1519 |
+
# should match the formats provided using --log-format and --log-date-format
|
| 1520 |
+
assert os.path.isfile(log_file)
|
| 1521 |
+
with open(log_file, encoding="utf-8") as rfh:
|
| 1522 |
+
contents = rfh.read()
|
| 1523 |
+
assert re.match(r"[0-9]{2}:[0-9]{2} error text going to logger\s*", contents)
|
| 1524 |
+
assert "info text going to logger" not in contents
|
| 1525 |
+
assert "warning text going to logger" not in contents
|
| 1526 |
+
assert "error text going to logger" in contents
|
| 1527 |
+
|
| 1528 |
+
# Try with a different format and date format to make sure that the formats
|
| 1529 |
+
# are being used
|
| 1530 |
+
result = pytester.runpytest(
|
| 1531 |
+
"--log-level=ERROR",
|
| 1532 |
+
"--log-format=%(asctime)s : %(message)s",
|
| 1533 |
+
"--log-date-format=%H:%M:%S",
|
| 1534 |
+
"--log-file=pytest.log",
|
| 1535 |
+
)
|
| 1536 |
+
assert result.ret == 1
|
| 1537 |
+
|
| 1538 |
+
# The log file should only contain the error log messages
|
| 1539 |
+
# not the warning or info ones and the format and date format
|
| 1540 |
+
# should match the formats provided using --log-format and --log-date-format
|
| 1541 |
+
assert os.path.isfile(log_file)
|
| 1542 |
+
with open(log_file, encoding="utf-8") as rfh:
|
| 1543 |
+
contents = rfh.read()
|
| 1544 |
+
assert re.match(
|
| 1545 |
+
r"[0-9]{2}:[0-9]{2}:[0-9]{2} : error text going to logger\s*", contents
|
| 1546 |
+
)
|
| 1547 |
+
assert "info text going to logger" not in contents
|
| 1548 |
+
assert "warning text going to logger" not in contents
|
| 1549 |
+
assert "error text going to logger" in contents
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/.gitignore
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.html
|
| 2 |
+
assets/
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/README.rst
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
This directory contains tests and support files for smoke testing popular plugins against the current pytest version.
|
| 2 |
+
|
| 3 |
+
The objective is to gauge if any intentional or unintentional changes in pytest break plugins.
|
| 4 |
+
|
| 5 |
+
As a rule of thumb, we should add plugins here:
|
| 6 |
+
|
| 7 |
+
1. That are used at large. This might be subjective in some cases, but if answer is yes to
|
| 8 |
+
the question: *if a new release of pytest causes pytest-X to break, will this break a ton of test suites out there?*.
|
| 9 |
+
2. That don't have large external dependencies: such as external services.
|
| 10 |
+
|
| 11 |
+
Besides adding the plugin as dependency, we should also add a quick test which uses some
|
| 12 |
+
minimal part of the plugin, a smoke test. Also consider reusing one of the existing tests if that's
|
| 13 |
+
possible.
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/bdd_wallet.feature
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Feature: Buy things with apple
|
| 2 |
+
|
| 3 |
+
Scenario: Buy fruits
|
| 4 |
+
Given A wallet with 50
|
| 5 |
+
|
| 6 |
+
When I buy some apples for 1
|
| 7 |
+
And I buy some bananas for 2
|
| 8 |
+
|
| 9 |
+
Then I have 47 left
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/bdd_wallet.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from pytest_bdd import given
|
| 5 |
+
from pytest_bdd import scenario
|
| 6 |
+
from pytest_bdd import then
|
| 7 |
+
from pytest_bdd import when
|
| 8 |
+
|
| 9 |
+
import pytest
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@scenario("bdd_wallet.feature", "Buy fruits")
|
| 13 |
+
def test_publish():
|
| 14 |
+
pass
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@pytest.fixture
|
| 18 |
+
def wallet():
|
| 19 |
+
class Wallet:
|
| 20 |
+
amount = 0
|
| 21 |
+
|
| 22 |
+
return Wallet()
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@given("A wallet with 50")
|
| 26 |
+
def fill_wallet(wallet):
|
| 27 |
+
wallet.amount = 50
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@when("I buy some apples for 1")
|
| 31 |
+
def buy_apples(wallet):
|
| 32 |
+
wallet.amount -= 1
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@when("I buy some bananas for 2")
|
| 36 |
+
def buy_bananas(wallet):
|
| 37 |
+
wallet.amount -= 2
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@then("I have 47 left")
|
| 41 |
+
def check(wallet):
|
| 42 |
+
assert wallet.amount == 47
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/django_settings.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
SECRET_KEY = "mysecret"
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest.ini
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[pytest]
|
| 2 |
+
strict_markers = True
|
| 3 |
+
asyncio_mode = strict
|
| 4 |
+
filterwarnings =
|
| 5 |
+
error::pytest.PytestWarning
|
| 6 |
+
ignore:usefixtures.* without arguments has no effect:pytest.PytestWarning
|
| 7 |
+
ignore:.*.fspath is deprecated and will be replaced by .*.path.*:pytest.PytestDeprecationWarning
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_anyio_integration.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import anyio
|
| 5 |
+
|
| 6 |
+
import pytest
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@pytest.mark.anyio
|
| 10 |
+
async def test_sleep():
|
| 11 |
+
await anyio.sleep(0)
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_asyncio_integration.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import asyncio
|
| 5 |
+
|
| 6 |
+
import pytest
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@pytest.mark.asyncio
|
| 10 |
+
async def test_sleep():
|
| 11 |
+
await asyncio.sleep(0)
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_mock_integration.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def test_mocker(mocker):
|
| 6 |
+
mocker.MagicMock()
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_rerunfailures_integration.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import unittest
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class MyTestCase(unittest.TestCase):
|
| 7 |
+
first_time = True
|
| 8 |
+
|
| 9 |
+
def test_fail_the_first_time(self) -> None:
|
| 10 |
+
"""Regression test for issue #12424."""
|
| 11 |
+
if self.first_time:
|
| 12 |
+
type(self).first_time = False
|
| 13 |
+
self.fail()
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_trio_integration.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import trio
|
| 5 |
+
|
| 6 |
+
import pytest
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@pytest.mark.trio
|
| 10 |
+
async def test_sleep():
|
| 11 |
+
await trio.sleep(0)
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/pytest_twisted_integration.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import pytest_twisted
|
| 5 |
+
from twisted.internet.task import deferLater
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def sleep():
|
| 9 |
+
import twisted.internet.reactor
|
| 10 |
+
|
| 11 |
+
return deferLater(clock=twisted.internet.reactor, delay=0)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@pytest_twisted.inlineCallbacks
|
| 15 |
+
def test_inlineCallbacks():
|
| 16 |
+
yield sleep()
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@pytest_twisted.ensureDeferred
|
| 20 |
+
async def test_inlineCallbacks_async():
|
| 21 |
+
await sleep()
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/requirements.txt
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
anyio[trio]==4.13.0
|
| 2 |
+
django==6.0.4
|
| 3 |
+
pytest-asyncio==1.3.0
|
| 4 |
+
pytest-bdd==8.1.0
|
| 5 |
+
pytest-cov==7.1.0
|
| 6 |
+
pytest-django==4.12.0
|
| 7 |
+
pytest-flakes==4.0.5
|
| 8 |
+
pytest-html==4.2.0
|
| 9 |
+
pytest-mock==3.15.1
|
| 10 |
+
pytest-rerunfailures==16.1
|
| 11 |
+
pytest-sugar==1.1.1
|
| 12 |
+
pytest-trio==0.8.0
|
| 13 |
+
pytest-twisted==1.14.3
|
| 14 |
+
twisted==25.5.0
|
| 15 |
+
pytest-xvfb==3.1.1
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/plugins_integration/simple_integration.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def test_foo():
|
| 8 |
+
assert True
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@pytest.mark.parametrize("i", range(3))
|
| 12 |
+
def test_bar(i):
|
| 13 |
+
assert True
|
tasks/tasksmith-5e916b3f6da1/tests/source/testing/python/approx.py
ADDED
|
@@ -0,0 +1,1162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from contextlib import contextmanager
|
| 5 |
+
import decimal
|
| 6 |
+
from decimal import Decimal
|
| 7 |
+
from fractions import Fraction
|
| 8 |
+
from math import inf
|
| 9 |
+
from math import nan
|
| 10 |
+
from math import sqrt
|
| 11 |
+
import operator
|
| 12 |
+
from operator import eq
|
| 13 |
+
from operator import ne
|
| 14 |
+
import re
|
| 15 |
+
|
| 16 |
+
from _pytest.pytester import Pytester
|
| 17 |
+
from _pytest.python_api import _recursive_sequence_map
|
| 18 |
+
import pytest
|
| 19 |
+
from pytest import approx
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@pytest.fixture
|
| 23 |
+
def mocked_doctest_runner(monkeypatch):
|
| 24 |
+
import doctest
|
| 25 |
+
|
| 26 |
+
class MockedPdb:
|
| 27 |
+
def __init__(self, out):
|
| 28 |
+
pass
|
| 29 |
+
|
| 30 |
+
def set_trace(self):
|
| 31 |
+
raise NotImplementedError("not used")
|
| 32 |
+
|
| 33 |
+
def reset(self):
|
| 34 |
+
pass
|
| 35 |
+
|
| 36 |
+
def set_continue(self):
|
| 37 |
+
pass
|
| 38 |
+
|
| 39 |
+
monkeypatch.setattr("doctest._OutputRedirectingPdb", MockedPdb)
|
| 40 |
+
|
| 41 |
+
class MyDocTestRunner(doctest.DocTestRunner):
|
| 42 |
+
def report_failure(self, out, test, example, got):
|
| 43 |
+
raise AssertionError(
|
| 44 |
+
f"'{example.source.strip()}' evaluates to '{got.strip()}', not '{example.want.strip()}'"
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
return MyDocTestRunner()
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@contextmanager
|
| 51 |
+
def temporary_verbosity(config, verbosity=0):
|
| 52 |
+
original_verbosity = config.getoption("verbose")
|
| 53 |
+
config.option.verbose = verbosity
|
| 54 |
+
try:
|
| 55 |
+
yield
|
| 56 |
+
finally:
|
| 57 |
+
config.option.verbose = original_verbosity
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
@pytest.fixture
|
| 61 |
+
def assert_approx_raises_regex(pytestconfig):
|
| 62 |
+
def do_assert(lhs, rhs, expected_message, verbosity_level=0):
|
| 63 |
+
import re
|
| 64 |
+
|
| 65 |
+
with temporary_verbosity(pytestconfig, verbosity_level):
|
| 66 |
+
with pytest.raises(AssertionError) as e:
|
| 67 |
+
assert lhs == approx(rhs)
|
| 68 |
+
|
| 69 |
+
nl = "\n"
|
| 70 |
+
obtained_message = str(e.value).splitlines()[1:]
|
| 71 |
+
assert len(obtained_message) == len(expected_message), (
|
| 72 |
+
"Regex message length doesn't match obtained.\n"
|
| 73 |
+
"Obtained:\n"
|
| 74 |
+
f"{nl.join(obtained_message)}\n\n"
|
| 75 |
+
"Expected regex:\n"
|
| 76 |
+
f"{nl.join(expected_message)}\n\n"
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
for i, (obtained_line, expected_line) in enumerate(
|
| 80 |
+
zip(obtained_message, expected_message, strict=True)
|
| 81 |
+
):
|
| 82 |
+
regex = re.compile(expected_line)
|
| 83 |
+
assert regex.match(obtained_line) is not None, (
|
| 84 |
+
"Unexpected error message:\n"
|
| 85 |
+
f"{nl.join(obtained_message)}\n\n"
|
| 86 |
+
"Did not match regex:\n"
|
| 87 |
+
f"{nl.join(expected_message)}\n\n"
|
| 88 |
+
f"With verbosity level = {verbosity_level}, on line {i}"
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
return do_assert
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
SOME_FLOAT = r"[+-]?((?:([0-9]*[.])?[0-9]+(e-?[0-9]+)?)|inf|nan)\s*"
|
| 95 |
+
SOME_INT = r"[0-9]+\s*"
|
| 96 |
+
SOME_TOLERANCE = rf"({SOME_FLOAT}|[+-]?[0-9]+(\.[0-9]+)?[eE][+-]?[0-9]+\s*)"
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class TestApprox:
|
| 100 |
+
def test_error_messages_native_dtypes(self, assert_approx_raises_regex):
|
| 101 |
+
# Treat bool exactly.
|
| 102 |
+
assert_approx_raises_regex(
|
| 103 |
+
{"a": 1.0, "b": True},
|
| 104 |
+
{"a": 1.0, "b": False},
|
| 105 |
+
[
|
| 106 |
+
"",
|
| 107 |
+
" comparison failed. Mismatched elements: 1 / 2:",
|
| 108 |
+
f" Max absolute difference: {SOME_FLOAT}",
|
| 109 |
+
f" Max relative difference: {SOME_FLOAT}",
|
| 110 |
+
r" Index\s+\| Obtained\s+\| Expected",
|
| 111 |
+
r".*(True|False)\s+",
|
| 112 |
+
],
|
| 113 |
+
)
|
| 114 |
+
assert_approx_raises_regex(
|
| 115 |
+
2.0,
|
| 116 |
+
1.0,
|
| 117 |
+
[
|
| 118 |
+
"",
|
| 119 |
+
" comparison failed",
|
| 120 |
+
f" Obtained: {SOME_FLOAT}",
|
| 121 |
+
f" Expected: {SOME_FLOAT} ± {SOME_TOLERANCE}",
|
| 122 |
+
],
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
assert_approx_raises_regex(
|
| 126 |
+
{"a": 1.0, "b": 1000.0, "c": 1000000.0},
|
| 127 |
+
{
|
| 128 |
+
"a": 2.0,
|
| 129 |
+
"b": 1000.0,
|
| 130 |
+
"c": 3000000.0,
|
| 131 |
+
},
|
| 132 |
+
[
|
| 133 |
+
r"",
|
| 134 |
+
r" comparison failed. Mismatched elements: 2 / 3:",
|
| 135 |
+
rf" Max absolute difference: {SOME_FLOAT}",
|
| 136 |
+
rf" Max relative difference: {SOME_FLOAT}",
|
| 137 |
+
r" Index \| Obtained\s+\| Expected\s+",
|
| 138 |
+
rf" a \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_TOLERANCE}",
|
| 139 |
+
rf" c \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_TOLERANCE}",
|
| 140 |
+
],
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
assert_approx_raises_regex(
|
| 144 |
+
{"a": 1.0, "b": None, "c": None},
|
| 145 |
+
{
|
| 146 |
+
"a": None,
|
| 147 |
+
"b": 1000.0,
|
| 148 |
+
"c": None,
|
| 149 |
+
},
|
| 150 |
+
[
|
| 151 |
+
r"",
|
| 152 |
+
r" comparison failed. Mismatched elements: 2 / 3:",
|
| 153 |
+
r" Max absolute difference: -inf",
|
| 154 |
+
r" Max relative difference: -inf",
|
| 155 |
+
r" Index \| Obtained\s+\| Expected\s+",
|
| 156 |
+
rf" a \| {SOME_FLOAT} \| None",
|
| 157 |
+
rf" b \| None\s+\| {SOME_FLOAT} ± {SOME_FLOAT}",
|
| 158 |
+
],
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
assert_approx_raises_regex(
|
| 162 |
+
[1.0, 2.0, 3.0, 4.0],
|
| 163 |
+
[1.0, 3.0, 3.0, 5.0],
|
| 164 |
+
[
|
| 165 |
+
r"",
|
| 166 |
+
r" comparison failed. Mismatched elements: 2 / 4:",
|
| 167 |
+
rf" Max absolute difference: {SOME_FLOAT}",
|
| 168 |
+
rf" Max relative difference: {SOME_FLOAT}",
|
| 169 |
+
r" Index \| Obtained\s+\| Expected ",
|
| 170 |
+
rf" 1 \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
|
| 171 |
+
rf" 3 \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
|
| 172 |
+
],
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
assert_approx_raises_regex(
|
| 176 |
+
(1, 2.2, 4),
|
| 177 |
+
(1, 3.2, 4),
|
| 178 |
+
[
|
| 179 |
+
r"",
|
| 180 |
+
r" comparison failed. Mismatched elements: 1 / 3:",
|
| 181 |
+
rf" Max absolute difference: {SOME_FLOAT}",
|
| 182 |
+
rf" Max relative difference: {SOME_FLOAT}",
|
| 183 |
+
r" Index \| Obtained\s+\| Expected ",
|
| 184 |
+
rf" 1 \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
|
| 185 |
+
],
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
# Specific test for comparison with 0.0 (relative diff will be 'inf')
|
| 189 |
+
assert_approx_raises_regex(
|
| 190 |
+
[0.0],
|
| 191 |
+
[1.0],
|
| 192 |
+
[
|
| 193 |
+
r"",
|
| 194 |
+
r" comparison failed. Mismatched elements: 1 / 1:",
|
| 195 |
+
rf" Max absolute difference: {SOME_FLOAT}",
|
| 196 |
+
r" Max relative difference: inf",
|
| 197 |
+
r" Index \| Obtained\s+\| Expected ",
|
| 198 |
+
rf"\s*0\s*\| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
|
| 199 |
+
],
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
def test_error_messages_numpy_dtypes(self, assert_approx_raises_regex):
|
| 203 |
+
np = pytest.importorskip("numpy")
|
| 204 |
+
|
| 205 |
+
a = np.linspace(0, 100, 20)
|
| 206 |
+
b = np.linspace(0, 100, 20)
|
| 207 |
+
a[10] += 0.5
|
| 208 |
+
assert_approx_raises_regex(
|
| 209 |
+
a,
|
| 210 |
+
b,
|
| 211 |
+
[
|
| 212 |
+
r"",
|
| 213 |
+
r" comparison failed. Mismatched elements: 1 / 20:",
|
| 214 |
+
rf" Max absolute difference: {SOME_FLOAT}",
|
| 215 |
+
rf" Max relative difference: {SOME_FLOAT}",
|
| 216 |
+
r" Index \| Obtained\s+\| Expected",
|
| 217 |
+
rf" \(10,\) \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
|
| 218 |
+
],
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
assert_approx_raises_regex(
|
| 222 |
+
np.array(
|
| 223 |
+
[
|
| 224 |
+
[[1.1987311, 12412342.3], [3.214143244, 1423412423415.677]],
|
| 225 |
+
[[1, 2], [3, 219371297321973]],
|
| 226 |
+
]
|
| 227 |
+
),
|
| 228 |
+
np.array(
|
| 229 |
+
[
|
| 230 |
+
[[1.12313, 12412342.3], [3.214143244, 534523542345.677]],
|
| 231 |
+
[[1, 2], [3, 7]],
|
| 232 |
+
]
|
| 233 |
+
),
|
| 234 |
+
[
|
| 235 |
+
r"",
|
| 236 |
+
r" comparison failed. Mismatched elements: 3 / 8:",
|
| 237 |
+
rf" Max absolute difference: {SOME_FLOAT}",
|
| 238 |
+
rf" Max relative difference: {SOME_FLOAT}",
|
| 239 |
+
r" Index\s+\| Obtained\s+\| Expected\s+",
|
| 240 |
+
rf" \(0, 0, 0\) \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
|
| 241 |
+
rf" \(0, 1, 1\) \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
|
| 242 |
+
rf" \(1, 1, 1\) \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
|
| 243 |
+
],
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
# Specific test for comparison with 0.0 (relative diff will be 'inf')
|
| 247 |
+
assert_approx_raises_regex(
|
| 248 |
+
np.array([0.0]),
|
| 249 |
+
np.array([1.0]),
|
| 250 |
+
[
|
| 251 |
+
r"",
|
| 252 |
+
r" comparison failed. Mismatched elements: 1 / 1:",
|
| 253 |
+
rf" Max absolute difference: {SOME_FLOAT}",
|
| 254 |
+
r" Max relative difference: inf",
|
| 255 |
+
r" Index \| Obtained\s+\| Expected ",
|
| 256 |
+
rf"\s*\(0,\)\s*\| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
|
| 257 |
+
],
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
def test_error_messages_invalid_args(self, assert_approx_raises_regex):
|
| 261 |
+
np = pytest.importorskip("numpy")
|
| 262 |
+
with pytest.raises(AssertionError) as e:
|
| 263 |
+
assert np.array([[1.2, 3.4], [4.0, 5.0]]) == pytest.approx(
|
| 264 |
+
np.array([[4.0], [5.0]])
|
| 265 |
+
)
|
| 266 |
+
message = "\n".join(str(e.value).split("\n")[1:])
|
| 267 |
+
assert message == "\n".join(
|
| 268 |
+
[
|
| 269 |
+
" ",
|
| 270 |
+
" Impossible to compare arrays with different shapes.",
|
| 271 |
+
" Shapes: (2, 1) and (2, 2)",
|
| 272 |
+
]
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
with pytest.raises(AssertionError) as e:
|
| 276 |
+
assert [1.0, 2.0, 3.0] == pytest.approx([4.0, 5.0])
|
| 277 |
+
message = "\n".join(str(e.value).split("\n")[1:])
|
| 278 |
+
assert message == "\n".join(
|
| 279 |
+
[
|
| 280 |
+
" ",
|
| 281 |
+
" Impossible to compare lists with different sizes.",
|
| 282 |
+
" Lengths: 2 and 3",
|
| 283 |
+
]
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
def test_error_messages_with_different_verbosity(self, assert_approx_raises_regex):
|
| 287 |
+
np = pytest.importorskip("numpy")
|
| 288 |
+
for v in [0, 1, 2]:
|
| 289 |
+
# Verbosity level doesn't affect the error message for scalars
|
| 290 |
+
assert_approx_raises_regex(
|
| 291 |
+
2.0,
|
| 292 |
+
1.0,
|
| 293 |
+
[
|
| 294 |
+
"",
|
| 295 |
+
" comparison failed",
|
| 296 |
+
f" Obtained: {SOME_FLOAT}",
|
| 297 |
+
f" Expected: {SOME_FLOAT} ± {SOME_FLOAT}",
|
| 298 |
+
],
|
| 299 |
+
verbosity_level=v,
|
| 300 |
+
)
|
| 301 |
+
|
| 302 |
+
a = np.linspace(1, 101, 20)
|
| 303 |
+
b = np.linspace(2, 102, 20)
|
| 304 |
+
assert_approx_raises_regex(
|
| 305 |
+
a,
|
| 306 |
+
b,
|
| 307 |
+
[
|
| 308 |
+
r"^ $",
|
| 309 |
+
r"^ comparison failed. Mismatched elements: 20 / 20:$",
|
| 310 |
+
rf"^ Max absolute difference: {SOME_FLOAT}$",
|
| 311 |
+
rf"^ Max relative difference: {SOME_FLOAT}$",
|
| 312 |
+
r"^ Index \| Obtained\s+\| Expected\s+$",
|
| 313 |
+
rf"^ \(0,\)\s+\| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}e-{SOME_INT}$",
|
| 314 |
+
rf"^ \(1,\)\s+\| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}e-{SOME_INT}\.\.\.$",
|
| 315 |
+
"^ $",
|
| 316 |
+
rf"^ ...Full output truncated \({SOME_INT} lines hidden\), use '-vv' to show$",
|
| 317 |
+
],
|
| 318 |
+
verbosity_level=0,
|
| 319 |
+
)
|
| 320 |
+
|
| 321 |
+
assert_approx_raises_regex(
|
| 322 |
+
a,
|
| 323 |
+
b,
|
| 324 |
+
[
|
| 325 |
+
r" ",
|
| 326 |
+
r" comparison failed. Mismatched elements: 20 / 20:",
|
| 327 |
+
rf" Max absolute difference: {SOME_FLOAT}",
|
| 328 |
+
rf" Max relative difference: {SOME_FLOAT}",
|
| 329 |
+
r" Index \| Obtained\s+\| Expected",
|
| 330 |
+
]
|
| 331 |
+
+ [
|
| 332 |
+
rf" \({i},\)\s+\| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}"
|
| 333 |
+
for i in range(20)
|
| 334 |
+
],
|
| 335 |
+
verbosity_level=2,
|
| 336 |
+
)
|
| 337 |
+
|
| 338 |
+
def test_repr_string(self):
|
| 339 |
+
assert repr(approx(1.0)) == "1.0 ± 1.0e-06"
|
| 340 |
+
assert repr(approx([1.0, 2.0])) == "approx([1.0 ± 1.0e-06, 2.0 ± 2.0e-06])"
|
| 341 |
+
assert repr(approx((1.0, 2.0))) == "approx((1.0 ± 1.0e-06, 2.0 ± 2.0e-06))"
|
| 342 |
+
assert repr(approx(inf)) == "inf"
|
| 343 |
+
assert repr(approx(1.0, rel=nan)) == "1.0 ± ???"
|
| 344 |
+
assert repr(approx(1.0, rel=inf)) == "1.0 ± inf"
|
| 345 |
+
|
| 346 |
+
# Dictionaries aren't ordered, so we need to check both orders.
|
| 347 |
+
assert repr(approx({"a": 1.0, "b": 2.0})) in (
|
| 348 |
+
"approx({'a': 1.0 ± 1.0e-06, 'b': 2.0 ± 2.0e-06})",
|
| 349 |
+
"approx({'b': 2.0 ± 2.0e-06, 'a': 1.0 ± 1.0e-06})",
|
| 350 |
+
)
|
| 351 |
+
|
| 352 |
+
assert repr(approx(42, abs=1)) == "42 ± 1"
|
| 353 |
+
assert repr(approx(5, rel=0.01)) == "5 ± 0.05"
|
| 354 |
+
assert repr(approx(24000, abs=500)) == "24000 ± 500"
|
| 355 |
+
assert repr(approx(1500, abs=555)) == "1500 ± 555"
|
| 356 |
+
|
| 357 |
+
def test_repr_complex_numbers(self):
|
| 358 |
+
assert repr(approx(inf + 1j)) == "(inf+1j)"
|
| 359 |
+
assert repr(approx(1.0j, rel=inf)) == "1j ± inf"
|
| 360 |
+
|
| 361 |
+
# can't compute a sensible tolerance
|
| 362 |
+
assert repr(approx(nan + 1j)) == "(nan+1j) ± ???"
|
| 363 |
+
|
| 364 |
+
assert repr(approx(1.0j)) == "1j ± 1.0e-06 ∠ ±180°"
|
| 365 |
+
|
| 366 |
+
# relative tolerance is scaled to |3+4j| = 5
|
| 367 |
+
assert repr(approx(3 + 4 * 1j)) == "(3+4j) ± 5.0e-06 ∠ ±180°"
|
| 368 |
+
|
| 369 |
+
# absolute tolerance is not scaled
|
| 370 |
+
assert repr(approx(3.3 + 4.4 * 1j, abs=0.02)) == "(3.3+4.4j) ± 0.02 ∠ ±180°"
|
| 371 |
+
|
| 372 |
+
@pytest.mark.parametrize(
|
| 373 |
+
"value, expected_repr_string",
|
| 374 |
+
[
|
| 375 |
+
(5.0, "approx(5.0 ± 5.0e-06)"),
|
| 376 |
+
([5.0], "approx([5.0 ± 5.0e-06])"),
|
| 377 |
+
([[5.0]], "approx([[5.0 ± 5.0e-06]])"),
|
| 378 |
+
([[5.0, 6.0]], "approx([[5.0 ± 5.0e-06, 6.0 ± 6.0e-06]])"),
|
| 379 |
+
([[5.0], [6.0]], "approx([[5.0 ± 5.0e-06], [6.0 ± 6.0e-06]])"),
|
| 380 |
+
],
|
| 381 |
+
)
|
| 382 |
+
def test_repr_nd_array(self, value, expected_repr_string):
|
| 383 |
+
"""Make sure that arrays of all different dimensions are repr'd correctly."""
|
| 384 |
+
np = pytest.importorskip("numpy")
|
| 385 |
+
np_array = np.array(value)
|
| 386 |
+
assert repr(approx(np_array)) == expected_repr_string
|
| 387 |
+
|
| 388 |
+
def test_bool(self):
|
| 389 |
+
with pytest.raises(AssertionError) as err:
|
| 390 |
+
assert approx(1)
|
| 391 |
+
|
| 392 |
+
assert err.match(r"approx\(\) is not supported in a boolean context")
|
| 393 |
+
|
| 394 |
+
def test_mixed_sequence(self, assert_approx_raises_regex) -> None:
|
| 395 |
+
"""Approx should work on sequences that also contain non-numbers (#13010)."""
|
| 396 |
+
assert_approx_raises_regex(
|
| 397 |
+
[1.1, 2, "word"],
|
| 398 |
+
[1.0, 2, "different"],
|
| 399 |
+
[
|
| 400 |
+
"",
|
| 401 |
+
r" comparison failed. Mismatched elements: 2 / 3:",
|
| 402 |
+
rf" Max absolute difference: {SOME_FLOAT}",
|
| 403 |
+
rf" Max relative difference: {SOME_FLOAT}",
|
| 404 |
+
r" Index \| Obtained\s+\| Expected\s+",
|
| 405 |
+
r"\s*0\s*\|\s*1\.1\s*\|\s*1\.0\s*±\s*1\.0e\-06\s*",
|
| 406 |
+
r"\s*2\s*\|\s*word\s*\|\s*different\s*",
|
| 407 |
+
],
|
| 408 |
+
verbosity_level=2,
|
| 409 |
+
)
|
| 410 |
+
assert_approx_raises_regex(
|
| 411 |
+
[1.1, 2, "word"],
|
| 412 |
+
[1.0, 2, "word"],
|
| 413 |
+
[
|
| 414 |
+
"",
|
| 415 |
+
r" comparison failed. Mismatched elements: 1 / 3:",
|
| 416 |
+
rf" Max absolute difference: {SOME_FLOAT}",
|
| 417 |
+
rf" Max relative difference: {SOME_FLOAT}",
|
| 418 |
+
r" Index \| Obtained\s+\| Expected\s+",
|
| 419 |
+
r"\s*0\s*\|\s*1\.1\s*\|\s*1\.0\s*±\s*1\.0e\-06\s*",
|
| 420 |
+
],
|
| 421 |
+
verbosity_level=2,
|
| 422 |
+
)
|
| 423 |
+
assert [1.1, 2, "word"] == pytest.approx([1.1, 2, "word"])
|
| 424 |
+
|
| 425 |
+
def test_operator_overloading(self):
|
| 426 |
+
assert 1 == approx(1, rel=1e-6, abs=1e-12)
|
| 427 |
+
assert not (1 != approx(1, rel=1e-6, abs=1e-12))
|
| 428 |
+
assert 10 != approx(1, rel=1e-6, abs=1e-12)
|
| 429 |
+
assert not (10 == approx(1, rel=1e-6, abs=1e-12))
|
| 430 |
+
|
| 431 |
+
def test_exactly_equal(self):
|
| 432 |
+
examples = [
|
| 433 |
+
(2.0, 2.0),
|
| 434 |
+
(0.1e200, 0.1e200),
|
| 435 |
+
(1.123e-300, 1.123e-300),
|
| 436 |
+
(12345, 12345.0),
|
| 437 |
+
(0.0, -0.0),
|
| 438 |
+
(345678, 345678),
|
| 439 |
+
(Decimal("1.0001"), Decimal("1.0001")),
|
| 440 |
+
(Fraction(1, 3), Fraction(-1, -3)),
|
| 441 |
+
]
|
| 442 |
+
for a, x in examples:
|
| 443 |
+
assert a == approx(x)
|
| 444 |
+
|
| 445 |
+
def test_opposite_sign(self):
|
| 446 |
+
examples = [(eq, 1e-100, -1e-100), (ne, 1e100, -1e100)]
|
| 447 |
+
for op, a, x in examples:
|
| 448 |
+
assert op(a, approx(x))
|
| 449 |
+
|
| 450 |
+
def test_zero_tolerance(self):
|
| 451 |
+
within_1e10 = [(1.1e-100, 1e-100), (-1.1e-100, -1e-100)]
|
| 452 |
+
for a, x in within_1e10:
|
| 453 |
+
assert x == approx(x, rel=0.0, abs=0.0)
|
| 454 |
+
assert a != approx(x, rel=0.0, abs=0.0)
|
| 455 |
+
assert a == approx(x, rel=0.0, abs=5e-101)
|
| 456 |
+
assert a != approx(x, rel=0.0, abs=5e-102)
|
| 457 |
+
assert a == approx(x, rel=5e-1, abs=0.0)
|
| 458 |
+
assert a != approx(x, rel=5e-2, abs=0.0)
|
| 459 |
+
|
| 460 |
+
@pytest.mark.parametrize(
|
| 461 |
+
("rel", "abs"),
|
| 462 |
+
[
|
| 463 |
+
(-1e100, None),
|
| 464 |
+
(None, -1e100),
|
| 465 |
+
(1e100, -1e100),
|
| 466 |
+
(-1e100, 1e100),
|
| 467 |
+
(-1e100, -1e100),
|
| 468 |
+
],
|
| 469 |
+
)
|
| 470 |
+
def test_negative_tolerance(self, rel: float | None, abs: float | None) -> None:
|
| 471 |
+
# Negative tolerances are not allowed.
|
| 472 |
+
with pytest.raises(ValueError):
|
| 473 |
+
1.1 == approx(1, rel, abs)
|
| 474 |
+
|
| 475 |
+
def test_negative_tolerance_message(self):
|
| 476 |
+
# Error message for negative tolerance should include the value.
|
| 477 |
+
with pytest.raises(ValueError, match="-3"):
|
| 478 |
+
0 == approx(1, abs=-3)
|
| 479 |
+
with pytest.raises(ValueError, match="-3"):
|
| 480 |
+
0 == approx(1, rel=-3)
|
| 481 |
+
|
| 482 |
+
def test_inf_tolerance(self):
|
| 483 |
+
# Everything should be equal if the tolerance is infinite.
|
| 484 |
+
large_diffs = [(1, 1000), (1e-50, 1e50), (-1.0, -1e300), (0.0, 10)]
|
| 485 |
+
for a, x in large_diffs:
|
| 486 |
+
assert a != approx(x, rel=0.0, abs=0.0)
|
| 487 |
+
assert a == approx(x, rel=inf, abs=0.0)
|
| 488 |
+
assert a == approx(x, rel=0.0, abs=inf)
|
| 489 |
+
assert a == approx(x, rel=inf, abs=inf)
|
| 490 |
+
|
| 491 |
+
def test_inf_tolerance_expecting_zero(self) -> None:
|
| 492 |
+
# If the relative tolerance is zero but the expected value is infinite,
|
| 493 |
+
# the actual tolerance is a NaN, which should be an error.
|
| 494 |
+
with pytest.raises(ValueError):
|
| 495 |
+
1 == approx(0, rel=inf, abs=0.0)
|
| 496 |
+
with pytest.raises(ValueError):
|
| 497 |
+
1 == approx(0, rel=inf, abs=inf)
|
| 498 |
+
|
| 499 |
+
def test_nan_tolerance(self) -> None:
|
| 500 |
+
with pytest.raises(ValueError):
|
| 501 |
+
1.1 == approx(1, rel=nan)
|
| 502 |
+
with pytest.raises(ValueError):
|
| 503 |
+
1.1 == approx(1, abs=nan)
|
| 504 |
+
with pytest.raises(ValueError):
|
| 505 |
+
1.1 == approx(1, rel=nan, abs=nan)
|
| 506 |
+
|
| 507 |
+
def test_reasonable_defaults(self):
|
| 508 |
+
# Whatever the defaults are, they should work for numbers close to 1
|
| 509 |
+
# than have a small amount of floating-point error.
|
| 510 |
+
assert 0.1 + 0.2 == approx(0.3)
|
| 511 |
+
|
| 512 |
+
def test_default_tolerances(self):
|
| 513 |
+
# This tests the defaults as they are currently set. If you change the
|
| 514 |
+
# defaults, this test will fail but you should feel free to change it.
|
| 515 |
+
# None of the other tests (except the doctests) should be affected by
|
| 516 |
+
# the choice of defaults.
|
| 517 |
+
examples = [
|
| 518 |
+
# Relative tolerance used.
|
| 519 |
+
(eq, 1e100 + 1e94, 1e100),
|
| 520 |
+
(ne, 1e100 + 2e94, 1e100),
|
| 521 |
+
(eq, 1e0 + 1e-6, 1e0),
|
| 522 |
+
(ne, 1e0 + 2e-6, 1e0),
|
| 523 |
+
# Absolute tolerance used.
|
| 524 |
+
(eq, 1e-100, +1e-106),
|
| 525 |
+
(eq, 1e-100, +2e-106),
|
| 526 |
+
(eq, 1e-100, 0),
|
| 527 |
+
]
|
| 528 |
+
for op, a, x in examples:
|
| 529 |
+
assert op(a, approx(x))
|
| 530 |
+
|
| 531 |
+
def test_custom_tolerances(self):
|
| 532 |
+
assert 1e8 + 1e0 == approx(1e8, rel=5e-8, abs=5e0)
|
| 533 |
+
assert 1e8 + 1e0 == approx(1e8, rel=5e-9, abs=5e0)
|
| 534 |
+
assert 1e8 + 1e0 == approx(1e8, rel=5e-8, abs=5e-1)
|
| 535 |
+
assert 1e8 + 1e0 != approx(1e8, rel=5e-9, abs=5e-1)
|
| 536 |
+
|
| 537 |
+
assert 1e0 + 1e-8 == approx(1e0, rel=5e-8, abs=5e-8)
|
| 538 |
+
assert 1e0 + 1e-8 == approx(1e0, rel=5e-9, abs=5e-8)
|
| 539 |
+
assert 1e0 + 1e-8 == approx(1e0, rel=5e-8, abs=5e-9)
|
| 540 |
+
assert 1e0 + 1e-8 != approx(1e0, rel=5e-9, abs=5e-9)
|
| 541 |
+
|
| 542 |
+
assert 1e-8 + 1e-16 == approx(1e-8, rel=5e-8, abs=5e-16)
|
| 543 |
+
assert 1e-8 + 1e-16 == approx(1e-8, rel=5e-9, abs=5e-16)
|
| 544 |
+
assert 1e-8 + 1e-16 == approx(1e-8, rel=5e-8, abs=5e-17)
|
| 545 |
+
assert 1e-8 + 1e-16 != approx(1e-8, rel=5e-9, abs=5e-17)
|
| 546 |
+
|
| 547 |
+
def test_relative_tolerance(self):
|
| 548 |
+
within_1e8_rel = [(1e8 + 1e0, 1e8), (1e0 + 1e-8, 1e0), (1e-8 + 1e-16, 1e-8)]
|
| 549 |
+
for a, x in within_1e8_rel:
|
| 550 |
+
assert a == approx(x, rel=5e-8, abs=0.0)
|
| 551 |
+
assert a != approx(x, rel=5e-9, abs=0.0)
|
| 552 |
+
|
| 553 |
+
def test_absolute_tolerance(self):
|
| 554 |
+
within_1e8_abs = [(1e8 + 9e-9, 1e8), (1e0 + 9e-9, 1e0), (1e-8 + 9e-9, 1e-8)]
|
| 555 |
+
for a, x in within_1e8_abs:
|
| 556 |
+
assert a == approx(x, rel=0, abs=5e-8)
|
| 557 |
+
assert a != approx(x, rel=0, abs=5e-9)
|
| 558 |
+
|
| 559 |
+
def test_expecting_zero(self):
|
| 560 |
+
examples = [
|
| 561 |
+
(ne, 1e-6, 0.0),
|
| 562 |
+
(ne, -1e-6, 0.0),
|
| 563 |
+
(eq, 1e-12, 0.0),
|
| 564 |
+
(eq, -1e-12, 0.0),
|
| 565 |
+
(ne, 2e-12, 0.0),
|
| 566 |
+
(ne, -2e-12, 0.0),
|
| 567 |
+
(ne, inf, 0.0),
|
| 568 |
+
(ne, nan, 0.0),
|
| 569 |
+
]
|
| 570 |
+
for op, a, x in examples:
|
| 571 |
+
assert op(a, approx(x, rel=0.0, abs=1e-12))
|
| 572 |
+
assert op(a, approx(x, rel=1e-6, abs=1e-12))
|
| 573 |
+
|
| 574 |
+
def test_expecting_inf(self):
|
| 575 |
+
examples = [
|
| 576 |
+
(eq, inf, inf),
|
| 577 |
+
(eq, -inf, -inf),
|
| 578 |
+
(ne, inf, -inf),
|
| 579 |
+
(ne, 0.0, inf),
|
| 580 |
+
(ne, nan, inf),
|
| 581 |
+
]
|
| 582 |
+
for op, a, x in examples:
|
| 583 |
+
assert op(a, approx(x))
|
| 584 |
+
|
| 585 |
+
def test_expecting_nan(self):
|
| 586 |
+
examples = [
|
| 587 |
+
(eq, nan, nan),
|
| 588 |
+
(eq, -nan, -nan),
|
| 589 |
+
(eq, nan, -nan),
|
| 590 |
+
(ne, 0.0, nan),
|
| 591 |
+
(ne, inf, nan),
|
| 592 |
+
]
|
| 593 |
+
for op, a, x in examples:
|
| 594 |
+
# Nothing is equal to NaN by default.
|
| 595 |
+
assert a != approx(x)
|
| 596 |
+
|
| 597 |
+
# If ``nan_ok=True``, then NaN is equal to NaN.
|
| 598 |
+
assert op(a, approx(x, nan_ok=True))
|
| 599 |
+
|
| 600 |
+
def test_int(self):
|
| 601 |
+
within_1e6 = [(1000001, 1000000), (-1000001, -1000000)]
|
| 602 |
+
for a, x in within_1e6:
|
| 603 |
+
assert a == approx(x, rel=5e-6, abs=0)
|
| 604 |
+
assert a != approx(x, rel=5e-7, abs=0)
|
| 605 |
+
assert approx(x, rel=5e-6, abs=0) == a
|
| 606 |
+
assert approx(x, rel=5e-7, abs=0) != a
|
| 607 |
+
|
| 608 |
+
def test_decimal(self):
|
| 609 |
+
within_1e6 = [
|
| 610 |
+
(Decimal("1.000001"), Decimal("1.0")),
|
| 611 |
+
(Decimal("-1.000001"), Decimal("-1.0")),
|
| 612 |
+
]
|
| 613 |
+
for a, x in within_1e6:
|
| 614 |
+
assert a == approx(x)
|
| 615 |
+
assert a == approx(x, rel=Decimal("5e-6"), abs=0)
|
| 616 |
+
assert a != approx(x, rel=Decimal("5e-7"), abs=0)
|
| 617 |
+
assert approx(x, rel=Decimal("5e-6"), abs=0) == a
|
| 618 |
+
assert approx(x, rel=Decimal("5e-7"), abs=0) != a
|
| 619 |
+
assert approx(x, rel=0, abs=Decimal("5e-3")) == a
|
| 620 |
+
assert approx(x, rel=0, abs=Decimal("5e-7")) != a
|
| 621 |
+
|
| 622 |
+
def test_fraction(self):
|
| 623 |
+
within_1e6 = [
|
| 624 |
+
(1 + Fraction(1, 1000000), Fraction(1)),
|
| 625 |
+
(-1 - Fraction(-1, 1000000), Fraction(-1)),
|
| 626 |
+
]
|
| 627 |
+
for a, x in within_1e6:
|
| 628 |
+
assert a == approx(x, rel=5e-6, abs=0)
|
| 629 |
+
assert a != approx(x, rel=5e-7, abs=0)
|
| 630 |
+
assert approx(x, rel=5e-6, abs=0) == a
|
| 631 |
+
assert approx(x, rel=5e-7, abs=0) != a
|
| 632 |
+
|
| 633 |
+
def test_complex(self):
|
| 634 |
+
within_1e6 = [
|
| 635 |
+
(1.000001 + 1.0j, 1.0 + 1.0j),
|
| 636 |
+
(1.0 + 1.000001j, 1.0 + 1.0j),
|
| 637 |
+
(-1.000001 + 1.0j, -1.0 + 1.0j),
|
| 638 |
+
(1.0 - 1.000001j, 1.0 - 1.0j),
|
| 639 |
+
]
|
| 640 |
+
for a, x in within_1e6:
|
| 641 |
+
assert a == approx(x, rel=5e-6, abs=0)
|
| 642 |
+
assert a != approx(x, rel=5e-7, abs=0)
|
| 643 |
+
assert approx(x, rel=5e-6, abs=0) == a
|
| 644 |
+
assert approx(x, rel=5e-7, abs=0) != a
|
| 645 |
+
|
| 646 |
+
def test_expecting_bool(self) -> None:
|
| 647 |
+
assert True == approx(True) # noqa: E712
|
| 648 |
+
assert False == approx(False) # noqa: E712
|
| 649 |
+
assert True != approx(False) # noqa: E712
|
| 650 |
+
assert True != approx(False, abs=2) # noqa: E712
|
| 651 |
+
assert 1 != approx(True)
|
| 652 |
+
|
| 653 |
+
def test_expecting_bool_numpy(self) -> None:
|
| 654 |
+
"""Check approx comparing with numpy.bool (#13047)."""
|
| 655 |
+
np = pytest.importorskip("numpy")
|
| 656 |
+
assert np.False_ != approx(True)
|
| 657 |
+
assert np.True_ != approx(False)
|
| 658 |
+
assert np.True_ == approx(True)
|
| 659 |
+
assert np.False_ == approx(False)
|
| 660 |
+
assert np.True_ != approx(False, abs=2)
|
| 661 |
+
|
| 662 |
+
def test_list(self):
|
| 663 |
+
actual = [1 + 1e-7, 2 + 1e-8]
|
| 664 |
+
expected = [1, 2]
|
| 665 |
+
|
| 666 |
+
# Return false if any element is outside the tolerance.
|
| 667 |
+
assert actual == approx(expected, rel=5e-7, abs=0)
|
| 668 |
+
assert actual != approx(expected, rel=5e-8, abs=0)
|
| 669 |
+
assert approx(expected, rel=5e-7, abs=0) == actual
|
| 670 |
+
assert approx(expected, rel=5e-8, abs=0) != actual
|
| 671 |
+
|
| 672 |
+
def test_list_decimal(self):
|
| 673 |
+
actual = [Decimal("1.000001"), Decimal("2.000001")]
|
| 674 |
+
expected = [Decimal("1"), Decimal("2")]
|
| 675 |
+
|
| 676 |
+
assert actual == approx(expected)
|
| 677 |
+
|
| 678 |
+
def test_list_wrong_len(self):
|
| 679 |
+
assert [1, 2] != approx([1])
|
| 680 |
+
assert [1, 2] != approx([1, 2, 3])
|
| 681 |
+
|
| 682 |
+
def test_tuple(self):
|
| 683 |
+
actual = (1 + 1e-7, 2 + 1e-8)
|
| 684 |
+
expected = (1, 2)
|
| 685 |
+
|
| 686 |
+
# Return false if any element is outside the tolerance.
|
| 687 |
+
assert actual == approx(expected, rel=5e-7, abs=0)
|
| 688 |
+
assert actual != approx(expected, rel=5e-8, abs=0)
|
| 689 |
+
assert approx(expected, rel=5e-7, abs=0) == actual
|
| 690 |
+
assert approx(expected, rel=5e-8, abs=0) != actual
|
| 691 |
+
|
| 692 |
+
def test_tuple_wrong_len(self):
|
| 693 |
+
assert (1, 2) != approx((1,))
|
| 694 |
+
assert (1, 2) != approx((1, 2, 3))
|
| 695 |
+
|
| 696 |
+
def test_tuple_vs_other(self):
|
| 697 |
+
assert 1 != approx((1,))
|
| 698 |
+
|
| 699 |
+
def test_dict(self):
|
| 700 |
+
actual = {"a": 1 + 1e-7, "b": 2 + 1e-8}
|
| 701 |
+
# Dictionaries became ordered in python3.6, so switch up the order here
|
| 702 |
+
# to make sure it doesn't matter.
|
| 703 |
+
expected = {"b": 2, "a": 1}
|
| 704 |
+
|
| 705 |
+
# Return false if any element is outside the tolerance.
|
| 706 |
+
assert actual == approx(expected, rel=5e-7, abs=0)
|
| 707 |
+
assert actual != approx(expected, rel=5e-8, abs=0)
|
| 708 |
+
assert approx(expected, rel=5e-7, abs=0) == actual
|
| 709 |
+
assert approx(expected, rel=5e-8, abs=0) != actual
|
| 710 |
+
|
| 711 |
+
def test_dict_decimal(self):
|
| 712 |
+
actual = {"a": Decimal("1.000001"), "b": Decimal("2.000001")}
|
| 713 |
+
# Dictionaries became ordered in python3.6, so switch up the order here
|
| 714 |
+
# to make sure it doesn't matter.
|
| 715 |
+
expected = {"b": Decimal("2"), "a": Decimal("1")}
|
| 716 |
+
|
| 717 |
+
assert actual == approx(expected)
|
| 718 |
+
|
| 719 |
+
def test_dict_wrong_len(self):
|
| 720 |
+
assert {"a": 1, "b": 2} != approx({"a": 1})
|
| 721 |
+
assert {"a": 1, "b": 2} != approx({"a": 1, "c": 2})
|
| 722 |
+
assert {"a": 1, "b": 2} != approx({"a": 1, "b": 2, "c": 3})
|
| 723 |
+
|
| 724 |
+
def test_dict_nonnumeric(self):
|
| 725 |
+
assert {"a": 1.0, "b": None} == pytest.approx({"a": 1.0, "b": None})
|
| 726 |
+
assert {"a": 1.0, "b": 1} != pytest.approx({"a": 1.0, "b": None})
|
| 727 |
+
assert {"a": 1.0, "b": True} != pytest.approx({"a": 1.0, "b": False}, abs=2)
|
| 728 |
+
|
| 729 |
+
def test_dict_vs_other(self):
|
| 730 |
+
assert 1 != approx({"a": 0})
|
| 731 |
+
|
| 732 |
+
def test_dict_for_div_by_zero(self, assert_approx_raises_regex):
|
| 733 |
+
assert_approx_raises_regex(
|
| 734 |
+
{"foo": 42.0},
|
| 735 |
+
{"foo": 0.0},
|
| 736 |
+
[
|
| 737 |
+
r"",
|
| 738 |
+
r" comparison failed. Mismatched elements: 1 / 1:",
|
| 739 |
+
rf" Max absolute difference: {SOME_FLOAT}",
|
| 740 |
+
r" Max relative difference: inf",
|
| 741 |
+
r" Index \| Obtained\s+\| Expected ",
|
| 742 |
+
rf" foo | {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
|
| 743 |
+
],
|
| 744 |
+
)
|
| 745 |
+
|
| 746 |
+
def test_dict_differing_lengths(self, assert_approx_raises_regex):
|
| 747 |
+
assert_approx_raises_regex(
|
| 748 |
+
{"a": 0},
|
| 749 |
+
{"a": 0, "b": 1},
|
| 750 |
+
[
|
| 751 |
+
" ",
|
| 752 |
+
r" Impossible to compare mappings with different sizes\.",
|
| 753 |
+
r" Lengths: 2 and 1",
|
| 754 |
+
],
|
| 755 |
+
)
|
| 756 |
+
|
| 757 |
+
def test_numpy_array(self):
|
| 758 |
+
np = pytest.importorskip("numpy")
|
| 759 |
+
|
| 760 |
+
actual = np.array([1 + 1e-7, 2 + 1e-8])
|
| 761 |
+
expected = np.array([1, 2])
|
| 762 |
+
|
| 763 |
+
# Return false if any element is outside the tolerance.
|
| 764 |
+
assert actual == approx(expected, rel=5e-7, abs=0)
|
| 765 |
+
assert actual != approx(expected, rel=5e-8, abs=0)
|
| 766 |
+
assert approx(expected, rel=5e-7, abs=0) == expected
|
| 767 |
+
assert approx(expected, rel=5e-8, abs=0) != actual
|
| 768 |
+
|
| 769 |
+
# Should be able to compare lists with numpy arrays.
|
| 770 |
+
assert list(actual) == approx(expected, rel=5e-7, abs=0)
|
| 771 |
+
assert list(actual) != approx(expected, rel=5e-8, abs=0)
|
| 772 |
+
assert actual == approx(list(expected), rel=5e-7, abs=0)
|
| 773 |
+
assert actual != approx(list(expected), rel=5e-8, abs=0)
|
| 774 |
+
|
| 775 |
+
def test_numpy_tolerance_args(self):
|
| 776 |
+
"""
|
| 777 |
+
Check that numpy rel/abs args are handled correctly
|
| 778 |
+
for comparison against an np.array
|
| 779 |
+
Check both sides of the operator, hopefully it doesn't impact things.
|
| 780 |
+
Test all permutations of where the approx and np.array() can show up
|
| 781 |
+
"""
|
| 782 |
+
np = pytest.importorskip("numpy")
|
| 783 |
+
expected = 100.0
|
| 784 |
+
actual = 99.0
|
| 785 |
+
abs_diff = expected - actual
|
| 786 |
+
rel_diff = (expected - actual) / expected
|
| 787 |
+
|
| 788 |
+
tests = [
|
| 789 |
+
(eq, abs_diff, 0),
|
| 790 |
+
(eq, 0, rel_diff),
|
| 791 |
+
(ne, 0, rel_diff / 2.0), # rel diff fail
|
| 792 |
+
(ne, abs_diff / 2.0, 0), # abs diff fail
|
| 793 |
+
]
|
| 794 |
+
|
| 795 |
+
for op, _abs, _rel in tests:
|
| 796 |
+
assert op(np.array(actual), approx(expected, abs=_abs, rel=_rel)) # a, b
|
| 797 |
+
assert op(approx(expected, abs=_abs, rel=_rel), np.array(actual)) # b, a
|
| 798 |
+
|
| 799 |
+
assert op(actual, approx(np.array(expected), abs=_abs, rel=_rel)) # a, b
|
| 800 |
+
assert op(approx(np.array(expected), abs=_abs, rel=_rel), actual) # b, a
|
| 801 |
+
|
| 802 |
+
assert op(np.array(actual), approx(np.array(expected), abs=_abs, rel=_rel))
|
| 803 |
+
assert op(approx(np.array(expected), abs=_abs, rel=_rel), np.array(actual))
|
| 804 |
+
|
| 805 |
+
def test_numpy_expecting_nan(self):
|
| 806 |
+
np = pytest.importorskip("numpy")
|
| 807 |
+
examples = [
|
| 808 |
+
(eq, nan, nan),
|
| 809 |
+
(eq, -nan, -nan),
|
| 810 |
+
(eq, nan, -nan),
|
| 811 |
+
(ne, 0.0, nan),
|
| 812 |
+
(ne, inf, nan),
|
| 813 |
+
]
|
| 814 |
+
for op, a, x in examples:
|
| 815 |
+
# Nothing is equal to NaN by default.
|
| 816 |
+
assert np.array(a) != approx(x)
|
| 817 |
+
assert a != approx(np.array(x))
|
| 818 |
+
|
| 819 |
+
# If ``nan_ok=True``, then NaN is equal to NaN.
|
| 820 |
+
assert op(np.array(a), approx(x, nan_ok=True))
|
| 821 |
+
assert op(a, approx(np.array(x), nan_ok=True))
|
| 822 |
+
|
| 823 |
+
def test_numpy_expecting_inf(self):
|
| 824 |
+
np = pytest.importorskip("numpy")
|
| 825 |
+
examples = [
|
| 826 |
+
(eq, inf, inf),
|
| 827 |
+
(eq, -inf, -inf),
|
| 828 |
+
(ne, inf, -inf),
|
| 829 |
+
(ne, 0.0, inf),
|
| 830 |
+
(ne, nan, inf),
|
| 831 |
+
]
|
| 832 |
+
for op, a, x in examples:
|
| 833 |
+
assert op(np.array(a), approx(x))
|
| 834 |
+
assert op(a, approx(np.array(x)))
|
| 835 |
+
assert op(np.array(a), approx(np.array(x)))
|
| 836 |
+
|
| 837 |
+
def test_numpy_array_wrong_shape(self):
|
| 838 |
+
np = pytest.importorskip("numpy")
|
| 839 |
+
|
| 840 |
+
a12 = np.array([[1, 2]])
|
| 841 |
+
a21 = np.array([[1], [2]])
|
| 842 |
+
|
| 843 |
+
assert a12 != approx(a21)
|
| 844 |
+
assert a21 != approx(a12)
|
| 845 |
+
|
| 846 |
+
def test_numpy_array_implicit_conversion(self):
|
| 847 |
+
np = pytest.importorskip("numpy")
|
| 848 |
+
|
| 849 |
+
class ImplicitArray:
|
| 850 |
+
"""Type which is implicitly convertible to a numpy array."""
|
| 851 |
+
|
| 852 |
+
def __init__(self, vals):
|
| 853 |
+
self.vals = vals
|
| 854 |
+
|
| 855 |
+
def __array__(self, dtype=None, copy=None):
|
| 856 |
+
return np.array(self.vals)
|
| 857 |
+
|
| 858 |
+
vec1 = ImplicitArray([1.0, 2.0, 3.0])
|
| 859 |
+
vec2 = ImplicitArray([1.0, 2.0, 4.0])
|
| 860 |
+
# see issue #12114 for test case
|
| 861 |
+
assert vec1 != approx(vec2)
|
| 862 |
+
|
| 863 |
+
def test_numpy_array_protocol(self):
|
| 864 |
+
"""
|
| 865 |
+
array-like objects such as tensorflow's DeviceArray are handled like ndarray.
|
| 866 |
+
See issue #8132
|
| 867 |
+
"""
|
| 868 |
+
np = pytest.importorskip("numpy")
|
| 869 |
+
|
| 870 |
+
class DeviceArray:
|
| 871 |
+
def __init__(self, value, size):
|
| 872 |
+
self.value = value
|
| 873 |
+
self.size = size
|
| 874 |
+
|
| 875 |
+
def __array__(self):
|
| 876 |
+
return self.value * np.ones(self.size)
|
| 877 |
+
|
| 878 |
+
class DeviceScalar:
|
| 879 |
+
def __init__(self, value):
|
| 880 |
+
self.value = value
|
| 881 |
+
|
| 882 |
+
def __array__(self):
|
| 883 |
+
return np.array(self.value)
|
| 884 |
+
|
| 885 |
+
expected = 1
|
| 886 |
+
actual = 1 + 1e-6
|
| 887 |
+
assert approx(expected) == DeviceArray(actual, size=1)
|
| 888 |
+
assert approx(expected) == DeviceArray(actual, size=2)
|
| 889 |
+
assert approx(expected) == DeviceScalar(actual)
|
| 890 |
+
assert approx(DeviceScalar(expected)) == actual
|
| 891 |
+
assert approx(DeviceScalar(expected)) == DeviceScalar(actual)
|
| 892 |
+
|
| 893 |
+
def test_doctests(self, mocked_doctest_runner) -> None:
|
| 894 |
+
import doctest
|
| 895 |
+
|
| 896 |
+
parser = doctest.DocTestParser()
|
| 897 |
+
assert approx.__doc__ is not None
|
| 898 |
+
test = parser.get_doctest(
|
| 899 |
+
approx.__doc__, {"approx": approx}, approx.__name__, None, None
|
| 900 |
+
)
|
| 901 |
+
mocked_doctest_runner.run(test)
|
| 902 |
+
|
| 903 |
+
def test_unicode_plus_minus(self, pytester: Pytester) -> None:
|
| 904 |
+
"""
|
| 905 |
+
Comparing approx instances inside lists should not produce an error in the detailed diff.
|
| 906 |
+
Integration test for issue #2111.
|
| 907 |
+
"""
|
| 908 |
+
pytester.makepyfile(
|
| 909 |
+
"""
|
| 910 |
+
import pytest
|
| 911 |
+
def test_foo():
|
| 912 |
+
assert [3] == [pytest.approx(4)]
|
| 913 |
+
"""
|
| 914 |
+
)
|
| 915 |
+
expected = "4.0e-06"
|
| 916 |
+
result = pytester.runpytest()
|
| 917 |
+
result.stdout.fnmatch_lines(
|
| 918 |
+
[f"*At index 0 diff: 3 != 4 ± {expected}", "=* 1 failed in *="]
|
| 919 |
+
)
|
| 920 |
+
|
| 921 |
+
@pytest.mark.parametrize(
|
| 922 |
+
"x, name",
|
| 923 |
+
[
|
| 924 |
+
pytest.param([[1]], "data structures", id="nested-list"),
|
| 925 |
+
pytest.param({"key": {"key": 1}}, "dictionaries", id="nested-dict"),
|
| 926 |
+
],
|
| 927 |
+
)
|
| 928 |
+
def test_expected_value_type_error(self, x, name):
|
| 929 |
+
with pytest.raises(
|
| 930 |
+
TypeError,
|
| 931 |
+
match=rf"pytest.approx\(\) does not support nested {name}:",
|
| 932 |
+
):
|
| 933 |
+
approx(x)
|
| 934 |
+
|
| 935 |
+
@pytest.mark.parametrize(
|
| 936 |
+
"x",
|
| 937 |
+
[
|
| 938 |
+
pytest.param(None),
|
| 939 |
+
pytest.param("string"),
|
| 940 |
+
pytest.param(["string"], id="nested-str"),
|
| 941 |
+
pytest.param({"key": "string"}, id="dict-with-string"),
|
| 942 |
+
],
|
| 943 |
+
)
|
| 944 |
+
def test_nonnumeric_okay_if_equal(self, x):
|
| 945 |
+
assert x == approx(x)
|
| 946 |
+
|
| 947 |
+
@pytest.mark.parametrize(
|
| 948 |
+
"x",
|
| 949 |
+
[
|
| 950 |
+
pytest.param("string"),
|
| 951 |
+
pytest.param(["string"], id="nested-str"),
|
| 952 |
+
pytest.param({"key": "string"}, id="dict-with-string"),
|
| 953 |
+
],
|
| 954 |
+
)
|
| 955 |
+
def test_nonnumeric_false_if_unequal(self, x):
|
| 956 |
+
"""For non-numeric types, x != pytest.approx(y) reduces to x != y"""
|
| 957 |
+
assert "ab" != approx("abc")
|
| 958 |
+
assert ["ab"] != approx(["abc"])
|
| 959 |
+
# in particular, both of these should return False
|
| 960 |
+
assert {"a": 1.0} != approx({"a": None})
|
| 961 |
+
assert {"a": None} != approx({"a": 1.0})
|
| 962 |
+
|
| 963 |
+
assert 1.0 != approx(None)
|
| 964 |
+
assert None != approx(1.0) # noqa: E711
|
| 965 |
+
|
| 966 |
+
assert 1.0 != approx([None])
|
| 967 |
+
assert None != approx([1.0]) # noqa: E711
|
| 968 |
+
|
| 969 |
+
def test_nonnumeric_dict_repr(self):
|
| 970 |
+
"""Dicts with non-numerics and infinites have no tolerances"""
|
| 971 |
+
x1 = {"foo": 1.0000005, "bar": None, "foobar": inf}
|
| 972 |
+
assert (
|
| 973 |
+
repr(approx(x1))
|
| 974 |
+
== "approx({'foo': 1.0000005 ± 1.0e-06, 'bar': None, 'foobar': inf})"
|
| 975 |
+
)
|
| 976 |
+
|
| 977 |
+
def test_nonnumeric_list_repr(self):
|
| 978 |
+
"""Lists with non-numerics and infinites have no tolerances"""
|
| 979 |
+
x1 = [1.0000005, None, inf]
|
| 980 |
+
assert repr(approx(x1)) == "approx([1.0000005 ± 1.0e-06, None, inf])"
|
| 981 |
+
|
| 982 |
+
@pytest.mark.parametrize(
|
| 983 |
+
"op",
|
| 984 |
+
[
|
| 985 |
+
pytest.param(operator.le, id="<="),
|
| 986 |
+
pytest.param(operator.lt, id="<"),
|
| 987 |
+
pytest.param(operator.ge, id=">="),
|
| 988 |
+
pytest.param(operator.gt, id=">"),
|
| 989 |
+
],
|
| 990 |
+
)
|
| 991 |
+
def test_comparison_operator_type_error(self, op):
|
| 992 |
+
"""pytest.approx should raise TypeError for operators other than == and != (#2003)."""
|
| 993 |
+
with pytest.raises(TypeError):
|
| 994 |
+
op(1, approx(1, rel=1e-6, abs=1e-12))
|
| 995 |
+
|
| 996 |
+
def test_numpy_array_with_scalar(self):
|
| 997 |
+
np = pytest.importorskip("numpy")
|
| 998 |
+
|
| 999 |
+
actual = np.array([1 + 1e-7, 1 - 1e-8])
|
| 1000 |
+
expected = 1.0
|
| 1001 |
+
|
| 1002 |
+
assert actual == approx(expected, rel=5e-7, abs=0)
|
| 1003 |
+
assert actual != approx(expected, rel=5e-8, abs=0)
|
| 1004 |
+
assert approx(expected, rel=5e-7, abs=0) == actual
|
| 1005 |
+
assert approx(expected, rel=5e-8, abs=0) != actual
|
| 1006 |
+
|
| 1007 |
+
def test_numpy_scalar_with_array(self):
|
| 1008 |
+
np = pytest.importorskip("numpy")
|
| 1009 |
+
|
| 1010 |
+
actual = 1.0
|
| 1011 |
+
expected = np.array([1 + 1e-7, 1 - 1e-8])
|
| 1012 |
+
|
| 1013 |
+
assert actual == approx(expected, rel=5e-7, abs=0)
|
| 1014 |
+
assert actual != approx(expected, rel=5e-8, abs=0)
|
| 1015 |
+
assert approx(expected, rel=5e-7, abs=0) == actual
|
| 1016 |
+
assert approx(expected, rel=5e-8, abs=0) != actual
|
| 1017 |
+
|
| 1018 |
+
def test_generic_ordered_sequence(self):
|
| 1019 |
+
class MySequence:
|
| 1020 |
+
def __getitem__(self, i):
|
| 1021 |
+
return [1, 2, 3, 4][i]
|
| 1022 |
+
|
| 1023 |
+
def __len__(self):
|
| 1024 |
+
return 4
|
| 1025 |
+
|
| 1026 |
+
expected = MySequence()
|
| 1027 |
+
assert [1, 2, 3, 4] == approx(expected, abs=1e-4)
|
| 1028 |
+
|
| 1029 |
+
expected_repr = "approx([1 ± 1.0e-06, 2 ± 2.0e-06, 3 ± 3.0e-06, 4 ± 4.0e-06])"
|
| 1030 |
+
assert repr(approx(expected)) == expected_repr
|
| 1031 |
+
|
| 1032 |
+
def test_decimal_approx_repr(self, monkeypatch) -> None:
|
| 1033 |
+
monkeypatch.setitem(decimal.getcontext().traps, decimal.FloatOperation, True)
|
| 1034 |
+
approx_obj = pytest.approx(decimal.Decimal("2.60"))
|
| 1035 |
+
assert decimal.Decimal("2.600001") == approx_obj
|
| 1036 |
+
|
| 1037 |
+
def test_allow_ordered_sequences_only(self) -> None:
|
| 1038 |
+
"""pytest.approx() should raise an error on unordered sequences (#9692)."""
|
| 1039 |
+
with pytest.raises(TypeError, match="only supports ordered sequences"):
|
| 1040 |
+
assert {1, 2, 3} == approx({1, 2, 3})
|
| 1041 |
+
|
| 1042 |
+
def test_strange_sequence(self):
|
| 1043 |
+
"""https://github.com/pytest-dev/pytest/issues/11797"""
|
| 1044 |
+
a = MyVec3(1, 2, 3)
|
| 1045 |
+
b = MyVec3(0, 1, 2)
|
| 1046 |
+
|
| 1047 |
+
# this would trigger the error inside the test
|
| 1048 |
+
pytest.approx(a, abs=0.5)._repr_compare(b)
|
| 1049 |
+
|
| 1050 |
+
assert b == pytest.approx(a, abs=2)
|
| 1051 |
+
assert b != pytest.approx(a, abs=0.5)
|
| 1052 |
+
|
| 1053 |
+
def test_approx_dicts_with_mismatch_on_keys(self) -> None:
|
| 1054 |
+
"""https://github.com/pytest-dev/pytest/issues/13816"""
|
| 1055 |
+
expected = {"a": 1, "b": 3}
|
| 1056 |
+
actual = {"a": 1, "c": 3}
|
| 1057 |
+
|
| 1058 |
+
with pytest.raises(
|
| 1059 |
+
AssertionError,
|
| 1060 |
+
match=re.escape(
|
| 1061 |
+
"comparison failed.\n Mappings has different keys: "
|
| 1062 |
+
"expected dict_keys(['a', 'b']) but got dict_keys(['a', 'c'])"
|
| 1063 |
+
),
|
| 1064 |
+
):
|
| 1065 |
+
assert actual == approx(expected)
|
| 1066 |
+
|
| 1067 |
+
def test_approx_on_unordered_mapping_with_mismatch(
|
| 1068 |
+
self, pytester: Pytester
|
| 1069 |
+
) -> None:
|
| 1070 |
+
"""https://github.com/pytest-dev/pytest/issues/12444"""
|
| 1071 |
+
pytester.makepyfile(
|
| 1072 |
+
"""
|
| 1073 |
+
import pytest
|
| 1074 |
+
|
| 1075 |
+
def test_approx_on_unordered_mapping_with_mismatch():
|
| 1076 |
+
expected = {"a": 1, "b": 2, "c": 3, "d": 4}
|
| 1077 |
+
actual = {"d": 4, "c": 5, "a": 8, "b": 2}
|
| 1078 |
+
assert actual == pytest.approx(expected)
|
| 1079 |
+
"""
|
| 1080 |
+
)
|
| 1081 |
+
result = pytester.runpytest()
|
| 1082 |
+
result.assert_outcomes(failed=1)
|
| 1083 |
+
result.stdout.fnmatch_lines(
|
| 1084 |
+
[
|
| 1085 |
+
"*comparison failed.**Mismatched elements: 2 / 4:*",
|
| 1086 |
+
"*Max absolute difference: 7*",
|
| 1087 |
+
"*Index | Obtained | Expected *",
|
| 1088 |
+
"* a * | 8 * | 1 *",
|
| 1089 |
+
"* c * | 5 * | 3 *",
|
| 1090 |
+
]
|
| 1091 |
+
)
|
| 1092 |
+
|
| 1093 |
+
def test_approx_on_unordered_mapping_matching(self, pytester: Pytester) -> None:
|
| 1094 |
+
"""https://github.com/pytest-dev/pytest/issues/12444"""
|
| 1095 |
+
pytester.makepyfile(
|
| 1096 |
+
"""
|
| 1097 |
+
import pytest
|
| 1098 |
+
def test_approx_on_unordered_mapping_matching():
|
| 1099 |
+
expected = {"a": 1, "b": 2, "c": 3, "d": 4}
|
| 1100 |
+
actual = {"d": 4, "c": 3, "a": 1, "b": 2}
|
| 1101 |
+
assert actual == pytest.approx(expected)
|
| 1102 |
+
"""
|
| 1103 |
+
)
|
| 1104 |
+
result = pytester.runpytest()
|
| 1105 |
+
result.assert_outcomes(passed=1)
|
| 1106 |
+
|
| 1107 |
+
|
| 1108 |
+
class MyVec3: # incomplete
|
| 1109 |
+
"""sequence like"""
|
| 1110 |
+
|
| 1111 |
+
_x: int
|
| 1112 |
+
_y: int
|
| 1113 |
+
_z: int
|
| 1114 |
+
|
| 1115 |
+
def __init__(self, x: int, y: int, z: int):
|
| 1116 |
+
self._x, self._y, self._z = x, y, z
|
| 1117 |
+
|
| 1118 |
+
def __repr__(self) -> str:
|
| 1119 |
+
return f"<MyVec3 {self._x} {self._y} {self._z}>"
|
| 1120 |
+
|
| 1121 |
+
def __len__(self) -> int:
|
| 1122 |
+
return 3
|
| 1123 |
+
|
| 1124 |
+
def __getitem__(self, key: int) -> int:
|
| 1125 |
+
if key == 0:
|
| 1126 |
+
return self._x
|
| 1127 |
+
if key == 1:
|
| 1128 |
+
return self._y
|
| 1129 |
+
if key == 2:
|
| 1130 |
+
return self._z
|
| 1131 |
+
raise IndexError(key)
|
| 1132 |
+
|
| 1133 |
+
|
| 1134 |
+
class TestRecursiveSequenceMap:
|
| 1135 |
+
def test_map_over_scalar(self):
|
| 1136 |
+
assert _recursive_sequence_map(sqrt, 16) == 4
|
| 1137 |
+
|
| 1138 |
+
def test_map_over_empty_list(self):
|
| 1139 |
+
assert _recursive_sequence_map(sqrt, []) == []
|
| 1140 |
+
|
| 1141 |
+
def test_map_over_list(self):
|
| 1142 |
+
assert _recursive_sequence_map(sqrt, [4, 16, 25, 676]) == [2, 4, 5, 26]
|
| 1143 |
+
|
| 1144 |
+
def test_map_over_tuple(self):
|
| 1145 |
+
assert _recursive_sequence_map(sqrt, (4, 16, 25, 676)) == (2, 4, 5, 26)
|
| 1146 |
+
|
| 1147 |
+
def test_map_over_nested_lists(self):
|
| 1148 |
+
assert _recursive_sequence_map(sqrt, [4, [25, 64], [[49]]]) == [
|
| 1149 |
+
2,
|
| 1150 |
+
[5, 8],
|
| 1151 |
+
[[7]],
|
| 1152 |
+
]
|
| 1153 |
+
|
| 1154 |
+
def test_map_over_mixed_sequence(self):
|
| 1155 |
+
assert _recursive_sequence_map(sqrt, [4, (25, 64), [49]]) == [
|
| 1156 |
+
2,
|
| 1157 |
+
(5, 8),
|
| 1158 |
+
[7],
|
| 1159 |
+
]
|
| 1160 |
+
|
| 1161 |
+
def test_map_over_sequence_like(self):
|
| 1162 |
+
assert _recursive_sequence_map(int, MyVec3(1, 2, 3)) == [1, 2, 3]
|