Skip to content

Commit 206d0a3

Browse files
committed
Refactor env_file fixture to dynamically locate repository root and improve test isolation
1 parent 476396a commit 206d0a3

File tree

1 file changed

+19
-7
lines changed

1 file changed

+19
-7
lines changed

tests/catch_dotenv_test.py

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,13 +28,18 @@ def env_file(tmp_path: Path) -> Path:
2828
All tests rely on this baseline content (optionally appending extra lines
2929
for edge cases) to ensure consistent parsing behavior.
3030
"""
31-
# __file__ => <repo_root>/tests/catch_dotenv_test.py
32-
# parents[0] = <repo_root>/tests, parents[1] = <repo_root>
31+
# Find repository root by looking for .git directory
32+
test_file_path = Path(__file__).resolve()
33+
repo_root = test_file_path
34+
while repo_root.parent != repo_root: # Stop at filesystem root
35+
if (repo_root / '.git').exists():
36+
break
37+
repo_root = repo_root.parent
38+
else:
39+
raise RuntimeError('Could not find repository root (.git directory)')
40+
3341
# Source file stored as test.env in repo (cannot commit a real .env in CI)
34-
resource_env = (
35-
Path(__file__).resolve().parents[1] /
36-
'testing' / 'resources' / 'test.env'
37-
)
42+
resource_env = repo_root / 'testing' / 'resources' / 'test.env'
3843
dest = tmp_path / DEFAULT_ENV_FILE
3944
shutil.copyfile(resource_env, dest)
4045
return dest
@@ -144,8 +149,15 @@ def test_create_example_duplicate_key_variant_ignored(
144149
"""Appending whitespace duplicate of existing key should not duplicate
145150
in example.
146151
"""
147-
with open(env_file, 'a', encoding='utf-8') as f:
152+
# Create a copy of the env_file to avoid contaminating the fixture
153+
modified_env = tmp_path / 'modified.env'
154+
shutil.copyfile(env_file, modified_env)
155+
with open(modified_env, 'a', encoding='utf-8') as f:
148156
f.write('BACKEND_CONTAINER_PORT =999 # duplicate variant\n')
157+
158+
# Override the env file path for this test
159+
original_env = tmp_path / DEFAULT_ENV_FILE
160+
shutil.copyfile(modified_env, original_env)
149161
run_hook(tmp_path, [DEFAULT_ENV_FILE], create_example=True)
150162
lines = (tmp_path / DEFAULT_EXAMPLE_ENV_FILE).read_text().splitlines()
151163
key_lines = [ln for ln in lines if ln and not ln.startswith('#')]

0 commit comments

Comments
 (0)