Pythonã®æ¨æºã©ã¤ãã©ãªã«å«ã¾ããunittest.mockã¢ã¸ã¥ã¼ã«ã®ä½¿ãæ¹ã¡ã¢ãpatchã®ã¿ã
試ãããã¼ã¸ã§ã³ã¯ãPython 3.5
ãã¹ã対象
main.py
import subprocess def say(message): """echoã³ãã³ãã§messageãå®è¡ãã """ return subprocess.call(['echo', message]) def say_hello(somebody): """ãHello, {somebody}!ãã¨ç»é¢ã«è¡¨ç¤ºããé¢æ° """ message = "Hello, {}!".format(somebody) return say(message) if __name__ == '__main__': say_hello("tokibito")
å®è¡ããã¨æ¬¡ã®ããã«ãªãã
$ python main.py Hello, tokibito!
ãã¹ãã³ã¼ã
test_main.py
from unittest import TestCase, mock class SayHelloTest(TestCase): """say_helloé¢æ°ã®ãã¹ã """ def _get_target(self): from main import say_hello as target return target def _callFUT(self, *args, **kwargs): return self._get_target()(*args, **kwargs) def test_somebody(self): """somebodyå¼æ°ã使ããã¦ãããã¨ã確èªãããã¹ã """ with mock.patch('main.say', return_value=0) as patcher: result = self._callFUT("Spam") self.assertEqual(result, 0, "æ£å¸¸ãªçµäºã³ã¼ãã«ãªããã¨") # somebodyå¼æ°ã使ãããã¡ãã»ã¼ã¸ãæå®ã㦠# sayé¢æ°ãå®è¡ãã¦ããã㨠patcher.assert_called_with("Hello, Spam!")