From 3bfb50b9c542f85851da090e3db842648f04e032 Mon Sep 17 00:00:00 2001 From: Benjamin Dauvergne Date: Wed, 15 Apr 2020 11:25:24 +0200 Subject: [PATCH 1/4] utils: add a lazy_join function (#41342) Use it to join translated strings. --- src/authentic2/utils/lazy.py | 26 ++++++++++++++++++++++++++ tests/test_utils.py | 18 ++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 src/authentic2/utils/lazy.py diff --git a/src/authentic2/utils/lazy.py b/src/authentic2/utils/lazy.py new file mode 100644 index 00000000..0e5fea9d --- /dev/null +++ b/src/authentic2/utils/lazy.py @@ -0,0 +1,26 @@ +# authentic2 - versatile identity manager +# Copyright (C) 2010-2020 Entr'ouvert +# +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU Affero General Public License as published +# by the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . + +from django.utils.text import format_lazy + + +def lazy_join(join, args): + if not args: + return '' + + fstring = '{}' + ''.join([join + '{}'] * (len(args) - 1)) + return format_lazy(fstring, *args) + diff --git a/tests/test_utils.py b/tests/test_utils.py index ce803b98..73371307 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -18,6 +18,7 @@ from django.contrib.auth.middleware import AuthenticationMiddleware from django.contrib.sessions.middleware import SessionMiddleware from django.core import mail +from django.utils.functional import lazy from django_rbac.utils import get_ou_model @@ -25,6 +26,7 @@ from authentic2.utils import (good_next_url, same_origin, select_next_url, user_can_change_password, login, get_authentication_events, authenticate, send_templated_mail) +from authentic2.utils.lazy import lazy_join def test_good_next_url(db, rf, settings): @@ -155,3 +157,19 @@ def test_send_templated_mail_template_selection(simple_user): sent_mail = mail.outbox.pop() assert sent_mail.subject == specific_template_ou assert sent_mail.body == specific_template_ou + + +def test_lazy_join(): + a = 'a' + + def f(): + return a + f = lazy(f, str) + + joined = lazy_join(',', ['a', f()]) + + assert str(joined) == 'a,a' + + a = 'b' + + assert str(joined) == 'a,b' -- 2.24.0