Skip to content

Instantly share code, notes, and snippets.

@gidgid
Last active October 4, 2020 14:04
Show Gist options
  • Save gidgid/fc0d6fa375eaa542f634699038b13889 to your computer and use it in GitHub Desktop.
Save gidgid/fc0d6fa375eaa542f634699038b13889 to your computer and use it in GitHub Desktop.
Pydantic strict types prevent type coercion
import pytest
from pydantic import BaseModel, ValidationError, StrictInt, StrictBool
class UserResponse(BaseModel):
user_input: StrictBool # 1
def test_only_bool_responses_are_accepted():
assert UserResponse(user_input=True).user_input is True # 2
assert UserResponse(user_input=False).user_input is False # 2
@pytest.mark.parametrize(
'user_input',
['yes', 'no', 'true', 'false', 'True', 'False']
)
def test_non_bool_responses_are_not_strict_enough(user_input):
with pytest.raises(ValidationError): # 3
UserResponse(user_input=user_input) # 3
class Summary(BaseModel):
score: StrictInt # 4
@pytest.mark.parametrize(
'score',
[3.4, '3', '4.0']
)
def test_only_ints_are_valid_scores(score):
with pytest.raises(ValidationError): # 5
Summary(score=score) # 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment