0

I want to test if a exception is raised when I delete a instance. But it does not work like expected. I use Python 3.7.9 and pytest-6.2.4

I crated some example code:

import pytest

class Hello:
    def __del__(self):
        raise ValueError

    def say_hello(self):
        raise ValueError() 


def test_hello():
    hello = Hello() 

    with pytest.raises(ValueError):
        hello.say_hello() 

    with pytest.raises(ValueError):
        del hello

The first exception is recognized correctly but the exception in the __del__ method is not recognized. It outputs, that the exception got ignored:

_________________________________________________________________________________________ test_hello _________________________________________________________________________________________ 

    def test_hello():
        hello = Hello()

        with pytest.raises(ValueError):
            hello.say_hello()

        with pytest.raises(ValueError):
>           del hello
E           Failed: DID NOT RAISE <class 'ValueError'>

tests\database\test_connection_db.py:92: Failed
------------------------------------------------------------------------------------ Captured stderr call ------------------------------------------------------------------------------------ 
Exception ignored in: <function Hello.__del__ at 0x0DF17930>
Traceback (most recent call last):
  File "c:...\tests\database\test_connection_db.py", line 79, in __del__
    raise ValueError
ValueError:
================================================================================== short test summary info =================================================================================== 
FAILED tests/database/test_connection_db.py::test_hello - Failed: DID NOT RAISE <class 'ValueError'>

Is pytest ignoring exceptions in the __del__ method?

Andiyi
  • 1
  • 2
    Maybe a good time to [read the docs on \_\_del__](https://docs.python.org/3/reference/datamodel.html#object.\__del__) – Mark Jul 28 '21 at 15:45
  • 1
    Can you clarify why you expect this to work? ``del hello`` does not execute ``hello.__del__()``. Note that ``__del__`` should never raise an exception – Python *will* ignore such exceptions. – MisterMiyagi Jul 28 '21 at 15:46
  • 1
    In particular, from @Mark's link: "exceptions that occur during their execution are ignored" – Fred Larson Jul 28 '21 at 15:48
  • Okay now I got it thanks @Mark and @MisterMiyagi. When I call `__del__()` it works – Andiyi Jul 28 '21 at 15:53

0 Answers0