【问题标题】:python function not mocked if called from list如果从列表中调用 python 函数,则不会模拟
【发布时间】:2020-05-13 12:15:09
【问题描述】:

当从函数列表调用函数时,我试图模拟一个函数。

以下工作:

# demo_module.py

import demo_module_b

def run_me():
    run_me_too()

# demo_module_b

def run_me_too():
    pass
# test.py

from demo_module import run_me
from demo_module_b import run_me_too

@patch('demo_module_b.run_me_too')
def test_run_me_with_patch(mock_run_me_too):
    run_me()
    assert mock_run_me_too.called # PASSES

以下失败:

# demo_module.py

import demo_module_b

PROCESS = [
    demo_module_b.run_me_too,
]

def run_me():
    PROCESSES[0]()

# demo_module_b

def run_me_too():
    pass
# test.py

from demo_module import run_me
from demo_module_b import run_me_too

@patch('demo_module_b.run_me_too')
def test_run_me_with_patch(mock_run_me_too):
    run_me()
    assert mock_run_me_too.called # FAILS

有没有办法让它工作而无需模拟列表?

编辑 1

这也失败了(并且直接导入失败了两个测试):

# demo_module.py

from demo_module_b import run_me_too

processes = [
    run_me_too,
]


def run_me():
    processes[0]() # FAILS IN TEST
    run_me_too() # ALSO FAILS IN TEST

【问题讨论】:

  • 这就是你应该如何定义PROCESSESPROCESS = [run_me_too] 而不是PROCESS = [demo_module_b.run_me_too]
  • 谢谢我试过这个,它也失败了。以上编辑

标签: python python-3.x pytest python-mock


【解决方案1】:

您需要在导入被测模块之前进行模拟。模块范围内的代码将在导入模块时执行。测试用例执行的时候再通过装饰器来模拟已经来不及了。

例如

demo_module.py:

import demo_module_b

PROCESSES = [
    demo_module_b.run_me_too,
]


def run_me():
    PROCESSES[0]()

demo_module_b.py:

def run_me_too():
    pass

test_demo_module.py:

import unittest
from unittest.mock import patch


class TestDemoModule(unittest.TestCase):
    @patch('demo_module_b.run_me_too')
    def test_run_me_with_patch(self, mock_run_me_too):
        from demo_module import run_me
        run_me()
        assert mock_run_me_too.called


if __name__ == '__main__':
    unittest.main()

测试结果:

.
----------------------------------------------------------------------
Ran 1 test in 0.002s

OK
Name                                             Stmts   Miss  Cover   Missing
------------------------------------------------------------------------------
src/stackoverflow/61774393/demo_module.py            4      0   100%
src/stackoverflow/61774393/demo_module_b.py          2      1    50%   2
src/stackoverflow/61774393/test_demo_module.py      10      0   100%
------------------------------------------------------------------------------
TOTAL                                               16      1    94%

【讨论】:

    猜你喜欢
    • 2018-07-18
    • 1970-01-01
    • 2017-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-28
    • 2015-05-01
    相关资源
    最近更新 更多