![](/img/trans.png)
[英]Patching has no effect when applied to a parameter of a function called by the patched function
[英]Function called by a Celery task has no calls when patched in a unit test?
考慮以下tasks.py
模塊(改編自http://docs.celeryproject.org/en/latest/getting-started/first-steps-with-celery.html#first-steps ):
import logging
import sys
from celery import Celery
app = Celery('tasks', broker='pyamqp://guest@localhost//')
@app.task
def add(x, y):
logging.info(f"Adding {x} and {y}...")
return x + y
def call_add(x, y):
add.delay(x, y)
在同一個目錄中,我有一個test_tasks.py
測試模塊,它讀取
from unittest.mock import patch
import tasks
@patch('logging.info')
def test_adder(info_mock):
tasks.call_add(1, 2)
info_mock.assert_not_called()
這個測試通過了(如果我用pytest test_tasks.py
運行它),但我不確定為什么沒有調用info_mock
? 我希望以下斷言通過
info_mock.assert_called_with("Adding 1 and 2...")
為什么在這個例子中沒有通過tasks.call_add()
調用logging.info
? 在我看來,它等同於http://docs.celeryproject.org/en/latest/userguide/testing.html 中給出的示例。
確保在運行單元測試時直接在同一進程中運行測試。
Celery 使得在“同步”運行任務時保持相同的 API 變得非常簡單,並跳過損壞的/工作器部分。
app = Celery('tasks', broker='pyamqp://guest@localhost//', task_always_eager=True)
http://docs.celeryproject.org/en/latest/userguide/configuration.html#task-always-eager
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.