Meaning
Creates a mock object whose return value is computed dynamically from its input arguments via a lambda function. Addresses the limitation of return_value, which always returns the same value regardless of call arguments. Reached for when the code under test passes varying arguments to a dependency and the test must produce context-dependent responses.
Primary Function
Mocking
Communicative Purpose
Enables dynamic mock return values that depend on the arguments passed at call time.
Pattern
Mock(side_effect=lambda x: expression)
Core Structure
Mock(side_effect=lambda ...: ...)
Função primária
Mocking
Propósito comunicativo
Enables dynamic mock return values that depend on the arguments passed at call time.
Situações de gatilho
Unit testing: verifying a function that calls a dependency whose output depends on its input arguments. Dependency injection: simulating a service that transforms or looks up values based on request parameters. Edge case testing: creating a mock that returns different values for different inputs in a single test run.
Contextos
Unit testing with Python's unittest.mock module, especially for dependency injection.
Padrão
Mock(side_effect=lambda x: expression)
Estrutura central
Mock(side_effect=lambda ...: ...)
Slots de substituição
{"expression": "any expression using variable x (e.g., x * 2, x + 1)"}
Colocados típicos
- Mock side_effect lambda lambda x return mock unittest.mock
Substituições comuns
- lambda x: x + 1 lambda x: x * 3 lambda x: x - 5 lambda x: str(x)
Erros comuns
Using return_value instead of side_effect for argument-dependent behavior Forgetting to return a value in lambda (returns None) Using side_effect with a non-callable causing TypeError
Similar / contraste
Mock(return_value=5) returns constant Mock(side_effect=lambda x: x) identity Mock(side_effect=Exception) raises exception
Interferências
Coming from JavaScript: may expect jest.fn().mockImplementation() chaining syntax — Python's Mock uses a single side_effect parameter with a callable. Coming from Ruby: may expect RSpec's allow().to receive().and_return() chain — Python's Mock uses a single side_effect argument instead.
Família do chunk
- unittest.mock.Mock side_effect patterns
Nuance
Do not use side_effect with lambda when the mock should always return the same value regardless of arguments — use return_value instead, which is simpler and more explicit. Each call to a side_effect lambda executes the function, so expensive computations in the lambda will slow tests proportionally. If the lambda raises an exception, the mock propagates it to the caller, which is useful for error-path testing but surprising if unintended.
Efeito pragmático
Shows how to simulate a function that transforms its input, useful for testing pure functions.
Dica de memória
side_effect is the mock's brain: return_value is a recorded answer, side_effect is a live calculator that sees the question.
Nota
Ensure the lambda returns a value; otherwise the mock returns None.
Upgrade path
Consider using side_effect for more complex behaviors like raising exceptions or returning sequences.
Log in to save chunks.