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>
This commit is contained in:
@@ -934,6 +934,29 @@ class TestBanTrend:
|
|||||||
parsed = datetime.fromisoformat(bucket.timestamp)
|
parsed = datetime.fromisoformat(bucket.timestamp)
|
||||||
assert parsed.tzinfo is not None # Must be timezone-aware (UTC)
|
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
|
# bans_by_jail
|
||||||
|
|||||||
@@ -134,3 +134,15 @@ class TestSinceUnix:
|
|||||||
# The slack should be ~60 seconds
|
# The slack should be ~60 seconds
|
||||||
assert actual_slack >= TIME_RANGE_SLACK_SECONDS - 1
|
assert actual_slack >= TIME_RANGE_SLACK_SECONDS - 1
|
||||||
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
|
||||||
|
|||||||
Reference in New Issue
Block a user