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 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
|
import importlib.metadata
from decimal import Decimal
from re import Pattern
from typing import Any, Optional, Union
import pytest
from packaging.version import Version
from pydantic import BaseModel, ValidationError
from pydantic_core._pydantic_core import ArgsKwargs
from pydantic_extra_types.coordinate import Coordinate, Latitude, Longitude
class Coord(BaseModel):
coord: Coordinate
class Lat(BaseModel):
lat: Latitude
class Lng(BaseModel):
lng: Longitude
@pytest.mark.parametrize(
'coord, result, error',
[
# Valid coordinates
((20.0, 10.0), (20.0, 10.0), None),
((-90.0, 0.0), (-90.0, 0.0), None),
(('20.0', 10.0), (20.0, 10.0), None),
((20.0, '10.0'), (20.0, 10.0), None),
((45.678, -123.456), (45.678, -123.456), None),
(('45.678, -123.456'), (45.678, -123.456), None),
(Coordinate(20.0, 10.0), (20.0, 10.0), None),
(Coordinate(latitude=0, longitude=0), (0, 0), None),
(ArgsKwargs(args=()), (0, 0), None),
(ArgsKwargs(args=(1, 0.0)), (1.0, 0), None),
# Decimal test cases
((Decimal('20.0'), Decimal('10.0')), (Decimal('20.0'), Decimal('10.0')), None),
((Decimal('-90.0'), Decimal('0.0')), (Decimal('-90.0'), Decimal('0.0')), None),
((Decimal('45.678'), Decimal('-123.456')), (Decimal('45.678'), Decimal('-123.456')), None),
(Coordinate(Decimal('20.0'), Decimal('10.0')), (Decimal('20.0'), Decimal('10.0')), None),
(Coordinate(latitude=Decimal('0'), longitude=Decimal('0')), (Decimal('0'), Decimal('0')), None),
(ArgsKwargs(args=(Decimal('1'), Decimal('0.0'))), (Decimal('1.0'), Decimal('0.0')), None),
# Invalid coordinates
((), None, 'Field required'), # Empty tuple
((10.0,), None, 'Field required'), # Tuple with only one value
(('ten, '), None, 'string is not recognized as a valid coordinate'),
((20.0, 10.0, 30.0), None, 'Tuple should have at most 2 items'), # Tuple with more than 2 values
(ArgsKwargs(args=(1.0,)), None, 'Input should be a dictionary or an instance of Coordinate'),
(
'20.0, 10.0, 30.0',
None,
'Input should be a dictionary or an instance of Coordinate ',
), # Str with more than 2 values
('20.0, 10.0, 30.0', None, 'Unexpected positional argument'), # Str with more than 2 values
(2, None, 'Input should be a dictionary or an instance of Coordinate'), # Wrong type
],
)
def test_format_for_coordinate(
coord: (Any, Any), result: (Union[float, Decimal], Union[float, Decimal]), error: Optional[Pattern]
):
if error is None:
_coord: Coordinate = Coord(coord=coord).coord
assert _coord.latitude == result[0]
assert _coord.longitude == result[1]
else:
with pytest.raises(ValidationError, match=error):
Coord(coord=coord).coord
@pytest.mark.parametrize(
'coord, error',
[
# Valid coordinates
((-90.0, 0.0), None),
((50.0, 180.0), None),
# Invalid coordinates
((-91.0, 0.0), 'Input should be greater than or equal to -90'),
((50.0, 181.0), 'Input should be less than or equal to 180'),
# Valid Decimal coordinates
((Decimal('-90.0'), Decimal('0.0')), None),
((Decimal('50.0'), Decimal('180.0')), None),
((Decimal('-89.999999'), Decimal('179.999999')), None),
((Decimal('0.0'), Decimal('0.0')), None),
# Invalid Decimal coordinates
((Decimal('-90.1'), Decimal('0.0')), 'Input should be greater than or equal to -90'),
((Decimal('50.0'), Decimal('180.1')), 'Input should be less than or equal to 180'),
((Decimal('90.1'), Decimal('0.0')), 'Input should be less than or equal to 90'),
((Decimal('0.0'), Decimal('-180.1')), 'Input should be greater than or equal to -180'),
],
)
def test_limit_for_coordinate(coord: (Any, Any), error: Optional[Pattern]):
if error is None:
_coord: Coordinate = Coord(coord=coord).coord
assert _coord.latitude == coord[0]
assert _coord.longitude == coord[1]
else:
with pytest.raises(ValidationError, match=error):
Coord(coord=coord).coord
@pytest.mark.parametrize(
'latitude, valid',
[
# Valid latitude
(20.0, True),
(3.0000000000000000000000, True),
(90.0, True),
('90.0', True),
(-90.0, True),
('-90.0', True),
(Decimal('90.0'), True),
(Decimal('-90.0'), True),
# Unvalid latitude
(91.0, False),
(-91.0, False),
(Decimal('91.0'), False),
(Decimal('-91.0'), False),
],
)
def test_format_latitude(latitude: float, valid: bool):
if valid:
_lat = Lat(lat=latitude).lat
assert _lat == float(latitude)
else:
with pytest.raises(ValidationError, match='2 validation errors for Lat'):
Lat(lat=latitude)
@pytest.mark.parametrize(
'longitude, valid',
[
# Valid latitude
(20.0, True),
(3.0000000000000000000000, True),
(90.0, True),
('90.0', True),
(-90.0, True),
('-90.0', True),
(91.0, True),
(-91.0, True),
(180.0, True),
(-180.0, True),
(Decimal('180.0'), True),
(Decimal('-180.0'), True),
# Unvalid latitude
(181.0, False),
(-181.0, False),
(Decimal('181.0'), False),
(Decimal('-181.0'), False),
],
)
def test_format_longitude(longitude: float, valid: bool):
if valid:
_lng = Lng(lng=longitude).lng
assert _lng == float(longitude)
else:
with pytest.raises(ValidationError, match='2 validation errors for Lng'):
Lng(lng=longitude)
def test_str_repr():
# Float tests
assert str(Coord(coord=(20.0, 10.0)).coord) == '20.0,10.0'
assert str(Coord(coord=('20.0, 10.0')).coord) == '20.0,10.0'
assert repr(Coord(coord=(20.0, 10.0)).coord) == 'Coordinate(latitude=20.0, longitude=10.0)'
# Decimal tests
assert str(Coord(coord=(Decimal('20.0'), Decimal('10.0'))).coord) == '20.0,10.0'
assert str(Coord(coord=(Decimal('20.000'), Decimal('10.000'))).coord) == '20.000,10.000'
assert (
repr(Coord(coord=(Decimal('20.0'), Decimal('10.0'))).coord)
== "Coordinate(latitude=Decimal('20.0'), longitude=Decimal('10.0'))"
)
def test_eq():
# Float tests
assert Coord(coord=(20.0, 10.0)).coord != Coord(coord='20.0,11.0').coord
assert Coord(coord=('20.0, 10.0')).coord != Coord(coord='20.0,11.0').coord
assert Coord(coord=('20.0, 10.0')).coord != Coord(coord='20.0,11.0').coord
assert Coord(coord=(20.0, 10.0)).coord == Coord(coord='20.0,10.0').coord
# Decimal tests
assert Coord(coord=(Decimal('20.0'), Decimal('10.0'))).coord == Coord(coord='20.0,10.0').coord
assert Coord(coord=(Decimal('20.0'), Decimal('10.0'))).coord == Coord(coord=(20.0, 10.0)).coord
assert (
Coord(coord=(Decimal('20.0'), Decimal('10.0'))).coord != Coord(coord=(Decimal('20.0'), Decimal('11.0'))).coord
)
assert (
Coord(coord=(Decimal('20.000'), Decimal('10.000'))).coord
== Coord(coord=(Decimal('20.0'), Decimal('10.0'))).coord
)
def test_hashable():
# Float tests
assert hash(Coord(coord=(20.0, 10.0)).coord) == hash(Coord(coord=(20.0, 10.0)).coord)
assert hash(Coord(coord=(20.0, 11.0)).coord) != hash(Coord(coord=(20.0, 10.0)).coord)
# Decimal tests
assert hash(Coord(coord=(Decimal('20.0'), Decimal('10.0'))).coord) == hash(
Coord(coord=(Decimal('20.0'), Decimal('10.0'))).coord
)
assert hash(Coord(coord=(Decimal('20.0'), Decimal('10.0'))).coord) == hash(Coord(coord=(20.0, 10.0)).coord)
assert hash(Coord(coord=(Decimal('20.0'), Decimal('11.0'))).coord) != hash(
Coord(coord=(Decimal('20.0'), Decimal('10.0'))).coord
)
assert hash(Coord(coord=(Decimal('20.000'), Decimal('10.000'))).coord) == hash(
Coord(coord=(Decimal('20.0'), Decimal('10.0'))).coord
)
def test_json_schema():
class Model(BaseModel):
value: Coordinate
decimal_type = {'type': 'string'}
if Version(importlib.metadata.version('pydantic')) >= Version('2.12.0a1'):
decimal_type['pattern'] = '^(?!^[-+.]*$)[+-]?0*\\d*\\.?\\d*$'
assert Model.model_json_schema(mode='validation')['$defs']['Coordinate'] == {
'properties': {
'latitude': {
'anyOf': [{'maximum': 90.0, 'minimum': -90.0, 'type': 'number'}, decimal_type],
'title': 'Latitude',
},
'longitude': {
'anyOf': [{'maximum': 180.0, 'minimum': -180.0, 'type': 'number'}, decimal_type],
'title': 'Longitude',
},
},
'required': ['latitude', 'longitude'],
'title': 'Coordinate',
'type': 'object',
}
assert Model.model_json_schema(mode='validation')['properties']['value'] == {
'anyOf': [
{'$ref': '#/$defs/Coordinate'},
{
'maxItems': 2,
'minItems': 2,
'prefixItems': [
{'anyOf': [{'type': 'number'}, decimal_type]},
{'anyOf': [{'type': 'number'}, decimal_type]},
],
'type': 'array',
},
{'type': 'string'},
],
'title': 'Value',
}
assert Model.model_json_schema(mode='serialization') == {
'$defs': {
'Coordinate': {
'properties': {
'latitude': {
'anyOf': [{'maximum': 90.0, 'minimum': -90.0, 'type': 'number'}, decimal_type],
'title': 'Latitude',
},
'longitude': {
'anyOf': [{'maximum': 180.0, 'minimum': -180.0, 'type': 'number'}, decimal_type],
'title': 'Longitude',
},
},
'required': ['latitude', 'longitude'],
'title': 'Coordinate',
'type': 'object',
}
},
'properties': {'value': {'$ref': '#/$defs/Coordinate', 'title': 'Value'}},
'required': ['value'],
'title': 'Model',
'type': 'object',
}
|