我试图对我在视图中运行线程的函数进行单元测试。每当我试图模仿它时,它总是转到原始函数,而不是模拟函数。
我在测试模块中测试的代码:
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)中放置了一个print命令,它始终运行,因此不会进行模拟。
错误似乎将该函数视为视图,尽管它不是。
我不确定错误在哪里,线程,测试还有其他什么?
答案 0 :(得分:0)
网址变量错误。应该是views.restart_process而不是views.restart_from_last_completed_state
复制/粘贴错误很多次......