如何在休伊任务中进行嘲笑/猴子修补?

2024-04-24 12:53:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我想测试一个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'))

运行测试的文件:

^{pr2}$

启动休伊消费者: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()装饰器,修补工作和{}将被打印。在

休伊任务我该怎么测试?毕竟,我不能每次都把装修工都搬走,得有个更好的办法。在


Tags: importinfocomtaskgetpackageswwwgoogle
2条回答

如果我读对了这就是你的问题

  • 休伊任务在单独的使用者进程中运行

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

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

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

  • 使用线程在测试进程中运行huey

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

# huey_tasks.py

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

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

其中最重要的部分是先定义实际任务函数,然后对其进行修饰。注意,huey.task是一个需要参数的修饰符。在

^{pr2}$

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

相关问题 更多 >