我在文件 myfile.py 中有以下功能:
#myfile.py
import psutil
class RunnableObject:
def run(self):
parent = psutil.Process()
print(parent)
children = parent.children(recursive=True)
print(children)
然后我有一个单元测试,其中 runnable_object 是我使用 pytest 固定装置设置的 RunnableObject 类的一个实例。@patch("myfile.psutil")
def test_run_post_request(self, psutil_, runnable_object):
runnable_object.run()
assert psutil_.Process.call_count == 1
assert psutil_.Process.children.call_count == 1
但是,当我运行测试时,出现以下错误: assert psutil_.Process.call_count == 1
> assert psutil_.Process.children.call_count == 1
E assert 0 == 1
E +0
E -1
-1
tests/unit/test_experiment.py:1651: AssertionError
我的标准输出:<MagicMock name='psutil.Process()' id='3001903696'>
<MagicMock name='psutil.Process().children()' id='3000968624'>
我也尝试使用 @patch.object(psutil.Process, "children")
以及 @patch("myfile.psutil.Process")
和 @patch("myfile.psutil.Process.children")
但这给了我同样的问题。
最佳答案
children
是psutil.Process()
的返回值的属性.不是 Process
的属性(property)方法。
所以正确的断言是:test_myfile.py
:
from unittest import TestCase
import unittest
from unittest.mock import patch
from myfile import RunnableObject
class TestRunnableObject(TestCase):
@patch("myfile.psutil")
def test_run_post_request(self, psutil_):
runnable_object = RunnableObject()
runnable_object.run()
assert psutil_.Process.call_count == 1
assert psutil_.Process().children.call_count == 1
if __name__ == '__main__':
unittest.main()
测试结果:<MagicMock name='psutil.Process()' id='4394128192'>
<MagicMock name='psutil.Process().children()' id='4394180912'>
.
----------------------------------------------------------------------
Ran 1 test in 0.002s
OK
Name Stmts Miss Cover Missing
-------------------------------------------------------------------------
src/stackoverflow/67362647/myfile.py 7 0 100%
src/stackoverflow/67362647/test_myfile.py 13 0 100%
-------------------------------------------------------------------------
TOTAL 20 0 100%
关于python - 不能模拟被模拟对象的方法? pytest 中的 call_count 为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67362647/