| 1 | import pytest |
| 2 | from flask import request |
| 3 | from wtforms import StringField |
| 4 | from wtforms.validators import DataRequired |
| 5 | from wtforms.validators import Length |
| 6 | |
| 7 | from flask_wtf import FlaskForm |
| 8 | |
| 9 | pytest.importorskip("flask_wtf.i18n", reason="Flask-Babel is not installed.") |
| 10 | |
| 11 | |
| 12 | class NameForm(FlaskForm): |
| 13 | class Meta: |
| 14 | csrf = False |
| 15 | |
| 16 | name = StringField(validators=[DataRequired(), Length(min=8)]) |
| 17 | |
| 18 | |
| 19 | def test_no_extension(app, client): |
| 20 | @app.route("/", methods=["POST"]) |
| 21 | def index(): |
| 22 | form = NameForm() |
| 23 | form.validate() |
| 24 | assert form.name.errors[0] == "This field is required." |
| 25 | |
| 26 | client.post("/", headers={"Accept-Language": "zh-CN,zh;q=0.8"}) |
| 27 | |
| 28 | |
| 29 | def test_i18n(app, client): |
| 30 | try: |
| 31 | from flask_babel import Babel |
| 32 | except ImportError: |
| 33 | pytest.skip("Flask-Babel must be installed.") |
| 34 | |
| 35 | def get_locale(): |
| 36 | return request.accept_languages.best_match(["en", "zh"], "en") |
| 37 | |
| 38 | Babel(app, locale_selector=get_locale) |
| 39 | |
| 40 | @app.route("/", methods=["POST"]) |
| 41 | def index(): |
| 42 | form = NameForm() |
| 43 | form.validate() |
| 44 | |
| 45 | if not app.config.get("WTF_I18N_ENABLED", True): |
| 46 | assert form.name.errors[0] == "This field is required." |
| 47 | elif not form.name.data: |
| 48 | assert form.name.errors[0] == "该字段是必填字段。" |
| 49 | else: |
| 50 | assert form.name.errors[0] == "字段长度必须至少 8 个字符。" |
| 51 | |
| 52 | client.post("/", headers={"Accept-Language": "zh-CN,zh;q=0.8"}) |
| 53 | client.post("/", headers={"Accept-Language": "zh"}, data={"name": "short"}) |
| 54 | app.config["WTF_I18N_ENABLED"] = False |
| 55 | client.post("/", headers={"Accept-Language": "zh"}) |
| 56 | |
| 57 | |
| 58 | def test_outside_request(): |
| 59 | pytest.importorskip("babel") |
| 60 | from flask_wtf.i18n import translations |
| 61 | |
| 62 | s = "This field is required." |
| 63 | assert translations.gettext(s) == s |
| 64 | |
| 65 | ss = "Field must be at least %(min)d character long." |
| 66 | sp = "Field must be at least %(min)d character long." |
| 67 | assert translations.ngettext(ss, sp, 1) == ss |
| 68 | assert translations.ngettext(ss, sp, 2) == sp |