Mock os.path.exists与os.makedirs触发AssertionError问题排查
Let's break down why your mock isn't working as expected and fix it.
First, let's recap your scenario: you have a function create_output_csv_file_path_and_name in retrieve_data.py that checks if an output folder exists with os.path.exists, creates it with os.makedirs if not, then returns the CSV path. Your unit test mocks os.path.exists to return False, but the test fails because os.makedirs was never called—even though you confirmed the mock for exists was applied.
The Root Cause: Incorrect Mock Target Path
The most common reason for this issue is that you're mocking the wrong instance of os.path.exists and os.makedirs.
When you write import os inside retrieve_data.py, the module creates its own local reference to the os module. If your test mocks the global os module (e.g., patch('os.path.exists')), that won't affect the os reference that your function is using—it's still pointing to the original, unmocked module.
The Fix: Mock the Module-Local os References
You need to mock the os instances that live inside the retrieve_data module (the one your function is using), not the global os module. Here's how to adjust your test correctly:
Example Working Test (using unittest.mock)
from unittest.mock import patch import retrieve_data def test_create_output_csv_creates_folder(): # Mock the os.path.exists and os.makedirs that retrieve_data.py uses with patch('retrieve_data.os.path.exists') as mock_exists, \ patch('retrieve_data.os.makedirs') as mock_makedirs: # Set up the mock to return False (folder doesn't exist) mock_exists.return_value = False # Call your function csv_path = retrieve_data.create_output_csv_file_path_and_name() # Verify makedirs was called exactly once with the default folder name mock_makedirs.assert_called_once_with('outputs') # Optional: Verify the returned path is correct assert csv_path == 'outputs/results.csv'
Additional Checks to Rule Out Other Issues
If the above fix doesn't resolve the problem, double-check these:
- Ensure you're setting
mock_exists.return_value = Falsecorrectly (typos here are easy to miss). - Confirm there's no other code in your test or function that might override the mock (e.g., accidental reimports of
osinside the function). - Note: Your function uses
logging.infobut doesn't importlogging—this will throw an error when the folder is created, but that's a separate issue that doesn't preventmakedirsfrom being called.
内容的提问来源于stack exchange,提问作者user1330974

