Meaning
Replaces a method of a class with a lambda that returns a constant value, typically used in testing to stub dependencies.
Primary Function
Temporarily replace a method's implementation with a lambda returning a fixed value to isolate code under test.
Communicative Purpose
Indicate that a specific method should be stubbed to return a constant during test execution.
Pattern
monkeypatch.setattr('<target>', lambda self: <constant>)
Core Structure
monkeypatch.setattr(target, lambda self: constant)
Função primária
Temporarily replace a method's implementation with a lambda returning a fixed value to isolate code under test.
Propósito comunicativo
Indicate that a specific method should be stubbed to return a constant during test execution.
Situações de gatilho
When writing unit tests and need to isolate a unit by replacing a dependency method with a deterministic stub, especially for external APIs, randomness, or time‑dependent logic.
Contextos
Unit testing with pytest's monkeypatch fixture, mocking external services, simulating edge cases, temporary stubbing during debugging.
Padrão
monkeypatch.setattr('<target>', lambda self: <constant>)
Estrutura central
monkeypatch.setattr(target, lambda self: constant)
Slots de substituição
target: str (dotted path to method, e.g., 'module.Class.method'), constant: any (return value, often a literal or simple expression)
Colocados típicos
- pytest
- monkeypatch fixture
- unittest.mock
- mock
- stub
- mock.return_value
- patch
- fixture
Substituições comuns
- Using unittest.mock.patch instead of monkeypatch.setattr for automatic cleanup
- using a lambda that returns a dynamic value or calls another function
- employing MagicMock to simulate more complex behavior.
Erros comuns
- Forgetting to undo the patch: cause – missing cleanup leads to the patched method affecting other tests → consequence: test pollution and flaky failures. - Patching the wrong attribute path: cause – typo in the module.Class.method string → consequence: AttributeError or silent failure where the real method is not mocked. - Using a lambda that captures mutable state incorrectly: cause – lambda references an outer variable that changes → consequence: unexpected return values across tests. - Assuming the patched method is bound when it is a classmethod or staticmethod: cause – lambda signature mismatch → consequence: TypeError when the method is invoked. - Patching a property instead of a method: cause – treating a property as callable → consequence: AttributeError when code attempts to call it.
Similar / contraste
- unittest.mock.patch: provides automatic start/stop and richer mock objects vs manual monkeypatch. - Dependency injection via constructor: replaces dependency through explicit parameters vs runtime monkey‑patching. - Dependency injection container: manages lifecycle centrally vs ad‑hoc patching. - Monkey‑patching a class attribute vs an instance attribute: class‑level affects all instances, instance‑level affects only that object.
Interferências
Coming from Java: may attempt to mock by subclassing or using interfaces, unaware that Python's monkey‑patching modifies the class globally and requires explicit cleanup → use unittest.mock.patch with addCleanup or pytest's monkeypatch fixture for automatic teardown. Coming from JavaScript: may expect mocking to affect only a specific instance, not realizing that patching a class method impacts all instances unless the object is a singleton → patch the instance directly or use mock.patch.object on the instance.
Família do chunk
- monkeypatch
- mocking
- stubbing
- mock
- patch
- dependency injection
Nuance
NOT to use when the dependency is instantiated multiple times and state must be isolated per instance, because monkey‑patching affects all instances globally; Performance impact is negligible as the lambda is lightweight, but excessive patching can increase import time and complicate test teardown; Boundary condition: patching a property or descriptor (e.g., @property) requires PropertyMock instead of a plain lambda, otherwise attribute access fails.
Efeito pragmático
Enables deterministic unit tests by replacing unpredictable dependencies with fixed stubs, yielding faster, more reliable test suites and simpler debugging of edge cases.
Dica de memória
Think of monkeypatch.setattr as swapping a real car's engine with a dummy engine that always reports 42 horsepower, letting you test the car's behavior without worrying about fuel consumption.
Upgrade path
Transition to using unittest.mock.patch or pytest's monkeypatch fixture with automatic cleanup for more robust, scoped mocking.
Log in to save chunks.