jarus / flask-testing

Unittest extensions for Flask
http://pythonhosted.org/Flask-Testing/
Other
501 stars 110 forks source link

g fields persist across requests #156

Open mephi42 opened 1 year ago

mephi42 commented 1 year ago

Consider the following app:

import unittest

from flask import Flask, g, request
from flask_testing.utils import TestCase

def create_app():
    app = Flask(__name__)

    @app.route('/', methods=['POST'])
    def index():
        try:
            result = g.dejavu
        except AttributeError:
            result = '?'
        g.dejavu = request.json['dejavu']
        return result

    return app

app = create_app()

class MyTestCase(TestCase):
    def create_app(self):
        return create_app()

    def test(self):
        with self.app.test_client() as client:
            response = client.post('/', json={'dejavu': '42'})
            self.assert200(response)
            self.assertEqual(b'?', response.data)
            response = client.post('/', json={'dejavu': '42'})
            self.assert200(response)
            self.assertEqual(b'?', response.data)

if __name__ == '__main__':
    unittest.main()

flask --app foo run works as expected:

$ curl http://127.0.0.1:5000 -H 'Content-Type: application/json' --data '{"dejavu": 42}'
?
$ curl http://127.0.0.1:5000 -H 'Content-Type: application/json' --data '{"dejavu": 42}'
?

However, the respective test fails:

$ python3 foo.py
# AssertionError: b'?' != b'42'