Skip to content

Attribute error in TestCaseFunction.teardown when exception encountered before TestCaseFunction.setup is run. #3788

@westhomas

Description

@westhomas

The sample code below raises an exception in a unittest.TestCase class in the __init__ method. This will produce an exception in TestCaseFunction.teardown() because self._testcase isn't defined, but teardown() attempts to call it here:

self._testcase.teardown_method(self._obj)

# cat test_setup_exception.py
import unittest
import pytest


class MuhUnitTests(unittest.TestCase):

    def __init__(self):
        raise Exception("testing123")

    def test_passing(self):
        assert True


# Execute Tests
def main():
    pytest.main(['test_setup_exception.py', '-s'])


if __name__ == '__main__':
    main()
self = <TestCaseFunction 'test_passing'>

    def teardown(self):
>       if hasattr(self._testcase, "teardown_method"):
E       AttributeError: 'TestCaseFunction' object has no attribute '_testcase'

../python3.6/site-packages/_pytest/unittest.py:96: AttributeError

Adding a check in teardown for existence of _testcase solves the issue and allows the exception to bubble correctly:

    def teardown(self):
        if hasattr(self, "_testcase") and hasattr(self._testcase, "teardown_method"):
            self._testcase.teardown_method(self._obj)
        # Allow garbage collection on TestCase instance attributes.
        self._testcase = None
        self._obj = None

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions