Test Overview
This test uses monkeypatch.delattr to temporarily remove an attribute from a class during the test. It verifies that accessing the deleted attribute raises an AttributeError.
This test uses monkeypatch.delattr to temporarily remove an attribute from a class during the test. It verifies that accessing the deleted attribute raises an AttributeError.
import pytest class MyClass: attribute = "value" def test_delattr(monkeypatch): # Remove 'attribute' from MyClass monkeypatch.delattr(MyClass, "attribute") instance = MyClass() with pytest.raises(AttributeError): _ = instance.attribute
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | Test environment initialized with pytest and monkeypatch fixture available | — | PASS |
| 2 | monkeypatch.delattr removes 'attribute' from MyClass | MyClass no longer has 'attribute' attribute | — | PASS |
| 3 | Create instance of MyClass | Instance created without 'attribute' attribute | — | PASS |
| 4 | Attempt to access instance.attribute inside pytest.raises context | Accessing attribute triggers AttributeError | Verify AttributeError is raised when accessing deleted attribute | PASS |
| 5 | Test ends successfully | AttributeError correctly raised and caught, test passes | — | PASS |
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