Get IP Address when testing flask application through nosetests

时间秒杀一切 提交于 2019-11-30 08:16:57

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()

A friend gave me this solution, which works across all requests:

class myProxyHack(object):

    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        environ['REMOTE_ADDR'] = environ.get('REMOTE_ADDR', '127.0.0.1')
        return self.app(environ, start_response)

app.wsgi_app = myProxyHack(app.wsgi_app)

app.test_client().post(...)

You can also pass a header param to the test_request_context if you prefer.

Example:

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_headers(self):
        user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:52.0) Gecko/20100101 Firefox/52.0"
        ip_address = 127.0.0.1
        headers = {
            'Remote_Addr': ip_address,
            'User_Agent': user_agent
        }

        with self.test_request_context(headers=headers):
            # Do something
            pass

This is useful when you need to perform several unit tests using the request object in other modules.

See the test_request_context documentation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!