From 904db63fa2b2c4cfa7528f4084d9739ce3f20c1b Mon Sep 17 00:00:00 2001 From: Lukas Date: Sat, 23 May 2026 23:00:51 +0200 Subject: [PATCH] Add tests for since timestamp accuracy in ban_service - test_since_unix_returns_utc_epoch: validates since_unix('24h') returns UTC epoch - test_ban_trend_since_is_within_expected_range: validates 23h-ago ban falls in 24h+slack window Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../tests/test_services/test_ban_service.py | 23 +++++++++++++++++++ .../tests/test_services/test_time_utils.py | 12 ++++++++++ 2 files changed, 35 insertions(+) diff --git a/backend/tests/test_services/test_ban_service.py b/backend/tests/test_services/test_ban_service.py index bf7ff16..360ef6b 100644 --- a/backend/tests/test_services/test_ban_service.py +++ b/backend/tests/test_services/test_ban_service.py @@ -934,6 +934,29 @@ class TestBanTrend: parsed = datetime.fromisoformat(bucket.timestamp) assert parsed.tzinfo is not None # Must be timezone-aware (UTC) + async def test_ban_trend_since_is_within_expected_range(self, tmp_path: Path) -> None: + """``since`` value is within 24h + 60s slack of the current time.""" + from app.utils.constants import TIME_RANGE_SLACK_SECONDS + + now = int(time.time()) + # Place a ban just inside the expected range: 23 hours ago. + # With 60s slack, since ≈ now - 24h - 60s, so 23h-ago ban should be included. + just_inside_range = now - (23 * 3600) + path = str(tmp_path / "test_since_range.sqlite3") + await _create_f2b_db( + path, + [{"jail": "sshd", "ip": "1.2.3.4", "timeofban": just_inside_range}], + ) + + with patch( + "app.services.ban_service.get_fail2ban_db_path", + new=AsyncMock(return_value=path), + ): + result = await ban_service.ban_trend("/fake/sock", "24h") + + # Ban at 23h ago must appear (within 24h + 60s window). + assert sum(b.count for b in result.buckets) == 1 + # --------------------------------------------------------------------------- # bans_by_jail diff --git a/backend/tests/test_services/test_time_utils.py b/backend/tests/test_services/test_time_utils.py index aea50a8..5152f8f 100644 --- a/backend/tests/test_services/test_time_utils.py +++ b/backend/tests/test_services/test_time_utils.py @@ -134,3 +134,15 @@ class TestSinceUnix: # The slack should be ~60 seconds assert actual_slack >= TIME_RANGE_SLACK_SECONDS - 1 assert actual_slack <= TIME_RANGE_SLACK_SECONDS + 1 + + def test_since_unix_returns_utc_epoch(self) -> None: + """``since_unix('24h')`` returns a value within 24h + 60s of ``time.time()``.""" + before = int(time.time()) + result = since_unix("24h") + after = int(time.time()) + + # Allow 2 second tolerance for execution time + expected_min = before - (24 * 3600) - TIME_RANGE_SLACK_SECONDS - 2 + expected_max = after - (24 * 3600) - TIME_RANGE_SLACK_SECONDS + 2 + + assert expected_min <= result <= expected_max