简体   繁体   中英

Use mock to patch sleep in unit test

I have a piece of code sitting in a module like this:

MyWorker.py:

from gevent import sleep

class MyWorker(object):
  def run(self):
    for _ in range(10):
      do_something()
      sleep(1)

Then I want to test this while mocking sleep. I tried multiple ways of doing it but all failed. One way I thought should be working:

from mock import patch
from x.y.z.MyWorker import MyWorker

class TestWorker(unitest.testCase):
  def Test_my_worker(self):
    with patch('x.y.z.MyWorker.sleep'):
      a = MyWorker()
      a.run()

I tried some more and turns out it's very simple to fix: Change from xyzMyWorker import MyWorker to from xyzMyWorker import MyWorker, sleep , or you can do from xyzMyWorker import * and all unit tests work. The comment above gave me this idea.

This is what I end up doing:

from x.y.z.MyWorker import MyWorker, sleep

Class TestMyWorker(unittest.TestCase):

  def setUp(self):
    self.patcher = patch('x.y.z.MyWorker.sleep')
    self.patcher.start()

  def tearDown(self):
    self.patcher.stop()

  def Test_my_worker_success():
    MyWorker().run()

  def Test_my_worker_fail():
    ...

This is full working version of the mocking away sleep

# TestMyWorker.py
#!/usr/bin/python
import unittest
import mock

# myWorker.py MyWorker(class)
from myWorker import MyWorker

class TestWorker(unittest.TestCase):

    # myWorker.py - mock away sleep
    @mock.patch('myWorker.sleep')
    def test_my_worker(self, mock_sleep):
        # mock away the sleep()
        mock_sleep.return_value = False
        worker = MyWorker()
        # should run witout calling sleep()
        worker.run()
        self.assertFalse(mock_sleep.sleep.called,"Fail - sleep really called!")

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(TestWorker)
    unittest.TextTestRunner(verbosity=2).run(suite)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM