|
5 | 5 | import sys
|
6 | 6 | import uuid
|
7 | 7 | from decimal import ROUND_DOWN, ROUND_UP, Decimal
|
| 8 | +from enum import auto |
8 | 9 | from unittest.mock import patch
|
9 | 10 |
|
10 | 11 | import pytest
|
11 | 12 | import pytz
|
12 | 13 | from django.core.exceptions import ValidationError as DjangoValidationError
|
| 14 | +from django.db.models import IntegerChoices, TextChoices |
13 | 15 | from django.http import QueryDict
|
14 | 16 | from django.test import TestCase, override_settings
|
15 | 17 | from django.utils.timezone import activate, deactivate, override
|
@@ -1824,6 +1826,54 @@ def test_edit_choices(self):
|
1824 | 1826 | field.run_validation(2)
|
1825 | 1827 | assert exc_info.value.detail == ['"2" is not a valid choice.']
|
1826 | 1828 |
|
| 1829 | + def test_integer_choices(self): |
| 1830 | + class ChoiceCase(IntegerChoices): |
| 1831 | + first = auto() |
| 1832 | + second = auto() |
| 1833 | + # Enum validate |
| 1834 | + choices = [ |
| 1835 | + (ChoiceCase.first, "1"), |
| 1836 | + (ChoiceCase.second, "2") |
| 1837 | + ] |
| 1838 | + |
| 1839 | + field = serializers.ChoiceField(choices=choices) |
| 1840 | + assert field.run_validation(1) == 1 |
| 1841 | + assert field.run_validation(ChoiceCase.first) == 1 |
| 1842 | + assert field.run_validation("1") == 1 |
| 1843 | + |
| 1844 | + choices = [ |
| 1845 | + (ChoiceCase.first.value, "1"), |
| 1846 | + (ChoiceCase.second.value, "2") |
| 1847 | + ] |
| 1848 | + |
| 1849 | + field = serializers.ChoiceField(choices=choices) |
| 1850 | + assert field.run_validation(1) == 1 |
| 1851 | + assert field.run_validation(ChoiceCase.first) == 1 |
| 1852 | + assert field.run_validation("1") == 1 |
| 1853 | + |
| 1854 | + def test_text_choices(self): |
| 1855 | + class ChoiceCase(TextChoices): |
| 1856 | + first = auto() |
| 1857 | + second = auto() |
| 1858 | + # Enum validate |
| 1859 | + choices = [ |
| 1860 | + (ChoiceCase.first, "first"), |
| 1861 | + (ChoiceCase.second, "second") |
| 1862 | + ] |
| 1863 | + |
| 1864 | + field = serializers.ChoiceField(choices=choices) |
| 1865 | + assert field.run_validation(ChoiceCase.first) == "first" |
| 1866 | + assert field.run_validation("first") == "first" |
| 1867 | + |
| 1868 | + choices = [ |
| 1869 | + (ChoiceCase.first.value, "first"), |
| 1870 | + (ChoiceCase.second.value, "second") |
| 1871 | + ] |
| 1872 | + |
| 1873 | + field = serializers.ChoiceField(choices=choices) |
| 1874 | + assert field.run_validation(ChoiceCase.first) == "first" |
| 1875 | + assert field.run_validation("first") == "first" |
| 1876 | + |
1827 | 1877 |
|
1828 | 1878 | class TestChoiceFieldWithType(FieldValues):
|
1829 | 1879 | """
|
|
0 commit comments