@@ -29,23 +29,47 @@ def mock_config():
2929 return config
3030
3131
32- @pytest .fixture (autouse = True )
32+ @pytest .fixture (scope = "session" , autouse = True )
33+ def _set_test_db_path ():
34+ """Set DATABASE_PATH environment variable for all tests.
35+
36+ This runs once at the start of the test session to ensure no test
37+ can accidentally write to the development database.
38+ """
39+ original_db = os .environ .get ("DATABASE_PATH" )
40+ test_db = os .path .join (tempfile .gettempdir (), "test_audio_history.db" )
41+ os .environ ["DATABASE_PATH" ] = test_db
42+
43+ yield
44+
45+ # Restore original
46+ if original_db :
47+ os .environ ["DATABASE_PATH" ] = original_db
48+ else :
49+ os .environ .pop ("DATABASE_PATH" , None )
50+
51+ # Cleanup test database
52+ if os .path .exists (test_db ):
53+ try :
54+ os .unlink (test_db )
55+ except Exception :
56+ pass
57+
58+
59+ @pytest .fixture
3360def db_path (monkeypatch ):
3461 """Temporary SQLite database for testing.
3562
36- This fixture runs automatically for ALL tests to ensure they never
37- touch the development database.
38-
39- Renamed from temp_db to db_path to match existing test expectations.
63+ This fixture creates a fresh database for tests that explicitly request it.
64+ Most tests will just use the session-level database via _set_test_db_path.
4065 """
4166 with tempfile .NamedTemporaryFile (suffix = ".db" , delete = False ) as f :
4267 temp_path = f .name
4368
4469 # Set environment variable for database using monkeypatch
45- # This ensures proper cleanup even if tests fail
4670 monkeypatch .setenv ("DATABASE_PATH" , temp_path )
4771
48- # Force reload of database module to pick up new DATABASE_PATH
72+ # Reload database module to pick up new DATABASE_PATH
4973 import services .database
5074 import importlib
5175
@@ -63,7 +87,6 @@ def db_path(monkeypatch):
6387 try :
6488 os .unlink (temp_path )
6589 except Exception :
66- # Ignore cleanup errors
6790 pass
6891
6992
0 commit comments