| 1 |
# mypy: allow-untyped-defs |
| 2 |
from __future__ import annotations |
| 3 |
|
| 4 |
from collections.abc import Iterator |
| 5 |
from collections.abc import Mapping |
| 6 |
from collections.abc import MutableSequence |
| 7 |
import dataclasses |
| 8 |
import sys |
| 9 |
import textwrap |
| 10 |
from typing import Any |
| 11 |
from typing import NamedTuple |
| 12 |
|
| 13 |
import attr |
| 14 |
|
| 15 |
from _pytest import outcomes |
| 16 |
import _pytest.assertion as plugin |
| 17 |
from _pytest.assertion import truncate |
| 18 |
from _pytest.assertion import util |
| 19 |
from _pytest.assertion._compare_any import _compare_eq_cls |
| 20 |
from _pytest.assertion.compare_text import _compare_eq_text |
| 21 |
from _pytest.config import Config as _Config |
| 22 |
from _pytest.monkeypatch import MonkeyPatch |
| 23 |
from _pytest.pytester import Pytester |
| 24 |
import pytest |
| 25 |
|
| 26 |
|
| 27 |
def mock_config( |
| 28 |
verbose: int = 0, |
| 29 |
assertion_override: int | None = None, |
| 30 |
assertion_text_diff_style: str = util.ASSERTION_TEXT_DIFF_STYLE_NDIFF, |
| 31 |
): |
| 32 |
class TerminalWriter: |
| 33 |
def _highlight(self, source, lexer="python"): |
| 34 |
return source |
| 35 |
|
| 36 |
class PluginManager: |
| 37 |
def has_plugin(self, name: str) -> bool: |
| 38 |
return True |
| 39 |
|
| 40 |
class Config: |
| 41 |
pluginmanager = PluginManager() |
| 42 |
|
| 43 |
def get_terminal_writer(self): |
| 44 |
return TerminalWriter() |
| 45 |
|
| 46 |
def get_verbosity(self, verbosity_type: str | None = None) -> int: |
| 47 |
if verbosity_type is None: |
| 48 |
return verbose |
| 49 |
if verbosity_type == _Config.VERBOSITY_ASSERTIONS: |
| 50 |
if assertion_override is not None: |
| 51 |
return assertion_override |
| 52 |
return verbose |
| 53 |
|
| 54 |
raise KeyError(f"Not mocked out: {verbosity_type}") |
| 55 |
|
| 56 |
def getini(self, name: str) -> str: |
| 57 |
if name == util.ASSERTION_TEXT_DIFF_STYLE_INI: |
| 58 |
return assertion_text_diff_style |
| 59 |
raise KeyError(f"Not mocked out: {name}") |
| 60 |
|
| 61 |
return Config() |
| 62 |
|
| 63 |
|
| 64 |
class TestMockConfig: |
| 65 |
SOME_VERBOSITY_LEVEL = 3 |
| 66 |
SOME_OTHER_VERBOSITY_LEVEL = 10 |
| 67 |
|
| 68 |
def test_verbose_exposes_value(self): |
| 69 |
config = mock_config(verbose=TestMockConfig.SOME_VERBOSITY_LEVEL) |
| 70 |
|
| 71 |
assert config.get_verbosity() == TestMockConfig.SOME_VERBOSITY_LEVEL |
| 72 |
|
| 73 |
def test_get_assertion_override_not_set_verbose_value(self): |
| 74 |
config = mock_config(verbose=TestMockConfig.SOME_VERBOSITY_LEVEL) |
| 75 |
|
| 76 |
assert ( |
| 77 |
config.get_verbosity(_Config.VERBOSITY_ASSERTIONS) |
| 78 |
== TestMockConfig.SOME_VERBOSITY_LEVEL |
| 79 |
) |
| 80 |
|
| 81 |
def test_get_assertion_override_set_custom_value(self): |
| 82 |
config = mock_config( |
| 83 |
verbose=TestMockConfig.SOME_VERBOSITY_LEVEL, |
| 84 |
assertion_override=TestMockConfig.SOME_OTHER_VERBOSITY_LEVEL, |
| 85 |
) |
| 86 |
|
| 87 |
assert ( |
| 88 |
config.get_verbosity(_Config.VERBOSITY_ASSERTIONS) |
| 89 |
== TestMockConfig.SOME_OTHER_VERBOSITY_LEVEL |
| 90 |
) |
| 91 |
|
| 92 |
def test_get_unsupported_type_error(self): |
| 93 |
config = mock_config(verbose=TestMockConfig.SOME_VERBOSITY_LEVEL) |
| 94 |
|
| 95 |
with pytest.raises(KeyError): |
| 96 |
config.get_verbosity("--- NOT A VERBOSITY LEVEL ---") |
| 97 |
|
| 98 |
def test_getini_unsupported_error(self): |
| 99 |
config = mock_config() |
| 100 |
|
| 101 |
with pytest.raises(KeyError, match="Not mocked out: --- NOT AN INI ---"): |
| 102 |
config.getini("--- NOT AN INI ---") |
| 103 |
|
| 104 |
|
| 105 |
class TestImportHookInstallation: |
| 106 |
@pytest.mark.parametrize("initial_conftest", [True, False]) |
| 107 |
@pytest.mark.parametrize("mode", ["plain", "rewrite"]) |
| 108 |
def test_conftest_assertion_rewrite( |
| 109 |
self, pytester: Pytester, initial_conftest, mode |
| 110 |
) -> None: |
| 111 |
"""Test that conftest files are using assertion rewrite on import (#1619).""" |
| 112 |
pytester.mkdir("foo") |
| 113 |
pytester.mkdir("foo/tests") |
| 114 |
conftest_path = "conftest.py" if initial_conftest else "foo/conftest.py" |
| 115 |
contents = { |
| 116 |
conftest_path: """ |
| 117 |
import pytest |
| 118 |
@pytest.fixture |
| 119 |
def check_first(): |
| 120 |
def check(values, value): |
| 121 |
assert values.pop(0) == value |
| 122 |
return check |
| 123 |
""", |
| 124 |
"foo/tests/test_foo.py": """ |
| 125 |
def test(check_first): |
| 126 |
check_first([10, 30], 30) |
| 127 |
""", |
| 128 |
} |
| 129 |
pytester.makepyfile(**contents) |
| 130 |
result = pytester.runpytest_subprocess(f"--assert={mode}") |
| 131 |
if mode == "plain": |
| 132 |
expected = "E AssertionError" |
| 133 |
elif mode == "rewrite": |
| 134 |
expected = "*assert 10 == 30*" |
| 135 |
else: |
| 136 |
assert 0 |
| 137 |
result.stdout.fnmatch_lines([expected]) |
| 138 |
|
| 139 |
def test_rewrite_assertions_pytester_plugin(self, pytester: Pytester) -> None: |
| 140 |
""" |
| 141 |
Assertions in the pytester plugin must also benefit from assertion |
| 142 |
rewriting (#1920). |
| 143 |
""" |
| 144 |
pytester.makepyfile( |
| 145 |
""" |
| 146 |
pytest_plugins = ['pytester'] |
| 147 |
def test_dummy_failure(pytester): # how meta! |
| 148 |
pytester.makepyfile('def test(): assert 0') |
| 149 |
r = pytester.inline_run() |
| 150 |
r.assertoutcome(passed=1) |
| 151 |
""" |
| 152 |
) |
| 153 |
result = pytester.runpytest_subprocess() |
| 154 |
result.stdout.fnmatch_lines( |
| 155 |
[ |
| 156 |
"> r.assertoutcome(passed=1)", |
| 157 |
"E AssertionError: ([[][]], [[][]], [[]<TestReport *>[]])*", |
| 158 |
"E assert {'failed': 1,... 'skipped': 0} == {'failed': 0,... 'skipped': 0}", |
| 159 |
"E Omitting 1 identical items, use -vv to show", |
| 160 |
"E Differing items:", |
| 161 |
"E Use -v to get more diff", |
| 162 |
] |
| 163 |
) |
| 164 |
# XXX: unstable output. |
| 165 |
result.stdout.fnmatch_lines_random( |
| 166 |
[ |
| 167 |
"E {'failed': 1} != {'failed': 0}", |
| 168 |
"E {'passed': 0} != {'passed': 1}", |
| 169 |
] |
| 170 |
) |
| 171 |
|
| 172 |
@pytest.mark.parametrize("mode", ["plain", "rewrite"]) |
| 173 |
def test_pytest_plugins_rewrite(self, pytester: Pytester, mode) -> None: |
| 174 |
contents = { |
| 175 |
"conftest.py": """ |
| 176 |
pytest_plugins = ['ham'] |
| 177 |
""", |
| 178 |
"ham.py": """ |
| 179 |
import pytest |
| 180 |
@pytest.fixture |
| 181 |
def check_first(): |
| 182 |
def check(values, value): |
| 183 |
assert values.pop(0) == value |
| 184 |
return check |
| 185 |
""", |
| 186 |
"test_foo.py": """ |
| 187 |
def test_foo(check_first): |
| 188 |
check_first([10, 30], 30) |
| 189 |
""", |
| 190 |
} |
| 191 |
pytester.makepyfile(**contents) |
| 192 |
result = pytester.runpytest_subprocess(f"--assert={mode}") |
| 193 |
if mode == "plain": |
| 194 |
expected = "E AssertionError" |
| 195 |
elif mode == "rewrite": |
| 196 |
expected = "*assert 10 == 30*" |
| 197 |
else: |
| 198 |
assert 0 |
| 199 |
result.stdout.fnmatch_lines([expected]) |
| 200 |
|
| 201 |
@pytest.mark.parametrize("mode", ["str", "list"]) |
| 202 |
def test_pytest_plugins_rewrite_module_names( |
| 203 |
self, pytester: Pytester, mode |
| 204 |
) -> None: |
| 205 |
"""Test that pluginmanager correct marks pytest_plugins variables |
| 206 |
for assertion rewriting if they are defined as plain strings or |
| 207 |
list of strings (#1888). |
| 208 |
""" |
| 209 |
plugins = '"ham"' if mode == "str" else '["ham"]' |
| 210 |
contents = { |
| 211 |
"conftest.py": f""" |
| 212 |
pytest_plugins = {plugins} |
| 213 |
""", |
| 214 |
"ham.py": """ |
| 215 |
import pytest |
| 216 |
""", |
| 217 |
"test_foo.py": """ |
| 218 |
def test_foo(pytestconfig): |
| 219 |
assert 'ham' in pytestconfig.pluginmanager.rewrite_hook._must_rewrite |
| 220 |
""", |
| 221 |
} |
| 222 |
pytester.makepyfile(**contents) |
| 223 |
result = pytester.runpytest_subprocess("--assert=rewrite") |
| 224 |
assert result.ret == 0 |
| 225 |
|
| 226 |
def test_pytest_plugins_rewrite_module_names_correctly( |
| 227 |
self, pytester: Pytester |
| 228 |
) -> None: |
| 229 |
"""Test that we match files correctly when they are marked for rewriting (#2939).""" |
| 230 |
contents = { |
| 231 |
"conftest.py": """\ |
| 232 |
pytest_plugins = "ham" |
| 233 |
""", |
| 234 |
"ham.py": "", |
| 235 |
"hamster.py": "", |
| 236 |
"test_foo.py": """\ |
| 237 |
def test_foo(pytestconfig): |
| 238 |
assert pytestconfig.pluginmanager.rewrite_hook.find_spec('ham') is not None |
| 239 |
assert pytestconfig.pluginmanager.rewrite_hook.find_spec('hamster') is None |
| 240 |
""", |
| 241 |
} |
| 242 |
pytester.makepyfile(**contents) |
| 243 |
result = pytester.runpytest_subprocess("--assert=rewrite") |
| 244 |
assert result.ret == 0 |
| 245 |
|
| 246 |
@pytest.mark.parametrize("mode", ["plain", "rewrite"]) |
| 247 |
@pytest.mark.parametrize("disable_plugin_autoload", ["env_var", "cli", ""]) |
| 248 |
@pytest.mark.parametrize("explicit_specify", ["env_var", "cli", ""]) |
| 249 |
def test_installed_plugin_rewrite( |
| 250 |
self, |
| 251 |
pytester: Pytester, |
| 252 |
mode: str, |
| 253 |
monkeypatch: pytest.MonkeyPatch, |
| 254 |
disable_plugin_autoload: str, |
| 255 |
explicit_specify: str, |
| 256 |
) -> None: |
| 257 |
args = ["mainwrapper.py", "-s", f"--assert={mode}"] |
| 258 |
if disable_plugin_autoload == "env_var": |
| 259 |
monkeypatch.setenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", "1") |
| 260 |
elif disable_plugin_autoload == "cli": |
| 261 |
monkeypatch.delenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", raising=False) |
| 262 |
args.append("--disable-plugin-autoload") |
| 263 |
else: |
| 264 |
assert disable_plugin_autoload == "" |
| 265 |
monkeypatch.delenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", raising=False) |
| 266 |
|
| 267 |
name = "spamplugin" |
| 268 |
|
| 269 |
if explicit_specify == "env_var": |
| 270 |
monkeypatch.setenv("PYTEST_PLUGINS", name) |
| 271 |
elif explicit_specify == "cli": |
| 272 |
args.append("-p") |
| 273 |
args.append(name) |
| 274 |
else: |
| 275 |
assert explicit_specify == "" |
| 276 |
|
| 277 |
# Make sure the hook is installed early enough so that plugins |
| 278 |
# installed via distribution package are rewritten. |
| 279 |
pytester.mkdir("hampkg") |
| 280 |
contents = { |
| 281 |
"hampkg/__init__.py": """\ |
| 282 |
import pytest |
| 283 |
|
| 284 |
@pytest.fixture |
| 285 |
def check_first2(): |
| 286 |
def check(values, value): |
| 287 |
assert values.pop(0) == value |
| 288 |
return check |
| 289 |
""", |
| 290 |
"spamplugin.py": """\ |
| 291 |
import pytest |
| 292 |
from hampkg import check_first2 |
| 293 |
|
| 294 |
@pytest.fixture |
| 295 |
def check_first(): |
| 296 |
def check(values, value): |
| 297 |
assert values.pop(0) == value |
| 298 |
return check |
| 299 |
""", |
| 300 |
"mainwrapper.py": """\ |
| 301 |
import importlib.metadata |
| 302 |
import pytest |
| 303 |
|
| 304 |
class DummyEntryPoint(object): |
| 305 |
name = 'spamplugin' |
| 306 |
module_name = 'spam.py' |
| 307 |
group = 'pytest11' |
| 308 |
|
| 309 |
def load(self): |
| 310 |
import spamplugin |
| 311 |
return spamplugin |
| 312 |
|
| 313 |
class DummyDistInfo(object): |
| 314 |
version = '1.0' |
| 315 |
files = ('spamplugin.py', 'hampkg/__init__.py') |
| 316 |
entry_points = (DummyEntryPoint(),) |
| 317 |
metadata = {'name': 'foo'} |
| 318 |
|
| 319 |
def distributions(): |
| 320 |
return (DummyDistInfo(),) |
| 321 |
|
| 322 |
importlib.metadata.distributions = distributions |
| 323 |
pytest.main() |
| 324 |
""", |
| 325 |
"test_foo.py": """\ |
| 326 |
def test(check_first): |
| 327 |
check_first([10, 30], 30) |
| 328 |
|
| 329 |
def test2(check_first2): |
| 330 |
check_first2([10, 30], 30) |
| 331 |
""", |
| 332 |
} |
| 333 |
pytester.makepyfile(**contents) |
| 334 |
result = pytester.run(sys.executable, *args) |
| 335 |
if mode == "plain": |
| 336 |
expected = "E AssertionError" |
| 337 |
elif mode == "rewrite": |
| 338 |
expected = "*assert 10 == 30*" |
| 339 |
else: |
| 340 |
assert 0 |
| 341 |
|
| 342 |
if not disable_plugin_autoload or explicit_specify: |
| 343 |
result.assert_outcomes(failed=2) |
| 344 |
result.stdout.fnmatch_lines([expected, expected]) |
| 345 |
else: |
| 346 |
result.assert_outcomes(errors=2) |
| 347 |
result.stdout.fnmatch_lines( |
| 348 |
[ |
| 349 |
"E fixture 'check_first' not found", |
| 350 |
"E fixture 'check_first2' not found", |
| 351 |
] |
| 352 |
) |
| 353 |
|
| 354 |
def test_rewrite_ast(self, pytester: Pytester) -> None: |
| 355 |
pytester.mkdir("pkg") |
| 356 |
contents = { |
| 357 |
"pkg/__init__.py": """ |
| 358 |
import pytest |
| 359 |
pytest.register_assert_rewrite('pkg.helper') |
| 360 |
""", |
| 361 |
"pkg/helper.py": """ |
| 362 |
def tool(): |
| 363 |
a, b = 2, 3 |
| 364 |
assert a == b |
| 365 |
""", |
| 366 |
"pkg/plugin.py": """ |
| 367 |
import pytest, pkg.helper |
| 368 |
@pytest.fixture |
| 369 |
def tool(): |
| 370 |
return pkg.helper.tool |
| 371 |
""", |
| 372 |
"pkg/other.py": """ |
| 373 |
values = [3, 2] |
| 374 |
def tool(): |
| 375 |
assert values.pop() == 3 |
| 376 |
""", |
| 377 |
"conftest.py": """ |
| 378 |
pytest_plugins = ['pkg.plugin'] |
| 379 |
""", |
| 380 |
"test_pkg.py": """ |
| 381 |
import pkg.other |
| 382 |
def test_tool(tool): |
| 383 |
tool() |
| 384 |
def test_other(): |
| 385 |
pkg.other.tool() |
| 386 |
""", |
| 387 |
} |
| 388 |
pytester.makepyfile(**contents) |
| 389 |
result = pytester.runpytest_subprocess("--assert=rewrite") |
| 390 |
result.stdout.fnmatch_lines( |
| 391 |
[ |
| 392 |
">*assert a == b*", |
| 393 |
"E*assert 2 == 3*", |
| 394 |
">*assert values.pop() == 3*", |
| 395 |
"E*AssertionError", |
| 396 |
] |
| 397 |
) |
| 398 |
|
| 399 |
def test_register_assert_rewrite_checks_types(self) -> None: |
| 400 |
with pytest.raises(TypeError): |
| 401 |
pytest.register_assert_rewrite(["pytest_tests_internal_non_existing"]) # type: ignore |
| 402 |
pytest.register_assert_rewrite( |
| 403 |
"pytest_tests_internal_non_existing", "pytest_tests_internal_non_existing2" |
| 404 |
) |
| 405 |
|
| 406 |
|
| 407 |
class TestBinReprIntegration: |
| 408 |
def test_pytest_assertrepr_compare_called(self, pytester: Pytester) -> None: |
| 409 |
pytester.makeconftest( |
| 410 |
""" |
| 411 |
import pytest |
| 412 |
values = [] |
| 413 |
def pytest_assertrepr_compare(op, left, right): |
| 414 |
values.append((op, left, right)) |
| 415 |
|
| 416 |
@pytest.fixture |
| 417 |
def list(request): |
| 418 |
return values |
| 419 |
""" |
| 420 |
) |
| 421 |
pytester.makepyfile( |
| 422 |
""" |
| 423 |
def test_hello(): |
| 424 |
assert 0 == 1 |
| 425 |
def test_check(list): |
| 426 |
assert list == [("==", 0, 1)] |
| 427 |
""" |
| 428 |
) |
| 429 |
result = pytester.runpytest("-v") |
| 430 |
result.stdout.fnmatch_lines(["*test_hello*FAIL*", "*test_check*PASS*"]) |
| 431 |
|
| 432 |
|
| 433 |
def callop( |
| 434 |
op: str, |
| 435 |
left: Any, |
| 436 |
right: Any, |
| 437 |
verbose: int = 0, |
| 438 |
assertion_text_diff_style: str = util.ASSERTION_TEXT_DIFF_STYLE_NDIFF, |
| 439 |
) -> list[str] | None: |
| 440 |
config = mock_config( |
| 441 |
verbose=verbose, |
| 442 |
assertion_text_diff_style=assertion_text_diff_style, |
| 443 |
) |
| 444 |
return plugin.pytest_assertrepr_compare(config, op, left, right) |
| 445 |
|
| 446 |
|
| 447 |
def callequal( |
| 448 |
left: Any, |
| 449 |
right: Any, |
| 450 |
verbose: int = 0, |
| 451 |
assertion_text_diff_style: str = util.ASSERTION_TEXT_DIFF_STYLE_NDIFF, |
| 452 |
) -> list[str] | None: |
| 453 |
return callop( |
| 454 |
"==", |
| 455 |
left, |
| 456 |
right, |
| 457 |
verbose, |
| 458 |
assertion_text_diff_style=assertion_text_diff_style, |
| 459 |
) |
| 460 |
|
| 461 |
|
| 462 |
class TestAssert_reprcompare: |
| 463 |
def test_different_types(self) -> None: |
| 464 |
assert callequal([0, 1], "foo") is None |
| 465 |
|
| 466 |
def test_summary(self) -> None: |
| 467 |
lines = callequal([0, 1], [0, 2]) |
| 468 |
assert lines is not None |
| 469 |
summary = lines[0] |
| 470 |
assert len(summary) < 65 |
| 471 |
|
| 472 |
def test_text_diff(self) -> None: |
| 473 |
assert callequal("spam", "eggs") == [ |
| 474 |
"'spam' == 'eggs'", |
| 475 |
"", |
| 476 |
"- eggs", |
| 477 |
"+ spam", |
| 478 |
] |
| 479 |
|
| 480 |
def test_text_diff_ndiff_style(self) -> None: |
| 481 |
assert list( |
| 482 |
_compare_eq_text( |
| 483 |
"spam", |
| 484 |
"eggs", |
| 485 |
util.dummy_highlighter, |
| 486 |
0, |
| 487 |
util.ASSERTION_TEXT_DIFF_STYLE_NDIFF, |
| 488 |
) |
| 489 |
) == [ |
| 490 |
"- eggs", |
| 491 |
"+ spam", |
| 492 |
] |
| 493 |
|
| 494 |
def test_text_skipping(self) -> None: |
| 495 |
lines = callequal("a" * 50 + "spam", "a" * 50 + "eggs") |
| 496 |
assert lines is not None |
| 497 |
assert "Skipping" in lines[2] |
| 498 |
for line in lines: |
| 499 |
assert "a" * 50 not in line |
| 500 |
|
| 501 |
def test_text_skipping_trailing(self) -> None: |
| 502 |
# Same length, differ at index 1, then ~50 identical trailing chars. |
| 503 |
# Exercises the trailing-skip branch in ``_diff_text``. |
| 504 |
lines = callequal("a" + "x" + "z" * 50, "a" + "y" + "z" * 50) |
| 505 |
assert lines is not None |
| 506 |
assert any("identical trailing" in line for line in lines) |
| 507 |
for line in lines: |
| 508 |
assert "z" * 50 not in line |
| 509 |
|
| 510 |
def test_text_skipping_verbose(self) -> None: |
| 511 |
lines = callequal("a" * 50 + "spam", "a" * 50 + "eggs", verbose=1) |
| 512 |
assert lines is not None |
| 513 |
assert "- " + "a" * 50 + "eggs" in lines |
| 514 |
assert "+ " + "a" * 50 + "spam" in lines |
| 515 |
|
| 516 |
def test_multiline_text_diff(self) -> None: |
| 517 |
left = "foo\nspam\nbar" |
| 518 |
right = "foo\neggs\nbar" |
| 519 |
diff = callequal(left, right) |
| 520 |
assert diff is not None |
| 521 |
assert "- eggs" in diff |
| 522 |
assert "+ spam" in diff |
| 523 |
|
| 524 |
def test_multiline_text_diff_block(self) -> None: |
| 525 |
assert callequal( |
| 526 |
"foo\nspam\nbar", |
| 527 |
"foo\neggs\nbar", |
| 528 |
assertion_text_diff_style=util.ASSERTION_TEXT_DIFF_STYLE_BLOCK, |
| 529 |
) == [ |
| 530 |
r"'foo\nspam\nbar' == 'foo\neggs\nbar'", |
| 531 |
"", |
| 532 |
"Left:", |
| 533 |
" foo", |
| 534 |
" spam", |
| 535 |
" bar", |
| 536 |
"", |
| 537 |
"Right:", |
| 538 |
" foo", |
| 539 |
" eggs", |
| 540 |
" bar", |
| 541 |
] |
| 542 |
|
| 543 |
def test_multiline_text_diff_block_preserves_blank_lines(self) -> None: |
| 544 |
assert callequal( |
| 545 |
"\nfoo\n", |
| 546 |
"\nbar", |
| 547 |
assertion_text_diff_style=util.ASSERTION_TEXT_DIFF_STYLE_BLOCK, |
| 548 |
) == [ |
| 549 |
r"'\nfoo\n' == '\nbar'", |
| 550 |
"", |
| 551 |
"Left:", |
| 552 |
" ", |
| 553 |
" foo", |
| 554 |
" ", |
| 555 |
"", |
| 556 |
"Right:", |
| 557 |
" ", |
| 558 |
" bar", |
| 559 |
] |
| 560 |
|
| 561 |
def test_single_line_text_diff_block(self) -> None: |
| 562 |
assert callequal( |
| 563 |
"spam", |
| 564 |
"eggs", |
| 565 |
assertion_text_diff_style=util.ASSERTION_TEXT_DIFF_STYLE_BLOCK, |
| 566 |
) == [ |
| 567 |
"'spam' == 'eggs'", |
| 568 |
"", |
| 569 |
"Left:", |
| 570 |
" spam", |
| 571 |
"", |
| 572 |
"Right:", |
| 573 |
" eggs", |
| 574 |
] |
| 575 |
|
| 576 |
def test_bytes_diff_normal(self) -> None: |
| 577 |
"""Check special handling for bytes diff (#5260)""" |
| 578 |
diff = callequal(b"spam", b"eggs") |
| 579 |
|
| 580 |
assert diff == [ |
| 581 |
"b'spam' == b'eggs'", |
| 582 |
"", |
| 583 |
"At index 0 diff: b's' != b'e'", |
| 584 |
"Use -v to get more diff", |
| 585 |
] |
| 586 |
|
| 587 |
def test_bytes_diff_verbose(self) -> None: |
| 588 |
"""Check special handling for bytes diff (#5260)""" |
| 589 |
diff = callequal(b"spam", b"eggs", verbose=1) |
| 590 |
assert diff == [ |
| 591 |
"b'spam' == b'eggs'", |
| 592 |
"", |
| 593 |
"At index 0 diff: b's' != b'e'", |
| 594 |
"", |
| 595 |
"Full diff:", |
| 596 |
"- b'eggs'", |
| 597 |
"+ b'spam'", |
| 598 |
] |
| 599 |
|
| 600 |
def test_list(self) -> None: |
| 601 |
expl = callequal([0, 1], [0, 2]) |
| 602 |
assert expl is not None |
| 603 |
assert len(expl) > 1 |
| 604 |
|
| 605 |
@pytest.mark.parametrize( |
| 606 |
["left", "right", "expected"], |
| 607 |
[ |
| 608 |
pytest.param( |
| 609 |
[0, 1], |
| 610 |
[0, 2], |
| 611 |
""" |
| 612 |
Full diff: |
| 613 |
[ |
| 614 |
0, |
| 615 |
- 2, |
| 616 |
? ^ |
| 617 |
+ 1, |
| 618 |
? ^ |
| 619 |
] |
| 620 |
""", |
| 621 |
id="lists", |
| 622 |
), |
| 623 |
pytest.param( |
| 624 |
{0: 1}, |
| 625 |
{0: 2}, |
| 626 |
""" |
| 627 |
Full diff: |
| 628 |
{ |
| 629 |
- 0: 2, |
| 630 |
? ^ |
| 631 |
+ 0: 1, |
| 632 |
? ^ |
| 633 |
} |
| 634 |
""", |
| 635 |
id="dicts", |
| 636 |
), |
| 637 |
pytest.param( |
| 638 |
{0, 1}, |
| 639 |
{0, 2}, |
| 640 |
""" |
| 641 |
Full diff: |
| 642 |
{ |
| 643 |
0, |
| 644 |
- 2, |
| 645 |
? ^ |
| 646 |
+ 1, |
| 647 |
? ^ |
| 648 |
} |
| 649 |
""", |
| 650 |
id="sets", |
| 651 |
), |
| 652 |
], |
| 653 |
) |
| 654 |
def test_iterable_full_diff(self, left, right, expected) -> None: |
| 655 |
"""Test the full diff assertion failure explanation. |
| 656 |
|
| 657 |
When verbose is False, then just a -v notice to get the diff is rendered, |
| 658 |
when verbose is True, then ndiff of the pprint is returned. |
| 659 |
""" |
| 660 |
expl = callequal(left, right, verbose=0) |
| 661 |
assert expl is not None |
| 662 |
assert expl[-1] == "Use -v to get more diff" |
| 663 |
verbose_expl = callequal(left, right, verbose=1) |
| 664 |
assert verbose_expl is not None |
| 665 |
assert "\n".join(verbose_expl).endswith(textwrap.dedent(expected).strip()) |
| 666 |
|
| 667 |
def test_iterable_quiet(self) -> None: |
| 668 |
expl = callequal([1, 2], [10, 2], verbose=-1) |
| 669 |
assert expl == [ |
| 670 |
"[1, 2] == [10, 2]", |
| 671 |
"", |
| 672 |
"At index 0 diff: 1 != 10", |
| 673 |
"Use -v to get more diff", |
| 674 |
] |
| 675 |
|
| 676 |
def test_iterable_full_diff_ci( |
| 677 |
self, monkeypatch: MonkeyPatch, pytester: Pytester |
| 678 |
) -> None: |
| 679 |
pytester.makepyfile( |
| 680 |
r""" |
| 681 |
def test_full_diff(): |
| 682 |
left = [0, 1] |
| 683 |
right = [0, 2] |
| 684 |
assert left == right |
| 685 |
""" |
| 686 |
) |
| 687 |
monkeypatch.setenv("CI", "true") |
| 688 |
result = pytester.runpytest() |
| 689 |
result.stdout.fnmatch_lines(["E Full diff:"]) |
| 690 |
|
| 691 |
# Setting CI to empty string is same as having it undefined |
| 692 |
monkeypatch.setenv("CI", "") |
| 693 |
result = pytester.runpytest() |
| 694 |
result.stdout.fnmatch_lines(["E Use -v to get more diff"]) |
| 695 |
|
| 696 |
monkeypatch.delenv("CI", raising=False) |
| 697 |
result = pytester.runpytest() |
| 698 |
result.stdout.fnmatch_lines(["E Use -v to get more diff"]) |
| 699 |
|
| 700 |
def test_list_different_lengths(self) -> None: |
| 701 |
expl = callequal([0, 1], [0, 1, 2]) |
| 702 |
assert expl is not None |
| 703 |
assert len(expl) > 1 |
| 704 |
expl = callequal([0, 1, 2], [0, 1]) |
| 705 |
assert expl is not None |
| 706 |
assert len(expl) > 1 |
| 707 |
|
| 708 |
def test_list_wrap_for_multiple_lines(self) -> None: |
| 709 |
long_d = "d" * 80 |
| 710 |
l1 = ["a", "b", "c"] |
| 711 |
l2 = ["a", "b", "c", long_d] |
| 712 |
diff = callequal(l1, l2, verbose=True) |
| 713 |
assert diff == [ |
| 714 |
"['a', 'b', 'c'] == ['a', 'b', 'c...dddddddddddd']", |
| 715 |
"", |
| 716 |
"Right contains one more item: '" + long_d + "'", |
| 717 |
"", |
| 718 |
"Full diff:", |
| 719 |
" [", |
| 720 |
" 'a',", |
| 721 |
" 'b',", |
| 722 |
" 'c',", |
| 723 |
"- '" + long_d + "',", |
| 724 |
" ]", |
| 725 |
] |
| 726 |
|
| 727 |
diff = callequal(l2, l1, verbose=True) |
| 728 |
assert diff == [ |
| 729 |
"['a', 'b', 'c...dddddddddddd'] == ['a', 'b', 'c']", |
| 730 |
"", |
| 731 |
"Left contains one more item: '" + long_d + "'", |
| 732 |
"", |
| 733 |
"Full diff:", |
| 734 |
" [", |
| 735 |
" 'a',", |
| 736 |
" 'b',", |
| 737 |
" 'c',", |
| 738 |
"+ '" + long_d + "',", |
| 739 |
" ]", |
| 740 |
] |
| 741 |
|
| 742 |
def test_list_wrap_for_width_rewrap_same_length(self) -> None: |
| 743 |
long_a = "a" * 30 |
| 744 |
long_b = "b" * 30 |
| 745 |
long_c = "c" * 30 |
| 746 |
l1 = [long_a, long_b, long_c] |
| 747 |
l2 = [long_b, long_c, long_a] |
| 748 |
diff = callequal(l1, l2, verbose=True) |
| 749 |
assert diff == [ |
| 750 |
"['aaaaaaaaaaa...cccccccccccc'] == ['bbbbbbbbbbb...aaaaaaaaaaaa']", |
| 751 |
"", |
| 752 |
"At index 0 diff: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' != 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'", |
| 753 |
"", |
| 754 |
"Full diff:", |
| 755 |
" [", |
| 756 |
"+ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',", |
| 757 |
" 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',", |
| 758 |
" 'cccccccccccccccccccccccccccccc',", |
| 759 |
"- 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',", |
| 760 |
" ]", |
| 761 |
] |
| 762 |
|
| 763 |
def test_list_dont_wrap_strings(self) -> None: |
| 764 |
long_a = "a" * 10 |
| 765 |
l1 = ["a"] + [long_a for _ in range(7)] |
| 766 |
l2 = ["should not get wrapped"] |
| 767 |
diff = callequal(l1, l2, verbose=True) |
| 768 |
assert diff == [ |
| 769 |
"['a', 'aaaaaa...aaaaaaa', ...] == ['should not get wrapped']", |
| 770 |
"", |
| 771 |
"At index 0 diff: 'a' != 'should not get wrapped'", |
| 772 |
"Left contains 7 more items, first extra item: 'aaaaaaaaaa'", |
| 773 |
"", |
| 774 |
"Full diff:", |
| 775 |
" [", |
| 776 |
"- 'should not get wrapped',", |
| 777 |
"+ 'a',", |
| 778 |
"+ 'aaaaaaaaaa',", |
| 779 |
"+ 'aaaaaaaaaa',", |
| 780 |
"+ 'aaaaaaaaaa',", |
| 781 |
"+ 'aaaaaaaaaa',", |
| 782 |
"+ 'aaaaaaaaaa',", |
| 783 |
"+ 'aaaaaaaaaa',", |
| 784 |
"+ 'aaaaaaaaaa',", |
| 785 |
" ]", |
| 786 |
] |
| 787 |
|
| 788 |
def test_dict_wrap(self) -> None: |
| 789 |
d1 = {"common": 1, "env": {"env1": 1, "env2": 2}} |
| 790 |
d2 = {"common": 1, "env": {"env1": 1}} |
| 791 |
|
| 792 |
diff = callequal(d1, d2, verbose=True) |
| 793 |
assert diff == [ |
| 794 |
"{'common': 1,...1, 'env2': 2}} == {'common': 1,...: {'env1': 1}}", |
| 795 |
"", |
| 796 |
"Omitting 1 identical items, use -vv to show", |
| 797 |
"Differing items:", |
| 798 |
"{'env': {'env1': 1, 'env2': 2}} != {'env': {'env1': 1}}", |
| 799 |
"", |
| 800 |
"Full diff:", |
| 801 |
" {", |
| 802 |
" 'common': 1,", |
| 803 |
" 'env': {", |
| 804 |
" 'env1': 1,", |
| 805 |
"+ 'env2': 2,", |
| 806 |
" },", |
| 807 |
" }", |
| 808 |
] |
| 809 |
|
| 810 |
long_a = "a" * 80 |
| 811 |
sub = {"long_a": long_a, "sub1": {"long_a": "substring that gets wrapped " * 3}} |
| 812 |
d1 = {"env": {"sub": sub}} |
| 813 |
d2 = {"env": {"sub": sub}, "new": 1} |
| 814 |
diff = callequal(d1, d2, verbose=True) |
| 815 |
assert diff == [ |
| 816 |
"{'env': {'sub... wrapped '}}}} == {'env': {'sub...}}}, 'new': 1}", |
| 817 |
"", |
| 818 |
"Omitting 1 identical items, use -vv to show", |
| 819 |
"Right contains 1 more item:", |
| 820 |
"{'new': 1}", |
| 821 |
"", |
| 822 |
"Full diff:", |
| 823 |
" {", |
| 824 |
" 'env': {", |
| 825 |
" 'sub': {", |
| 826 |
f" 'long_a': '{long_a}',", |
| 827 |
" 'sub1': {", |
| 828 |
" 'long_a': 'substring that gets wrapped substring that gets wrapped '", |
| 829 |
" 'substring that gets wrapped ',", |
| 830 |
" },", |
| 831 |
" },", |
| 832 |
" },", |
| 833 |
"- 'new': 1,", |
| 834 |
" }", |
| 835 |
] |
| 836 |
|
| 837 |
def test_dict(self) -> None: |
| 838 |
expl = callequal({"a": 0}, {"a": 1}) |
| 839 |
assert expl is not None |
| 840 |
assert len(expl) > 1 |
| 841 |
|
| 842 |
def test_dict_omitting(self) -> None: |
| 843 |
lines = callequal({"a": 0, "b": 1}, {"a": 1, "b": 1}) |
| 844 |
assert lines is not None |
| 845 |
assert lines[2].startswith("Omitting 1 identical item") |
| 846 |
assert "Common items" not in lines |
| 847 |
for line in lines[1:]: |
| 848 |
assert "b" not in line |
| 849 |
|
| 850 |
def test_dict_omitting_with_verbosity_1(self) -> None: |
| 851 |
"""Ensure differing items are visible for verbosity=1 (#1512).""" |
| 852 |
lines = callequal({"a": 0, "b": 1}, {"a": 1, "b": 1}, verbose=1) |
| 853 |
assert lines is not None |
| 854 |
assert lines[1] == "" |
| 855 |
assert lines[2].startswith("Omitting 1 identical item") |
| 856 |
assert lines[3].startswith("Differing items") |
| 857 |
assert lines[4] == "{'a': 0} != {'a': 1}" |
| 858 |
assert "Common items" not in lines |
| 859 |
|
| 860 |
def test_dict_omitting_with_verbosity_2(self) -> None: |
| 861 |
lines = callequal({"a": 0, "b": 1}, {"a": 1, "b": 1}, verbose=2) |
| 862 |
assert lines is not None |
| 863 |
assert lines[2].startswith("Common items:") |
| 864 |
assert "Omitting" not in lines[2] |
| 865 |
assert lines[3] == "{'b': 1}" |
| 866 |
|
| 867 |
def test_dict_different_items(self) -> None: |
| 868 |
lines = callequal({"a": 0}, {"b": 1, "c": 2}, verbose=2) |
| 869 |
assert lines == [ |
| 870 |
"{'a': 0} == {'b': 1, 'c': 2}", |
| 871 |
"", |
| 872 |
"Left contains 1 more item:", |
| 873 |
"{'a': 0}", |
| 874 |
"Right contains 2 more items:", |
| 875 |
"{'b': 1, 'c': 2}", |
| 876 |
"", |
| 877 |
"Full diff:", |
| 878 |
" {", |
| 879 |
"- 'b': 1,", |
| 880 |
"? ^ ^", |
| 881 |
"+ 'a': 0,", |
| 882 |
"? ^ ^", |
| 883 |
"- 'c': 2,", |
| 884 |
" }", |
| 885 |
] |
| 886 |
lines = callequal({"b": 1, "c": 2}, {"a": 0}, verbose=2) |
| 887 |
assert lines == [ |
| 888 |
"{'b': 1, 'c': 2} == {'a': 0}", |
| 889 |
"", |
| 890 |
"Left contains 2 more items:", |
| 891 |
"{'b': 1, 'c': 2}", |
| 892 |
"Right contains 1 more item:", |
| 893 |
"{'a': 0}", |
| 894 |
"", |
| 895 |
"Full diff:", |
| 896 |
" {", |
| 897 |
"- 'a': 0,", |
| 898 |
"? ^ ^", |
| 899 |
"+ 'b': 1,", |
| 900 |
"? ^ ^", |
| 901 |
"+ 'c': 2,", |
| 902 |
" }", |
| 903 |
] |
| 904 |
|
| 905 |
def test_mapping_different_items(self) -> None: |
| 906 |
class SimpleMapping(Mapping[str, int]): |
| 907 |
def __init__(self, values: dict[str, int]) -> None: |
| 908 |
self._values = values |
| 909 |
|
| 910 |
def __getitem__(self, key: str) -> int: |
| 911 |
return self._values[key] |
| 912 |
|
| 913 |
def __iter__(self) -> Iterator[str]: |
| 914 |
return iter(self._values) |
| 915 |
|
| 916 |
def __len__(self) -> int: # pragma: no cover |
| 917 |
return len(self._values) |
| 918 |
|
| 919 |
def __repr__(self) -> str: |
| 920 |
return f"SimpleMapping({self._values!r})" |
| 921 |
|
| 922 |
lines = callequal( |
| 923 |
SimpleMapping({"a": 0, "b": 1}), |
| 924 |
SimpleMapping({"a": 1, "b": 1, "c": 2}), |
| 925 |
) |
| 926 |
|
| 927 |
assert lines is not None |
| 928 |
assert lines[2:] == [ |
| 929 |
"Omitting 1 identical items, use -vv to show", |
| 930 |
"Differing items:", |
| 931 |
"{'a': 0} != {'a': 1}", |
| 932 |
"Right contains 1 more item:", |
| 933 |
"{'c': 2}", |
| 934 |
"Use -v to get more diff", |
| 935 |
] |
| 936 |
|
| 937 |
def test_sequence_different_items(self) -> None: |
| 938 |
lines = callequal((1, 2), (3, 4, 5), verbose=2) |
| 939 |
assert lines == [ |
| 940 |
"(1, 2) == (3, 4, 5)", |
| 941 |
"", |
| 942 |
"At index 0 diff: 1 != 3", |
| 943 |
"Right contains one more item: 5", |
| 944 |
"", |
| 945 |
"Full diff:", |
| 946 |
" (", |
| 947 |
"- 3,", |
| 948 |
"? ^", |
| 949 |
"+ 1,", |
| 950 |
"? ^", |
| 951 |
"- 4,", |
| 952 |
"? ^", |
| 953 |
"+ 2,", |
| 954 |
"? ^", |
| 955 |
"- 5,", |
| 956 |
" )", |
| 957 |
] |
| 958 |
lines = callequal((1, 2, 3), (4,), verbose=2) |
| 959 |
assert lines == [ |
| 960 |
"(1, 2, 3) == (4,)", |
| 961 |
"", |
| 962 |
"At index 0 diff: 1 != 4", |
| 963 |
"Left contains 2 more items, first extra item: 2", |
| 964 |
"", |
| 965 |
"Full diff:", |
| 966 |
" (", |
| 967 |
"- 4,", |
| 968 |
"? ^", |
| 969 |
"+ 1,", |
| 970 |
"? ^", |
| 971 |
"+ 2,", |
| 972 |
"+ 3,", |
| 973 |
" )", |
| 974 |
] |
| 975 |
lines = callequal((1, 2, 3), (1, 20, 3), verbose=2) |
| 976 |
assert lines == [ |
| 977 |
"(1, 2, 3) == (1, 20, 3)", |
| 978 |
"", |
| 979 |
"At index 1 diff: 2 != 20", |
| 980 |
"", |
| 981 |
"Full diff:", |
| 982 |
" (", |
| 983 |
" 1,", |
| 984 |
"- 20,", |
| 985 |
"? -", |
| 986 |
"+ 2,", |
| 987 |
" 3,", |
| 988 |
" )", |
| 989 |
] |
| 990 |
|
| 991 |
def test_set(self) -> None: |
| 992 |
expl = callequal({0, 1}, {0, 2}) |
| 993 |
assert expl is not None |
| 994 |
assert len(expl) > 1 |
| 995 |
|
| 996 |
def test_frozenzet(self) -> None: |
| 997 |
expl = callequal(frozenset([0, 1]), {0, 2}) |
| 998 |
assert expl is not None |
| 999 |
assert len(expl) > 1 |
| 1000 |
|
| 1001 |
def test_Sequence(self) -> None: |
| 1002 |
# Test comparing with a Sequence subclass. |
| 1003 |
class TestSequence(MutableSequence[int]): |
| 1004 |
def __init__(self, iterable): |
| 1005 |
self.elements = list(iterable) |
| 1006 |
|
| 1007 |
def __getitem__(self, item): |
| 1008 |
return self.elements[item] |
| 1009 |
|
| 1010 |
def __len__(self): |
| 1011 |
return len(self.elements) |
| 1012 |
|
| 1013 |
def __setitem__(self, item, value): |
| 1014 |
pass |
| 1015 |
|
| 1016 |
def __delitem__(self, item): |
| 1017 |
pass |
| 1018 |
|
| 1019 |
def insert(self, index, value): |
| 1020 |
pass |
| 1021 |
|
| 1022 |
expl = callequal(TestSequence([0, 1]), list([0, 2])) |
| 1023 |
assert expl is not None |
| 1024 |
assert len(expl) > 1 |
| 1025 |
|
| 1026 |
def test_list_tuples(self) -> None: |
| 1027 |
expl = callequal([], [(1, 2)]) |
| 1028 |
assert expl is not None |
| 1029 |
assert len(expl) > 1 |
| 1030 |
expl = callequal([(1, 2)], []) |
| 1031 |
assert expl is not None |
| 1032 |
assert len(expl) > 1 |
| 1033 |
|
| 1034 |
def test_list_bad_repr(self) -> None: |
| 1035 |
class A: |
| 1036 |
def __repr__(self): |
| 1037 |
raise ValueError(42) |
| 1038 |
|
| 1039 |
expl = callequal([], [A()]) |
| 1040 |
assert expl is not None |
| 1041 |
assert "ValueError" in "".join(expl) |
| 1042 |
expl = callequal({}, {"1": A()}, verbose=2) |
| 1043 |
assert expl is not None |
| 1044 |
assert expl[0].startswith("{} == <[ValueError") |
| 1045 |
assert "raised in repr" in expl[0] |
| 1046 |
# Streaming explanation: any per-line output produced before the |
| 1047 |
# bad repr is preserved, then the failure notice is appended. |
| 1048 |
assert expl[-2:] == [ |
| 1049 |
"(pytest_assertion plugin: representation of details failed:" |
| 1050 |
f" {__file__}:{A.__repr__.__code__.co_firstlineno + 1}: ValueError: 42.", |
| 1051 |
" Probably an object has a faulty __repr__.)", |
| 1052 |
] |
| 1053 |
|
| 1054 |
def test_one_repr_empty(self) -> None: |
| 1055 |
"""The faulty empty string repr did trigger an unbound local error in _diff_text.""" |
| 1056 |
|
| 1057 |
class A(str): |
| 1058 |
def __repr__(self): |
| 1059 |
return "" |
| 1060 |
|
| 1061 |
expl = callequal(A(), "") |
| 1062 |
assert not expl |
| 1063 |
|
| 1064 |
def test_repr_no_exc(self) -> None: |
| 1065 |
expl = callequal("foo", "bar") |
| 1066 |
assert expl is not None |
| 1067 |
assert "raised in repr()" not in " ".join(expl) |
| 1068 |
|
| 1069 |
def test_unicode(self) -> None: |
| 1070 |
assert callequal("£€", "£") == [ |
| 1071 |
"'£€' == '£'", |
| 1072 |
"", |
| 1073 |
"- £", |
| 1074 |
"+ £€", |
| 1075 |
] |
| 1076 |
|
| 1077 |
def test_nonascii_text(self) -> None: |
| 1078 |
""" |
| 1079 |
:issue: 877 |
| 1080 |
non ascii python2 str caused a UnicodeDecodeError |
| 1081 |
""" |
| 1082 |
|
| 1083 |
class A(str): |
| 1084 |
def __repr__(self): |
| 1085 |
return "\xff" |
| 1086 |
|
| 1087 |
expl = callequal(A(), "1") |
| 1088 |
assert expl == ["ÿ == '1'", "", "- 1"] |
| 1089 |
|
| 1090 |
def test_format_nonascii_explanation(self) -> None: |
| 1091 |
assert util.format_explanation("λ") |
| 1092 |
|
| 1093 |
def test_mojibake(self) -> None: |
| 1094 |
# issue 429 |
| 1095 |
left = b"e" |
| 1096 |
right = b"\xc3\xa9" |
| 1097 |
expl = callequal(left, right) |
| 1098 |
assert expl is not None |
| 1099 |
for line in expl: |
| 1100 |
assert isinstance(line, str) |
| 1101 |
msg = "\n".join(expl) |
| 1102 |
assert msg |
| 1103 |
|
| 1104 |
def test_nfc_nfd_same_string(self) -> None: |
| 1105 |
# issue 3426 |
| 1106 |
left = "hyv\xe4" |
| 1107 |
right = "hyva\u0308" |
| 1108 |
expl = callequal(left, right) |
| 1109 |
assert expl == [ |
| 1110 |
r"'hyv\xe4' == 'hyva\u0308'", |
| 1111 |
"", |
| 1112 |
f"- {right!s}", |
| 1113 |
f"+ {left!s}", |
| 1114 |
] |
| 1115 |
|
| 1116 |
expl = callequal(left, right, verbose=2) |
| 1117 |
assert expl == [ |
| 1118 |
r"'hyv\xe4' == 'hyva\u0308'", |
| 1119 |
"", |
| 1120 |
f"- {right!s}", |
| 1121 |
f"+ {left!s}", |
| 1122 |
] |
| 1123 |
|
| 1124 |
|
| 1125 |
class TestAssert_reprcompare_dataclass: |
| 1126 |
def test_dataclasses(self, pytester: Pytester) -> None: |
| 1127 |
p = pytester.copy_example("dataclasses/test_compare_dataclasses.py") |
| 1128 |
result = pytester.runpytest(p) |
| 1129 |
result.assert_outcomes(failed=1, passed=0) |
| 1130 |
result.stdout.fnmatch_lines( |
| 1131 |
[ |
| 1132 |
"E Omitting 1 identical items, use -vv to show", |
| 1133 |
"E Differing attributes:", |
| 1134 |
"E ['field_b']", |
| 1135 |
"E ", |
| 1136 |
"E Drill down into differing attribute field_b:", |
| 1137 |
"E field_b: 'b' != 'c'", |
| 1138 |
"E - c", |
| 1139 |
"E + b", |
| 1140 |
], |
| 1141 |
consecutive=True, |
| 1142 |
) |
| 1143 |
|
| 1144 |
def test_recursive_dataclasses(self, pytester: Pytester) -> None: |
| 1145 |
p = pytester.copy_example("dataclasses/test_compare_recursive_dataclasses.py") |
| 1146 |
result = pytester.runpytest(p) |
| 1147 |
result.assert_outcomes(failed=1, passed=0) |
| 1148 |
result.stdout.fnmatch_lines( |
| 1149 |
[ |
| 1150 |
"E Omitting 1 identical items, use -vv to show", |
| 1151 |
"E Differing attributes:", |
| 1152 |
"E ['g', 'h', 'j']", |
| 1153 |
"E ", |
| 1154 |
"E Drill down into differing attribute g:", |
| 1155 |
"E g: S(a=10, b='ten') != S(a=20, b='xxx')...", |
| 1156 |
"E ", |
| 1157 |
"E ...Full output truncated (51 lines hidden), use '-vv' to show", |
| 1158 |
], |
| 1159 |
consecutive=True, |
| 1160 |
) |
| 1161 |
|
| 1162 |
def test_recursive_dataclasses_verbose(self, pytester: Pytester) -> None: |
| 1163 |
p = pytester.copy_example("dataclasses/test_compare_recursive_dataclasses.py") |
| 1164 |
result = pytester.runpytest(p, "-vv") |
| 1165 |
result.assert_outcomes(failed=1, passed=0) |
| 1166 |
result.stdout.fnmatch_lines( |
| 1167 |
[ |
| 1168 |
"E Matching attributes:", |
| 1169 |
"E ['i']", |
| 1170 |
"E Differing attributes:", |
| 1171 |
"E ['g', 'h', 'j']", |
| 1172 |
"E ", |
| 1173 |
"E Drill down into differing attribute g:", |
| 1174 |
"E g: S(a=10, b='ten') != S(a=20, b='xxx')", |
| 1175 |
"E ", |
| 1176 |
"E Differing attributes:", |
| 1177 |
"E ['a', 'b']", |
| 1178 |
"E ", |
| 1179 |
"E Drill down into differing attribute a:", |
| 1180 |
"E a: 10 != 20", |
| 1181 |
"E ", |
| 1182 |
"E Drill down into differing attribute b:", |
| 1183 |
"E b: 'ten' != 'xxx'", |
| 1184 |
"E - xxx", |
| 1185 |
"E + ten", |
| 1186 |
"E ", |
| 1187 |
"E Drill down into differing attribute h:", |
| 1188 |
], |
| 1189 |
consecutive=True, |
| 1190 |
) |
| 1191 |
|
| 1192 |
def test_dataclasses_verbose(self, pytester: Pytester) -> None: |
| 1193 |
p = pytester.copy_example("dataclasses/test_compare_dataclasses_verbose.py") |
| 1194 |
result = pytester.runpytest(p, "-vv") |
| 1195 |
result.assert_outcomes(failed=1, passed=0) |
| 1196 |
result.stdout.fnmatch_lines( |
| 1197 |
[ |
| 1198 |
"*Matching attributes:*", |
| 1199 |
"*['field_a']*", |
| 1200 |
"*Differing attributes:*", |
| 1201 |
"*field_b: 'b' != 'c'*", |
| 1202 |
] |
| 1203 |
) |
| 1204 |
|
| 1205 |
def test_dataclasses_with_attribute_comparison_off( |
| 1206 |
self, pytester: Pytester |
| 1207 |
) -> None: |
| 1208 |
p = pytester.copy_example( |
| 1209 |
"dataclasses/test_compare_dataclasses_field_comparison_off.py" |
| 1210 |
) |
| 1211 |
result = pytester.runpytest(p, "-vv") |
| 1212 |
result.assert_outcomes(failed=0, passed=1) |
| 1213 |
|
| 1214 |
def test_comparing_two_different_data_classes(self, pytester: Pytester) -> None: |
| 1215 |
p = pytester.copy_example( |
| 1216 |
"dataclasses/test_compare_two_different_dataclasses.py" |
| 1217 |
) |
| 1218 |
result = pytester.runpytest(p, "-vv") |
| 1219 |
result.assert_outcomes(failed=0, passed=1) |
| 1220 |
|
| 1221 |
def test_data_classes_with_custom_eq(self, pytester: Pytester) -> None: |
| 1222 |
p = pytester.copy_example( |
| 1223 |
"dataclasses/test_compare_dataclasses_with_custom_eq.py" |
| 1224 |
) |
| 1225 |
# issue 9362 |
| 1226 |
result = pytester.runpytest(p, "-vv") |
| 1227 |
result.assert_outcomes(failed=1, passed=0) |
| 1228 |
result.stdout.no_re_match_line(".*Differing attributes.*") |
| 1229 |
|
| 1230 |
def test_data_classes_with_initvar(self, pytester: Pytester) -> None: |
| 1231 |
p = pytester.copy_example("dataclasses/test_compare_initvar.py") |
| 1232 |
# issue 9820 |
| 1233 |
result = pytester.runpytest(p, "-vv") |
| 1234 |
result.assert_outcomes(failed=1, passed=0) |
| 1235 |
result.stdout.no_re_match_line(".*AttributeError.*") |
| 1236 |
|
| 1237 |
|
| 1238 |
class TestAssert_reprcompare_attrsclass: |
| 1239 |
def test_attrs(self) -> None: |
| 1240 |
@attr.s |
| 1241 |
class SimpleDataObject: |
| 1242 |
field_a = attr.ib() |
| 1243 |
field_b = attr.ib() |
| 1244 |
|
| 1245 |
left = SimpleDataObject(1, "b") |
| 1246 |
right = SimpleDataObject(1, "c") |
| 1247 |
|
| 1248 |
lines = callequal(left, right) |
| 1249 |
assert lines is not None |
| 1250 |
assert lines[2].startswith("Omitting 1 identical item") |
| 1251 |
assert "Matching attributes" not in lines |
| 1252 |
for line in lines[2:]: |
| 1253 |
assert "field_a" not in line |
| 1254 |
|
| 1255 |
def test_attrs_recursive(self) -> None: |
| 1256 |
@attr.s |
| 1257 |
class OtherDataObject: |
| 1258 |
field_c = attr.ib() |
| 1259 |
field_d = attr.ib() |
| 1260 |
|
| 1261 |
@attr.s |
| 1262 |
class SimpleDataObject: |
| 1263 |
field_a = attr.ib() |
| 1264 |
field_b = attr.ib() |
| 1265 |
|
| 1266 |
left = SimpleDataObject(OtherDataObject(1, "a"), "b") |
| 1267 |
right = SimpleDataObject(OtherDataObject(1, "b"), "b") |
| 1268 |
|
| 1269 |
lines = callequal(left, right) |
| 1270 |
assert lines is not None |
| 1271 |
assert "Matching attributes" not in lines |
| 1272 |
for line in lines[1:]: |
| 1273 |
assert "field_b:" not in line |
| 1274 |
assert "field_c:" not in line |
| 1275 |
|
| 1276 |
def test_attrs_recursive_verbose(self) -> None: |
| 1277 |
@attr.s |
| 1278 |
class OtherDataObject: |
| 1279 |
field_c = attr.ib() |
| 1280 |
field_d = attr.ib() |
| 1281 |
|
| 1282 |
@attr.s |
| 1283 |
class SimpleDataObject: |
| 1284 |
field_a = attr.ib() |
| 1285 |
field_b = attr.ib() |
| 1286 |
|
| 1287 |
left = SimpleDataObject(OtherDataObject(1, "a"), "b") |
| 1288 |
right = SimpleDataObject(OtherDataObject(1, "b"), "b") |
| 1289 |
|
| 1290 |
lines = callequal(left, right) |
| 1291 |
assert lines is not None |
| 1292 |
# indentation in output because of nested object structure |
| 1293 |
assert " field_d: 'a' != 'b'" in lines |
| 1294 |
|
| 1295 |
def test_attrs_verbose(self) -> None: |
| 1296 |
@attr.s |
| 1297 |
class SimpleDataObject: |
| 1298 |
field_a = attr.ib() |
| 1299 |
field_b = attr.ib() |
| 1300 |
|
| 1301 |
left = SimpleDataObject(1, "b") |
| 1302 |
right = SimpleDataObject(1, "c") |
| 1303 |
|
| 1304 |
lines = callequal(left, right, verbose=2) |
| 1305 |
assert lines is not None |
| 1306 |
assert lines[2].startswith("Matching attributes:") |
| 1307 |
assert "Omitting" not in lines[2] |
| 1308 |
assert lines[3] == "['field_a']" |
| 1309 |
|
| 1310 |
def test_attrs_with_attribute_comparison_off(self) -> None: |
| 1311 |
@attr.s |
| 1312 |
class SimpleDataObject: |
| 1313 |
field_a = attr.ib() |
| 1314 |
field_b = attr.ib(eq=False) |
| 1315 |
|
| 1316 |
left = SimpleDataObject(1, "b") |
| 1317 |
right = SimpleDataObject(1, "b") |
| 1318 |
|
| 1319 |
lines = callequal(left, right, verbose=2) |
| 1320 |
assert lines is not None |
| 1321 |
assert lines[2].startswith("Matching attributes:") |
| 1322 |
assert "Omitting" not in lines[1] |
| 1323 |
assert lines[3] == "['field_a']" |
| 1324 |
for line in lines[3:]: |
| 1325 |
assert "field_b" not in line |
| 1326 |
|
| 1327 |
def test_comparing_two_different_attrs_classes(self) -> None: |
| 1328 |
@attr.s |
| 1329 |
class SimpleDataObjectOne: |
| 1330 |
field_a = attr.ib() |
| 1331 |
field_b = attr.ib() |
| 1332 |
|
| 1333 |
@attr.s |
| 1334 |
class SimpleDataObjectTwo: |
| 1335 |
field_a = attr.ib() |
| 1336 |
field_b = attr.ib() |
| 1337 |
|
| 1338 |
left = SimpleDataObjectOne(1, "b") |
| 1339 |
right = SimpleDataObjectTwo(1, "c") |
| 1340 |
|
| 1341 |
lines = callequal(left, right) |
| 1342 |
assert lines is None |
| 1343 |
|
| 1344 |
def test_attrs_with_auto_detect_and_custom_eq(self) -> None: |
| 1345 |
@attr.s( |
| 1346 |
auto_detect=True |
| 1347 |
) # attr.s doesn't ignore a custom eq if auto_detect=True |
| 1348 |
class SimpleDataObject: |
| 1349 |
field_a = attr.ib() |
| 1350 |
|
| 1351 |
def __eq__(self, other): # pragma: no cover |
| 1352 |
return super().__eq__(other) |
| 1353 |
|
| 1354 |
left = SimpleDataObject(1) |
| 1355 |
right = SimpleDataObject(2) |
| 1356 |
# issue 9362 |
| 1357 |
lines = callequal(left, right, verbose=2) |
| 1358 |
assert lines is None |
| 1359 |
|
| 1360 |
def test_attrs_with_custom_eq(self) -> None: |
| 1361 |
@attr.define(slots=False) |
| 1362 |
class SimpleDataObject: |
| 1363 |
field_a = attr.ib() |
| 1364 |
|
| 1365 |
def __eq__(self, other): # pragma: no cover |
| 1366 |
return super().__eq__(other) |
| 1367 |
|
| 1368 |
left = SimpleDataObject(1) |
| 1369 |
right = SimpleDataObject(2) |
| 1370 |
# issue 9362 |
| 1371 |
lines = callequal(left, right, verbose=2) |
| 1372 |
assert lines is None |
| 1373 |
|
| 1374 |
|
| 1375 |
class TestAssert_reprcompare_namedtuple: |
| 1376 |
def test_namedtuple(self) -> None: |
| 1377 |
class NT(NamedTuple): |
| 1378 |
a: Any |
| 1379 |
b: Any |
| 1380 |
|
| 1381 |
left = NT(1, "b") |
| 1382 |
right = NT(1, "c") |
| 1383 |
|
| 1384 |
lines = callequal(left, right) |
| 1385 |
assert lines == [ |
| 1386 |
"NT(a=1, b='b') == NT(a=1, b='c')", |
| 1387 |
"", |
| 1388 |
"Omitting 1 identical items, use -vv to show", |
| 1389 |
"Differing attributes:", |
| 1390 |
"['b']", |
| 1391 |
"", |
| 1392 |
"Drill down into differing attribute b:", |
| 1393 |
" b: 'b' != 'c'", |
| 1394 |
" - c", |
| 1395 |
" + b", |
| 1396 |
"Use -v to get more diff", |
| 1397 |
] |
| 1398 |
|
| 1399 |
def test_comparing_two_different_namedtuple(self) -> None: |
| 1400 |
class NT1(NamedTuple): |
| 1401 |
a: Any |
| 1402 |
b: Any |
| 1403 |
|
| 1404 |
class NT2(NamedTuple): |
| 1405 |
a: Any |
| 1406 |
b: Any |
| 1407 |
|
| 1408 |
left = NT1(1, "b") |
| 1409 |
right = NT2(2, "b") |
| 1410 |
|
| 1411 |
lines = callequal(left, right) |
| 1412 |
# Because the types are different, uses the generic sequence matcher. |
| 1413 |
assert lines == [ |
| 1414 |
"NT1(a=1, b='b') == NT2(a=2, b='b')", |
| 1415 |
"", |
| 1416 |
"At index 0 diff: 1 != 2", |
| 1417 |
"Use -v to get more diff", |
| 1418 |
] |
| 1419 |
|
| 1420 |
|
| 1421 |
class TestFormatExplanation: |
| 1422 |
def test_special_chars_full(self, pytester: Pytester) -> None: |
| 1423 |
# Issue 453, for the bug this would raise IndexError |
| 1424 |
pytester.makepyfile( |
| 1425 |
""" |
| 1426 |
def test_foo(): |
| 1427 |
assert '\\n}' == '' |
| 1428 |
""" |
| 1429 |
) |
| 1430 |
result = pytester.runpytest() |
| 1431 |
assert result.ret == 1 |
| 1432 |
result.stdout.fnmatch_lines(["*AssertionError*"]) |
| 1433 |
|
| 1434 |
def test_fmt_simple(self) -> None: |
| 1435 |
expl = "assert foo" |
| 1436 |
assert util.format_explanation(expl) == "assert foo" |
| 1437 |
|
| 1438 |
def test_fmt_where(self) -> None: |
| 1439 |
expl = "\n".join(["assert 1", "{1 = foo", "} == 2"]) |
| 1440 |
res = "\n".join(["assert 1 == 2", " + where 1 = foo"]) |
| 1441 |
assert util.format_explanation(expl) == res |
| 1442 |
|
| 1443 |
def test_fmt_and(self) -> None: |
| 1444 |
expl = "\n".join(["assert 1", "{1 = foo", "} == 2", "{2 = bar", "}"]) |
| 1445 |
res = "\n".join(["assert 1 == 2", " + where 1 = foo", " + and 2 = bar"]) |
| 1446 |
assert util.format_explanation(expl) == res |
| 1447 |
|
| 1448 |
def test_fmt_where_nested(self) -> None: |
| 1449 |
expl = "\n".join(["assert 1", "{1 = foo", "{foo = bar", "}", "} == 2"]) |
| 1450 |
res = "\n".join(["assert 1 == 2", " + where 1 = foo", " + where foo = bar"]) |
| 1451 |
assert util.format_explanation(expl) == res |
| 1452 |
|
| 1453 |
def test_fmt_newline(self) -> None: |
| 1454 |
expl = "\n".join(['assert "foo" == "bar"', "~- foo", "~+ bar"]) |
| 1455 |
res = "\n".join(['assert "foo" == "bar"', " - foo", " + bar"]) |
| 1456 |
assert util.format_explanation(expl) == res |
| 1457 |
|
| 1458 |
def test_fmt_newline_escaped(self) -> None: |
| 1459 |
expl = "\n".join(["assert foo == bar", "baz"]) |
| 1460 |
res = "assert foo == bar\\nbaz" |
| 1461 |
assert util.format_explanation(expl) == res |
| 1462 |
|
| 1463 |
def test_fmt_newline_before_where(self) -> None: |
| 1464 |
expl = "\n".join( |
| 1465 |
[ |
| 1466 |
"the assertion message here", |
| 1467 |
">assert 1", |
| 1468 |
"{1 = foo", |
| 1469 |
"} == 2", |
| 1470 |
"{2 = bar", |
| 1471 |
"}", |
| 1472 |
] |
| 1473 |
) |
| 1474 |
res = "\n".join( |
| 1475 |
[ |
| 1476 |
"the assertion message here", |
| 1477 |
"assert 1 == 2", |
| 1478 |
" + where 1 = foo", |
| 1479 |
" + and 2 = bar", |
| 1480 |
] |
| 1481 |
) |
| 1482 |
assert util.format_explanation(expl) == res |
| 1483 |
|
| 1484 |
def test_fmt_multi_newline_before_where(self) -> None: |
| 1485 |
expl = "\n".join( |
| 1486 |
[ |
| 1487 |
"the assertion", |
| 1488 |
"~message here", |
| 1489 |
">assert 1", |
| 1490 |
"{1 = foo", |
| 1491 |
"} == 2", |
| 1492 |
"{2 = bar", |
| 1493 |
"}", |
| 1494 |
] |
| 1495 |
) |
| 1496 |
res = "\n".join( |
| 1497 |
[ |
| 1498 |
"the assertion", |
| 1499 |
" message here", |
| 1500 |
"assert 1 == 2", |
| 1501 |
" + where 1 = foo", |
| 1502 |
" + and 2 = bar", |
| 1503 |
] |
| 1504 |
) |
| 1505 |
assert util.format_explanation(expl) == res |
| 1506 |
|
| 1507 |
|
| 1508 |
class TestTruncateExplanation: |
| 1509 |
# The number of lines in the truncation explanation message. Used |
| 1510 |
# to calculate that results have the expected length. |
| 1511 |
LINES_IN_TRUNCATION_MSG = 2 |
| 1512 |
|
| 1513 |
def test_doesnt_truncate_when_input_is_empty_list(self) -> None: |
| 1514 |
expl: list[str] = [] |
| 1515 |
result = truncate._truncate_explanation(expl, max_lines=8, max_chars=100) |
| 1516 |
assert result == expl |
| 1517 |
|
| 1518 |
def test_doesnt_truncate_at_when_input_is_5_lines_and_LT_max_chars(self) -> None: |
| 1519 |
expl = ["a" * 100 for x in range(5)] |
| 1520 |
result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8 * 80) |
| 1521 |
assert result == expl |
| 1522 |
|
| 1523 |
def test_truncates_at_8_lines_when_given_list_of_empty_strings(self) -> None: |
| 1524 |
expl = ["" for x in range(50)] |
| 1525 |
result = truncate._truncate_explanation(expl, max_lines=8, max_chars=100) |
| 1526 |
assert len(result) != len(expl) |
| 1527 |
assert result != expl |
| 1528 |
assert len(result) == 8 + self.LINES_IN_TRUNCATION_MSG |
| 1529 |
assert "Full output truncated" in result[-1] |
| 1530 |
assert "42 lines hidden" in result[-1] |
| 1531 |
last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1] |
| 1532 |
assert last_line_before_trunc_msg.endswith("...") |
| 1533 |
|
| 1534 |
def test_truncates_at_8_lines_when_first_8_lines_are_LT_max_chars(self) -> None: |
| 1535 |
total_lines = 100 |
| 1536 |
expl = ["a" for x in range(total_lines)] |
| 1537 |
result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8 * 80) |
| 1538 |
assert result != expl |
| 1539 |
assert len(result) == 8 + self.LINES_IN_TRUNCATION_MSG |
| 1540 |
assert "Full output truncated" in result[-1] |
| 1541 |
assert f"{total_lines - 8} lines hidden" in result[-1] |
| 1542 |
last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1] |
| 1543 |
assert last_line_before_trunc_msg.endswith("...") |
| 1544 |
|
| 1545 |
def test_truncates_at_8_lines_when_there_is_one_line_to_remove(self) -> None: |
| 1546 |
"""The number of line in the result is 9, the same number as if we truncated.""" |
| 1547 |
expl = ["a" for x in range(9)] |
| 1548 |
result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8 * 80) |
| 1549 |
assert result == expl |
| 1550 |
assert "truncated" not in result[-1] |
| 1551 |
|
| 1552 |
def test_truncates_full_line_because_of_max_chars(self) -> None: |
| 1553 |
"""A line is fully truncated because of the max_chars value.""" |
| 1554 |
expl = ["a" * 10, "b" * 71] |
| 1555 |
result = truncate._truncate_explanation(expl, max_lines=10, max_chars=10) |
| 1556 |
assert result == [ |
| 1557 |
"a" * 10, |
| 1558 |
"...", |
| 1559 |
"", |
| 1560 |
"...Full output truncated (1 line hidden), use '-vv' to show", |
| 1561 |
] |
| 1562 |
|
| 1563 |
def test_truncates_edgecase_when_truncation_message_makes_the_result_longer_for_chars( |
| 1564 |
self, |
| 1565 |
) -> None: |
| 1566 |
line = "a" * 10 |
| 1567 |
expl = [line, line] |
| 1568 |
result = truncate._truncate_explanation(expl, max_lines=10, max_chars=10) |
| 1569 |
assert result == [line, line] |
| 1570 |
|
| 1571 |
def test_truncates_edgecase_when_truncation_message_makes_the_result_longer_for_lines( |
| 1572 |
self, |
| 1573 |
) -> None: |
| 1574 |
line = "a" * 10 |
| 1575 |
expl = [line, line] |
| 1576 |
result = truncate._truncate_explanation(expl, max_lines=1, max_chars=100) |
| 1577 |
assert result == [line, line] |
| 1578 |
|
| 1579 |
def test_truncates_at_8_lines_when_first_8_lines_are_EQ_max_chars(self) -> None: |
| 1580 |
expl = [chr(97 + x) * 80 for x in range(16)] |
| 1581 |
result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8 * 80) |
| 1582 |
assert result != expl |
| 1583 |
assert len(result) == 16 - 8 + self.LINES_IN_TRUNCATION_MSG |
| 1584 |
assert "Full output truncated" in result[-1] |
| 1585 |
assert "8 lines hidden" in result[-1] |
| 1586 |
last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1] |
| 1587 |
assert last_line_before_trunc_msg.endswith("...") |
| 1588 |
|
| 1589 |
def test_truncates_at_4_lines_when_first_4_lines_are_GT_max_chars(self) -> None: |
| 1590 |
expl = ["a" * 250 for x in range(10)] |
| 1591 |
result = truncate._truncate_explanation(expl, max_lines=8, max_chars=999) |
| 1592 |
assert result != expl |
| 1593 |
assert len(result) == 4 + self.LINES_IN_TRUNCATION_MSG |
| 1594 |
assert "Full output truncated" in result[-1] |
| 1595 |
assert "7 lines hidden" in result[-1] |
| 1596 |
last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1] |
| 1597 |
assert last_line_before_trunc_msg.endswith("...") |
| 1598 |
|
| 1599 |
def test_truncates_at_1_line_when_first_line_is_GT_max_chars(self) -> None: |
| 1600 |
expl = ["a" * 250 for x in range(1000)] |
| 1601 |
result = truncate._truncate_explanation(expl, max_lines=8, max_chars=100) |
| 1602 |
assert result != expl |
| 1603 |
assert len(result) == 1 + self.LINES_IN_TRUNCATION_MSG |
| 1604 |
assert "Full output truncated" in result[-1] |
| 1605 |
assert "1000 lines hidden" in result[-1] |
| 1606 |
last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1] |
| 1607 |
assert last_line_before_trunc_msg.endswith("...") |
| 1608 |
|
| 1609 |
def test_full_output_truncated(self, monkeypatch, pytester: Pytester) -> None: |
| 1610 |
"""Test against full runpytest() output.""" |
| 1611 |
line_count = 7 |
| 1612 |
line_len = 100 |
| 1613 |
expected_truncated_lines = 2 |
| 1614 |
pytester.makepyfile( |
| 1615 |
rf""" |
| 1616 |
def test_many_lines(): |
| 1617 |
a = list([str(i)[0] * {line_len} for i in range({line_count})]) |
| 1618 |
b = a[::2] |
| 1619 |
a = '\n'.join(map(str, a)) |
| 1620 |
b = '\n'.join(map(str, b)) |
| 1621 |
assert a == b |
| 1622 |
""" |
| 1623 |
) |
| 1624 |
monkeypatch.delenv("CI", raising=False) |
| 1625 |
|
| 1626 |
result = pytester.runpytest() |
| 1627 |
# without -vv, truncate the message showing a few diff lines only |
| 1628 |
result.stdout.fnmatch_lines( |
| 1629 |
[ |
| 1630 |
"*+ 1*", |
| 1631 |
"*+ 3*", |
| 1632 |
f"*truncated ({expected_truncated_lines} lines hidden)*use*-vv*", |
| 1633 |
] |
| 1634 |
) |
| 1635 |
|
| 1636 |
result = pytester.runpytest("-vv") |
| 1637 |
result.stdout.fnmatch_lines(["* 6*"]) |
| 1638 |
|
| 1639 |
# Setting CI to empty string is same as having it undefined |
| 1640 |
monkeypatch.setenv("CI", "") |
| 1641 |
result = pytester.runpytest() |
| 1642 |
result.stdout.fnmatch_lines( |
| 1643 |
[ |
| 1644 |
"*+ 1*", |
| 1645 |
"*+ 3*", |
| 1646 |
f"*truncated ({expected_truncated_lines} lines hidden)*use*-vv*", |
| 1647 |
] |
| 1648 |
) |
| 1649 |
|
| 1650 |
monkeypatch.setenv("CI", "1") |
| 1651 |
result = pytester.runpytest() |
| 1652 |
result.stdout.fnmatch_lines(["* 6*"]) |
| 1653 |
|
| 1654 |
@pytest.mark.parametrize( |
| 1655 |
["truncation_lines", "truncation_chars", "expected_lines_hidden"], |
| 1656 |
( |
| 1657 |
(3, None, 3), |
| 1658 |
(4, None, 0), |
| 1659 |
(0, None, 0), |
| 1660 |
(None, 8, 6), |
| 1661 |
(None, 9, 0), |
| 1662 |
(None, 0, 0), |
| 1663 |
(0, 0, 0), |
| 1664 |
(0, 1000, 0), |
| 1665 |
(1000, 0, 0), |
| 1666 |
), |
| 1667 |
) |
| 1668 |
def test_truncation_with_ini( |
| 1669 |
self, |
| 1670 |
monkeypatch, |
| 1671 |
pytester: Pytester, |
| 1672 |
truncation_lines: int | None, |
| 1673 |
truncation_chars: int | None, |
| 1674 |
expected_lines_hidden: int, |
| 1675 |
) -> None: |
| 1676 |
pytester.makepyfile( |
| 1677 |
"""\ |
| 1678 |
string_a = "123456789\\n23456789\\n3" |
| 1679 |
string_b = "123456789\\n23456789\\n4" |
| 1680 |
|
| 1681 |
def test(): |
| 1682 |
assert string_a == string_b |
| 1683 |
""" |
| 1684 |
) |
| 1685 |
|
| 1686 |
# This test produces 6 lines of diff output or 79 characters |
| 1687 |
# So the effect should be when threshold is < 4 lines (considering 2 additional lines for explanation) |
| 1688 |
# Or < 9 characters (considering 70 additional characters for explanation) |
| 1689 |
|
| 1690 |
monkeypatch.delenv("CI", raising=False) |
| 1691 |
|
| 1692 |
ini = "[pytest]\n" |
| 1693 |
if truncation_lines is not None: |
| 1694 |
ini += f"truncation_limit_lines = {truncation_lines}\n" |
| 1695 |
if truncation_chars is not None: |
| 1696 |
ini += f"truncation_limit_chars = {truncation_chars}\n" |
| 1697 |
pytester.makeini(ini) |
| 1698 |
|
| 1699 |
result = pytester.runpytest() |
| 1700 |
|
| 1701 |
if expected_lines_hidden != 0: |
| 1702 |
result.stdout.fnmatch_lines( |
| 1703 |
[f"*truncated ({expected_lines_hidden} lines hidden)*"] |
| 1704 |
) |
| 1705 |
else: |
| 1706 |
result.stdout.no_fnmatch_line("*truncated*") |
| 1707 |
result.stdout.fnmatch_lines( |
| 1708 |
[ |
| 1709 |
"*- 4*", |
| 1710 |
"*+ 3*", |
| 1711 |
] |
| 1712 |
) |
| 1713 |
|
| 1714 |
|
| 1715 |
def test_python25_compile_issue257(pytester: Pytester) -> None: |
| 1716 |
pytester.makepyfile( |
| 1717 |
""" |
| 1718 |
def test_rewritten(): |
| 1719 |
assert 1 == 2 |
| 1720 |
# some comment |
| 1721 |
""" |
| 1722 |
) |
| 1723 |
result = pytester.runpytest() |
| 1724 |
assert result.ret == 1 |
| 1725 |
result.stdout.fnmatch_lines( |
| 1726 |
""" |
| 1727 |
*E*assert 1 == 2* |
| 1728 |
*1 failed* |
| 1729 |
""" |
| 1730 |
) |
| 1731 |
|
| 1732 |
|
| 1733 |
def test_rewritten(pytester: Pytester) -> None: |
| 1734 |
pytester.makepyfile( |
| 1735 |
""" |
| 1736 |
def test_rewritten(): |
| 1737 |
assert "@py_builtins" in globals() |
| 1738 |
""" |
| 1739 |
) |
| 1740 |
assert pytester.runpytest().ret == 0 |
| 1741 |
|
| 1742 |
|
| 1743 |
def test_reprcompare_notin() -> None: |
| 1744 |
assert callop("not in", "foo", "aaafoobbb") == [ |
| 1745 |
"'foo' not in 'aaafoobbb'", |
| 1746 |
"", |
| 1747 |
"'foo' is contained here:", |
| 1748 |
" aaafoobbb", |
| 1749 |
"? +++", |
| 1750 |
] |
| 1751 |
|
| 1752 |
|
| 1753 |
def test_reprcompare_notin_nontext() -> None: |
| 1754 |
# ``not in`` with non-text operands has no specialised explanation. |
| 1755 |
assert callop("not in", 1, [1, 2]) is None |
| 1756 |
|
| 1757 |
|
| 1758 |
def test_reprcompare_notin_long_text() -> None: |
| 1759 |
# Long enough surrounding context to make the underlying ``_diff_text`` call |
| 1760 |
# emit a "Skipping ... identical leading characters" line, which |
| 1761 |
# ``_notin_text`` filters out. |
| 1762 |
lines = callop("not in", "x", "a" * 50 + "x") |
| 1763 |
assert lines is not None |
| 1764 |
assert not any("Skipping" in line for line in lines) |
| 1765 |
|
| 1766 |
|
| 1767 |
def test_compare_eq_cls_no_comparable_fields() -> None: |
| 1768 |
# A dataclass with no compared fields always compares equal, so the |
| 1769 |
# comparison hook is never reached via a failed assertion. Call the |
| 1770 |
# helper directly to exercise the "nothing to report" path. |
| 1771 |
@dataclasses.dataclass |
| 1772 |
class NoCompare: |
| 1773 |
x: int = dataclasses.field(default=0, compare=False) |
| 1774 |
|
| 1775 |
assert ( |
| 1776 |
list( |
| 1777 |
_compare_eq_cls( |
| 1778 |
NoCompare(1), |
| 1779 |
NoCompare(2), |
| 1780 |
util.dummy_highlighter, |
| 1781 |
0, |
| 1782 |
util.ASSERTION_TEXT_DIFF_STYLE_NDIFF, |
| 1783 |
) |
| 1784 |
) |
| 1785 |
== [] |
| 1786 |
) |
| 1787 |
|
| 1788 |
|
| 1789 |
def test_reprcompare_whitespaces() -> None: |
| 1790 |
assert callequal("\r\n", "\n") == [ |
| 1791 |
r"'\r\n' == '\n'", |
| 1792 |
"", |
| 1793 |
r"Strings contain only whitespace, escaping them using repr()", |
| 1794 |
r"- '\n'", |
| 1795 |
r"+ '\r\n'", |
| 1796 |
r"? ++", |
| 1797 |
] |
| 1798 |
|
| 1799 |
|
| 1800 |
class TestSetAssertions: |
| 1801 |
@pytest.mark.parametrize("op", [">=", ">", "<=", "<", "=="]) |
| 1802 |
def test_set_extra_item(self, op, pytester: Pytester) -> None: |
| 1803 |
pytester.makepyfile( |
| 1804 |
f""" |
| 1805 |
def test_hello(): |
| 1806 |
x = set("hello x") |
| 1807 |
y = set("hello y") |
| 1808 |
assert x {op} y |
| 1809 |
""" |
| 1810 |
) |
| 1811 |
|
| 1812 |
result = pytester.runpytest() |
| 1813 |
result.stdout.fnmatch_lines( |
| 1814 |
[ |
| 1815 |
"*def test_hello():*", |
| 1816 |
f"*assert x {op} y*", |
| 1817 |
] |
| 1818 |
) |
| 1819 |
if op in [">=", ">", "=="]: |
| 1820 |
result.stdout.fnmatch_lines( |
| 1821 |
[ |
| 1822 |
"*E*Extra items in the right set:*", |
| 1823 |
"*E*'y'", |
| 1824 |
] |
| 1825 |
) |
| 1826 |
if op in ["<=", "<", "=="]: |
| 1827 |
result.stdout.fnmatch_lines( |
| 1828 |
[ |
| 1829 |
"*E*Extra items in the left set:*", |
| 1830 |
"*E*'x'", |
| 1831 |
] |
| 1832 |
) |
| 1833 |
|
| 1834 |
@pytest.mark.parametrize("op", [">", "<", "!="]) |
| 1835 |
def test_set_proper_superset_equal(self, pytester: Pytester, op) -> None: |
| 1836 |
pytester.makepyfile( |
| 1837 |
f""" |
| 1838 |
def test_hello(): |
| 1839 |
x = set([1, 2, 3]) |
| 1840 |
y = x.copy() |
| 1841 |
assert x {op} y |
| 1842 |
""" |
| 1843 |
) |
| 1844 |
|
| 1845 |
result = pytester.runpytest() |
| 1846 |
result.stdout.fnmatch_lines( |
| 1847 |
[ |
| 1848 |
"*def test_hello():*", |
| 1849 |
f"*assert x {op} y*", |
| 1850 |
"*E*Both sets are equal*", |
| 1851 |
] |
| 1852 |
) |
| 1853 |
|
| 1854 |
def test_pytest_assertrepr_compare_integration(self, pytester: Pytester) -> None: |
| 1855 |
pytester.makepyfile( |
| 1856 |
""" |
| 1857 |
def test_hello(): |
| 1858 |
x = set(range(100)) |
| 1859 |
y = x.copy() |
| 1860 |
y.remove(50) |
| 1861 |
assert x == y |
| 1862 |
""" |
| 1863 |
) |
| 1864 |
result = pytester.runpytest() |
| 1865 |
result.stdout.fnmatch_lines( |
| 1866 |
[ |
| 1867 |
"*def test_hello():*", |
| 1868 |
"*assert x == y*", |
| 1869 |
"*E*Extra items*left*", |
| 1870 |
"*E*50*", |
| 1871 |
"*= 1 failed in*", |
| 1872 |
] |
| 1873 |
) |
| 1874 |
|
| 1875 |
|
| 1876 |
def test_assertrepr_loaded_per_dir(pytester: Pytester) -> None: |
| 1877 |
pytester.makepyfile(test_base=["def test_base(): assert 1 == 2"]) |
| 1878 |
a = pytester.mkdir("a") |
| 1879 |
a.joinpath("test_a.py").write_text("def test_a(): assert 1 == 2", encoding="utf-8") |
| 1880 |
a.joinpath("conftest.py").write_text( |
| 1881 |
'def pytest_assertrepr_compare(): return ["summary a"]', encoding="utf-8" |
| 1882 |
) |
| 1883 |
b = pytester.mkdir("b") |
| 1884 |
b.joinpath("test_b.py").write_text("def test_b(): assert 1 == 2", encoding="utf-8") |
| 1885 |
b.joinpath("conftest.py").write_text( |
| 1886 |
'def pytest_assertrepr_compare(): return ["summary b"]', encoding="utf-8" |
| 1887 |
) |
| 1888 |
|
| 1889 |
result = pytester.runpytest() |
| 1890 |
result.stdout.fnmatch_lines( |
| 1891 |
[ |
| 1892 |
"*def test_a():*", |
| 1893 |
"*E*assert summary a*", |
| 1894 |
"*def test_b():*", |
| 1895 |
"*E*assert summary b*", |
| 1896 |
"*def test_base():*", |
| 1897 |
"*E*assert 1 == 2*", |
| 1898 |
] |
| 1899 |
) |
| 1900 |
|
| 1901 |
|
| 1902 |
def test_assertion_options(pytester: Pytester) -> None: |
| 1903 |
pytester.makepyfile( |
| 1904 |
""" |
| 1905 |
def test_hello(): |
| 1906 |
x = 3 |
| 1907 |
assert x == 4 |
| 1908 |
""" |
| 1909 |
) |
| 1910 |
result = pytester.runpytest() |
| 1911 |
assert "3 == 4" in result.stdout.str() |
| 1912 |
result = pytester.runpytest_subprocess("--assert=plain") |
| 1913 |
result.stdout.no_fnmatch_line("*3 == 4*") |
| 1914 |
|
| 1915 |
|
| 1916 |
def test_triple_quoted_string_issue113(pytester: Pytester) -> None: |
| 1917 |
pytester.makepyfile( |
| 1918 |
""" |
| 1919 |
def test_hello(): |
| 1920 |
assert "" == ''' |
| 1921 |
'''""" |
| 1922 |
) |
| 1923 |
result = pytester.runpytest("--fulltrace") |
| 1924 |
result.stdout.fnmatch_lines(["*1 failed*"]) |
| 1925 |
result.stdout.no_fnmatch_line("*SyntaxError*") |
| 1926 |
|
| 1927 |
|
| 1928 |
def test_traceback_failure(pytester: Pytester) -> None: |
| 1929 |
p1 = pytester.makepyfile( |
| 1930 |
""" |
| 1931 |
def g(): |
| 1932 |
return 2 |
| 1933 |
def f(x): |
| 1934 |
assert x == g() |
| 1935 |
def test_onefails(): |
| 1936 |
f(3) |
| 1937 |
""" |
| 1938 |
) |
| 1939 |
result = pytester.runpytest(p1, "--tb=long") |
| 1940 |
result.stdout.fnmatch_lines( |
| 1941 |
[ |
| 1942 |
"*test_traceback_failure.py F*", |
| 1943 |
"====* FAILURES *====", |
| 1944 |
"____*____", |
| 1945 |
"", |
| 1946 |
" def test_onefails():", |
| 1947 |
"> f(3)", |
| 1948 |
"", |
| 1949 |
"*test_*.py:6: ", |
| 1950 |
"_ _ _ *", |
| 1951 |
# "", |
| 1952 |
" def f(x):", |
| 1953 |
"> assert x == g()", |
| 1954 |
"E assert 3 == 2", |
| 1955 |
"E + where 2 = g()", |
| 1956 |
"", |
| 1957 |
"*test_traceback_failure.py:4: AssertionError", |
| 1958 |
] |
| 1959 |
) |
| 1960 |
|
| 1961 |
result = pytester.runpytest(p1) # "auto" |
| 1962 |
result.stdout.fnmatch_lines( |
| 1963 |
[ |
| 1964 |
"*test_traceback_failure.py F*", |
| 1965 |
"====* FAILURES *====", |
| 1966 |
"____*____", |
| 1967 |
"", |
| 1968 |
" def test_onefails():", |
| 1969 |
"> f(3)", |
| 1970 |
"", |
| 1971 |
"*test_*.py:6: ", |
| 1972 |
"", |
| 1973 |
" def f(x):", |
| 1974 |
"> assert x == g()", |
| 1975 |
"E assert 3 == 2", |
| 1976 |
"E + where 2 = g()", |
| 1977 |
"", |
| 1978 |
"*test_traceback_failure.py:4: AssertionError", |
| 1979 |
] |
| 1980 |
) |
| 1981 |
|
| 1982 |
|
| 1983 |
def test_exception_handling_no_traceback(pytester: Pytester) -> None: |
| 1984 |
"""Handle chain exceptions in tasks submitted by the multiprocess module (#1984).""" |
| 1985 |
p1 = pytester.makepyfile( |
| 1986 |
""" |
| 1987 |
from multiprocessing import Pool |
| 1988 |
|
| 1989 |
def process_task(n): |
| 1990 |
assert n == 10 |
| 1991 |
|
| 1992 |
def multitask_job(): |
| 1993 |
tasks = [1] |
| 1994 |
with Pool(processes=1) as pool: |
| 1995 |
pool.map(process_task, tasks) |
| 1996 |
|
| 1997 |
def test_multitask_job(): |
| 1998 |
multitask_job() |
| 1999 |
""" |
| 2000 |
) |
| 2001 |
pytester.syspathinsert() |
| 2002 |
result = pytester.runpytest(p1, "--tb=long") |
| 2003 |
result.stdout.fnmatch_lines( |
| 2004 |
[ |
| 2005 |
"====* FAILURES *====", |
| 2006 |
"*multiprocessing.pool.RemoteTraceback:*", |
| 2007 |
"Traceback (most recent call last):", |
| 2008 |
"*assert n == 10", |
| 2009 |
"The above exception was the direct cause of the following exception:", |
| 2010 |
"> * multitask_job()", |
| 2011 |
] |
| 2012 |
) |
| 2013 |
|
| 2014 |
|
| 2015 |
@pytest.mark.skipif("'__pypy__' in sys.builtin_module_names") |
| 2016 |
@pytest.mark.parametrize( |
| 2017 |
"cmdline_args, warning_output", |
| 2018 |
[ |
| 2019 |
( |
| 2020 |
["-OO", "-m", "pytest", "-h"], |
| 2021 |
["warning :*PytestConfigWarning:*assert statements are not executed*"], |
| 2022 |
), |
| 2023 |
( |
| 2024 |
["-OO", "-m", "pytest"], |
| 2025 |
[ |
| 2026 |
"=*= warnings summary =*=", |
| 2027 |
"*PytestConfigWarning:*assert statements are not executed*", |
| 2028 |
], |
| 2029 |
), |
| 2030 |
( |
| 2031 |
["-OO", "-m", "pytest", "--assert=plain"], |
| 2032 |
[ |
| 2033 |
"=*= warnings summary =*=", |
| 2034 |
"*PytestConfigWarning: ASSERTIONS ARE NOT EXECUTED and FAILING TESTS WILL PASS. " |
| 2035 |
"Are you using python -O?", |
| 2036 |
], |
| 2037 |
), |
| 2038 |
], |
| 2039 |
) |
| 2040 |
def test_warn_missing(pytester: Pytester, cmdline_args, warning_output) -> None: |
| 2041 |
pytester.makepyfile("") |
| 2042 |
|
| 2043 |
result = pytester.run(sys.executable, *cmdline_args) |
| 2044 |
result.stdout.fnmatch_lines(warning_output) |
| 2045 |
|
| 2046 |
|
| 2047 |
def test_recursion_source_decode(pytester: Pytester) -> None: |
| 2048 |
pytester.makepyfile( |
| 2049 |
""" |
| 2050 |
def test_something(): |
| 2051 |
pass |
| 2052 |
""" |
| 2053 |
) |
| 2054 |
pytester.makeini( |
| 2055 |
""" |
| 2056 |
[pytest] |
| 2057 |
python_files = *.py |
| 2058 |
""" |
| 2059 |
) |
| 2060 |
result = pytester.runpytest("--collect-only") |
| 2061 |
result.stdout.fnmatch_lines( |
| 2062 |
[ |
| 2063 |
" <Module*>", |
| 2064 |
] |
| 2065 |
) |
| 2066 |
|
| 2067 |
|
| 2068 |
def test_AssertionError_message(pytester: Pytester) -> None: |
| 2069 |
pytester.makepyfile( |
| 2070 |
""" |
| 2071 |
def test_hello(): |
| 2072 |
x,y = 1,2 |
| 2073 |
assert 0, (x,y) |
| 2074 |
""" |
| 2075 |
) |
| 2076 |
result = pytester.runpytest() |
| 2077 |
result.stdout.fnmatch_lines( |
| 2078 |
""" |
| 2079 |
*def test_hello* |
| 2080 |
*assert 0, (x,y)* |
| 2081 |
*AssertionError: (1, 2)* |
| 2082 |
""" |
| 2083 |
) |
| 2084 |
|
| 2085 |
|
| 2086 |
def test_diff_newline_at_end(pytester: Pytester) -> None: |
| 2087 |
pytester.makepyfile( |
| 2088 |
r""" |
| 2089 |
def test_diff(): |
| 2090 |
assert 'asdf' == 'asdf\n' |
| 2091 |
""" |
| 2092 |
) |
| 2093 |
|
| 2094 |
result = pytester.runpytest() |
| 2095 |
result.stdout.fnmatch_lines( |
| 2096 |
r""" |
| 2097 |
*assert 'asdf' == 'asdf\n' |
| 2098 |
* - asdf |
| 2099 |
* ? - |
| 2100 |
* + asdf |
| 2101 |
""" |
| 2102 |
) |
| 2103 |
|
| 2104 |
|
| 2105 |
@pytest.mark.filterwarnings("default") |
| 2106 |
def test_assert_tuple_warning(pytester: Pytester) -> None: |
| 2107 |
msg = "assertion is always true" |
| 2108 |
pytester.makepyfile( |
| 2109 |
""" |
| 2110 |
def test_tuple(): |
| 2111 |
assert(False, 'you shall not pass') |
| 2112 |
""" |
| 2113 |
) |
| 2114 |
result = pytester.runpytest() |
| 2115 |
result.stdout.fnmatch_lines([f"*test_assert_tuple_warning.py:2:*{msg}*"]) |
| 2116 |
|
| 2117 |
# tuples with size != 2 should not trigger the warning |
| 2118 |
pytester.makepyfile( |
| 2119 |
""" |
| 2120 |
def test_tuple(): |
| 2121 |
assert () |
| 2122 |
""" |
| 2123 |
) |
| 2124 |
result = pytester.runpytest() |
| 2125 |
assert msg not in result.stdout.str() |
| 2126 |
|
| 2127 |
|
| 2128 |
def test_assert_indirect_tuple_no_warning(pytester: Pytester) -> None: |
| 2129 |
pytester.makepyfile( |
| 2130 |
""" |
| 2131 |
def test_tuple(): |
| 2132 |
tpl = ('foo', 'bar') |
| 2133 |
assert tpl |
| 2134 |
""" |
| 2135 |
) |
| 2136 |
result = pytester.runpytest() |
| 2137 |
output = "\n".join(result.stdout.lines) |
| 2138 |
assert "WR1" not in output |
| 2139 |
|
| 2140 |
|
| 2141 |
def test_assert_with_unicode(pytester: Pytester) -> None: |
| 2142 |
pytester.makepyfile( |
| 2143 |
"""\ |
| 2144 |
def test_unicode(): |
| 2145 |
assert '유니코드' == 'Unicode' |
| 2146 |
""" |
| 2147 |
) |
| 2148 |
result = pytester.runpytest() |
| 2149 |
result.stdout.fnmatch_lines(["*AssertionError*"]) |
| 2150 |
|
| 2151 |
|
| 2152 |
def test_raise_unprintable_assertion_error(pytester: Pytester) -> None: |
| 2153 |
pytester.makepyfile( |
| 2154 |
r""" |
| 2155 |
def test_raise_assertion_error(): |
| 2156 |
raise AssertionError('\xff') |
| 2157 |
""" |
| 2158 |
) |
| 2159 |
result = pytester.runpytest() |
| 2160 |
result.stdout.fnmatch_lines( |
| 2161 |
[r"> raise AssertionError('\xff')", "E AssertionError: *"] |
| 2162 |
) |
| 2163 |
|
| 2164 |
|
| 2165 |
def test_raise_assertion_error_raising_repr(pytester: Pytester) -> None: |
| 2166 |
pytester.makepyfile( |
| 2167 |
""" |
| 2168 |
class RaisingRepr(object): |
| 2169 |
def __repr__(self): |
| 2170 |
raise Exception() |
| 2171 |
def test_raising_repr(): |
| 2172 |
raise AssertionError(RaisingRepr()) |
| 2173 |
""" |
| 2174 |
) |
| 2175 |
result = pytester.runpytest() |
| 2176 |
result.stdout.fnmatch_lines(["E AssertionError: <exception str() failed>"]) |
| 2177 |
|
| 2178 |
|
| 2179 |
def test_issue_1944(pytester: Pytester) -> None: |
| 2180 |
pytester.makepyfile( |
| 2181 |
""" |
| 2182 |
def f(): |
| 2183 |
return |
| 2184 |
|
| 2185 |
assert f() == 10 |
| 2186 |
""" |
| 2187 |
) |
| 2188 |
result = pytester.runpytest() |
| 2189 |
result.stdout.fnmatch_lines(["*1 error*"]) |
| 2190 |
assert ( |
| 2191 |
"AttributeError: 'Module' object has no attribute '_obj'" |
| 2192 |
not in result.stdout.str() |
| 2193 |
) |
| 2194 |
|
| 2195 |
|
| 2196 |
def test_exit_from_assertrepr_compare(monkeypatch) -> None: |
| 2197 |
from _pytest.assertion import _compare_any |
| 2198 |
|
| 2199 |
def raise_exit(obj): |
| 2200 |
outcomes.exit("Quitting debugger") |
| 2201 |
|
| 2202 |
monkeypatch.setattr(_compare_any, "istext", raise_exit) |
| 2203 |
|
| 2204 |
with pytest.raises(outcomes.Exit, match="Quitting debugger"): |
| 2205 |
callequal(1, 1) |
| 2206 |
|
| 2207 |
|
| 2208 |
def test_assertion_location_with_coverage(pytester: Pytester) -> None: |
| 2209 |
"""This used to report the wrong location when run with coverage (#5754).""" |
| 2210 |
p = pytester.makepyfile( |
| 2211 |
""" |
| 2212 |
def test(): |
| 2213 |
assert False, 1 |
| 2214 |
assert False, 2 |
| 2215 |
""" |
| 2216 |
) |
| 2217 |
result = pytester.runpytest(str(p)) |
| 2218 |
result.stdout.fnmatch_lines( |
| 2219 |
[ |
| 2220 |
"> assert False, 1", |
| 2221 |
"E AssertionError: 1", |
| 2222 |
"E assert False", |
| 2223 |
"*= 1 failed in*", |
| 2224 |
] |
| 2225 |
) |
| 2226 |
|
| 2227 |
|
| 2228 |
def test_reprcompare_verbose_long() -> None: |
| 2229 |
a = {f"v{i}": i for i in range(11)} |
| 2230 |
b = a.copy() |
| 2231 |
b["v2"] += 10 |
| 2232 |
lines = callop("==", a, b, verbose=2) |
| 2233 |
assert lines is not None |
| 2234 |
assert lines[0] == ( |
| 2235 |
"{'v0': 0, 'v1': 1, 'v2': 2, 'v3': 3, 'v4': 4, 'v5': 5, " |
| 2236 |
"'v6': 6, 'v7': 7, 'v8': 8, 'v9': 9, 'v10': 10}" |
| 2237 |
" == " |
| 2238 |
"{'v0': 0, 'v1': 1, 'v2': 12, 'v3': 3, 'v4': 4, 'v5': 5, " |
| 2239 |
"'v6': 6, 'v7': 7, 'v8': 8, 'v9': 9, 'v10': 10}" |
| 2240 |
) |
| 2241 |
|
| 2242 |
|
| 2243 |
@pytest.mark.parametrize("enable_colors", [True, False]) |
| 2244 |
@pytest.mark.parametrize( |
| 2245 |
("test_code", "expected_lines"), |
| 2246 |
( |
| 2247 |
( |
| 2248 |
""" |
| 2249 |
def test(): |
| 2250 |
assert [0, 1] == [0, 2] |
| 2251 |
""", |
| 2252 |
[ |
| 2253 |
"{bold}{red}E At index 1 diff: {reset}{number}1{hl-reset}{endline} != {reset}{number}2*", |
| 2254 |
"{bold}{red}E {light-red}- 2,{hl-reset}{endline}{reset}", |
| 2255 |
"{bold}{red}E {light-green}+ 1,{hl-reset}{endline}{reset}", |
| 2256 |
], |
| 2257 |
), |
| 2258 |
( |
| 2259 |
""" |
| 2260 |
def test(): |
| 2261 |
assert {f"number-is-{i}": i for i in range(1, 6)} == { |
| 2262 |
f"number-is-{i}": i for i in range(5) |
| 2263 |
} |
| 2264 |
""", |
| 2265 |
[ |
| 2266 |
"{bold}{red}E Common items:{reset}", |
| 2267 |
"{bold}{red}E {reset}{{{str}'{hl-reset}{str}number-is-1{hl-reset}{str}'{hl-reset}: {number}1*", |
| 2268 |
"{bold}{red}E Left contains 1 more item:{reset}", |
| 2269 |
"{bold}{red}E {reset}{{{str}'{hl-reset}{str}number-is-5{hl-reset}{str}'{hl-reset}: {number}5*", |
| 2270 |
"{bold}{red}E Right contains 1 more item:{reset}", |
| 2271 |
"{bold}{red}E {reset}{{{str}'{hl-reset}{str}number-is-0{hl-reset}{str}'{hl-reset}: {number}0*", |
| 2272 |
"{bold}{red}E {reset}{light-gray} {hl-reset} {{{endline}{reset}", |
| 2273 |
"{bold}{red}E {light-gray} {hl-reset} 'number-is-1': 1,{endline}{reset}", |
| 2274 |
"{bold}{red}E {light-green}+ 'number-is-5': 5,{hl-reset}{endline}{reset}", |
| 2275 |
], |
| 2276 |
), |
| 2277 |
( |
| 2278 |
""" |
| 2279 |
def test(): |
| 2280 |
assert "abcd" == "abce" |
| 2281 |
""", |
| 2282 |
[ |
| 2283 |
"{bold}{red}E {reset}{light-red}- abce{hl-reset}{endline}{reset}", |
| 2284 |
"{bold}{red}E {light-green}+ abcd{hl-reset}{endline}{reset}", |
| 2285 |
], |
| 2286 |
), |
| 2287 |
), |
| 2288 |
) |
| 2289 |
def test_comparisons_handle_colors( |
| 2290 |
pytester: Pytester, color_mapping, enable_colors, test_code, expected_lines |
| 2291 |
) -> None: |
| 2292 |
p = pytester.makepyfile(test_code) |
| 2293 |
result = pytester.runpytest( |
| 2294 |
f"--color={'yes' if enable_colors else 'no'}", "-vv", str(p) |
| 2295 |
) |
| 2296 |
formatter = ( |
| 2297 |
color_mapping.format_for_fnmatch |
| 2298 |
if enable_colors |
| 2299 |
else color_mapping.strip_colors |
| 2300 |
) |
| 2301 |
|
| 2302 |
result.stdout.fnmatch_lines(formatter(expected_lines), consecutive=False) |
| 2303 |
|
| 2304 |
|
| 2305 |
def test_fine_grained_assertion_verbosity(pytester: Pytester): |
| 2306 |
long_text = "Lorem ipsum dolor sit amet " * 10 |
| 2307 |
p = pytester.makepyfile( |
| 2308 |
f""" |
| 2309 |
def test_ok(): |
| 2310 |
pass |
| 2311 |
|
| 2312 |
|
| 2313 |
def test_words_fail(): |
| 2314 |
fruits1 = ["banana", "apple", "grapes", "melon", "kiwi"] |
| 2315 |
fruits2 = ["banana", "apple", "orange", "melon", "kiwi"] |
| 2316 |
assert fruits1 == fruits2 |
| 2317 |
|
| 2318 |
|
| 2319 |
def test_numbers_fail(): |
| 2320 |
number_to_text1 = {{str(x): x for x in range(5)}} |
| 2321 |
number_to_text2 = {{str(x * 10): x * 10 for x in range(5)}} |
| 2322 |
assert number_to_text1 == number_to_text2 |
| 2323 |
|
| 2324 |
|
| 2325 |
def test_long_text_fail(): |
| 2326 |
long_text = "{long_text}" |
| 2327 |
assert "hello world" in long_text |
| 2328 |
""" |
| 2329 |
) |
| 2330 |
pytester.makeini( |
| 2331 |
""" |
| 2332 |
[pytest] |
| 2333 |
verbosity_assertions = 2 |
| 2334 |
""" |
| 2335 |
) |
| 2336 |
result = pytester.runpytest(p) |
| 2337 |
|
| 2338 |
result.stdout.fnmatch_lines( |
| 2339 |
[ |
| 2340 |
f"{p.name} .FFF [100%]", |
| 2341 |
"E At index 2 diff: 'grapes' != 'orange'", |
| 2342 |
"E Full diff:", |
| 2343 |
"E [", |
| 2344 |
"E 'banana',", |
| 2345 |
"E 'apple',", |
| 2346 |
"E - 'orange',", |
| 2347 |
"E ? ^ ^^", |
| 2348 |
"E + 'grapes',", |
| 2349 |
"E ? ^ ^ +", |
| 2350 |
"E 'melon',", |
| 2351 |
"E 'kiwi',", |
| 2352 |
"E ]", |
| 2353 |
"E Full diff:", |
| 2354 |
"E {", |
| 2355 |
"E '0': 0,", |
| 2356 |
"E - '10': 10,", |
| 2357 |
"E ? - -", |
| 2358 |
"E + '1': 1,", |
| 2359 |
"E - '20': 20,", |
| 2360 |
"E ? - -", |
| 2361 |
"E + '2': 2,", |
| 2362 |
"E - '30': 30,", |
| 2363 |
"E ? - -", |
| 2364 |
"E + '3': 3,", |
| 2365 |
"E - '40': 40,", |
| 2366 |
"E ? - -", |
| 2367 |
"E + '4': 4,", |
| 2368 |
"E }", |
| 2369 |
f"E AssertionError: assert 'hello world' in '{long_text}'", |
| 2370 |
] |
| 2371 |
) |
| 2372 |
|
| 2373 |
|
| 2374 |
def test_assertion_text_diff_style_block_for_multiline_strings( |
| 2375 |
pytester: Pytester, |
| 2376 |
) -> None: |
| 2377 |
pytester.makepyfile( |
| 2378 |
r""" |
| 2379 |
actual = "alpha\n beta\n" |
| 2380 |
expected = "alpha\n beta" |
| 2381 |
|
| 2382 |
def test_text_diff(): |
| 2383 |
assert actual == expected |
| 2384 |
""" |
| 2385 |
) |
| 2386 |
pytester.makeini( |
| 2387 |
f""" |
| 2388 |
[pytest] |
| 2389 |
assertion_text_diff_style = {util.ASSERTION_TEXT_DIFF_STYLE_BLOCK} |
| 2390 |
""" |
| 2391 |
) |
| 2392 |
|
| 2393 |
result = pytester.runpytest("-vv") |
| 2394 |
|
| 2395 |
result.stdout.fnmatch_lines( |
| 2396 |
[ |
| 2397 |
"E Left:", |
| 2398 |
"E alpha", |
| 2399 |
"E beta", |
| 2400 |
"E ", |
| 2401 |
"E Right:", |
| 2402 |
"E alpha", |
| 2403 |
"E beta", |
| 2404 |
] |
| 2405 |
) |
| 2406 |
result.stdout.no_fnmatch_line("*? -*") |
| 2407 |
|
| 2408 |
|
| 2409 |
def test_assertion_text_diff_style_block_for_single_line_strings( |
| 2410 |
pytester: Pytester, |
| 2411 |
) -> None: |
| 2412 |
pytester.makepyfile( |
| 2413 |
""" |
| 2414 |
def test_text_diff(): |
| 2415 |
assert "spam" == "eggs" |
| 2416 |
""" |
| 2417 |
) |
| 2418 |
pytester.makeini( |
| 2419 |
f""" |
| 2420 |
[pytest] |
| 2421 |
assertion_text_diff_style = {util.ASSERTION_TEXT_DIFF_STYLE_BLOCK} |
| 2422 |
""" |
| 2423 |
) |
| 2424 |
|
| 2425 |
result = pytester.runpytest("-vv") |
| 2426 |
|
| 2427 |
result.stdout.fnmatch_lines( |
| 2428 |
[ |
| 2429 |
"E Left:", |
| 2430 |
"E spam", |
| 2431 |
"E Right:", |
| 2432 |
"E eggs", |
| 2433 |
] |
| 2434 |
) |
| 2435 |
result.stdout.no_fnmatch_line("*- eggs*") |
| 2436 |
|
| 2437 |
|
| 2438 |
def test_assertion_text_diff_style_invalid(pytester: Pytester) -> None: |
| 2439 |
pytester.makepyfile( |
| 2440 |
""" |
| 2441 |
def test_ok(): |
| 2442 |
pass |
| 2443 |
""" |
| 2444 |
) |
| 2445 |
pytester.makeini( |
| 2446 |
""" |
| 2447 |
[pytest] |
| 2448 |
assertion_text_diff_style = side-by-side |
| 2449 |
""" |
| 2450 |
) |
| 2451 |
|
| 2452 |
result = pytester.runpytest() |
| 2453 |
|
| 2454 |
assert result.ret == pytest.ExitCode.USAGE_ERROR |
| 2455 |
result.stderr.fnmatch_lines( |
| 2456 |
[ |
| 2457 |
"*ERROR: assertion_text_diff_style must be one of 'ndiff', 'block'; got 'side-by-side'" |
| 2458 |
] |
| 2459 |
) |
| 2460 |
|
| 2461 |
|
| 2462 |
def test_full_output_vvv(pytester: Pytester) -> None: |
| 2463 |
pytester.makepyfile( |
| 2464 |
r""" |
| 2465 |
def crash_helper(m): |
| 2466 |
assert 1 == 2 |
| 2467 |
def test_vvv(): |
| 2468 |
crash_helper(500 * "a") |
| 2469 |
""" |
| 2470 |
) |
| 2471 |
result = pytester.runpytest("") |
| 2472 |
# without -vvv, the passed args are truncated |
| 2473 |
expected_non_vvv_arg_line = "m = 'aaaaaaaaaaaaaaa*..aaaaaaaaaaaa*" |
| 2474 |
result.stdout.fnmatch_lines( |
| 2475 |
[ |
| 2476 |
expected_non_vvv_arg_line, |
| 2477 |
"test_full_output_vvv.py:2: AssertionError", |
| 2478 |
], |
| 2479 |
) |
| 2480 |
# double check that the untruncated part is not in the output |
| 2481 |
expected_vvv_arg_line = "m = '{}'".format(500 * "a") |
| 2482 |
result.stdout.no_fnmatch_line(expected_vvv_arg_line) |
| 2483 |
|
| 2484 |
# but with "-vvv" the args are not truncated |
| 2485 |
result = pytester.runpytest("-vvv") |
| 2486 |
result.stdout.fnmatch_lines( |
| 2487 |
[ |
| 2488 |
expected_vvv_arg_line, |
| 2489 |
"test_full_output_vvv.py:2: AssertionError", |
| 2490 |
] |
| 2491 |
) |
| 2492 |
result.stdout.no_fnmatch_line(expected_non_vvv_arg_line) |
| 2493 |
|
| 2494 |
|
| 2495 |
def test_dict_extra_items_preserve_insertion_order(pytester: Pytester) -> None: |
| 2496 |
"""Assertion output of dict diff shows keys in insertion order (#13503).""" |
| 2497 |
pytester.makepyfile( |
| 2498 |
test_order=""" |
| 2499 |
def test_order(): |
| 2500 |
a = { |
| 2501 |
"b": 2, |
| 2502 |
"a": 1, |
| 2503 |
"d": 4, |
| 2504 |
"e": 5, |
| 2505 |
"c": 3, |
| 2506 |
} |
| 2507 |
assert a == {} |
| 2508 |
""" |
| 2509 |
) |
| 2510 |
|
| 2511 |
result = pytester.runpytest("-vv") |
| 2512 |
result.stdout.fnmatch_lines( |
| 2513 |
[ |
| 2514 |
"*Left contains 5 more items:*", |
| 2515 |
"*Full diff:", |
| 2516 |
"* + *'b': 2,", |
| 2517 |
"* + *'a': 1,", |
| 2518 |
"* + *'d': 4,", |
| 2519 |
"* + *'e': 5,", |
| 2520 |
"* + *'c': 3,", |
| 2521 |
"test_order.py:*: AssertionError", |
| 2522 |
] |
| 2523 |
) |