Last active
October 4, 2020 12:28
-
-
Save gidgid/6500135b5673decbb12376e4f0226401 to your computer and use it in GitHub Desktop.
pydantic constrained types
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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