从测试运行Django管理命令?

时间:2021-01-27 15:43:08

I have a Django management command to create materialized views on my database, that runs as follows (I store my database login details in environment variables):

我有一个Django管理命令来创建我的数据库的物化视图,运行如下(我将我的数据库登录详细信息存储在环境变量中):

python manage.py create_db_matviews $DB_NAME $DB_USER $DB_PASS

The management command code looks like this:

管理命令代码如下所示:

 class Command(BaseCommand):
   def handle(self, *args, **options):
    db_name = args[0]
    db_user = args[1]
    db_pass = args[2]
    self.conn = psycopg2.connect(database=db_name, user=db_user,
                                 password=db_pass)

Now I want to run the management command from inside my tests, so that the materialized views get created on my test data. However this does not work:

现在我想从我的测试中运行管理命令,以便在我的测试数据上创建物化视图。但是这不起作用:

def setUpModule():
    # load fixtures, then... 
    management.call_command('create_db_matviews',
                        ['test', 'test', 'test'], verbosity=0)

It fails as follows:

它失败如下:

.... 
db_user = args[1]
IndexError: tuple index out of range

How can I supply arguments to the management script in the way that it wants?

如何以管理脚本的方式提供参数?

Also, what credentials should I use to get access to the test database?

另外,我应该使用哪些凭据来访问测试数据库?

1 个解决方案

#1


1  

It fails because in tuple of args You set only one argument, with is list of 3 values. You should use:

它失败了,因为在args的元组中你只设置了一个参数,其中包含3个值的列表。你应该使用:

management.call_command('create_db_matviews', 'test', 'test', 'test', verbosity=0)

*agrs is pythons way to send multiple parameters and all of them will be send as tuple. You send (['test', 'test', 'test', ],) so args[0] was ['test', 'test', 'test', ], not 'test'

* agrs是pythons发送多个参数的方式,所有参数都将作为元组发送。你发送(['test','test','test',],所以args [0]是['test','test','test',],而不是'test'

#1


1  

It fails because in tuple of args You set only one argument, with is list of 3 values. You should use:

它失败了,因为在args的元组中你只设置了一个参数,其中包含3个值的列表。你应该使用:

management.call_command('create_db_matviews', 'test', 'test', 'test', verbosity=0)

*agrs is pythons way to send multiple parameters and all of them will be send as tuple. You send (['test', 'test', 'test', ],) so args[0] was ['test', 'test', 'test', ], not 'test'

* agrs是pythons发送多个参数的方式,所有参数都将作为元组发送。你发送(['test','test','test',],所以args [0]是['test','test','test',],而不是'test'