From 7f554f50e317c23430ecf10227f888000f7dfb43 Mon Sep 17 00:00:00 2001 From: Floris Bruynooghe Date: Thu, 30 Apr 2015 02:31:12 +0100 Subject: [PATCH] Fix collapse false to look at unescaped braces only Sometimes the repr of an object can contain the "\n{" sequence which is used as a formatting language, so they are escaped to "\\n{". But the collapse-false code needs to look for the real "\n{" token instead of simply "{" as otherwise it may get unbalanced braces from the object's repr (sometimes caused by the collapsing of long reprs by saferepr). Fixes issue #731. --HG-- branch : pytest-2.7 --- CHANGELOG | 4 ++++ _pytest/assertion/util.py | 6 ++++-- testing/test_assertrewrite.py | 21 +++++++++++++++++++++ 3 files changed, 29 insertions(+), 2 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 4ffce2dcd..87800c9c9 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,6 +1,10 @@ 2.7.1.dev (compared to 2.7.0) ----------------------------- +- fix issue731: do not get confused by the braces which may be present + and unbalanced in an object's repr while collapsing False + explanations. Thanks Carl Meyer for the report and test case. + - fix issue553: properly handling inspect.getsourcelines failures in FixtureLookupError which would lead to to an internal error, obfuscating the original problem. Thanks talljosh for initial diff --git a/_pytest/assertion/util.py b/_pytest/assertion/util.py index 69d5d8b1a..07389e781 100644 --- a/_pytest/assertion/util.py +++ b/_pytest/assertion/util.py @@ -45,13 +45,15 @@ def _collapse_false(explanation): if where == -1: break level = 0 + prev_c = explanation[start] for i, c in enumerate(explanation[start:]): - if c == "{": + if prev_c + c == "\n{": level += 1 - elif c == "}": + elif prev_c + c == "\n}": level -= 1 if not level: break + prev_c = c else: raise AssertionError("unbalanced braces: %r" % (explanation,)) end = start + i diff --git a/testing/test_assertrewrite.py b/testing/test_assertrewrite.py index 820fcabff..5ea2f2bf8 100644 --- a/testing/test_assertrewrite.py +++ b/testing/test_assertrewrite.py @@ -665,3 +665,24 @@ class TestAssertionRewriteHookDetails(object): result.stdout.fnmatch_lines([ "* 1 passed*", ]) + + +def test_issue731(testdir): + testdir.makepyfile(""" + class LongReprWithBraces(object): + def __repr__(self): + return 'LongReprWithBraces({' + ('a' * 80) + '}' + ('a' * 120) + ')' + + def some_method(self): + return False + + def test_long_repr(): + obj = LongReprWithBraces() + assert obj.some_method() + """) + result = testdir.runpytest() + assert 'unbalanced braces' not in result.stdout.str() + + +def test_collapse_false_unbalanced_braces(): + util._collapse_false('some text{ False\n{False = some more text\n}')