Coverage for tests/test_dotenv.py: 100%
40 statements
« prev ^ index » next coverage.py v7.2.7, created at 2024-08-27 18:25 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2024-08-27 18:25 +0000
1import os
2from typing import Iterator
4import pytest
6from prisma import Prisma, load_env
8from .utils import Testdir
10ENV_KEY = '_PRISMA_PY_TESTING_DOTENV_DATABSE_URL'
11DEFAULT_VALUE = 'file:dev.db'
14def make_env_file(testdir: Testdir, name: str = '.env') -> None:
15 path = testdir.path.joinpath(name)
16 if not path.parent.exists():
17 path.parent.mkdir(parents=True)
19 with path.open('w') as file:
20 file.write(f'export {ENV_KEY}="{DEFAULT_VALUE}"')
23@pytest.fixture(autouse=True)
24def clear_env(testdir: Testdir) -> Iterator[None]:
25 os.environ.pop(ENV_KEY, None)
27 yield
29 paths = [
30 testdir.path.joinpath('.env'),
31 testdir.path.joinpath('prisma/.env'),
32 ]
33 for path in paths:
34 if path.exists(): # pragma: no branch
35 path.unlink()
38@pytest.mark.parametrize('name', ['.env', 'prisma/.env'])
39def test_client_loads_dotenv(testdir: Testdir, name: str) -> None:
40 """Initializing the client overrides os.environ variables"""
41 make_env_file(testdir, name=name)
43 Prisma(use_dotenv=False)
44 assert ENV_KEY not in os.environ
46 Prisma()
47 assert ENV_KEY in os.environ
50def test_load_env_no_files(testdir: Testdir) -> None:
51 """Loading dotenv files without any files present does not error"""
52 assert len(list(testdir.path.iterdir())) == 0
53 load_env()
54 assert ENV_KEY not in os.environ
57def test_system_env_takes_priority(testdir: Testdir) -> None:
58 """When an environment variable is present in both the system env and the .env file,
59 the system env should take priority.
60 """
61 make_env_file(testdir)
62 os.environ[ENV_KEY] = 'foo'
64 Prisma()
65 assert os.environ[ENV_KEY] == 'foo'
67 os.environ.pop(ENV_KEY)
68 Prisma()
69 assert os.environ[ENV_KEY] == DEFAULT_VALUE