django-如何检测测试环境(检查/确定是否正在运行测试)
问题描述:
如何检测测试环境中是否正在调用视图(例如,通过 manage.py test
)?
How can I detect whether a view is being called in a test environment (e.g., from manage.py test
)?
#pseudo_code
def my_view(request):
if not request.is_secure() and not TEST_ENVIRONMENT:
return HttpResponseForbidden()
答
将其放入您的settings.py:
Put this in your settings.py:
import sys
TESTING = len(sys.argv) > 1 and sys.argv[1] == 'test'
这将测试第二个命令行参数( ./ manage.py
)之后进行了测试
。然后,您可以从其他模块访问此变量,例如:
This tests whether the second commandline argument (after ./manage.py
) was test
. Then you can access this variable from other modules, like so:
from django.conf import settings
if settings.TESTING:
...
这样做有充分的理由:假设您正在访问某些后端服务,而不是Django的模型和数据库连接。然后,您可能需要知道何时调用生产服务与测试服务。
There are good reasons to do this: suppose you're accessing some backend service, other than Django's models and DB connections. Then you might need to know when to call the production service vs. the test service.