Skip to content

Commit

Permalink
Merge pull request #3764 from asottile/fix_3763
Browse files Browse the repository at this point in the history
Fix `TypeError` when the assertion message is `bytes` in python 3.
  • Loading branch information
RonnyPfannschmidt committed Aug 2, 2018
2 parents 33769d0 + 452e5c1 commit 7e92930
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 14 deletions.
1 change: 1 addition & 0 deletions changelog/3763.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix ``TypeError`` when the assertion message is ``bytes`` in python 3.
26 changes: 12 additions & 14 deletions src/_pytest/assertion/rewrite.py
Original file line number Diff line number Diff line change
Expand Up @@ -425,20 +425,18 @@ def _format_assertmsg(obj):
# contains a newline it gets escaped, however if an object has a
# .__repr__() which contains newlines it does not get escaped.
# However in either case we want to preserve the newline.
if isinstance(obj, six.text_type) or isinstance(obj, six.binary_type):
s = obj
is_repr = False
else:
s = py.io.saferepr(obj)
is_repr = True
if isinstance(s, six.text_type):
t = six.text_type
else:
t = six.binary_type
s = s.replace(t("\n"), t("\n~")).replace(t("%"), t("%%"))
if is_repr:
s = s.replace(t("\\n"), t("\n~"))
return s
replaces = [(u"\n", u"\n~"), (u"%", u"%%")]
if not isinstance(obj, six.string_types):
obj = py.io.saferepr(obj)
replaces.append((u"\\n", u"\n~"))

if isinstance(obj, bytes):
replaces = [(r1.encode(), r2.encode()) for r1, r2 in replaces]

for r1, r2 in replaces:
obj = obj.replace(r1, r2)

return obj


def _should_repr_global_name(obj):
Expand Down
9 changes: 9 additions & 0 deletions testing/test_assertrewrite.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,15 @@ def test_foo():
["*AssertionError: To be escaped: %", "*assert 1 == 2"]
)

@pytest.mark.skipif(
sys.version_info < (3,), reason="bytes is a string type in python 2"
)
def test_assertion_messages_bytes(self, testdir):
testdir.makepyfile("def test_bytes_assertion():\n assert False, b'ohai!'\n")
result = testdir.runpytest()
assert result.ret == 1
result.stdout.fnmatch_lines(["*AssertionError: b'ohai!'", "*assert False"])

def test_boolop(self):
def f():
f = g = False
Expand Down

0 comments on commit 7e92930

Please sign in to comment.