Last active
November 20, 2020 14:42
-
-
Save gidgid/d953cbe3bee1b2c2b9b711f745d54832 to your computer and use it in GitHub Desktop.
Reading settings with Pydantic
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 os | |
import pytest | |
from pydantic import BaseSettings, HttpUrl, ValidationError | |
class Config(BaseSettings): # 1, 2 | |
auth_url: HttpUrl | |
db_name: str | |
max_retries: int | |
def test_read_and_parse_env_vars(): | |
os.environ.clear() | |
os.environ['auth_url'] = 'http://www.weird.auth.name.com' | |
os.environ['db_name'] = 'mydb' | |
os.environ['max_retries'] = '7' | |
config = Config() # 3 | |
assert config.auth_url == 'http://www.weird.auth.name.com' | |
assert config.db_name == 'mydb' | |
assert config.max_retries == 7 | |
def test_all_errors_appear_together(): | |
os.environ.clear() | |
os.environ['auth_url'] = 'not a url' | |
os.environ['max_retries'] = 'not an int' | |
with pytest.raises(ValidationError) as e: # 4 | |
Config() # 3 | |
assert 'auth_url' in str(e.value) # 5 | |
assert 'max_retries' in str(e.value) # 5 | |
assert 'db_name' in str(e.value) # 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment