【问题标题】:Testing and mocking a threaded function within a view在视图中测试和模拟线程函数
【发布时间】:2018-02-21 01:27:00
【问题描述】:

我正在尝试对我在视图中以线程方式运行的函数进行单元测试。每当我尝试模拟它时,它总是转到原始函数,而不是模拟函数。

我正在测试的代码,来自视图模块:

def restart_process(request):
    batch_name = request.POST.get("batch_name", "")
    if batch_name:
        try:
            batch = models.Batch.objects.get(num=batch_name)
        except models.Batch.DoesNotExist:
            logger.warning("Trying to restart a batch that does not exist: " + batch_name)
            return HttpResponse(404)
        else:
            logger.info(batch_name + " restarted")
            try:
                t = threading.Thread(target=restart_from_last_completed_state, args=(batch,))
                t.daemon = True
                t.start()
            except RuntimeError:
                return HttpResponse(500, "Threading error")
            return HttpResponse(200)
    else:
        return HttpResponse(400)

测试功能:

class ThreadTestCases(TransactionTestCase):

def test_restart_process(self):
    client = Client()
    mock_restart_from_last_completed_state = mock.Mock()
    with mock.patch("processapp.views.restart_from_last_completed_state", mock_restart_from_last_completed_state):
        response = client.post('/batch/restart/', {"batch_name": "BATCH555"})
        self.assertEqual(response.status_code, 200)
    mock_restart_from_last_completed_state.assert_called_once()

网址:

url(r'^batch/restart/$', views.restart_from_last_completed_state, name="restart_batch"),

我总是收到这个错误:

ValueError: The view processapp.processing.process_runner.restart_from_last_completed_state didn't return an HttpResponse object. It returned None instead.

我在原始函数 (restart_from_last_completed_state) 中放置了一个打印命令,它始终运行,因此不会发生模拟。

错误似乎将函数视为视图,但实际上并非如此。

我不确定错误出在哪里,是线程、测试还是其他?

【问题讨论】:

    标签: python django multithreading unit-testing


    【解决方案1】:

    URL 变量错误。应该是 views.restart_process 而不是 views.restart_from_last_completed_state

    多次复制/粘贴错误...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-06
      • 2016-05-08
      相关资源
      最近更新 更多