在单元测试中使用mock来修补sleep

时间:2015-12-31 20:37:33

标签: python unit-testing mocking

我有一段代码放在这样的模块中:

MyWorker.py:

from gevent import sleep

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

然后我想在模仿睡眠时测试这个。我尝试了多种方法,但都失败了。我认为应该工作的一种方式是:

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

2 个答案:

答案 0 :(得分:0)

我尝试了一些,结果发现它非常简单: 将from x.y.z.MyWorker import MyWorker更改为from x.y.z.MyWorker import MyWorker, sleep,或者您可以from x.y.z.MyWorker import *进行所有单元测试。上面的评论给了我这个想法。

这就是我最终要做的事情:

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

答案 1 :(得分:0)

这是模拟休眠的完整工作版本

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