如何知道在django中运行单元测试的环境

时间:2016-07-24 12:41:35

标签: python django unit-testing

问题

我想将我的prod设置与我的本地设置分开。我发现这个库django-split-settings很好用。

然而,在我的代码的某处,我有类似的东西:

if settings.DEBUG:

  # do debug stuff
else:
  # do prod stuff

问题是当我运行我的单元测试命令时:

./run ./manage.py test

以上if语句将settings.DEBUG评估为false。这让我想知道,哪个设置文件是读取的测试命令以及如何纠正它

我尝试了什么

我尝试运行这样的命令:

./run ./manage.py test --settings=bx/settings

让我崩溃:

Traceback (most recent call last):
  File "./manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/beneple/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line
    utility.execute()
  File "/beneple/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 302, in execute
    settings.INSTALLED_APPS
  File "/beneple/venv/local/lib/python2.7/site-packages/django/conf/__init__.py", line 55, in __getattr__
    self._setup(name)
  File "/beneple/venv/local/lib/python2.7/site-packages/django/conf/__init__.py", line 43, in _setup
    self._wrapped = Settings(settings_module)
  File "/beneple/venv/local/lib/python2.7/site-packages/django/conf/__init__.py", line 99, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
ImportError: Import by filename is not supported.

任何想法?

更新

这是我的运行命令的样子

#!/usr/bin/env bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
docker run \
  --env "PATH=/beneple/venv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" \
  -e "DJANGO_SETTINGS_MODULE=bx.settings.local" \
  --link beneple_db:db \
  -v $DIR:/beneple \
  -t -i --rm \
  beneple/beneple \
  $@

目前我的manage.py看起来像这样

#!/usr/bin/env python
import os
import sys

    if __name__ == "__main__":

        from django.core.management import execute_from_command_line

        execute_from_command_line(sys.argv)

如果我运行此命令:

./run ./manage.py shell

它工作正常..但例如当我尝试运行

./run ./flu.sh 

反过来运行test_data.py,它开始如下:

#!/usr/bin/env python
if __name__ == "__main__":
    import os, sys
    sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

    import django
    django.setup()


..
from django.conf import settings
from settings import DOMAIN

它给了我错误:

Traceback (most recent call last):
  File "./bx/test_data.py", line 18, in <module>
    from settings import DOMAIN
ImportError: cannot import name DOMAIN
Done.

我不确定为什么会发生这种情况,因为我的base.py肯定有DOMAIN设置。

2 个答案:

答案 0 :(得分:0)

--settingsThe Python path to a settings module。所以bx是你的根项目文件夹,然后是settings.py文件

  

./ run ./manage.py test --settings =“bx”

答案 1 :(得分:0)