pytest icon indicating copy to clipboard operation
pytest copied to clipboard

``ExceptionInfo.for_later()`` wont add assertion strip text

Open picnixz opened this issue 10 months ago • 3 comments

Using exc_info.exconly(tryshort=True) is meant to remove AssertionError: from the exception message according to (ref)

When 'tryshort' resolves to True, and the exception is an AssertionError, only the actual exception part of the exception representation is returned (so 'AssertionError: ' is removed from the beginning).

However, this is not the case. In addition, the tests do not assert this behaviour:

https://github.com/pytest-dev/pytest/blob/44895289c725ed922889c882b7f1b78b741eba20/testing/code/test_excinfo.py#L332-L339

MWE

cat <<-EOF > excinfo_exconly.py
import pytest

def test():
    with pytest.raises(AssertionError) as exc_info:
        raise AssertionError('message')

    assert exc_info.exconly(tryshort=True) == 'message'
EOF
pytest excinfo_exconly.py

Environment

Platform:              linux; (Linux-5.14.21-150500.55.52-default-x86_64-with-glibc2.31)
Python version:        3.10.13 (main, Sep 05 2023, 11:46:10) [GCC])
Python implementation: CPython
Pytest version:		   8.0.2

picnixz avatar Apr 01 '24 10:04 picnixz

https://github.com/pytest-dev/pytest/blob/44895289c725ed922889c882b7f1b78b741eba20/src/_pytest/_code/code.py#L503 seems to fill the strip text incorrectly in this case

RonnyPfannschmidt avatar Apr 02 '24 06:04 RonnyPfannschmidt

the root cause is the for_later helper for making a instance before the exception

we never fill in the strip text for that case

if you create a new exception info object from the value of the one captured the new instance would behave correct

RonnyPfannschmidt avatar Apr 02 '24 06:04 RonnyPfannschmidt

By the way, here is the current workaround I am using in Sphinx (probably imperfect but suitable for my needs):

def parse_excinfo(excinfo: ExceptionInfo[AssertionError]) -> str:
    assert excinfo.type is AssertionError
    assert excinfo.value is not None
    return str(excinfo.value).removeprefix('AssertionError: ')

picnixz avatar Apr 04 '24 08:04 picnixz