File: test_timezone_names.py

package info (click to toggle)
pydantic-extra-types 2.10.5-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 788 kB
  • sloc: python: 4,600; makefile: 46
file content (209 lines) | stat: -rw-r--r-- 6,487 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import re

import pytest
import pytz
from pydantic import BaseModel, ValidationError
from pydantic_core import PydanticCustomError

from pydantic_extra_types.timezone_name import TimeZoneName, TimeZoneNameSettings, timezone_name_settings

has_zone_info = True
try:
    from zoneinfo import available_timezones
except ImportError:
    has_zone_info = False

pytz_zones_bad = [(zone.lower(), zone) for zone in pytz.all_timezones]
pytz_zones_bad.extend([(f' {zone}', zone) for zone in pytz.all_timezones_set])


class TZNameCheck(BaseModel):
    timezone_name: TimeZoneName


@timezone_name_settings(strict=False)
class TZNonStrict(TimeZoneName):
    pass


class NonStrictTzName(BaseModel):
    timezone_name: TZNonStrict


@pytest.mark.parametrize('zone', pytz.all_timezones)
def test_all_timezones_non_strict_pytz(zone):
    assert TZNameCheck(timezone_name=zone).timezone_name == zone
    assert NonStrictTzName(timezone_name=zone).timezone_name == zone


@pytest.mark.parametrize('zone', pytz_zones_bad)
def test_all_timezones_pytz_lower(zone):
    assert NonStrictTzName(timezone_name=zone[0]).timezone_name == zone[1]


def test_fail_non_existing_timezone():
    with pytest.raises(
        ValidationError,
        match=re.escape(
            '1 validation error for TZNameCheck\n'
            'timezone_name\n  '
            'Invalid timezone name. '
            "[type=TimeZoneName, input_value='mars', input_type=str]"
        ),
    ):
        TZNameCheck(timezone_name='mars')

    with pytest.raises(
        ValidationError,
        match=re.escape(
            '1 validation error for NonStrictTzName\n'
            'timezone_name\n  '
            'Invalid timezone name. '
            "[type=TimeZoneName, input_value='mars', input_type=str]"
        ),
    ):
        NonStrictTzName(timezone_name='mars')


if has_zone_info:
    zones = [zone for zone in available_timezones() if zone not in {'Factory', 'localtime'}]
    zones.sort()
    zones_bad = [(zone.lower(), zone) for zone in zones]

    @pytest.mark.parametrize('zone', zones)
    def test_all_timezones_zone_info(zone):
        assert TZNameCheck(timezone_name=zone).timezone_name == zone
        assert NonStrictTzName(timezone_name=zone).timezone_name == zone

    @pytest.mark.parametrize('zone', zones_bad)
    def test_all_timezones_zone_info_NonStrict(zone):
        assert NonStrictTzName(timezone_name=zone[0]).timezone_name == zone[1]


def test_timezone_name_settings_metaclass():
    class TestStrictTZ(TimeZoneName, strict=True, metaclass=TimeZoneNameSettings):
        pass

    class TestNonStrictTZ(TimeZoneName, strict=False, metaclass=TimeZoneNameSettings):
        pass

    assert TestStrictTZ.strict is True
    assert TestNonStrictTZ.strict is False

    # Test default value
    class TestDefaultStrictTZ(TimeZoneName, metaclass=TimeZoneNameSettings):
        pass

    assert TestDefaultStrictTZ.strict is True


def test_timezone_name_validation():
    valid_tz = 'America/New_York'
    invalid_tz = 'Invalid/Timezone'

    assert TimeZoneName._validate(valid_tz, None) == valid_tz

    with pytest.raises(PydanticCustomError):
        TimeZoneName._validate(invalid_tz, None)

    assert TZNonStrict._validate(valid_tz.lower(), None) == valid_tz
    assert TZNonStrict._validate(f' {valid_tz} ', None) == valid_tz

    with pytest.raises(PydanticCustomError):
        TZNonStrict._validate(invalid_tz, None)


def test_timezone_name_pydantic_core_schema():
    schema = TimeZoneName.__get_pydantic_core_schema__(TimeZoneName, None)
    assert isinstance(schema, dict)
    assert schema['type'] == 'function-after'
    assert 'function' in schema
    assert 'schema' in schema
    assert schema['schema']['type'] == 'str'
    assert schema['schema']['min_length'] == 1


def test_timezone_name_pydantic_json_schema():
    core_schema = TimeZoneName.__get_pydantic_core_schema__(TimeZoneName, None)

    class MockJsonSchemaHandler:
        def __call__(self, schema):
            return {'type': 'string'}

    handler = MockJsonSchemaHandler()
    json_schema = TimeZoneName.__get_pydantic_json_schema__(core_schema, handler)
    assert 'enum' in json_schema
    assert isinstance(json_schema['enum'], list)
    assert len(json_schema['enum']) > 0


def test_timezone_name_repr():
    tz = TimeZoneName('America/New_York')
    assert repr(tz) == "'America/New_York'"
    assert str(tz) == 'America/New_York'


def test_timezone_name_allowed_values():
    assert isinstance(TimeZoneName.allowed_values, set)
    assert len(TimeZoneName.allowed_values) > 0
    assert all(isinstance(tz, str) for tz in TimeZoneName.allowed_values)

    assert isinstance(TimeZoneName.allowed_values_list, list)
    assert len(TimeZoneName.allowed_values_list) > 0
    assert all(isinstance(tz, str) for tz in TimeZoneName.allowed_values_list)

    assert isinstance(TimeZoneName.allowed_values_upper_to_correct, dict)
    assert len(TimeZoneName.allowed_values_upper_to_correct) > 0
    assert all(
        isinstance(k, str) and isinstance(v, str) for k, v in TimeZoneName.allowed_values_upper_to_correct.items()
    )


def test_timezone_name_inheritance():
    class CustomTZ(TimeZoneName, metaclass=TimeZoneNameSettings):
        pass

    assert issubclass(CustomTZ, TimeZoneName)
    assert issubclass(CustomTZ, str)
    assert isinstance(CustomTZ('America/New_York'), (CustomTZ, TimeZoneName, str))


def test_timezone_name_string_operations():
    tz = TimeZoneName('America/New_York')
    assert tz.upper() == 'AMERICA/NEW_YORK'
    assert tz.lower() == 'america/new_york'
    assert tz.strip() == 'America/New_York'
    assert f'{tz} Time' == 'America/New_York Time'
    assert tz.startswith('America')
    assert tz.endswith('York')


def test_timezone_name_comparison():
    tz1 = TimeZoneName('America/New_York')
    tz2 = TimeZoneName('Europe/London')
    tz3 = TimeZoneName('America/New_York')

    assert tz1 == tz3
    assert tz1 != tz2
    assert tz1 < tz2  # Alphabetical comparison
    assert tz2 > tz1
    assert tz1 <= tz3
    assert tz1 >= tz3


def test_timezone_name_hash():
    tz1 = TimeZoneName('America/New_York')
    tz2 = TimeZoneName('America/New_York')
    tz3 = TimeZoneName('Europe/London')

    assert hash(tz1) == hash(tz2)
    assert hash(tz1) != hash(tz3)

    tz_set = {tz1, tz2, tz3}
    assert len(tz_set) == 2


def test_timezone_name_slots():
    tz = TimeZoneName('America/New_York')
    with pytest.raises(AttributeError):
        tz.new_attribute = 'test'