You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mock os.path.exists与os.makedirs触发AssertionError问题排查

Troubleshooting Mock Issues with os.path.exists and os.makedirs in Unit Tests

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 = False correctly (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 os inside the function).
  • Note: Your function uses logging.info but doesn't import logging—this will throw an error when the folder is created, but that's a separate issue that doesn't prevent makedirs from being called.

内容的提问来源于stack exchange,提问作者user1330974

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 18:35:27