python - 不能模拟被模拟对象的方法? pytest 中的 call_count 为 0

标签 python unit-testing mocking pytest psutil

我在文件 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")但这给了我同样的问题。

最佳答案

childrenpsutil.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/

相关文章:

python - 在二叉树中查找指定节点的路径(Python)

python - Openlayers + Mapnik + Tilecache 配置问题

python - “函数”对象没有属性 'assert_called_once_with'

python - 如何在幻灯片的特定位置通过 python 将 Excel 文件和链接数据嵌入 PowerPoint

python - 尝试断言有关异常的某些内容,但收到 AttributeError?

java - TDD 和工厂模式

c# - 一起运行时单元测试失败,单独通过

python - 用模拟替换对象

c - 是否可以在运行时交换 C 函数实现?

python - Python opencv在空白的白色 Canvas 中概述黑色像素