unittest.mock.seal
Let's say, you have the following mock:
from unittest.mock import Mock
user = Mock()
user.name = 'Guido'
You fully specified all attributes and methods it should have, and you pass it into the tested code, but then that code uses an attribute that you don't expect it to use:
user.age
# <Mock name='mock.age' id='...'>
Instead of failing with an AttributeError
, the mock instead will create a new mock when its unspecified attribute is accessed. To fix it, you can (and should) use the unittest.mock.seal function (introduced in Python 3.7):
from unittest.mock import seal
seal(user)
user.name
# 'Guido'
user.occupation
# AttributeError: mock.occupation