feat(i18n): francais comme langue principale, anglais accessible

Le site s'affiche desormais en francais par defaut, avec un selecteur de
langue permettant de basculer vers l'anglais.

Choix de conception : les chaines sources restent en anglais
  Elles servent d'identifiants gettext, et le francais est fourni par
  catalogue avec BABEL_DEFAULT_LOCALE = 'fr'. Le code reste ainsi dans une
  seule langue -- la meme que ses commentaires et docstrings -- tandis que
  ce qu'un membre voit est du francais.

  Consequence qui rend la migration praticable : une chaine non encore
  traduite retombe en anglais, pas sur un identifiant brut. Les gabarits
  peuvent donc etre migres un par un sans jamais laisser le site a moitie
  casse.

Selection de la langue (app/i18n.py)
  1. choix explicite via le selecteur, garde en session
  2. sinon en-tete Accept-Language du navigateur, restreint a fr et en
  3. sinon francais
  Un choix explicite prime toujours, y compris sur un navigateur anglophone.

Selecteur
  Extrait en partiel et inclus dans les deux branches de la mise en page :
  barre laterale une fois connecte, ET page d'authentification. Quelqu'un
  qui ne lit pas la langue courante doit pouvoir en changer AVANT de se
  connecter -- le laisser derriere l'authentification aurait ete un defaut
  d'accessibilite. Chaque langue est ecrite dans sa propre langue.

  La route /lang/<locale> valide le Referer avant de rediriger : sans ce
  controle, elle constituait une redirection ouverte.

Migre dans cette passe
  navigation complete, page de connexion, les cinq pages d'erreur, et
  l'integralite des messages flash de routes/auth.py. 64 chaines, dont
  aucune non traduite.

Verification
  25 tests, dont deux garde-fous d'integrite : un catalogue .mo manquant
  ou une entree non traduite font echouer la suite. Sans cela, une
  compilation oubliee servirait de l'anglais partout, en silence et sans
  rien dans les journaux.

Un test existant a du etre corrige, et c'est instructif
  test_login_failure_message_does_not_reveal_account_existence cherchait la
  sous-chaine anglaise 'attempt(s) remaining'. La page etant desormais en
  francais, elle etait absente des deux cotes, l'assertion passait, et le
  mode strict a signale le faux succes. Le test comparait donc l'anglais,
  pas le comportement. Il compare desormais les messages flash rendus,
  quelle que soit la langue. La faille SEC-AUTH-006 reste ouverte, et le
  test la documente toujours.

Les catalogues .po ET .mo sont versionnes : le deploiement est un simple
miroir de fichiers, sans etape de compilation. messages.pot, regenerable,
ne l'est pas.

docs/translations.md documente le processus, les deux pieges (concatenation
de phrases, traduction a l'import), et l'etat de la migration. A noter pour
la suite : les chaines dans les blocs <script> ne peuvent pas etre balisees
telles quelles, il faudra les passer par des attributs data- -- ce qui
rejoint le chantier de sortie de unsafe-inline (OPS-010).

Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
GGThed
2026-08-07 20:31:25 -04:00
co-authored by Claude Opus 5
parent afab7070fb
commit a92600c305
24 changed files with 1318 additions and 83 deletions
+202
View File
@@ -0,0 +1,202 @@
"""Language selection and translation.
French is the primary language of the site; English stays available.
Source strings remain in English and act as gettext message ids, with the
French wording supplied by a catalogue. A string not yet translated
degrades to English rather than to a raw identifier — which is what lets
the migration proceed template by template without ever leaving the site
half broken.
"""
import pytest
from app.i18n import DEFAULT_LOCALE, SUPPORTED_LOCALES, select_locale
class TestDefaults:
def test_french_is_the_default_language(self):
assert DEFAULT_LOCALE == 'fr'
def test_english_is_available(self):
assert 'en' in SUPPORTED_LOCALES
def test_a_visitor_without_preferences_gets_french(self, client):
body = client.get('/auth/login').get_data(as_text=True)
assert 'lang="fr"' in body
assert 'Se connecter' in body
def test_the_html_lang_attribute_follows_the_locale(self, client):
english = client.get('/auth/login',
headers={'Accept-Language': 'en-CA,en;q=0.9'})
assert 'lang="en"' in english.get_data(as_text=True)
class TestBrowserNegotiation:
def test_an_english_browser_is_served_english(self, client):
body = client.get('/auth/login',
headers={'Accept-Language': 'en-CA,en;q=0.9'}
).get_data(as_text=True)
assert 'Sign In' in body
def test_an_unsupported_language_falls_back_to_french(self, client):
body = client.get('/auth/login',
headers={'Accept-Language': 'de-DE,de;q=0.9'}
).get_data(as_text=True)
assert 'Se connecter' in body
def test_a_french_browser_is_served_french(self, client):
body = client.get('/auth/login',
headers={'Accept-Language': 'fr-CA,fr;q=0.9'}
).get_data(as_text=True)
assert 'Se connecter' in body
class TestExplicitSwitch:
def test_switching_to_english_changes_the_page(self, client):
client.get('/lang/en')
body = client.get('/auth/login').get_data(as_text=True)
assert 'Sign In' in body
assert 'lang="en"' in body
def test_an_explicit_choice_overrides_the_browser_header(self, client):
"""Someone on an English machine who picks French must keep French."""
client.get('/lang/fr')
body = client.get('/auth/login',
headers={'Accept-Language': 'en-CA,en;q=0.9'}
).get_data(as_text=True)
assert 'Se connecter' in body
assert 'lang="fr"' in body
def test_the_choice_persists_across_requests(self, client):
client.get('/lang/en')
for _ in range(3):
assert 'Sign In' in client.get('/auth/login').get_data(as_text=True)
def test_an_unsupported_locale_is_refused(self, client):
client.get('/lang/en')
client.get('/lang/de')
body = client.get('/auth/login').get_data(as_text=True)
assert 'Sign In' in body, 'an unsupported code must not change the locale'
def test_the_switcher_redirects_back_to_the_referring_page(self, client):
response = client.get('/lang/en',
headers={'Referer': 'http://localhost/auth/register'},
follow_redirects=False)
assert response.headers['Location'].endswith('/auth/register')
def test_an_external_referer_is_not_followed(self, client):
"""An unchecked Referer would make this an open redirect."""
response = client.get('/lang/en',
headers={'Referer': 'https://evil.test/phishing'},
follow_redirects=False)
assert 'evil.test' not in response.headers['Location']
class TestSwitcherAvailability:
def test_the_switcher_is_visible_before_signing_in(self, client):
"""Someone who cannot read the current language has to be able to
change it without signing in first."""
body = client.get('/auth/login').get_data(as_text=True)
assert 'English' in body
assert '/lang/en' in body
def test_the_switcher_is_visible_once_signed_in(self, client, as_role):
as_role('player')
body = client.get('/users/profile').get_data(as_text=True)
assert 'English' in body
assert '/lang/en' in body
def test_each_language_is_named_in_its_own_language(self, client):
body = client.get('/auth/login').get_data(as_text=True)
assert 'English' in body
client.get('/lang/en')
body = client.get('/auth/login').get_data(as_text=True)
assert 'Français' in body
class TestTranslatedContent:
def test_navigation_is_translated(self, client, as_role):
as_role('player')
body = client.get('/users/profile').get_data(as_text=True)
assert 'Tableau de bord' in body
assert 'Déconnexion' in body
def test_error_pages_are_translated(self, client):
body = client.get('/no-such-page').get_data(as_text=True)
assert 'Page introuvable' in body
@pytest.mark.parametrize('locale,expected', [
('fr', 'Ce compte a été désactivé.'),
('en', 'This account has been deactivated.'),
])
def test_flash_messages_are_translated(
self, app, client, make_user, login, locale, expected
):
from app.extensions import db
from app.models import User
user_id = make_user('player')
with app.app_context():
user = db.session.get(User, user_id)
user.is_active_account = False
username = user.username
db.session.commit()
client.get(f'/lang/{locale}')
body = login(username).get_data(as_text=True)
assert expected in body
class TestCatalogueIntegrity:
"""A missing compiled catalogue is invisible at runtime: the site simply
serves English everywhere. Worth failing a build over."""
@pytest.mark.parametrize('locale', SUPPORTED_LOCALES)
def test_the_compiled_catalogue_exists(self, locale):
import os
path = os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
'app', 'translations', locale, 'LC_MESSAGES', 'messages.mo',
)
assert os.path.exists(path), (
f'{locale} catalogue is not compiled: run '
'`pybabel compile -d app/translations`'
)
@pytest.mark.parametrize('locale', SUPPORTED_LOCALES)
def test_every_message_is_translated(self, locale):
import io
import os
from babel.messages.pofile import read_po
path = os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
'app', 'translations', locale, 'LC_MESSAGES', 'messages.po',
)
with io.open(path, encoding='utf-8') as handle:
catalog = read_po(handle, locale=locale)
untranslated = [m.id for m in catalog if m.id and not m.string]
assert not untranslated, (
f'{len(untranslated)} untranslated string(s) in {locale}: '
f'{untranslated[:5]}'
)
class TestSelectorUnit:
def test_select_locale_returns_a_supported_code(self, app):
with app.test_request_context('/'):
assert select_locale() in SUPPORTED_LOCALES