通过鼻子测试来测试瓶子的应用时获取IP地址 [英] Get IP Address when testing flask application through nosetests

查看:149
本文介绍了通过鼻子测试来测试瓶子的应用时获取IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序依赖 request.remote_addr 这是当我通过鼻测试运行测试时,使用 app.test_client()。post('/ users / login',....)

我可以模拟一个IP(127.0.0.1工作正常),当我运行测试?
我已经尝试设置环境变量,用post()方法发送标题,我已经通过nosetests, werkzeugs和烧瓶的文档,但没有我试过的工作。

解决方案

您可以设置选项为基础的Werkzeug环境使用 environ_base

  from flask import Flask,request 
import unittest
$ b app = Flask(__ name__)
app.debug = True
app.testing = True

@ app.route('/')
def index():
return str(request.remote_addr)
$ b $ class TestApp(unittest.TestCase):

def test_remote_addr(self):
c = app.test_client()
resp = c.get('/',environ_base = {'REMOTE_ADDR':'127.0.0.1'})
self。 assertEqual('127.0.0.1',resp.data)


if __name__ =='__main__':
unittest.main()


My application depends on request.remote_addr which is None when i run tests through nosetests which uses app.test_client().post('/users/login', ....).

How can I emulate an IP (127.0.0.1 works fine) when I run tests? I've tried setting environment variables, sent in headers with the post() method and I've digged through nosetests, werkzeugs and flasks documentation but nothing I've tried has worked.

解决方案

You can set options for the underlying Werkzeug environment using environ_base:

from flask import Flask, request
import unittest

app = Flask(__name__)
app.debug = True
app.testing = True

@app.route('/')
def index():
    return str(request.remote_addr)

class TestApp(unittest.TestCase):

    def test_remote_addr(self):
        c = app.test_client()
        resp = c.get('/', environ_base={'REMOTE_ADDR': '127.0.0.1'})
        self.assertEqual('127.0.0.1', resp.data)


if __name__ == '__main__':
    unittest.main()

这篇关于通过鼻子测试来测试瓶子的应用时获取IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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