如何在 huey 任务中进行 mocking/monkey 修补?

How to do mocking/monkey patching in huey tasks?

我想测试一个 huey 任务,需要修补 requests.get

# huey_tasks.py

from huey import RedisHuey

huey = RedisHuey()

@huey.task()
def function():
    import requests
    print(requests.get('http://www.google.com'))

运行测试的文件:

import huey_tasks

@patch('requests.get')
def call_patched(fake_get):
    fake_get.return_value = '1'
    huey_tasks.function()

启动 huey_consumer:huey_tasks.huey -w 10 -l logs/huey.log
运行 测试,但是打补丁没有任何效果。

[2016-01-24 17:01:12,053] INFO:requests.packages.urllib3.connectionpool:Worker-1:Starting new HTTP connection (1): www.google.com
[2016-01-24 17:01:12,562] INFO:requests.packages.urllib3.connectionpool:Worker-1:Starting new HTTP connection (1): www.google.com.sg
<Response[200]>

如果我删除 @huey.task() 装饰器,修补程序会工作并且 1 会被打印出来。

那么我应该如何测试 huey 任务呢?毕竟,我不能每次都删除装饰器,必须有更好的方法。

如果我没看错,这就是你的问题

  • Huey 任务 运行 在单独的消费者进程中

  • 在自己的进程中进行单元测试运行

进程无法模拟或修补另一个进程。要么

  • 创建你的代码路径,这样你就不需要模拟补丁消费者进程......不要直接调用任务,而是让它们成为你可以公开和补丁的函数

  • 运行 huey 在你的测试过程中使用线程

好的,终于找到测试方法了

# huey_tasks.py

def _function():
    import requests
    print(requests.get('http://www.google.com'))

function = huey.task()(_function)
import huey_tasks

重要的部分是先定义实际的任务函数,然后再装饰它。请注意,huey.task 是一个需要参数的装饰器。

@patch('requests.get')
def test_patched(fake_get):
    fake_get.return_value = '1'
    huey_tasks._function()

直接运行测试代码而不启动huey_consumer