无法模拟被模拟对象的方法?pytest中的调用计数为0

2024-09-25 00:25:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我在myfile.py文件中有以下函数:

#myfile.py
import psutil
class RunnableObject:
    def run(self):
        parent = psutil.Process()
        print(parent)
        children = parent.children(recursive=True)
        print(children)

然后我有一个单元测试,其中runnable_对象是RunnableObject类的一个实例,我使用pytest夹具设置该类

@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"),但这给了我同样的问题


Tags: runpyobjectdefcountassertcallmyfile
1条回答
网友
1楼 · 发布于 2024-09-25 00:25:59

childrenpsutil.Process()的返回值的属性。不是Process方法的属性

因此,正确的断言是:

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%

相关问题 更多 >