Get IP Address when testing flask application through nosetests
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(...)