Skip to content

Commit 8cb1c87

Browse files
authored
assertion: _notin_text: handle non-printable characters (#239)
Ref: pytest-dev#6702
1 parent 0de3525 commit 8cb1c87

File tree

2 files changed

+30
-10
lines changed

2 files changed

+30
-10
lines changed

src/_pytest/assertion/util.py

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -498,21 +498,31 @@ def _compare_eq_cls(
498498

499499

500500
def _notin_text(term: str, text: str, verbose: int = 0) -> List[str]:
501+
from wcwidth import wcwidth
502+
501503
index = text.find(term)
502504
head = text[:index]
503505
tail = text[index + len(term) :]
504506
correct_text = head + tail
505-
diff = _diff_text(correct_text, text, verbose)
507+
506508
newdiff = ["%s is contained here:" % saferepr(term, maxsize=42)]
507-
for line in diff:
508-
if line.startswith("Skipping"):
509-
continue
510-
if line.startswith("- "):
511-
continue
512-
if line.startswith("+ "):
513-
newdiff.append(" " + line[2:])
514-
else:
515-
newdiff.append(line)
509+
if any(
510+
wcwidth(ch) <= 0
511+
for ch in [ch for lines in [term, correct_text] for ch in lines]
512+
):
513+
newdiff = [
514+
"NOTE: Strings contain non-printable characters. Escaping them using repr()."
515+
] + newdiff
516+
text = repr(text)
517+
indent = " " * (index + 1)
518+
marker = "+" * (len(repr(term)) - 2)
519+
else:
520+
indent = " " * index
521+
marker = "+" * len(term)
522+
newdiff += [
523+
" " + text,
524+
"? " + indent + marker,
525+
]
516526
return newdiff
517527

518528

testing/test_assertion.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1200,6 +1200,16 @@ def test_reprcompare_notin() -> None:
12001200
]
12011201

12021202

1203+
def test_reprcompare_notin_newline() -> None:
1204+
assert callop("not in", "foo\n", "aaafoo\nbbb") == [
1205+
r"'foo\n' not in 'aaafoo\nbbb'",
1206+
r"NOTE: Strings contain non-printable characters. Escaping them using repr().",
1207+
r"'foo\n' is contained here:",
1208+
r" 'aaafoo\nbbb'",
1209+
r"? +++++",
1210+
]
1211+
1212+
12031213
def test_reprcompare_whitespaces():
12041214
config = mock_config()
12051215
detail = plugin.pytest_assertrepr_compare(config, "==", "\r\n", "\n")

0 commit comments

Comments
 (0)