Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_number_ge():
class Model(BaseModel):
a: conint(ge=0) = 0
assert Model(a=0).dict() == {'a': 0}
message = base_message.format(msg='greater than or equal to 0', ty='ge', value=0)
with pytest.raises(ValidationError, match=message):
Model(a=-1)
def test_validation_error(result, expected):
class SubModel(BaseModel):
x: int
y: int
z: str
class Model(BaseModel):
a: int
b: SubModel
c: List[SubModel]
d: Union[int, UUID]
e: Dict[int, str]
f: List[Union[int, str]]
g: UUID1
h: conint(gt=42)
class Config:
error_msg_templates = {'value_error.number.not_gt': 'yet another error message template {limit_value}'}
with pytest.raises(ValidationError) as exc_info:
Model.parse_obj(
{
'a': 'not_int',
'b': {'y': 42},
'c': [{'x': 'not_int', 'y': 42, 'z': 'string'}],
'd': 'string',
'e': {'not_int': 'string'},
'f': [None],
'g': uuid4(),
'h': 21,
}
def test_number_multiple_of_int_valid(value):
class Model(BaseModel):
a: conint(multiple_of=5)
assert Model(a=value).dict() == {'a': value}
def test_int_validation():
class Model(BaseModel):
a: PositiveInt = None
b: NegativeInt = None
c: conint(gt=4, lt=10) = None
d: conint(ge=0, le=10) = None
e: conint(multiple_of=5) = None
m = Model(a=5, b=-5, c=5, d=0, e=25)
assert m == {'a': 5, 'b': -5, 'c': 5, 'd': 0, 'e': 25}
with pytest.raises(ValidationError) as exc_info:
Model(a=-5, b=5, c=-5, d=11, e=42)
assert exc_info.value.errors() == [
{
'loc': ('a',),
'msg': 'ensure this value is greater than 0',
'type': 'value_error.number.not_gt',
'ctx': {'limit_value': 0},
},
{
'loc': ('b',),
return raw_json_response(json_str)
@is_admin_or_host
async def event_updates_sent(request):
event_id = await _check_event_permissions(request)
json_str = await request['conn'].fetchval(event_updates_sent_sql, event_id)
return raw_json_response(json_str)
class SetTicketTypes(UpdateView):
class Model(BaseModel):
class TicketType(BaseModel):
name: str
id: int = None
slots_used: conint(ge=1)
active: bool
price: condecimal(ge=1, max_digits=6, decimal_places=2) = None
@validator('active', pre=True)
def none_bool(cls, v):
return v or False
ticket_types: List[TicketType]
@validator('ticket_types', whole=True)
def check_ticket_types(cls, v):
if sum(tt.active for tt in v) < 1:
raise ValueError('at least 1 ticket type must be active')
return v
async def check_permissions(self):
from pydantic import conint, BaseModel
class Post(BaseModel):
age: conint(gt=0)
name: str
from pydantic import BaseModel, conint
from boucanpy.core import DnsRecordStr
class DnsRecordCreateForm(BaseModel):
record: DnsRecordStr
sort: conint(ge=0, le=1024)
zone_id: int
class DnsRecordForZoneCreateForm(BaseModel):
record: DnsRecordStr
sort: conint(ge=0, le=1024)
class Model(BaseModel):
cos_function: PyObject = None
path_to_something: Path = None
path_to_file: FilePath = None
path_to_directory: DirectoryPath = None
short_bytes: conbytes(min_length=2, max_length=10) = None
strip_bytes: conbytes(strip_whitespace=True)
short_str: constr(min_length=2, max_length=10) = None
regex_str: constr(regex='apple (pie|tart|sandwich)') = None
strip_str: constr(strip_whitespace=True)
big_int: conint(gt=1000, lt=1024) = None
mod_int: conint(multiple_of=5) = None
pos_int: PositiveInt = None
neg_int: NegativeInt = None
big_float: confloat(gt=1000, lt=1024) = None
unit_interval: confloat(ge=0, le=1) = None
mod_float: confloat(multiple_of=0.5) = None
pos_float: PositiveFloat = None
neg_float: NegativeFloat = None
short_list: conlist(int, min_items=1, max_items=4)
email_address: EmailStr = None
email_and_name: NameEmail = None
password: SecretStr = None
password_bytes: SecretBytes = None
Street = "street"
Zone = "zone"
@dataclass
class QueryParams:
q: str = Query(..., title="query string")
lon: Optional[confloat(ge=-180, le=180)] = Query(None, title="latitude for the focus")
lat: Optional[confloat(ge=-90, le=90)] = Query(None, title="longitude for the focus")
lang: Optional[str] = Query(None, title="language")
limit: PositiveInt = 10
pt_dataset: List[str] = Query([])
poi_dataset: List[str] = Query([])
all_data: bool = False
offset: conint(gt=-1) = 0
timeout: Optional[conint(gt=-1)] = None
type: List[Type] = Query([])
zone_type: List[ZoneType] = Query([])
poi_type: List[str] = Query([])
nlu: bool = settings["AUTOCOMPLETE_NLU_DEFAULT"]
def bragi_query_dict(self):
"""
Return a dict with parameters accepted by the bragi API
See https://github.com/CanalTP/mimirsbrunn/blob/v1.14.0/libs/bragi/src/routes/autocomplete.rs#L60
"""
params = {
"q": self.q,
"lon": self.lon,
"lat": self.lat,
"lang": self.lang,
"""
coord = es_poi.get_coord()
if coord:
lon = coord.get("lon")
lat = coord.get("lat")
return (lat, lon)
return None
class OpeningHoursType(BaseModel):
beginning: str
end: str
class DaysType(BaseModel):
dayofweek: conint(ge=1, le=7)
local_date: str # should be date but for some reason, fastapi jsonable_encoder just don't care
status: constr(regex="(open|closed)")
opening_hours: List[OpeningHoursType]
def parse_time_block(cls, es_poi, lang, raw):
if not raw:
return None
poi_coord = get_coord(es_poi)
poi_lat = poi_coord[0]
poi_lon = poi_coord[1]
poi_tzname = tz.tzNameAt(poi_lat, poi_lon, forceTZ=True)
poi_tz = get_tz(poi_tzname, poi_lat, poi_lon)