Skip to content

Allow CheckContextManager to catch any exception #198

@JWCS

Description

@JWCS

Perhaps this is not the intended behavior, but I was surprised. My usecase was the following:

def test_xfail(check):
    # if any of the left hand side don't exist, IndexError or AttributeError or KeyError
    lst = []
    with check:
        assert lst[-1] == "Expected Value" # IndexError
    dct = {}
    with check:
        assert dct["k"] == "v" # KeyError
    o = object
    with check:
         assert o.v == "obj" # AttributeError
    with check:
        Path("./outputfile").resolve(strict=True) # Check for existence / resolvability; raises OSError / FileNotFoundError
    assert False, "expect to get here"

Expected all the check failures, and then the explicit assert False. Instead fails at each exception.
Expected that when check was used as a context manager, it would treat exceptions of any kind as failures.

The alternative involves re-writing, and is clunky for deeply nested access... so this is the cleanest solution I'm currently hacking:

# with check:
#     assert a.b.c[query].value == "ExpectedValue"
# No check helpers for "b" in a and "c" in a.b ...
# I have a lot of these deeply nested object/queries, and when things are working correctly, they exist; when they're not...

import traceback

def test_nofail(check):
    try:
        with check:
            assert 0 == 1 # This gets caught by the except check.fail below, not the check context manager
    except:
        check.fail(traceback.format_exc())
    lst = []
    # with check: assert ...
    try:
        assert lst[-1] == "Expected Value"
    except:
        check.fail(traceback.format_exc())
    dct = {}
    # with check: assert ...
    try:
        assert dct["k"] == "v"
    except:
        check.fail(traceback.format_exc())
    o = object
    # with check: assert ...
    try:
        assert o.v == "obj"
    except:
        check.fail(traceback.format_exc())
    # with check:
    try:
        Path("./notexist").resolve(strict=True)
    except:
        check.fail(traceback.format_exc())
    assert False, "get here"

Is there a cleaner idiom for this sort of problem?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions