Test attribute removal using monkeypatch.delattr in pytest
Preconditions (2)
✅ Expected Result: The test should pass by confirming that the attribute was successfully removed and accessing it raises AttributeError
import pytest class MyClass: attribute = 'value' def test_monkeypatch_delattr(monkeypatch): # Remove 'attribute' from MyClass monkeypatch.delattr(MyClass, 'attribute') # Check that accessing 'attribute' raises AttributeError with pytest.raises(AttributeError): _ = MyClass.attribute
This test defines a simple class MyClass with an attribute attribute.
Inside the test function, we use the monkeypatch.delattr method to remove the attribute from MyClass.
Then, we use pytest.raises(AttributeError) as a context manager to assert that accessing the removed attribute raises an AttributeError. This confirms the attribute was successfully removed during the test.
This approach keeps the test isolated and clean, using pytest's built-in tools for patching and exception checking.
Now add data-driven testing to remove multiple attributes from different classes and verify AttributeError for each
monkeypatch.delattr in pytest?foo from object obj using monkeypatch in pytest?test_func runs?class MyClass:
def greet(self):
return 'Hello'
def test_func(monkeypatch):
obj = MyClass()
monkeypatch.delattr(obj, 'greet')
try:
obj.greet()
except AttributeError:
print('Attribute missing')def test_example(monkeypatch):
class Sample:
def method(self):
return 42
obj = Sample()
monkeypatch.delattr('obj', 'method')
obj.method()calculate is missing from an object calculator. Which pytest monkeypatch.delattr usage correctly simulates this scenario and allows you to assert the error handling?Pass the test and this pattern moves unknown