Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting remote_addr in flask test_request_context

How can I set the remote_addr property in a flask test_request_context? This question: Get IP Address when testing flask application through nosetests (and other, similar questions) explains how to do it using the get/post/whatever test client calls, but I'm not using those (in this case). Instead, I get a test_request_context and then call a function, thereby allowing me to test the functions that are called by my view functions individually.

Edit: to clarify, my testing code looks something like this:

with app.test_request_context():
    result=my_function_which_expects_to_be_called_from_a_request_context()
<check result however>

So at no point am I using a test client call.

like image 534
ibrewster Avatar asked Jun 17 '26 21:06

ibrewster


1 Answers

Pass the same arguments to test_request_context as you would to client.get. Both set up the WSGI environment the same way internally.

with app.test_request_context(environ_base={'REMOTE_ADDR': '10.1.2.3'}):
like image 108
davidism Avatar answered Jun 19 '26 12:06

davidism