flask-testing icon indicating copy to clipboard operation
flask-testing copied to clipboard

g fields persist across requests

Open mephi42 opened this issue 2 years ago • 0 comments

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'

mephi42 avatar Dec 05 '22 19:12 mephi42