- Использование метода
assertRaisesиз модуляunittest:
import unittest
class MyTestClass(unittest.TestCase):
def test_property_raises_exception(self):
obj = MyClass()
with self.assertRaises(ValueError):
obj.my_property = 10
if __name__ == '__main__':
unittest.main()
- Использование платформы
pytestи менеджера контекстаraises:
import pytest
class TestMyClass:
def test_property_raises_exception(self):
obj = MyClass()
with pytest.raises(ValueError):
obj.my_property = 10
- Использование блока try-Exception:
class MyClass:
def __init__(self):
self._my_property = None
@property
def my_property(self):
return self._my_property
@my_property.setter
def my_property(self, value):
if value < 0:
raise ValueError("Value must be greater than or equal to zero")
self._my_property = value
obj = MyClass()
try:
obj.my_property = -1
except ValueError:
pass # Expected exception
else:
assert False, "Expected ValueError was not raised"
Это всего лишь несколько примеров того, как можно утверждать повышения с помощью свойств в Python. Вы можете выбрать метод, который лучше всего соответствует вашей системе тестирования или требованиям.