使用MagicMock在Python中嵌套模拟导入

外星人韦伯

我的档案(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('os.makedirs',@patch('src.util.fs.ensure_path.os.makedirs',和的一对夫妇的变化,但我得到

ImportError: No module named 'src.util.fs.ensure_path.os'; 'src.util.fs.ensure_path' is not a package

这是我的__init__.py流程:

在此处输入图片说明

我有明显的解决方法吗?

牛f

您的patch参数必须与@patch装饰器的顺序相反。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章