2

I have the following function in the file myfile.py:

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

Then I have a unit test where runnable_object is an instance of the RunnableObject class which I setup using a pytest fixture.

@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

When I run my test however I get the following error:

       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

My stdout:

<MagicMock name='psutil.Process()' id='3001903696'>
<MagicMock name='psutil.Process().children()' id='3000968624'>

I also tried to use @patch.object(psutil.Process, "children") as well as@patch("myfile.psutil.Process") and @patch("myfile.psutil.Process.children") but that gave me the same problem.

user3302735
  • 69
  • 2
  • 9

1 Answers1

1

children is the property of the return value of psutil.Process(). NOT the property of the Process method.

So the correct assertion is:

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()

test result:

<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%
Lin Du
  • 88,126
  • 95
  • 281
  • 483