New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
westhomas opened this Issue Aug 7, 2018 · 8 comments

Comments

Projects
None yet
5 participants
@westhomas
Contributor

westhomas commented Aug 7, 2018

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
@asottile

This comment has been minimized.

Show comment
Hide comment
@asottile

asottile Aug 7, 2018

Member

@westhomas looks good -- want to submit a patch for this? 🎉

Member

asottile commented Aug 7, 2018

@westhomas looks good -- want to submit a patch for this? 🎉

@westhomas

This comment has been minimized.

Show comment
Hide comment
@westhomas

westhomas Aug 8, 2018

Contributor

Submitted: #3792

I didn't add any unit tests, but would be happy to if someone wants to give me a little direction into exactly where/how to add one.

Contributor

westhomas commented Aug 8, 2018

Submitted: #3792

I didn't add any unit tests, but would be happy to if someone wants to give me a little direction into exactly where/how to add one.

@RonnyPfannschmidt

This comment has been minimized.

Show comment
Hide comment
@RonnyPfannschmidt

RonnyPfannschmidt Aug 8, 2018

Member

i believe we should instead ensure that a unittestcase never is in a state where that attribute is missing

Member

RonnyPfannschmidt commented Aug 8, 2018

i believe we should instead ensure that a unittestcase never is in a state where that attribute is missing

@westhomas

This comment has been minimized.

Show comment
Hide comment
@westhomas

westhomas Aug 8, 2018

Contributor

You'd have to at least move self._testcase = self.parent.obj(self.name) from the setup() method into the __init__() method.

But I'm not sure of the impact of that change or whether more of the setup() method should be moved as well. That's above my pay grade ;-)

Contributor

westhomas commented Aug 8, 2018

You'd have to at least move self._testcase = self.parent.obj(self.name) from the setup() method into the __init__() method.

But I'm not sure of the impact of that change or whether more of the setup() method should be moved as well. That's above my pay grade ;-)

@RonnyPfannschmidt

This comment has been minimized.

Show comment
Hide comment
@RonnyPfannschmidt

RonnyPfannschmidt Aug 8, 2018

Member

@westhomas existence of the attribute doesnt imply the actual value - if its set toNoneininit` it should be fine

i believe even a hack like setting it on the actual class as class level attribute would suffice

Member

RonnyPfannschmidt commented Aug 8, 2018

@westhomas existence of the attribute doesnt imply the actual value - if its set toNoneininit` it should be fine

i believe even a hack like setting it on the actual class as class level attribute would suffice

@westhomas

This comment has been minimized.

Show comment
Hide comment
@bindupatnaik

This comment has been minimized.

Show comment
Hide comment
@bindupatnaik

bindupatnaik Aug 16, 2018

I have same issue when i am trying to use init method in pytest class. I tried to un-install and install the pytest to get the latest code fix of the bug. But unfortunately i am not seeing above code fix in my local .
I am using
PS C:\Test\Win10DA> pytest --version
This is pytest version 3.7.1, imported from c:\program files (x86)\python36-32\lib\site-packages\pytest.py

Can anyone guide me how to overcome the problem?
my code looks like below


import unittest
from com.xxx.Main import Main
class GUI_tests(unittest.TestCase):

def __init__(self):
        self.main = Main()
        self.logger = logging

    def setUp(self):
        pass
        
    def tearDown(self):
        pass
    
    def test_1(self):
          assert True
        
    def test_2(self):
          assert True

Not sure if i have done something wrong. @westhomas @RonnyPfannschmidt @nicoddemus pls guide. is there any workaround as it is blocker for me now?

bindupatnaik commented Aug 16, 2018

I have same issue when i am trying to use init method in pytest class. I tried to un-install and install the pytest to get the latest code fix of the bug. But unfortunately i am not seeing above code fix in my local .
I am using
PS C:\Test\Win10DA> pytest --version
This is pytest version 3.7.1, imported from c:\program files (x86)\python36-32\lib\site-packages\pytest.py

Can anyone guide me how to overcome the problem?
my code looks like below


import unittest
from com.xxx.Main import Main
class GUI_tests(unittest.TestCase):

def __init__(self):
        self.main = Main()
        self.logger = logging

    def setUp(self):
        pass
        
    def tearDown(self):
        pass
    
    def test_1(self):
          assert True
        
    def test_2(self):
          assert True

Not sure if i have done something wrong. @westhomas @RonnyPfannschmidt @nicoddemus pls guide. is there any workaround as it is blocker for me now?

@asottile

This comment has been minimized.

Show comment
Hide comment
@asottile

asottile Aug 16, 2018

Member

Please open a new issue with a stack trace, I suspect this is a different issue (maybe not calling super?)

Member

asottile commented Aug 16, 2018

Please open a new issue with a stack trace, I suspect this is a different issue (maybe not calling super?)

sfdye added a commit to pydanny/cookiecutter-django that referenced this issue Aug 19, 2018

Update pytest to 3.7.2 (#1755)
This PR updates [pytest](https://pypi.org/project/pytest) from **3.7.1** to **3.7.2**.



<details>
  <summary>Changelog</summary>
  
  
   ### 3.7.2
   ```
   =========================

Bug Fixes
---------

- `3671 &lt;https://github.com/pytest-dev/pytest/issues/3671&gt;`_: Fix ``filterwarnings`` not being registered as a builtin mark.


- `3768 &lt;https://github.com/pytest-dev/pytest/issues/3768&gt;`_, `3789 &lt;https://github.com/pytest-dev/pytest/issues/3789&gt;`_: Fix test collection from packages mixed with normal directories.


- `3771 &lt;https://github.com/pytest-dev/pytest/issues/3771&gt;`_: Fix infinite recursion during collection if a ``pytest_ignore_collect`` hook returns ``False`` instead of ``None``.


- `3774 &lt;https://github.com/pytest-dev/pytest/issues/3774&gt;`_: Fix bug where decorated fixtures would lose functionality (for example ``mock.patch``).


- `3775 &lt;https://github.com/pytest-dev/pytest/issues/3775&gt;`_: Fix bug where importing modules or other objects with prefix ``pytest_`` prefix would raise a ``PluginValidationError``.


- `3788 &lt;https://github.com/pytest-dev/pytest/issues/3788&gt;`_: Fix ``AttributeError`` during teardown of ``TestCase`` subclasses which raise an exception during ``__init__``.


- `3804 &lt;https://github.com/pytest-dev/pytest/issues/3804&gt;`_: Fix traceback reporting for exceptions with ``__cause__`` cycles.



Improved Documentation
----------------------

- `3746 &lt;https://github.com/pytest-dev/pytest/issues/3746&gt;`_: Add documentation for ``metafunc.config`` that had been mistakenly hidden.
   ```
   
  
</details>


 

<details>
  <summary>Links</summary>
  
  - PyPI: https://pypi.org/project/pytest
  - Changelog: https://pyup.io/changelogs/pytest/
  - Homepage: http://pytest.org
</details>

cmccandless added a commit to cmccandless/tools that referenced this issue Aug 20, 2018

Update pytest to 3.7.2 (#25)
This PR updates [pytest](https://pypi.org/project/pytest) from **3.7.1** to **3.7.2**.



<details>
  <summary>Changelog</summary>
  
  
   ### 3.7.2
   ```
   =========================

Bug Fixes
---------

- `3671 &lt;https://github.com/pytest-dev/pytest/issues/3671&gt;`_: Fix ``filterwarnings`` not being registered as a builtin mark.


- `3768 &lt;https://github.com/pytest-dev/pytest/issues/3768&gt;`_, `3789 &lt;https://github.com/pytest-dev/pytest/issues/3789&gt;`_: Fix test collection from packages mixed with normal directories.


- `3771 &lt;https://github.com/pytest-dev/pytest/issues/3771&gt;`_: Fix infinite recursion during collection if a ``pytest_ignore_collect`` hook returns ``False`` instead of ``None``.


- `3774 &lt;https://github.com/pytest-dev/pytest/issues/3774&gt;`_: Fix bug where decorated fixtures would lose functionality (for example ``mock.patch``).


- `3775 &lt;https://github.com/pytest-dev/pytest/issues/3775&gt;`_: Fix bug where importing modules or other objects with prefix ``pytest_`` prefix would raise a ``PluginValidationError``.


- `3788 &lt;https://github.com/pytest-dev/pytest/issues/3788&gt;`_: Fix ``AttributeError`` during teardown of ``TestCase`` subclasses which raise an exception during ``__init__``.


- `3804 &lt;https://github.com/pytest-dev/pytest/issues/3804&gt;`_: Fix traceback reporting for exceptions with ``__cause__`` cycles.



Improved Documentation
----------------------

- `3746 &lt;https://github.com/pytest-dev/pytest/issues/3746&gt;`_: Add documentation for ``metafunc.config`` that had been mistakenly hidden.
   ```
   
  
</details>


 

<details>
  <summary>Links</summary>
  
  - PyPI: https://pypi.org/project/pytest
  - Changelog: https://pyup.io/changelogs/pytest/
  - Homepage: http://pytest.org
</details>

cmccandless added a commit to cmccandless/multisite that referenced this issue Aug 20, 2018

Update pytest to 3.7.2 (#8)
This PR updates [pytest](https://pypi.org/project/pytest) from **3.6.4** to **3.7.2**.



<details>
  <summary>Changelog</summary>
  
  
   ### 3.7.2
   ```
   =========================

Bug Fixes
---------

- `3671 &lt;https://github.com/pytest-dev/pytest/issues/3671&gt;`_: Fix ``filterwarnings`` not being registered as a builtin mark.


- `3768 &lt;https://github.com/pytest-dev/pytest/issues/3768&gt;`_, `3789 &lt;https://github.com/pytest-dev/pytest/issues/3789&gt;`_: Fix test collection from packages mixed with normal directories.


- `3771 &lt;https://github.com/pytest-dev/pytest/issues/3771&gt;`_: Fix infinite recursion during collection if a ``pytest_ignore_collect`` hook returns ``False`` instead of ``None``.


- `3774 &lt;https://github.com/pytest-dev/pytest/issues/3774&gt;`_: Fix bug where decorated fixtures would lose functionality (for example ``mock.patch``).


- `3775 &lt;https://github.com/pytest-dev/pytest/issues/3775&gt;`_: Fix bug where importing modules or other objects with prefix ``pytest_`` prefix would raise a ``PluginValidationError``.


- `3788 &lt;https://github.com/pytest-dev/pytest/issues/3788&gt;`_: Fix ``AttributeError`` during teardown of ``TestCase`` subclasses which raise an exception during ``__init__``.


- `3804 &lt;https://github.com/pytest-dev/pytest/issues/3804&gt;`_: Fix traceback reporting for exceptions with ``__cause__`` cycles.



Improved Documentation
----------------------

- `3746 &lt;https://github.com/pytest-dev/pytest/issues/3746&gt;`_: Add documentation for ``metafunc.config`` that had been mistakenly hidden.
   ```
   
  
  
   ### 3.7.1
   ```
   =========================

Bug Fixes
---------

- `3473 &lt;https://github.com/pytest-dev/pytest/issues/3473&gt;`_: Raise immediately if ``approx()`` is given an expected value of a type it doesn&#39;t understand (e.g. strings, nested dicts, etc.).


- `3712 &lt;https://github.com/pytest-dev/pytest/issues/3712&gt;`_: Correctly represent the dimensions of an numpy array when calling ``repr()`` on ``approx()``.

- `3742 &lt;https://github.com/pytest-dev/pytest/issues/3742&gt;`_: Fix incompatibility with third party plugins during collection, which produced the error ``object has no attribute &#39;_collectfile&#39;``.

- `3745 &lt;https://github.com/pytest-dev/pytest/issues/3745&gt;`_: Display the absolute path if ``cache_dir`` is not relative to the ``rootdir`` instead of failing.


- `3747 &lt;https://github.com/pytest-dev/pytest/issues/3747&gt;`_: Fix compatibility problem with plugins and the warning code issued by fixture functions when they are called directly.


- `3748 &lt;https://github.com/pytest-dev/pytest/issues/3748&gt;`_: Fix infinite recursion in ``pytest.approx`` with arrays in ``numpy&lt;1.13``.


- `3757 &lt;https://github.com/pytest-dev/pytest/issues/3757&gt;`_: Pin pathlib2 to ``&gt;=2.2.0`` as we require ``__fspath__`` support.


- `3763 &lt;https://github.com/pytest-dev/pytest/issues/3763&gt;`_: Fix ``TypeError`` when the assertion message is ``bytes`` in python 3.
   ```
   
  
  
   ### 3.7.0
   ```
   =========================

Deprecations and Removals
-------------------------

- `2639 &lt;https://github.com/pytest-dev/pytest/issues/2639&gt;`_: ``pytest_namespace`` has been deprecated.

  See the documentation for ``pytest_namespace`` hook for suggestions on how to deal
  with this in plugins which use this functionality.


- `3661 &lt;https://github.com/pytest-dev/pytest/issues/3661&gt;`_: Calling a fixture function directly, as opposed to request them in a test function, now issues a ``RemovedInPytest4Warning``. It will be changed into an error in pytest ``4.0``.

  This is a great source of confusion to new users, which will often call the fixture functions and request them from test functions interchangeably, which breaks the fixture resolution model.



Features
--------

- `2283 &lt;https://github.com/pytest-dev/pytest/issues/2283&gt;`_: New ``package`` fixture scope: fixtures are finalized when the last test of a *package* finishes. This feature is considered **experimental**, so use it sparingly.


- `3576 &lt;https://github.com/pytest-dev/pytest/issues/3576&gt;`_: ``Node.add_marker`` now supports an ``append=True/False`` parameter to determine whether the mark comes last (default) or first.


- `3579 &lt;https://github.com/pytest-dev/pytest/issues/3579&gt;`_: Fixture ``caplog`` now has a ``messages`` property, providing convenient access to the format-interpolated log messages without the extra data provided by the formatter/handler.


- `3610 &lt;https://github.com/pytest-dev/pytest/issues/3610&gt;`_: New ``--trace`` option to enter the debugger at the start of a test.


- `3623 &lt;https://github.com/pytest-dev/pytest/issues/3623&gt;`_: Introduce ``pytester.copy_example`` as helper to do acceptance tests against examples from the project.



Bug Fixes
---------

- `2220 &lt;https://github.com/pytest-dev/pytest/issues/2220&gt;`_: Fix a bug where fixtures overridden by direct parameters (for example parametrization) were being instantiated even if they were not being used by a test.


- `3695 &lt;https://github.com/pytest-dev/pytest/issues/3695&gt;`_: Fix ``ApproxNumpy`` initialisation argument mixup, ``abs`` and ``rel`` tolerances were flipped causing strange comparsion results.
  Add tests to check ``abs`` and ``rel`` tolerances for ``np.array`` and test for expecting ``nan`` with ``np.array()``


- `980 &lt;https://github.com/pytest-dev/pytest/issues/980&gt;`_: Fix truncated locals output in verbose mode.



Improved Documentation
----------------------

- `3295 &lt;https://github.com/pytest-dev/pytest/issues/3295&gt;`_: Correct the usage documentation of ``--last-failed-no-failures`` by adding the missing ``--last-failed`` argument in the presented examples, because they are misleading and lead to think that the missing argument is not needed.



Trivial/Internal Changes
------------------------

- `3519 &lt;https://github.com/pytest-dev/pytest/issues/3519&gt;`_: Now a ``README.md`` file is created in ``.pytest_cache`` to make it clear why the directory exists.
   ```
   
  
</details>


 

<details>
  <summary>Links</summary>
  
  - PyPI: https://pypi.org/project/pytest
  - Changelog: https://pyup.io/changelogs/pytest/
  - Homepage: http://pytest.org
</details>

bors bot added a commit to rehandalal/therapist that referenced this issue Aug 20, 2018

Merge #28
28: Update pytest to 3.7.2 r=rehandalal a=pyup-bot


This PR updates [pytest](https://pypi.org/project/pytest) from **3.7.1** to **3.7.2**.



<details>
  <summary>Changelog</summary>
  
  
   ### 3.7.2
   ```
   =========================

Bug Fixes
---------

- `3671 &lt;https://github.com/pytest-dev/pytest/issues/3671&gt;`_: Fix ``filterwarnings`` not being registered as a builtin mark.


- `3768 &lt;https://github.com/pytest-dev/pytest/issues/3768&gt;`_, `3789 &lt;https://github.com/pytest-dev/pytest/issues/3789&gt;`_: Fix test collection from packages mixed with normal directories.


- `3771 &lt;https://github.com/pytest-dev/pytest/issues/3771&gt;`_: Fix infinite recursion during collection if a ``pytest_ignore_collect`` hook returns ``False`` instead of ``None``.


- `3774 &lt;https://github.com/pytest-dev/pytest/issues/3774&gt;`_: Fix bug where decorated fixtures would lose functionality (for example ``mock.patch``).


- `3775 &lt;https://github.com/pytest-dev/pytest/issues/3775&gt;`_: Fix bug where importing modules or other objects with prefix ``pytest_`` prefix would raise a ``PluginValidationError``.


- `3788 &lt;https://github.com/pytest-dev/pytest/issues/3788&gt;`_: Fix ``AttributeError`` during teardown of ``TestCase`` subclasses which raise an exception during ``__init__``.


- `3804 &lt;https://github.com/pytest-dev/pytest/issues/3804&gt;`_: Fix traceback reporting for exceptions with ``__cause__`` cycles.



Improved Documentation
----------------------

- `3746 &lt;https://github.com/pytest-dev/pytest/issues/3746&gt;`_: Add documentation for ``metafunc.config`` that had been mistakenly hidden.
   ```
   
  
</details>


 

<details>
  <summary>Links</summary>
  
  - PyPI: https://pypi.org/project/pytest
  - Changelog: https://pyup.io/changelogs/pytest/
  - Homepage: http://pytest.org
</details>



Co-authored-by: pyup-bot <github-bot@pyup.io>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment