Skip to content

Instantly share code, notes, and snippets.

@gidgid
Last active October 4, 2020 12:28
Show Gist options
  • Save gidgid/6500135b5673decbb12376e4f0226401 to your computer and use it in GitHub Desktop.
Save gidgid/6500135b5673decbb12376e4f0226401 to your computer and use it in GitHub Desktop.
pydantic constrained types
import pytest
from pydantic import BaseModel, conlist, constr, ValidationError
class User(BaseModel):
name: constr(min_length=1) # 1
scores: conlist(int, min_items=1) # 2
def report(user: User):
# dummy implementation
print(f'Hi: {user}') # 3
print(f'Max score: {max(user.scores)}') # 4
def test_register_valid_user():
user = User(name='John', scores=[4, 5, 8])
report(user)
@pytest.mark.parametrize(
'name,friends',
[
('', [1, 2]), # 5
('John', []) # 6
]
)
def test_invalid_users(name, friends):
with pytest.raises(ValidationError): # 7
User(name=name, friends=friends)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment