|
1
|
|
|
from typing import Optional, ClassVar |
|
2
|
|
|
|
|
3
|
|
|
import pytest |
|
4
|
|
|
|
|
5
|
|
|
from lagom import Container |
|
6
|
|
|
from lagom.environment import Env |
|
7
|
|
|
from lagom.exceptions import MissingEnvVariable, InvalidEnvironmentVariables |
|
8
|
|
|
|
|
9
|
|
|
|
|
10
|
|
|
class MyEnv(Env): |
|
11
|
|
|
example_value: Optional[str] = None |
|
12
|
|
|
|
|
13
|
|
|
|
|
14
|
|
|
class MyEnvWithPrefix(Env): |
|
15
|
|
|
PREFIX: ClassVar[str] = "APPNAME" |
|
16
|
|
|
example_value: str |
|
17
|
|
|
|
|
18
|
|
|
|
|
19
|
|
|
class MyEnvNeedsANumberAndAString(Env): |
|
20
|
|
|
a_string: str |
|
21
|
|
|
a_number: int |
|
22
|
|
|
|
|
23
|
|
|
|
|
24
|
|
|
def test_env_can_be_loaded(container: Container): |
|
25
|
|
|
assert isinstance(container.resolve(MyEnv), MyEnv) |
|
26
|
|
|
|
|
27
|
|
|
|
|
28
|
|
|
def test_defined_env_variables_are_loaded_automatically( |
|
29
|
|
|
monkeypatch, container: Container |
|
30
|
|
|
): |
|
31
|
|
|
monkeypatch.setenv("EXAMPLE_VALUE", "from the environment") |
|
32
|
|
|
env = container.resolve(MyEnv) |
|
33
|
|
|
assert env.example_value == "from the environment" |
|
34
|
|
|
|
|
35
|
|
|
|
|
36
|
|
|
def test_envs_can_have_a_prefix(monkeypatch, container: Container): |
|
37
|
|
|
monkeypatch.setenv("APPNAME_EXAMPLE_VALUE", "from the environment with a prefix") |
|
38
|
|
|
env = container.resolve(MyEnvWithPrefix) |
|
39
|
|
|
assert env.example_value == "from the environment with a prefix" |
|
40
|
|
|
|
|
41
|
|
|
|
|
42
|
|
|
def test_errors_are_nice_if_the_env_variable_isnt_set(container: Container): |
|
43
|
|
|
with pytest.raises(MissingEnvVariable) as error: |
|
44
|
|
|
container.resolve(MyEnvWithPrefix) |
|
45
|
|
|
assert ( |
|
46
|
|
|
str(error.value) |
|
47
|
|
|
== "Expected environment variables not found: APPNAME_EXAMPLE_VALUE" |
|
48
|
|
|
) |
|
49
|
|
|
|
|
50
|
|
|
|
|
51
|
|
|
def test_all_missing_variable_names_are_listed(container: Container): |
|
52
|
|
|
with pytest.raises(MissingEnvVariable) as error: |
|
53
|
|
|
container.resolve(MyEnvNeedsANumberAndAString) |
|
54
|
|
|
error_message = str(error.value) |
|
55
|
|
|
assert "A_STRING" in error_message |
|
56
|
|
|
assert "A_NUMBER" in error_message |
|
57
|
|
|
|
|
58
|
|
|
|
|
59
|
|
|
def test_wrong_types_are_handled(monkeypatch, container: Container): |
|
60
|
|
|
monkeypatch.setenv("A_STRING", "correctly-a-string") |
|
61
|
|
|
monkeypatch.setenv("A_NUMBER", "false") |
|
62
|
|
|
with pytest.raises(InvalidEnvironmentVariables) as error: |
|
63
|
|
|
container.resolve(MyEnvNeedsANumberAndAString) |
|
64
|
|
|
assert "Unable to load environment variables: A_NUMBER" in str(error.value) |
|
65
|
|
|
|