Meaning
A context manager that temporarily replaces a class property with a PropertyMock, allowing the property's get/set/delete behavior to be controlled in unit tests.
Primary Function
Temporarily replace a class property with a mock object that can be programmed to return specific values, raise exceptions, or track accesses.
Communicative Purpose
Communicate to the reader/tester that a specific property is being isolated and controlled for the purpose of testing dependent code.
Pattern
with patch.object(Class, 'attribute', new_callable=PropertyMock) as mock:
Core Structure
with patch.object(Class, 'attribute', new_callable=PropertyMock) as mock:
Função primária
Temporarily replace a class property with a mock object that can be programmed to return specific values, raise exceptions, or track accesses.
Propósito comunicativo
Communicate to the reader/tester that a specific property is being isolated and controlled for the purpose of testing dependent code.
Situações de gatilho
When unit testing a method or property that accesses another class's property and you need to control its return value or simulate exceptions without altering the real implementation.
Contextos
Unit test suites using unittest.mock, especially when testing properties, descriptors, or properties that compute values on the fly.
Padrão
with patch.object(Class, 'attribute', new_callable=PropertyMock) as mock:
Estrutura central
with patch.object(Class, 'attribute', new_callable=PropertyMock) as mock:
Slots de substituição
Class: any class, attribute: str property name, mock_var: variable name for the PropertyMock
Colocados típicos
- unittest.mock.patch
- PropertyMock
- unittest.TestCase
- mock.return_value
- mock.side_effect
- assert_called_with
Substituições comuns
- Replace PropertyMock with MagicMock for mocking methods
- use patch.object with new=constant to replace a property with a static value
- use patch.object with new_callable=MagicMock and configure return_value for method‑like behavior.
Erros comuns
1. Forgetting to use PropertyMock and instead using MagicMock, causing property access to return a mock object rather than controlling the property's return value (leads to AttributeError when code expects a value). 2. Assigning to the mock (mock_prop = value) instead of setting mock_prop.return_value, which replaces the mock itself and breaks subsequent accesses. 3. Forgetting to exit the context manager (omit 'with' or not using it as a context), leaving the patch active beyond the test and causing test pollution. 4. Trying to mock a class attribute that is not a property (e.g., a regular attribute) with PropertyMock, which only works on descriptors defined with @property. 5. Neglecting to reset side_effect or return_value between tests, resulting in cross‑test contamination.
Similar / contraste
patch.object with MagicMock: used for mocking regular methods rather than properties; patch.object with new=value: replaces a property with a constant value, losing the ability to simulate dynamic behavior; unittest.mock.patch as a decorator: applies the patch at the function level rather than as a context manager.
Interferências
Coming from Java: may attempt to mock fields directly with frameworks like Mockito, but in Python properties are descriptors and require PropertyMock to intercept access. → Use patch.object with new_callable=PropertyMock. Coming from JavaScript: may try to overwrite the property via assignment, which only affects the instance, not the class descriptor, leading to incomplete mocking. → Use patch.object on the class. Coming from Ruby: may expect to stub getters/setters via instance variables, but Python properties require mocking the descriptor. → Apply patch.object to the class.
Família do chunk
- unittest.mock patching
- property mocking
- method mocking
- descriptor mocking
Nuance
1. Do not use this pattern to mock plain attributes; PropertyMock only works on properties defined with @property. 2. Performance impact is negligible as the patch lasts only for the context duration, though deep nesting of patches can increase test setup overhead. 3. PropertyMock intercepts attribute access (get, set, delete); accessing the property via the class (MyClass.prop) or an instance works the same because patch.object targets the class descriptor.
Efeito pragmático
Enables deterministic testing of code that depends on property values, allowing simulation of various return values, exceptions, or side effects without altering the real implementation, leading to more reliable and isolated unit tests.
Dica de memória
Think of patch.object with PropertyMock as hiring a stand‑in actor who only steps in when the property is queried, letting you script their lines and actions while the real actor stays off‑stage.
Nota
PropertyMock must be used with new_callable; assigning a value directly to the mock (e.g., mock_prop = 5) replaces the mock itself, not the property's return value. Use mock_prop.return_value to define what the property returns.
Upgrade path
After mastering property mocking, advance to using PropertyMock with side_effect to simulate stateful properties or to raise exceptions on successive accesses.
Log in to save chunks.