diff options
| author | Nick Pope <nick@nickpope.me.uk> | 2023-08-23 10:58:17 +0100 |
|---|---|---|
| committer | Mariusz Felisiak <felisiak.mariusz@gmail.com> | 2023-09-13 08:30:21 +0200 |
| commit | fe19b33e2f76045617067dd5123041ae4d3a91ee (patch) | |
| tree | 4246376602ed64f24ae4a4a2537ce5f0f88cc8a5 /tests | |
| parent | 170b0a47b09d735132bcfdcc9b303397eb03b34b (diff) | |
Modernized enumeration helpers on Python 3.11+.
- use @enum.property
https://docs.python.org/3/library/enum.html#enum.property
- use @enum.nonmember
Using @property on an enum class does not yield the expected result.
do_not_call_in_templates attribute works because a @property instance
is truthy. We can make this a literal True value as expected by using
@enum.nonmember in Python 3.11+.
https://docs.python.org/3/library/enum.html#enum.nonmember
- used enum.IntEnum/StrEnum
Python 3.11+ has ReprEnum which uses int.__str__() and str.__str__()
for __str__() in the `IntEnum` and `StrEnum` subclasses. We can emulate
that for Python < 3.11.
https://docs.python.org/3/library/enum.html#enum.ReprEnum
https://docs.python.org/3/library/enum.html#enum.IntEnum
https://docs.python.org/3/library/enum.html#enum.StrEnum
Diffstat (limited to 'tests')
| -rw-r--r-- | tests/model_enums/tests.py | 12 |
1 files changed, 12 insertions, 0 deletions
diff --git a/tests/model_enums/tests.py b/tests/model_enums/tests.py index 264a4b1703..32f0ad3668 100644 --- a/tests/model_enums/tests.py +++ b/tests/model_enums/tests.py @@ -9,6 +9,7 @@ from django.test import SimpleTestCase from django.utils.deprecation import RemovedInDjango60Warning from django.utils.functional import Promise from django.utils.translation import gettext_lazy as _ +from django.utils.version import PY311 class Suit(models.IntegerChoices): @@ -187,6 +188,7 @@ class ChoicesTests(SimpleTestCase): def test_do_not_call_in_templates_member(self): # do_not_call_in_templates is not implicitly treated as a member. Special = models.IntegerChoices("Special", "do_not_call_in_templates") + self.assertIn("do_not_call_in_templates", Special.__members__) self.assertEqual( Special.do_not_call_in_templates.label, "Do Not Call In Templates", @@ -197,6 +199,16 @@ class ChoicesTests(SimpleTestCase): "do_not_call_in_templates", ) + def test_do_not_call_in_templates_nonmember(self): + self.assertNotIn("do_not_call_in_templates", Suit.__members__) + if PY311: + self.assertIs(Suit.do_not_call_in_templates, True) + else: + # Using @property on an enum does not behave as expected. + self.assertTrue(Suit.do_not_call_in_templates) + self.assertIsNot(Suit.do_not_call_in_templates, True) + self.assertIsInstance(Suit.do_not_call_in_templates, property) + class Separator(bytes, models.Choices): FS = b"\x1c", "File Separator" |
