How can I call a custom Django manage.py command directly from a test driver?

后端 未结 5 1854
悲&欢浪女
悲&欢浪女 2020-11-29 17:30

I want to write a unit test for a Django manage.py command that does a backend operation on a database table. How would I invoke the management command directly from code?

5条回答
  •  猫巷女王i
    2020-11-29 18:29

    The best way to test such things - extract needed functionality from command itself to standalone function or class. It helps to abstract from "command execution stuff" and write test without additional requirements.

    But if you by some reason cannot decouple logic form command you can call it from any code using call_command method like this:

    from django.core.management import call_command
    
    call_command('my_command', 'foo', bar='baz')
    

提交回复
热议问题