While putting together tests for my Flask app, I have stumbled upon behaviour I can't quite understand. In my tests I'm using approach suggested by Flask documentation for accessing and modifying session
from the tests.
Say I have, really basic, project structure:
root
|-- my_app.py
|-- tests
|-- test_my_app.py
my_app.py
from flask import (
Flask,
session,
request
)
app = Flask(__name__)
app.secret_key = 'bad secret key'
@app.route('/action/', methods=['POST'])
def action():
the_action = request.form['action']
if session.get('test'):
return 'Test is set, action complete.'
else:
return 'Oy vey!'
test_my_app.py
import flask
from unittest import TestCase
import my_app
class TestApp(TestCase):
def setUp(self):
self.test_client = my_app.app.test_client()
def testUnsetKeyViaPostNegative(self):
with self.test_client as client:
response = client.post('/action/')
expected_response = 'Oy vey!'.encode('ascii')
self.assertTrue(expected_response == response.data)
Now, if I run the test it will fail, because response returns 400 Bad Request
. If the_action = request.form['action']
is commended out, everything goes smooth.
The reason I need it there is because there is a logic in app (and subsequently tests), that depends on data
received (which I have omitted for brevity).
I thought changing the_action = request.form['action']
to something like the_action = request.form['action'] or ''
would solve the problem, but it won't. An easy fix to this is to add some stub data
to the post request, like so response = client.post('/action/', data=dict(action='stub'))
It feels to me like I'm missing some important points on how accessing&modifying session from tests work, and thus I'm not able to understand the described behaviour.
What I would like to understand is:
- Why simply getting data from request without adding any other logic (i.e. line
the_action = request.form['action']
causing400 Bad Request
response on emptyPOST
- Why won't
the_action = request.form['action'] or ''
orthe_action = request.form['action'] or 'stub'
solve the problem, seems to me the case is as if empty string or'stub'
was sent viaPOST
?