Skip to content

Instantly share code, notes, and snippets.

@gidgid
Last active June 3, 2023 14:03
Show Gist options
  • Save gidgid/f44f72622957294efa11e20a6fa4f999 to your computer and use it in GitHub Desktop.
Save gidgid/f44f72622957294efa11e20a6fa4f999 to your computer and use it in GitHub Desktop.
Leveraging validate_arguments to perform validations
import pytest
from typing import Optional
from pydantic import validate_arguments, PositiveInt, ValidationError
@validate_arguments # 1
def validated_get_payload(url: str, retries: PositiveInt) -> Optional[dict]:
if url.startswith("http"):
# send the actual request and return the payload if valid response
return {}
return None
@pytest.mark.parametrize(
"url,retries",
[([1, 2], 3), (4, 'wrong_args'), ("http://fine.url.com", -4)] # 2
)
def test_validated_get_payload_raises_a_validation_error(url, retries):
with pytest.raises(ValidationError): # 3
validated_get_payload(url=url, retries=retries) # 3
@yned
Copy link

yned commented May 21, 2023

Seems like an import pytest is missing.
Nice to add pytest tests in your snippets.
Keep up the good work !

@gidgid
Copy link
Author

gidgid commented Jun 3, 2023

You are absolutely correct about the missing import. Thanks for pointing it out
And I appreciate the kind feedback :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment