from unittest.mock import patch with patch("lib.format_value", lambda value:…
- User
from unittest.mock import patch
with patch("lib.format_value", lambda value: f"
{value}"): with patch("lib.format_value", lambda value: f"{value}"): import lib assert lib.x == "35", "mock failed" print("mock success") Assistant
Looking at your code, you're trying to patch
lib.format_valuetwice with the same mock function, but there's an issue with how you're using the patches.The problem is that you're patching
lib.format_valuebefore importinglib. This means:- The patches are applied to a module that hasn't been imported yet
- When you import
lib, iflib.xis defined at module level usingformat_value, it will use the original function, not your mock
Here's what's likely happening in your
lib.py:# lib.py def format_value(value): return str(value) x = format_value(35) # This runs when the module is importedTo fix this, you need to either:
Option 1: Patch before the module is loaded in sys.modules
import sys from unittest.mock import patch # Make sure lib isn't already imported if 'lib' in sys.modules: del sys.modules['lib'] with patch("lib.format_value", lambda value: f"~{value}~"): import lib assert lib.x == "~35~", "mock failed" print("mock success")Option 2: If
xis computed dynamicallyfrom unittest.mock import patch import lib with patch.object(lib, "format_value", lambda value: f"~{value}~"): # If lib.x is a property or computed on access, this would work assert lib.x == "~35~", "mock failed" print("mock success")Option 3: Reload the module with the patch active
from unittest.mock import patch import importlib with patch("lib.format_value", lambda value: f"~{value}~"): import lib importlib.reload(lib) assert lib.x == "~35~", "mock failed" print("mock success")Also note that having two nested patches with the same target and replacement doesn't add any value - the inner patch would just override the outer one temporarily.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.