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

Incompatibility with flask-babel

Open azmeuk opened this issue 2 years ago • 7 comments

I found an incompatibility when using at the same time flask-babel 4.0.0 and pytest-flask 1.3.0. I am not sure whose responsability it is, maybe both, maybe neither, so I post this issue on both bugtrackers. Here is the link to the issue at flask-babel.

In the following snippet, a dummy view translates a dummy string and returns the current lang code. The lang code is dynamically set by a request argument lang. In this test environment the first visit is successful and sets the lang to fr but the second visit fails and the lang is not set to uk but still is fr.

import pytest
from flask import Flask
from flask import render_template_string
from flask import request
from flask import g
from flask_babel import Babel


def locale_selector():
    if request.args.get("lang"):
        g.lang = request.args["lang"]

    return g.get("lang", "en")


@pytest.fixture
def app():
    app = Flask(__name__)
    Babel(app, locale_selector=locale_selector)

    @app.route("/")
    def index():
        render_template_string("{% trans %}foobar{% endtrans %}")
        return g.get("lang")

    return app


def test_foobar(app):
    client_app = app.test_client()

    res = client_app.get("/?lang=fr")
    assert res.text == "fr"

    res = client_app.get("/?lang=en")
    assert res.text == "en" # This assertion fails

Note that this test fails if pytest-flask is installed in the environment, but passes if pytest-flask is not installed. In production, the behavior is OK too, so there is going on with pytest-flask.

With a little debugging, I can see that the locale_selector method is only called once. That explains why the language stays to fr. Looking closer, it seems that the get_locale method from flask-babel saves the loaded lang in the current context and reuses it on following calls. On different requests the language would indeed be recomputed.

https://github.com/python-babel/flask-babel/blob/a754eade39d9850693dd2b645ae8a2545df7fdf7/flask_babel/init.py#L257-L258

However, as far as I understand, pytest-flask loads a context for the unit tests (so session and g are accessible without loading a new context). That probably makes flask-babel not recomputing the locale, because the same context is used, and leads to my test failing.

Please correct me if my analysis is wrong. I don't know if there is a mis-usage from my side or if the two libraries do not belong together. If they don't, I hope we can find a solution by bringing every one in the same room :)

What do you think?

azmeuk avatar Dec 13 '23 17:12 azmeuk

Thanks to @tkteck insight I could narrow down the test to this:

import pytest
from flask import Flask
from flask import request
from flask import g


@pytest.fixture
def app():
    app = Flask(__name__)

    @app.route("/")
    def index():
        if "lang" not in g:
            g.lang = request.args["lang"]
        return g.get("lang")

    return app


def test_foobar(app):
    client_app = app.test_client()

    res = client_app.get("/?lang=fr")
    assert res.text == "fr"

    res = client_app.get("/?lang=en")
    assert res.text == "en" # This assertion fails

So it seems that g is kept between requests. I could not find any documentation about this behavior. Is this a bug in pytest-flask?

azmeuk avatar Dec 13 '23 20:12 azmeuk

a test request context is automatically pushed, this might throw flask-babel off

however i believe that test client requests ought to happen in a pushed context, so its not clear to me whats going on there

RonnyPfannschmidt avatar Dec 13 '23 20:12 RonnyPfannschmidt

based on https://flask.palletsprojects.com/en/2.3.x/testing/#accessing-and-modifying-the-session i under the impression that the pytest-flask default behaviour is wrong

RonnyPfannschmidt avatar Dec 13 '23 20:12 RonnyPfannschmidt

The code responsible for pushing a new context is this one:

https://github.com/pytest-dev/pytest-flask/blob/f04d3c22463b4bce27631d8a03bdb37cb70cc252/src/pytest_flask/plugin.py#L106-L133

This seems to be on purpose so url_for, g, session etc. are directly available on the test files.

azmeuk avatar Dec 14 '23 08:12 azmeuk

Yes,and based on modern flasks tests utilities,one should use the context Managers for correct control over globals

RonnyPfannschmidt avatar Dec 14 '23 08:12 RonnyPfannschmidt

If flask changed the rules, I wonder if there is a solution that would keep the same behavior in pytest-flask.

Maybe providing g, session and url_for fixtures would fix my situation and be less intrusive? If that solution was considered, I might work on a PR.

azmeuk avatar Dec 14 '23 14:12 azmeuk

Im currently not deeply working with flask, so I am unable to provide a correct assessment of the details

I just inferred from the examples in flask that the tools in pytest-flask are overstepping

I'll send this question towards the flask maintainers

RonnyPfannschmidt avatar Dec 14 '23 14:12 RonnyPfannschmidt