task里可以使用always语句吗_让Celery使用Django的测试数据库,而不需要task_always_eager...

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.

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.

How can I make Celery tasks use the Django test database when running Django tests without setting task_always_eager = True?

解决方案

Short = You must run celery worker as in production

Easy:

Use dedicated test db (as in production)

Configure celery to use it

Start celery worker manually before you run tests

Advanced:

Use auto created test db (it may be sqlite)

Run celery worker in your test setUp()

Configure celery to use auto created test db (copy django.conf.settings.DATABASE from test process to celery)

And always you must provide message broker for celery.

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/a7ad982fc77e8dfbc528bfc20fcf3b1e

This python module is two in one - a TestUnit and celery worker runner with self contained configuration.

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.

Additional info:

There is complete solution for this case https://github.com/RentMethod/celerytest (i tried

some old version of it and have no luck because it uses threads, with python GIL ... and i think it is over-complicated)

Sample code, how to configure DATABASE settings and init django itself in single module https://gist.github.com/Sovetnikov/369a8d05ba2b6482fa20769bc498f122

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值