我的文件(ensure_path.py):
import os
def ensure_path(path):
if not os.path.exists(path):
os.makedirs(path)
return path我的测试:
import unittest
from unittest.mock import patch, MagicMock
from src.util.fs.ensure_path import ensure_path
FAKE_PATH = '/foo/bar'
class EnsurePathSpec(unittest.TestCase):
@patch('os.path.exists', side_effect=MagicMock(return_value=False))
@patch('os.makedirs', side_effect=MagicMock(return_value=True))
def test_path_exists_false(self, _mock_os_path_exists_false, _mock_os_makedirs):
ensure_path(FAKE_PATH)
_mock_os_path_exists_false.assert_called_with(FAKE_PATH)
_mock_os_makedirs.assert_called_with(FAKE_PATH)
@patch('os.path.exists', side_effect=MagicMock(return_value=True))
@patch('os.makedirs', side_effect=MagicMock(return_value=True))
def test_path_exists_true(self, _mock_os_path_exists_true, _mock_os_makedirs):
ensure_path(FAKE_PATH)
_mock_os_path_exists_true.assert_called_with(FAKE_PATH)
_mock_os_makedirs.assert_not_called()这是给出了失败的断言Expected call: makedirs('/foo/bar'),我认为这是有意义的,因为我认为我在错误的级别嘲笑了os.makedirs。
我尝试过用@patch('src.util.fs.ensure_path.os.makedirs',和它的几个变体替换@patch('os.makedirs',,但是我得到了
ImportError: No module named 'src.util.fs.ensure_path.os'; 'src.util.fs.ensure_path' is not a package下面是我的__init__.py流程:

我是不是遗漏了什么明显的解决办法?
发布于 2017-12-19 06:20:00
您的patch参数需要与@patch修饰符的顺序相反。
https://stackoverflow.com/questions/47877164
复制相似问题