Skip to content

Instantly share code, notes, and snippets.

@pgjones
Created February 12, 2017 16:00
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pgjones/0bd192d3fae7f6dfadead178dbac0e1e to your computer and use it in GitHub Desktop.
Save pgjones/0bd192d3fae7f6dfadead178dbac0e1e to your computer and use it in GitHub Desktop.
Example of how to use the Flask `test_request_context` with a cookie set
@dgroh
Copy link

dgroh commented Mar 6, 2020

This is great, thanks (even if's 3 years ago).

Do you how to use this with header?

I tried:

header = dump_header('Name', 'value')
with app.test_request_context(environ_base={'HTTP_HEADER': header}):
    assert request.headers['Name'] == 'value'

But it doesn't work, I get:

KeyError: 'HTTP_NAME'

@pgjones
Copy link
Author

pgjones commented Mar 6, 2020

You shouldn't need the dump_header function (for a str value) and you need to change HTTP_HEADER -> HTTP_NAME (WSGI states that HTTP headers are added to the environ with a HTTP_ prefix.

with app.test_request_context(environ_base={'HTTP_NAME': 'value'}):
    assert request.headers['Name'] == 'value'

@dgroh
Copy link

dgroh commented Mar 6, 2020

I could find out, it's called: HTTP_{NAME_OF_THE_KEY}

This means, if my header key is called Access-Token, the code should look like this:

token = 'Tkahsd87z23jnsa,jdJSKHHjka.dsj1981%R'
with app.test_request_context(environ_base={'HTTP_ACCESS_TOKEN': token}):
    assert request.headers['Access-Token'] == token

@alanwilter
Copy link

Hi, I'm trying to login, using a terminal, for testing and debug reasons. All works in a browser but I need to replicate some functions in a terminal (iPython), so I'm doing:

from views import application, autocomplete
ctx = application.test_request_context(path='/login',method='POST', data={'name':'demo','password':'demo123'})
ctx.push()
application.preprocess_request()
query = 'ttll'
autocomplete.autocomplete(query,'gene')

but that fails with:

---------------------------------------------------------------------------
BadRequestKeyError                        Traceback (most recent call last)
<ipython-input-2-2202d00a5413> in <module>
      5 application.preprocess_request()
      6 query = 'ttll'
----> 7 autocomplete.autocomplete(query,'gene')

~/appi/views/auth.py in decorated(*args, **kwargs)
     29             return f(*args, **kwargs)
     30         if request.method == 'POST':
---> 31             username = request.form['user']
     32             password = request.form['password']
     33             if check_auth(username, password):

/usr/local/Caskroom/miniconda/base/lib/python3.7/site-packages/werkzeug/datastructures.py in __getitem__(self, key)
    440             if len(lst) > 0:
    441                 return lst[0]
--> 442         raise exceptions.BadRequestKeyError(key)
    443
    444     def __setitem__(self, key, value):

BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.

@pgjones
Copy link
Author

pgjones commented Jul 12, 2020

At a guess request.form['user'] should be request.form['name'] given {'name':'demo','password':'demo123'}. I'm not really sure what you are doing here though - I've not seen a Flask route invoked by calling it in a test context before.

@alanwilter
Copy link

alanwilter commented Jul 12, 2020

It did work!!! Thanks a lot.

from views import application, autocomplete
ctx = application.test_request_context(path='/login',method='POST', data={'user':'demo','password':'demo123'})
ctx.push()
application.preprocess_request()
query = 'ttll'
autocomplete.autocomplete(query,'gene').json

2020-07-12 13:11:44,523 INFO sqlalchemy.engine.base.Engine SELECT users."user" AS users_user, users.argon_password AS users_argon_password
FROM users
WHERE users."user" = %(user_1)s
2020-07-12 13:11:44,523 INFO sqlalchemy.engine.base.Engine {'user_1': 'demo'}
[D 200712 13:11:44 autocomplete:15] Autocomplete query 'ttll' and query type 'gene'
Out[5]:
['TTLL5',
 'ARPC4-TTLL3',
 'TTLL2',
 'TTLL7-IT1',
 'TTLL1',
 'TTLL10',
 'TTLL3',
 'TTLL6',
 'TTLL10-AS1',
 'TTLL4',
 'TTLL11',
 'TTLL13P',
 'TTLL12',
 'TTLL11-IT1',
 'TTLL8',
 'TTLL9',
 'TTLL7']

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment