Last active
October 4, 2020 14:04
-
-
Save gidgid/fc0d6fa375eaa542f634699038b13889 to your computer and use it in GitHub Desktop.
Pydantic strict types prevent type coercion
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, 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