Skip to content

Commit

Permalink
Add strict types tests
Browse files Browse the repository at this point in the history
Signed-off-by: Martin Vrachev <[email protected]>
  • Loading branch information
MVrachev committed Mar 15, 2021
1 parent 22932e2 commit d1bb21f
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
21 changes: 20 additions & 1 deletion tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -354,10 +354,29 @@ def test_validation(self):
with self.assertRaises(ValueError):
root.signed.test_validation(val)

# When it succeds in the cast to an int, no error or warning is raised.
# When it succeeds in the cast to an int, no error or warning is raised.
root.signed.test_validation("212")
root.signed.test_validation(True)

# But you can use "StrictStr", "StrictBytes", "StrictInt", "StrictFloat",
# and "StrictBool" as strict types which forbids the casting
# See: https://pydantic-docs.helpmanual.io/usage/types/#strict-types
for val in ['', '1.11', None, '2', True, False, root]:
# Raises an exception because "val" is not from type "int"
with self.assertRaises(ValueError):
root.signed.test_strict_int_validation(val)

for val in [1, 0, -1, None, True, False, root]:
# Raises an exception because "val" is not from type "str"
with self.assertRaises(ValueError):
root.signed.test_strict_str_validation(val)

# Does not raise an exception when calling with the right type:
root.signed.test_strict_int_validation(300)
root.signed.test_strict_int_validation(0)
root.signed.test_strict_int_validation(-10)
root.signed.test_strict_str_validation("")
root.signed.test_strict_str_validation("HI")

# Run unit test.
if __name__ == '__main__':
Expand Down
8 changes: 8 additions & 0 deletions tuf/api/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,14 @@ def test_validation(self, arg1: int):
print(arg1)


@pydantic.validate_arguments()
def test_strict_int_validation(self, arg1: pydantic.StrictInt):
print(arg1)

@pydantic.validate_arguments()
def test_strict_str_validation(self, arg1: pydantic.StrictStr):
print(arg1)

@staticmethod
def _common_fields_from_dict(signed_dict: Mapping[str, Any]) -> list:
"""Returns common fields of 'Signed' instances from the passed dict
Expand Down

0 comments on commit d1bb21f

Please sign in to comment.