【问题标题】:Mock nested import in Python with MagicMock使用 MagicMock 在 Python 中模拟嵌套导入
【发布时间】:2018-06-01 07:25:44
【问题描述】:

我的文件(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 流程:

我是否缺少明显的修复?

【问题讨论】:

    标签: python python-3.x python-unittest magicmock


    【解决方案1】:

    您的补丁参数需要与@patch 装饰器的顺序相反。

    【讨论】:

    • 天哪。你摇滚!谢谢老兄,我会在几分钟内接受。
    • 我希望我能记住它在文档中的位置。我可能刚刚在一些教程或团队成员编写的单元测试的 cmets 中看到它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    • 2022-01-07
    • 2020-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多