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

1import os 

2from typing import Iterator 

3 

4import pytest 

5 

6from prisma import Prisma, load_env 

7 

8from .utils import Testdir 

9 

10ENV_KEY = '_PRISMA_PY_TESTING_DOTENV_DATABSE_URL' 

11DEFAULT_VALUE = 'file:dev.db' 

12 

13 

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) 

18 

19 with path.open('w') as file: 

20 file.write(f'export {ENV_KEY}="{DEFAULT_VALUE}"') 

21 

22 

23@pytest.fixture(autouse=True) 

24def clear_env(testdir: Testdir) -> Iterator[None]: 

25 os.environ.pop(ENV_KEY, None) 

26 

27 yield 

28 

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() 

36 

37 

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) 

42 

43 Prisma(use_dotenv=False) 

44 assert ENV_KEY not in os.environ 

45 

46 Prisma() 

47 assert ENV_KEY in os.environ 

48 

49 

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 

55 

56 

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' 

63 

64 Prisma() 

65 assert os.environ[ENV_KEY] == 'foo' 

66 

67 os.environ.pop(ENV_KEY) 

68 Prisma() 

69 assert os.environ[ENV_KEY] == DEFAULT_VALUE