Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions tests/test_track_cli.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import tempfile
import unittest
from pathlib import Path
from unittest import mock
Expand Down Expand Up @@ -72,6 +73,19 @@ def test_invalid_settings_exit_before_constructing_dependencies(self) -> None:
"\n".join(logs.output),
)

def test_database_failure_logs_a_concise_error_and_exits_nonzero(self) -> None:
with tempfile.TemporaryDirectory() as directory:
# A directory cannot be opened as a SQLite database file.
with (
mock.patch("sys.argv", ["track.py", "--database", directory]),
mock.patch("track.WindowsActivityProvider"),
mock.patch("track.ActivityTracker") as tracker_cls,
self.assertLogs(level="ERROR") as logs,
):
self.assertEqual(track.main(), 1)
tracker_cls.assert_not_called()
self.assertIn("unable to open database file", "\n".join(logs.output))

def test_keyboard_interrupt_stops_the_tracker_and_closes_the_database(self) -> None:
database = mock.MagicMock()
tracker = mock.Mock()
Expand Down
12 changes: 10 additions & 2 deletions track.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import argparse
import logging
import math
import sqlite3
from pathlib import Path

from timetracker import __version__
Expand Down Expand Up @@ -57,7 +58,14 @@ def main() -> int:
if not math.isfinite(args.idle_after) or args.idle_after <= 0:
raise ValueError("--idle-after must be finite and greater than zero")
provider = WindowsActivityProvider()
with ActivityDatabase(args.database) as database:
try:
database_context = ActivityDatabase(args.database)
except OSError as exc:
# Only failures opening the database path are treated as expected here;
# other OS errors keep their traceback.
logging.error("%s", exc)
return 1
with database_context as database:
tracker = ActivityTracker(
database=database,
provider=provider,
Expand All @@ -68,7 +76,7 @@ def main() -> int:
tracker.run()
except KeyboardInterrupt:
tracker.stop()
except (RuntimeError, ValueError) as exc:
except (RuntimeError, ValueError, sqlite3.Error) as exc:
logging.error("%s", exc)
return 1
return 0
Expand Down