0

I'm working on a program which has a config. I need to use a different config for the tests and the normal running of the program.

I manage all the software and tests using a manage.pyscript and all the tests are under python manage.py test ... (eg: python manage.py test all, python manage.py test db, ...)

To choose the config I did in the __init__.py of the config:

is_testing = sys.argv[1] == 'test'
if is_testing:
    from app.config.own import TestConfig as Config
else:
    from app.config.own import Config

and after I import the config from this file.

But sometime the test runner takes the first place in the argv so the test is in argv[2] or sometimes I run the tests by launching the script directly and not the manage.py.

My question is by which ways can I share a variable across the full codebase?

Thanks.

4

1 回答 1

3

您可以从配置类中完全提取确定配置,并且只需让脚本接受配置路径的 CLI arg 即可执行。这将允许使用任何配置。

python manage.py test --config=import.path.to.settings

然后您必须将配置映射到加载实际模块。Django 用他们的settings文件做这个确切的事情,你可以参考它的实现细节


另外我推荐使用argsparse,这将使您不必处理sys.argv[1]它提供类型强制、文档生成、位置和关键字 arg 支持

于 2015-07-22T15:07:27.463 回答