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

后端 未结 5 1851
悲&欢浪女
悲&欢浪女 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条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-29 18:21

    The Django documentation on the call_command fails to mention that out must be redirected to sys.stdout. The example code should read:

    from django.core.management import call_command
    from django.test import TestCase
    from django.utils.six import StringIO
    import sys
    
    class ClosepollTest(TestCase):
        def test_command_output(self):
            out = StringIO()
            sys.stdout = out
            call_command('closepoll', stdout=out)
            self.assertIn('Expected output', out.getvalue())
    

提交回复
热议问题