1
votes

I'm doing some self-learning on the new python dataclasses.

One of the parameters that can be passed to the dataclass decorator is frozen=True, to make the object immutable.

The documentation (and experience) indicates that a:

dataclasses.FrozenInstanceError

exception will be raised.

When unit testing though (with pytest) the following test passes:

def test_change_page_url_values_raises_error(self, PAGE_URL):
    page_url = PageURL(PAGE_URL)
    with pytest.raises(AttributeError) as error:
        page_url.value = PAGE_URL

where PageURL is a dataclass with the frozen=True parameter.

Any ideas why why pytest indicates that this action (assigning a value to page_url.value) raises an Attribute Error? Does FrozenInstanceError inherit from AttributeError?

Note: If I change the unit test to test for a different exception (ie. TypeError), the test fails as expected.

1
Check in shell issubclass(dataclasses.FrozenInstanceError, AttributeError) - warvariuc
Ahh. Thank you. To investigate this I had been trying: assert issubclass(type(error), AttributeError) in the unit test itself. I just realised that pytest is returning a ExceptionInfo class as the error, not the original raised exception... facepalm To the shell next time. - Steven
@Steven For future reference, the originally raised exception is stored as the value attribute of that ExceptionInfo context manager, i.e. error.value. - wim

1 Answers

3
votes

This is a subclass, which you can verify easily with built-in function issubclass:

>>> issubclass(FrozenInstanceError, AttributeError)
True

If you want an exact type match in the tests, which I would consider best practice, then you can use an exception instance instead of an exception class. As an added bonus this also allows you to make an assertion on the exception context (i.e. which field has triggered the exception).

with pytest.raises(FrozenInstanceError("cannot assign to field 'value'")):
    page_url.value = PAGE_URL

This usage of pytest.raises requires installing my plugin pytest-raisin.