django-如何检测测试环境(检查/确定是否正在运行测试) [英] django - how to detect test environment (check / determine if tests are being run)

查看:268
本文介绍了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.

这篇关于django-如何检测测试环境(检查/确定是否正在运行测试)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆