Search code examples
python-3.xunit-testingimportmockingsleep

unittest, mock time.sleep in other package


I have a Pycharm project with some package code under test and i can import the package like import my_package from another module in the project as Pycharm configures python to include the projectdir into it's search path. The my_module in my_package imports time and uses time.sleep, which i want to mock out.

projectdir/my_package
  __init__.py
  my_module.py

projectdir/tests
  test_my_package.py

In the test I have the following code:

import unittest
from unittest.mock import patch

from my_package import my_module


@patch("my_package.my_module.time.sleep")
class TestMyPackage(unittest.TestCase):
    def test_bla(self, timepatch):
        my_module.my_function()

The problem I have is, that the time.sleep is not mocked out. My unittests need about 0.5s per testcase which i way too much. I guess I'm patching at the wrong spot. Can you help me fix the @patch("my_package.my_module.time.sleep") decorator ?


Solution

  • By experimenting I found the answer. I had to use

    sleeppatch = patch("my_package.my_module.time.sleep")
    sleeppatch.start()
    

    within the setUp method of the testclass and:

    sleeppatch.stop()
    

    in the tearDown method.

    Using the decoration, the patch was stopped too early.