Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change in unit test behavior when using test_client breaks makes tests less realistic #214

Open
jdimmerman opened this issue Jan 23, 2023 · 1 comment

Comments

@jdimmerman
Copy link

As of flask_babel 3.0.0, flask babel locale context is no longer reset between flask test_client requests. Consider the following unit test and config:

Test app has this locale_selector:

from flask import has_request_context, request

def locale_selector():
    if has_request_context():
        return request.accept_languages.best_match(LanguageType)
    return None

and then the test (assuming some basic flask app):

from flask_babel import get_locale

def test_get_locale(app):
    app.test_client.get(url_for("some_blueprint.some_route"), headers={"Accept-Language": "en"})
    assert str(get_locale()) == "en"

    app.test_client.get(url_for("some_blueprint.some_route"), headers={"Accept-Language": "es"})
    assert str(get_locale()) == "es"

This test succeeded in 2.x because get_locale() would call locale_selector on each test. In 3.0.0, the locale remains cached after the first request is made, causing the second assertion to fail.

To make the second test succeed, we can use refresh:

from flask_babel import get_locale, refresh

def test_get_locale(app):
    app.test_client.get(url_for("some_blueprint.some_route"), headers={"Accept-Language": "en"})
    assert str(get_locale()) == "en"

    refresh()

    app.test_client.get(url_for("some_blueprint.some_route"), headers={"Accept-Language": "es"})
    assert str(get_locale()) == "es"

However, this makes the tests more poorly reflect reality.

@jdimmerman
Copy link
Author

This is because the ctx flask_babel now uses is a custom context stored on the flask global g and not the request context (3883ee7). My tests were sharing flask global between requests so I had to add a custom before_request to clear to the tests.

amercader added a commit to ckan/ckan that referenced this issue Mar 14, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant