本文介绍了让Celery使用Django的测试数据库,而不需要task_always_eager的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 在使用Celery任务的Django应用程序中运行测试时,我无法完全测试需要从数据库获取数据的任务,因为它们未连接到Django创建的测试数据库。When running tests in Django applications that make use of Celery tasks I can't fully test tasks that need to get data from the database since they don't connect to the test database that Django creates.设置 task_always_eager 在Celery到 True 部分解决了这个问题,但作为用于测试的文档说,这并不能完全反映代码如何在真正的Celery工作人员上运行,并不适合测试。Setting task_always_eager in Celery to True partially solves this problem but as the documentation for testing says, this doesn't fully reflect how the code will run on a real Celery worker and isn't suitable for testing.如果在没有设置的情况下运行Django测试时,如何使Celery任务使用Django测试数据库task_always_eager = True ?推荐答案 Short =您必须像生产中一样运行芹菜工作Short = You must run celery worker as in production简单: 使用专用的st db(如生产中) 配置芹菜以使用 在运行测试之前手动启动芹菜工人高级: 使用自动创建的测试数据库(可能是sqlite) 在您的测试中运行芹菜工作setUp() 配置芹菜以使用自动创建的测试数据库(从测试中复制django.conf.settings.DATABASE芹菜的过程)总是你必须为芹菜提供消息代理。And always you must provide message broker for celery.我有一个测试,需要专门的芹菜工作者检查我的代码,通过芹菜任务和调用代码之间的消息: https://gist.github.com/Sovetnikov/a7ad982fc77e8dfbc528bfc20fcf3b1e 这个python模块是两个 - 一个具有自包含配置的TestUnit和芹菜工作者运行器。I have a test that requires dedicated celery worker to check my code that passes messages between celery task and calling code:https://gist.github.com/Sovetnikov/a7ad982fc77e8dfbc528bfc20fcf3b1eThis python module is two in one - a TestUnit and celery worker runner with self contained configuration.我的代码不使用任何数据库,但哟你可以很容易地适应你的需要。只需将django.conf.settings.DATABASE(作为json或pickle或任何您喜欢的方法)传递给芹菜启动器代码,并将Django DATABASE配置为指向测试数据库。My code does not utilize any db, but you can easily adapt it to your need. Just pass django.conf.settings.DATABASE (as json or pickle or whatever you like method) to celery starter code and configure Django DATABASE to point to test db. 附加信息: 这种情况有完整的解决方案 https://github.com/RentMethod/celerytest (我尝试一些旧版本,没有运气,因为它使用线程,与python GIL ...,我认为这是过于复杂的)There is complete solution for this case https://github.com/RentMethod/celerytest (i triedsome old version of it and have no luck because it uses threads, with python GIL ... and i think it is over-complicated)示例代码,如何配置DATABASE设置和init django本身在单个模块 https://gist.github.com/Sovetnikov/369a8d05ba2b6482fa20769bc498f122Sample code, how to configure DATABASE settings and init django itself in single module https://gist.github.com/Sovetnikov/369a8d05ba2b6482fa20769bc498f122 这篇关于让Celery使用Django的测试数据库,而不需要task_always_eager的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-13 16:02