django - 如何检测测试环境 [英] django - how to detect test environment

查看:109
本文介绍了django - 如何检测测试环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题似乎很简单,但不幸的是,谷歌很难。



我的问题是这样的:在测试环境中如何检测它是否被检测?




def my_view(request):
如果没有request.is_secure()而不是TEST_ENVIRONMENT:
返回HttpResponseForbidden()


解决方案

将其放在您的settings.py中:

  import sys 

TESTING = len(sys.argv)> 1和sys.argv [1] =='test'

这将测试第二个命令行参数在 ./ manage.py 之后)是 test 。然后,您可以从其他模块访问此变量,如下所示:

 从django.conf导入设置

如果settings.TESTING:
...

有很好的理由这样做:假设您正在访问一些后端服务,而不是Django的模型和数据库连接。那么您可能需要知道何时调用生产服务与测试服务。


The problem seems simple, but unfortunately it's a little hard to google for it.

My question is this: How can I detect inside a view wether it is called in a test environment or not?

#pseudo_code
def my_view(request):
    if not request.is_secure() and not TEST_ENVIRONMENT:
        return HttpResponseForbidden()

解决方案

Put this in your settings.py:

import sys

TESTING = len(sys.argv) > 1 and sys.argv[1] == 'test'

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:
    ...

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天全站免登陆