0

I want to write a test for this function while mocking check_call (I don't want it to be called):

from subprocess import check_call

def foo_method():
    check_call(["ls"])
    print("hello")

This is the test:

import unittest.mock
from scripts import foo_method

@unittest.mock.patch("subprocess.check_call")
def test_foo_method(subprocess_check_call):
    foo_method()

But the check_call function is always called and is not mocked. What is wrong with the test?

Lin Du
  • 88,126
  • 95
  • 281
  • 483
T.Poe
  • 1,949
  • 6
  • 28
  • 59
  • You have to patch the `check_call` imported in your module, e.g. `patch("mymodule.check_call")` - see [where to patch](https://docs.python.org/3/library/unittest.mock.html#id6), or for example [this answer](https://stackoverflow.com/a/62625882/12480730) a gave to a similar question. – MrBean Bremen Jan 06 '21 at 18:59
  • It's a subtle point, but `foo_method` uses `scripts.check_call`, not `subprocess.check_call`. Both names refer to the same underlying object, but `patch` operates on *names*, not the things they refer to. – chepner Jan 06 '21 at 21:00

1 Answers1

0

You should patch the check_call method for scripts.py module. So the target to be patched should be scripts.check_call. For more info, see where-to-patch

E.g.

scripts.py:

from subprocess import check_call


def foo_method():
    check_call(["ls"])
    print("hello")

test_scripts.py:

import unittest
from unittest.mock import patch
from scripts import foo_method


class TestScripts(unittest.TestCase):

    @patch("scripts.check_call")
    def test_foo_method(self, mock_check_call):
        foo_method()
        mock_check_call.assert_called_once_with(['ls'])


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

unit test result:

⚡  coverage run /Users/dulin/workspace/github.com/mrdulin/python-codelab/src/stackoverflow/65601680/test_scripts.py && coverage report -m --include='./src/**'
hello
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK
Name                                         Stmts   Miss  Cover   Missing
--------------------------------------------------------------------------
src/stackoverflow/65601680/scripts.py            4      0   100%
src/stackoverflow/65601680/test_scripts.py      10      0   100%
--------------------------------------------------------------------------
TOTAL                                           14      0   100%
Lin Du
  • 88,126
  • 95
  • 281
  • 483