Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get IP Address when testing flask application through nosetests

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.

like image 582
moodh Avatar asked Feb 14 '13 10:02

moodh


People also ask

How do I find my remote address in flask?

We access the remote address directly with request. remote_addr , through the REMOTE_ADDR key from request. environ , and in the cases where the user is using a proxy we should check the HTTP_X_FORWARDED_FOR key of request. environ .


2 Answers

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()
like image 65
DazWorrall Avatar answered Oct 20 '22 21:10

DazWorrall


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(...)
like image 40
moodh Avatar answered Oct 20 '22 21:10

moodh