简体   繁体   English

在单元测试中打补丁时,由 Celery 任务调用的函数没有调用?

[英]Function called by a Celery task has no calls when patched in a unit test?

Consider the following tasks.py module (adapted from http://docs.celeryproject.org/en/latest/getting-started/first-steps-with-celery.html#first-steps ):考虑以下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)

In the same directory, I have a test_tasks.py test module which reads在同一个目录中,我有一个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()

This test passes (if I run it with pytest test_tasks.py ), but I'm not sure why info_mock was not called?这个测试通过了(如果我用pytest test_tasks.py运行它),但我不确定为什么没有调用info_mock I would expect the following assertion to pass我希望以下断言通过

info_mock.assert_called_with("Adding 1 and 2...")

Why is logging.info not called through tasks.call_add() in this example?为什么在这个例子中没有通过tasks.call_add()调用logging.info It seems to me to be equivalent to the example given in http://docs.celeryproject.org/en/latest/userguide/testing.html .在我看来,它等同于http://docs.celeryproject.org/en/latest/userguide/testing.html 中给出的示例。

Make sure to run tests directly in the same process when running unit-tests.确保在运行单元测试时直接在同一进程中运行测试。

Celery makes it very simple to keep same APIs while running the task "in-sync" and skip the broken/worker part. 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 http://docs.celeryproject.org/en/latest/userguide/configuration.html#task-always-eager

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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