Files
meshcore-stats/tests/reports/test_aggregation.py
T
Jorijn Schrijvershof a9f6926104 test: add comprehensive pytest test suite with 95% coverage (#29)
* test: add comprehensive pytest test suite with 95% coverage

Add full unit and integration test coverage for the meshcore-stats project:

- 1020 tests covering all modules (db, charts, html, reports, client, etc.)
- 95.95% code coverage with pytest-cov (95% threshold enforced)
- GitHub Actions CI workflow for automated testing on push/PR
- Proper mocking of external dependencies (meshcore, serial, filesystem)
- SVG snapshot infrastructure for chart regression testing
- Integration tests for collection and rendering pipelines

Test organization:
- tests/charts/: Chart rendering and statistics
- tests/client/: MeshCore client and connection handling
- tests/config/: Environment and configuration parsing
- tests/database/: SQLite operations and migrations
- tests/html/: HTML generation and Jinja templates
- tests/reports/: Report generation and formatting
- tests/retry/: Circuit breaker and retry logic
- tests/unit/: Pure unit tests for utilities
- tests/integration/: End-to-end pipeline tests

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* chore: add test-engineer agent configuration

Add project-local test-engineer agent for pytest test development,
coverage analysis, and test review tasks.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* docs: comprehensive test suite review with 956 tests analyzed

Conducted thorough review of all 956 test cases across 47 test files:

- Unit Tests: 338 tests (battery, metrics, log, telemetry, env, charts, html, reports, formatters)
- Config Tests: 53 tests (env loading, config file parsing)
- Database Tests: 115 tests (init, insert, queries, migrations, maintenance, validation)
- Retry Tests: 59 tests (circuit breaker, async retries, factory)
- Charts Tests: 76 tests (transforms, statistics, timeseries, rendering, I/O)
- HTML Tests: 81 tests (site generation, Jinja2, metrics builders, reports index)
- Reports Tests: 149 tests (location, JSON/TXT formatting, aggregation, counter totals)
- Client Tests: 63 tests (contacts, connection, meshcore availability, commands)
- Integration Tests: 22 tests (reports, collection, rendering pipelines)

Results:
- Overall Pass Rate: 99.7% (953/956)
- 3 tests marked for improvement (empty test bodies in client tests)
- 0 tests requiring fixes

Key findings documented in test_review/tests.md including quality
observations, F.I.R.S.T. principle adherence, and recommendations.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* test: implement snapshot testing for charts and reports

Add comprehensive snapshot testing infrastructure:

SVG Chart Snapshots:
- Deterministic fixtures with fixed timestamps (2024-01-15 12:00:00)
- Tests for gauge/counter metrics in light/dark themes
- Empty chart and single-point edge cases
- Extended normalize_svg_for_snapshot_full() for reproducible comparisons

TXT Report Snapshots:
- Monthly/yearly report snapshots for repeater and companion
- Empty report handling tests
- Tests in tests/reports/test_snapshots.py

Infrastructure:
- tests/snapshots/conftest.py with shared fixtures
- UPDATE_SNAPSHOTS=1 environment variable for regeneration
- scripts/generate_snapshots.py for batch snapshot generation

Run `UPDATE_SNAPSHOTS=1 pytest tests/charts/test_chart_render.py::TestSvgSnapshots`
to generate initial snapshots.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* test: fix SVG normalization and generate initial snapshots

Fix normalize_svg_for_snapshot() to handle:
- clipPath IDs like id="p47c77a2a6e"
- url(#p...) references
- xlink:href="#p..." references
- <dc:date> timestamps

Generated initial snapshot files:
- 7 SVG chart snapshots (gauge, counter, empty, single-point in light/dark)
- 6 TXT report snapshots (monthly/yearly for repeater/companion + empty)

All 13 snapshot tests now pass.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* test: fix SVG normalization to preserve axis rendering

The SVG normalization was replacing all matplotlib-generated IDs with
the same value, causing duplicate IDs that broke SVG rendering:
- Font glyphs, clipPaths, and tick marks all got id="normalized"
- References couldn't resolve to the correct elements
- X and Y axes failed to render in normalized snapshots

Fix uses type-specific prefixes with sequential numbering:
- glyph_N for font glyphs (DejaVuSans-XX patterns)
- clip_N for clipPath definitions (p[0-9a-f]{8,} patterns)
- tick_N for tick marks (m[0-9a-f]{8,} patterns)

This ensures all IDs remain unique while still being deterministic
for snapshot comparison.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* chore: add coverage and pytest artifacts to gitignore

Add .coverage, .coverage.*, htmlcov/, and .pytest_cache/ to prevent
test artifacts from being committed.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* style: fix all ruff lint errors across codebase

- Sort and organize imports (I001)
- Use modern type annotations (X | Y instead of Union, collections.abc)
- Remove unused imports (F401)
- Combine nested if statements (SIM102)
- Use ternary operators where appropriate (SIM108)
- Combine nested with statements (SIM117)
- Use contextlib.suppress instead of try-except-pass (SIM105)
- Add noqa comments for intentional SIM115 violations (file locks)
- Add TYPE_CHECKING import for forward references
- Fix exception chaining (B904)

All 1033 tests pass.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* docs: add TDD workflow and pre-commit requirements to CLAUDE.md

- Add mandatory test-driven development workflow (write tests first)
- Add pre-commit requirements (must run lint and tests before committing)
- Document test organization and running commands
- Document 95% coverage requirement

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: resolve mypy type checking errors with proper structural fixes

- charts.py: Create PeriodConfig dataclass for type-safe period configuration,
  use mdates.date2num() for matplotlib datetime handling, fix x-axis limits
  for single-point charts
- db.py: Add explicit int() conversion with None handling for SQLite returns
- env.py: Add class-level type annotations to Config class
- html.py: Add MetricDisplay TypedDict, fix import order, add proper type
  annotations for table data functions
- meshcore_client.py: Add return type annotation

Update tests to use new dataclass attribute access and regenerate SVG
snapshots. Add mypy step to CLAUDE.md pre-commit requirements.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: cast Jinja2 template.render() to str for mypy

Jinja2's type stubs declare render() as returning Any, but it actually
returns str. Wrap with str() to satisfy mypy's no-any-return check.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* ci: improve workflow security and reliability

- test.yml: Pin all actions by SHA, add concurrency control to cancel
  in-progress runs on rapid pushes
- release-please.yml: Pin action by SHA, add 10-minute timeout
- conftest.py: Fix snapshot_base_time to use explicit UTC timezone for
  consistent behavior across CI and local environments

Regenerate SVG snapshots with UTC-aware timestamps.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: add mypy command to permissions in settings.local.json

* test: add comprehensive script tests with coroutine warning fixes

- Add tests/scripts/ with tests for collect_companion, collect_repeater,
  and render scripts (1135 tests total, 96% coverage)
- Fix unawaited coroutine warnings by using AsyncMock properly for async
  functions and async_context_manager_factory fixture for context managers
- Add --cov=scripts to CI workflow and pyproject.toml coverage config
- Omit scripts/generate_snapshots.py from coverage (dev utility)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* docs: migrate claude setup to codex skills

* feat: migrate dependencies to uv (#31)

* fix: run tests through uv

* test: fix ruff lint issues in tests

Consolidate patch context managers and clean unused imports/variables

Use datetime.UTC in snapshot fixtures

* test: avoid unawaited async mocks in entrypoint tests

* ci: replace codecov with github coverage artifacts

Add junit XML output and coverage summary in job output

Upload HTML and XML coverage artifacts (3.12 only) on every run

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-08 17:16:53 +01:00

185 lines
6.9 KiB
Python

"""Tests for report data aggregation functions."""
from datetime import date, datetime
from meshmon.db import insert_metrics
from meshmon.reports import (
DailyAggregate,
aggregate_daily,
aggregate_monthly,
aggregate_yearly,
get_rows_for_date,
)
class TestGetRowsForDate:
"""Tests for get_rows_for_date function."""
def test_returns_list(self, initialized_db, configured_env):
"""Returns a list."""
result = get_rows_for_date("repeater", date(2024, 1, 15))
assert isinstance(result, list)
def test_filters_by_date(self, initialized_db, configured_env):
"""Only returns rows for the specified date."""
# Insert data for different dates
ts_jan14 = int(datetime(2024, 1, 14, 12, 0, 0).timestamp())
ts_jan15 = int(datetime(2024, 1, 15, 12, 0, 0).timestamp())
ts_jan16 = int(datetime(2024, 1, 16, 12, 0, 0).timestamp())
insert_metrics(ts_jan14, "repeater", {"bat": 3800.0})
insert_metrics(ts_jan15, "repeater", {"bat": 3850.0})
insert_metrics(ts_jan16, "repeater", {"bat": 3900.0})
result = get_rows_for_date("repeater", date(2024, 1, 15))
# Should have data for Jan 15 only
assert len(result) == 1
assert result[0]["bat"] == 3850.0
def test_filters_by_role(self, initialized_db, configured_env):
"""Only returns rows for the specified role."""
ts = int(datetime(2024, 1, 15, 12, 0, 0).timestamp())
insert_metrics(ts, "repeater", {"bat": 3800.0})
insert_metrics(ts, "companion", {"battery_mv": 3850.0})
repeater_result = get_rows_for_date("repeater", date(2024, 1, 15))
companion_result = get_rows_for_date("companion", date(2024, 1, 15))
assert len(repeater_result) == 1
assert "bat" in repeater_result[0]
assert len(companion_result) == 1
assert "battery_mv" in companion_result[0]
def test_returns_empty_for_no_data(self, initialized_db, configured_env):
"""Returns empty list when no data for date."""
result = get_rows_for_date("repeater", date(2024, 1, 15))
assert result == []
class TestAggregateDaily:
"""Tests for aggregate_daily function."""
def test_returns_daily_aggregate(self, initialized_db, configured_env):
"""Returns a DailyAggregate."""
result = aggregate_daily("repeater", date(2024, 1, 15))
assert isinstance(result, DailyAggregate)
def test_calculates_gauge_stats(self, initialized_db, configured_env):
"""Calculates stats for gauge metrics."""
base_ts = int(datetime(2024, 1, 15, 0, 0, 0).timestamp())
# Insert several values
for i, value in enumerate([3700.0, 3800.0, 3900.0, 4000.0]):
insert_metrics(base_ts + i * 3600, "repeater", {"bat": value})
result = aggregate_daily("repeater", date(2024, 1, 15))
assert "bat" in result.metrics
bat_stats = result.metrics["bat"]
# Should have stats
assert bat_stats.count > 0
def test_calculates_counter_total(self, initialized_db, configured_env):
"""Calculates total for counter metrics."""
base_ts = int(datetime(2024, 1, 15, 0, 0, 0).timestamp())
# Insert increasing counter values
for i in range(5):
insert_metrics(base_ts + i * 900, "repeater", {"nb_recv": float(i * 100)})
result = aggregate_daily("repeater", date(2024, 1, 15))
assert "nb_recv" in result.metrics
# Counter should have total
assert result.metrics["nb_recv"].total is not None or result.metrics["nb_recv"].count > 0
def test_returns_empty_for_no_data(self, initialized_db, configured_env):
"""Returns aggregate with empty metrics when no data."""
result = aggregate_daily("repeater", date(2024, 1, 15))
assert isinstance(result, DailyAggregate)
# May have empty metrics or just no count
assert result.snapshot_count == 0 or len(result.metrics) == 0
class TestAggregateMonthly:
"""Tests for aggregate_monthly function."""
def test_returns_monthly_aggregate(self, initialized_db, configured_env):
"""Returns a MonthlyAggregate."""
from meshmon.reports import MonthlyAggregate
result = aggregate_monthly("repeater", 2024, 1)
assert isinstance(result, MonthlyAggregate)
def test_aggregates_all_days(self, initialized_db, configured_env):
"""Aggregates data from all days in month."""
# Insert data for multiple days
for day in [1, 5, 15, 20, 31]:
ts = int(datetime(2024, 1, day, 12, 0, 0).timestamp())
insert_metrics(ts, "repeater", {"bat": 3800.0 + day * 10})
result = aggregate_monthly("repeater", 2024, 1)
# Should have daily data
assert result.year == 2024
assert result.month == 1
# May have daily aggregates
assert len(result.daily) >= 0 # Can be 0 if aggregation skips empty days
def test_handles_partial_month(self, initialized_db, configured_env):
"""Handles months with partial data."""
# Insert data for only a few days
for day in [10, 11, 12]:
ts = int(datetime(2024, 1, day, 12, 0, 0).timestamp())
insert_metrics(ts, "repeater", {"bat": 3800.0})
result = aggregate_monthly("repeater", 2024, 1)
assert result.year == 2024
assert result.month == 1
class TestAggregateYearly:
"""Tests for aggregate_yearly function."""
def test_returns_yearly_aggregate(self, initialized_db, configured_env):
"""Returns a YearlyAggregate."""
from meshmon.reports import YearlyAggregate
result = aggregate_yearly("repeater", 2024)
assert isinstance(result, YearlyAggregate)
def test_aggregates_all_months(self, initialized_db, configured_env):
"""Aggregates data from all months in year."""
# Insert data for multiple months
for month in [1, 3, 6, 12]:
ts = int(datetime(2024, month, 15, 12, 0, 0).timestamp())
insert_metrics(ts, "repeater", {"bat": 3800.0 + month * 10})
result = aggregate_yearly("repeater", 2024)
assert result.year == 2024
# Should have monthly aggregates
assert len(result.monthly) >= 0
def test_returns_empty_for_no_data(self, initialized_db, configured_env):
"""Returns aggregate with empty monthly when no data."""
result = aggregate_yearly("repeater", 2024)
assert result.year == 2024
# Empty year may have no monthly data
assert isinstance(result.monthly, list)
def test_handles_leap_year(self, initialized_db, configured_env):
"""Correctly handles leap years."""
# Insert data for Feb 29 (2024 is a leap year)
ts = int(datetime(2024, 2, 29, 12, 0, 0).timestamp())
insert_metrics(ts, "repeater", {"bat": 3800.0})
result = aggregate_yearly("repeater", 2024)
assert result.year == 2024