diff --git a/src/apps/lyric/templatetags/__init__.py b/src/apps/lyric/templatetags/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/apps/lyric/templatetags/lyric_extras.py b/src/apps/lyric/templatetags/lyric_extras.py new file mode 100644 index 0000000..cf9df4e --- /dev/null +++ b/src/apps/lyric/templatetags/lyric_extras.py @@ -0,0 +1,26 @@ +from django import template + +register = template.Library() + + +def truncate_email(email): + local, domain = email.split("@", 1) + domain_name, domain_tld = domain.rsplit(".", 1) + + def truncate_segment(segment, n=2): + return segment[:n] + "…" + segment[-n:] + + if len(local) >= 8: + local = truncate_segment(local) + if len(domain_name) >= 6: + domain_name = truncate_segment(domain_name, 1) + + return local + "@" + domain_name + "." + domain_tld + +@register.filter +def display_name(user): + if user is None: + return "" + if user.username: + return user.username + return truncate_email(user.email) diff --git a/src/apps/lyric/tests/unit/test_templatetags.py b/src/apps/lyric/tests/unit/test_templatetags.py new file mode 100644 index 0000000..67ef906 --- /dev/null +++ b/src/apps/lyric/tests/unit/test_templatetags.py @@ -0,0 +1,36 @@ +from django.test import SimpleTestCase +from unittest.mock import Mock + +from apps.lyric.templatetags.lyric_extras import display_name, truncate_email + + +class TruncateEmailTest(SimpleTestCase): + def test_truncates_neither_short_local_nor_short_domain(self): + self.assertEqual(truncate_email("abc@d.e"), "abc@d.e") + + def test_truncates_only_long_local_not_short_domain(self): + self.assertEqual(truncate_email("sesquipedalian@abc.de"), "se…an@abc.de") + + def test_truncates_not_short_local_only_long_domain(self): + self.assertEqual(truncate_email("abc@longexample.com"), "abc@l…e.com") + + def test_truncates_both_long_local_and_long_domain(self): + self.assertEqual(truncate_email("onomatopoeia@earthmanrpg.com"), "on…ia@e…g.com") + + def test_boundary_case_longish_segments_no_truncate(self): + self.assertEqual(truncate_email("abcdefg@gmail.com"), "abcdefg@gmail.com") + + def test_boundary_case_exact_segments_do_truncate(self): + self.assertEqual(truncate_email("abcdefgh@icloud.com"), "ab…gh@i…d.com") + +class DisplayNameFilterTest(SimpleTestCase): + def test_returns_empty_string_for_none_user(self): + self.assertEqual(display_name(None), "") + + def test_returns_truncated_email_when_no_username(self): + user = Mock(username="", email="sesquipedalian@abc.de") + self.assertEqual(display_name(user), "se…an@abc.de") + + def test_returns_username_when_set(self): + user = Mock(username="earthman", email="sesquipedalian@abc.de") + self.assertEqual(display_name(user), "earthman")