mirror of
https://github.com/jorijn/meshcore-stats.git
synced 2026-07-07 02:01:26 +02:00
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>
This commit is contained in:
committed by
GitHub
parent
45bdf5d6d4
commit
a9f6926104
@@ -0,0 +1,867 @@
|
||||
"""Tests for collect_repeater.py script entry point.
|
||||
|
||||
These tests verify the actual script behavior, including:
|
||||
- Finding repeater contact by name or key prefix
|
||||
- Circuit breaker integration
|
||||
- Exit codes for monitoring
|
||||
- Database writes
|
||||
"""
|
||||
|
||||
import inspect
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.scripts.conftest import load_script_module
|
||||
|
||||
|
||||
def load_collect_repeater():
|
||||
"""Load collect_repeater.py as a module."""
|
||||
return load_script_module("collect_repeater.py")
|
||||
|
||||
|
||||
class TestCollectRepeaterImport:
|
||||
"""Verify script can be imported without errors."""
|
||||
|
||||
def test_imports_successfully(self, configured_env):
|
||||
"""Script should import without errors."""
|
||||
module = load_collect_repeater()
|
||||
|
||||
assert hasattr(module, "main")
|
||||
assert hasattr(module, "collect_repeater")
|
||||
assert hasattr(module, "find_repeater_contact")
|
||||
assert hasattr(module, "query_repeater_with_retry")
|
||||
assert callable(module.main)
|
||||
|
||||
def test_collect_repeater_is_async(self, configured_env):
|
||||
"""collect_repeater() should be an async function."""
|
||||
module = load_collect_repeater()
|
||||
assert inspect.iscoroutinefunction(module.collect_repeater)
|
||||
|
||||
def test_find_repeater_contact_is_async(self, configured_env):
|
||||
"""find_repeater_contact() should be an async function."""
|
||||
module = load_collect_repeater()
|
||||
assert inspect.iscoroutinefunction(module.find_repeater_contact)
|
||||
|
||||
|
||||
class TestFindRepeaterContact:
|
||||
"""Test the find_repeater_contact function."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_finds_contact_by_name(self, configured_env, monkeypatch):
|
||||
"""Should find repeater by advertised name."""
|
||||
monkeypatch.setenv("REPEATER_NAME", "MyRepeater")
|
||||
import meshmon.env
|
||||
|
||||
meshmon.env._config = None
|
||||
|
||||
module = load_collect_repeater()
|
||||
|
||||
mc = MagicMock()
|
||||
mc.commands = MagicMock()
|
||||
mc.contacts = {"abc123": {"adv_name": "MyRepeater", "public_key": "abc123"}}
|
||||
|
||||
with (
|
||||
patch.object(module, "run_command") as mock_run,
|
||||
patch.object(module, "get_contact_by_name") as mock_get,
|
||||
):
|
||||
mock_run.return_value = (True, "CONTACTS", mc.contacts, None)
|
||||
mock_get.return_value = mc.contacts["abc123"]
|
||||
|
||||
contact = await module.find_repeater_contact(mc)
|
||||
|
||||
assert contact is not None
|
||||
assert contact["adv_name"] == "MyRepeater"
|
||||
mock_get.assert_called_once_with(mc, "MyRepeater")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_finds_contact_by_key_prefix(self, configured_env, monkeypatch):
|
||||
"""Should find repeater by public key prefix when name not set."""
|
||||
monkeypatch.setenv("REPEATER_KEY_PREFIX", "abc123")
|
||||
import meshmon.env
|
||||
|
||||
meshmon.env._config = None
|
||||
|
||||
module = load_collect_repeater()
|
||||
|
||||
mc = MagicMock()
|
||||
mc.commands = MagicMock()
|
||||
mc.contacts = {"abc123def456": {"adv_name": "SomeNode", "public_key": "abc123def456"}}
|
||||
|
||||
with (
|
||||
patch.object(module, "run_command") as mock_run,
|
||||
patch.object(module, "get_contact_by_name", return_value=None),
|
||||
patch.object(module, "get_contact_by_key_prefix") as mock_get,
|
||||
):
|
||||
mock_run.return_value = (True, "CONTACTS", mc.contacts, None)
|
||||
mock_get.return_value = mc.contacts["abc123def456"]
|
||||
|
||||
contact = await module.find_repeater_contact(mc)
|
||||
|
||||
assert contact is not None
|
||||
mock_get.assert_called_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fallback_to_manual_name_search(self, configured_env, monkeypatch):
|
||||
"""Should fallback to manual name search in payload dict."""
|
||||
monkeypatch.setenv("REPEATER_NAME", "ManualFind")
|
||||
import meshmon.env
|
||||
|
||||
meshmon.env._config = None
|
||||
|
||||
module = load_collect_repeater()
|
||||
|
||||
mc = MagicMock()
|
||||
mc.commands = MagicMock()
|
||||
contacts_dict = {"xyz789": {"adv_name": "ManualFind", "public_key": "xyz789"}}
|
||||
|
||||
with (
|
||||
patch.object(module, "run_command") as mock_run,
|
||||
patch.object(module, "get_contact_by_name", return_value=None),
|
||||
):
|
||||
mock_run.return_value = (True, "CONTACTS", contacts_dict, None)
|
||||
# get_contact_by_name returns None, forcing manual search
|
||||
contact = await module.find_repeater_contact(mc)
|
||||
|
||||
assert contact is not None
|
||||
assert contact["adv_name"] == "ManualFind"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_case_insensitive_name_match(self, configured_env, monkeypatch):
|
||||
"""Name search should be case-insensitive."""
|
||||
monkeypatch.setenv("REPEATER_NAME", "myrepeater") # lowercase
|
||||
import meshmon.env
|
||||
|
||||
meshmon.env._config = None
|
||||
|
||||
module = load_collect_repeater()
|
||||
|
||||
mc = MagicMock()
|
||||
mc.commands = MagicMock()
|
||||
contacts_dict = {"key1": {"adv_name": "MyRepeater", "public_key": "key1"}} # Mixed case
|
||||
|
||||
with (
|
||||
patch.object(module, "run_command") as mock_run,
|
||||
patch.object(module, "get_contact_by_name", return_value=None),
|
||||
):
|
||||
mock_run.return_value = (True, "CONTACTS", contacts_dict, None)
|
||||
contact = await module.find_repeater_contact(mc)
|
||||
|
||||
assert contact is not None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_none_when_not_found(self, configured_env, monkeypatch):
|
||||
"""Should return None when repeater not in contacts."""
|
||||
monkeypatch.setenv("REPEATER_NAME", "NonExistent")
|
||||
import meshmon.env
|
||||
|
||||
meshmon.env._config = None
|
||||
|
||||
module = load_collect_repeater()
|
||||
|
||||
mc = MagicMock()
|
||||
mc.commands = MagicMock()
|
||||
|
||||
with (
|
||||
patch.object(module, "run_command") as mock_run,
|
||||
patch.object(module, "get_contact_by_name", return_value=None),
|
||||
):
|
||||
mock_run.return_value = (True, "CONTACTS", {}, None)
|
||||
contact = await module.find_repeater_contact(mc)
|
||||
|
||||
assert contact is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_none_when_get_contacts_fails(self, configured_env, monkeypatch):
|
||||
"""Should return None when get_contacts command fails."""
|
||||
monkeypatch.setenv("REPEATER_NAME", "AnyName")
|
||||
import meshmon.env
|
||||
|
||||
meshmon.env._config = None
|
||||
|
||||
module = load_collect_repeater()
|
||||
|
||||
mc = MagicMock()
|
||||
mc.commands = MagicMock()
|
||||
|
||||
with patch.object(module, "run_command") as mock_run:
|
||||
mock_run.return_value = (False, None, None, "Connection failed")
|
||||
|
||||
contact = await module.find_repeater_contact(mc)
|
||||
|
||||
assert contact is None
|
||||
|
||||
|
||||
class TestCircuitBreakerIntegration:
|
||||
"""Test circuit breaker integration in collect_repeater."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_skips_collection_when_circuit_open(self, configured_env):
|
||||
"""Should return 0 and skip collection when circuit breaker is open."""
|
||||
module = load_collect_repeater()
|
||||
|
||||
# Create mock circuit breaker that is open
|
||||
mock_cb = MagicMock()
|
||||
mock_cb.is_open.return_value = True
|
||||
mock_cb.cooldown_remaining.return_value = 1800
|
||||
|
||||
with patch.object(module, "get_repeater_circuit_breaker", return_value=mock_cb):
|
||||
exit_code = await module.collect_repeater()
|
||||
|
||||
# Should return 0 (not an error, just skipped)
|
||||
assert exit_code == 0
|
||||
# Should not have tried to connect
|
||||
mock_cb.is_open.assert_called_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_records_success_on_successful_status(
|
||||
self, configured_env, monkeypatch, async_context_manager_factory
|
||||
):
|
||||
"""Should record success when status query succeeds."""
|
||||
monkeypatch.setenv("REPEATER_NAME", "TestRepeater")
|
||||
import meshmon.env
|
||||
|
||||
meshmon.env._config = None
|
||||
|
||||
module = load_collect_repeater()
|
||||
|
||||
mock_cb = MagicMock()
|
||||
mock_cb.is_open.return_value = False
|
||||
|
||||
mc = MagicMock()
|
||||
mc.commands = MagicMock()
|
||||
ctx_mock = async_context_manager_factory(mc)
|
||||
|
||||
with (
|
||||
patch.object(module, "get_repeater_circuit_breaker", return_value=mock_cb),
|
||||
patch.object(module, "connect_with_lock", return_value=ctx_mock),
|
||||
patch.object(module, "run_command") as mock_run,
|
||||
patch.object(module, "find_repeater_contact") as mock_find,
|
||||
patch.object(module, "query_repeater_with_retry") as mock_query,
|
||||
patch.object(module, "insert_metrics", return_value=2),
|
||||
):
|
||||
mock_run.return_value = (True, "OK", {}, None)
|
||||
mock_find.return_value = {"adv_name": "TestRepeater"}
|
||||
mock_query.return_value = (True, {"bat": 3850, "uptime": 86400}, None)
|
||||
|
||||
await module.collect_repeater()
|
||||
|
||||
mock_cb.record_success.assert_called_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_records_failure_on_status_timeout(
|
||||
self, configured_env, monkeypatch, async_context_manager_factory
|
||||
):
|
||||
"""Should record failure when status query times out."""
|
||||
monkeypatch.setenv("REPEATER_NAME", "TestRepeater")
|
||||
import meshmon.env
|
||||
|
||||
meshmon.env._config = None
|
||||
|
||||
module = load_collect_repeater()
|
||||
|
||||
mock_cb = MagicMock()
|
||||
mock_cb.is_open.return_value = False
|
||||
|
||||
mc = MagicMock()
|
||||
mc.commands = MagicMock()
|
||||
ctx_mock = async_context_manager_factory(mc)
|
||||
|
||||
with (
|
||||
patch.object(module, "get_repeater_circuit_breaker", return_value=mock_cb),
|
||||
patch.object(module, "connect_with_lock", return_value=ctx_mock),
|
||||
patch.object(module, "run_command") as mock_run,
|
||||
patch.object(module, "find_repeater_contact") as mock_find,
|
||||
patch.object(module, "query_repeater_with_retry") as mock_query,
|
||||
):
|
||||
mock_run.return_value = (True, "OK", {}, None)
|
||||
mock_find.return_value = {"adv_name": "TestRepeater"}
|
||||
mock_query.return_value = (False, None, "Timeout")
|
||||
|
||||
exit_code = await module.collect_repeater()
|
||||
|
||||
mock_cb.record_failure.assert_called_once()
|
||||
assert exit_code == 1
|
||||
|
||||
|
||||
class TestCollectRepeaterExitCodes:
|
||||
"""Test exit code behavior - critical for monitoring."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_zero_on_successful_collection(
|
||||
self, configured_env, monkeypatch, async_context_manager_factory
|
||||
):
|
||||
"""Successful collection should return exit code 0."""
|
||||
monkeypatch.setenv("REPEATER_NAME", "TestRepeater")
|
||||
import meshmon.env
|
||||
|
||||
meshmon.env._config = None
|
||||
|
||||
module = load_collect_repeater()
|
||||
|
||||
mock_cb = MagicMock()
|
||||
mock_cb.is_open.return_value = False
|
||||
|
||||
mc = MagicMock()
|
||||
mc.commands = MagicMock()
|
||||
ctx_mock = async_context_manager_factory(mc)
|
||||
|
||||
with (
|
||||
patch.object(module, "get_repeater_circuit_breaker", return_value=mock_cb),
|
||||
patch.object(module, "connect_with_lock", return_value=ctx_mock),
|
||||
patch.object(module, "run_command") as mock_run,
|
||||
patch.object(module, "find_repeater_contact") as mock_find,
|
||||
patch.object(module, "query_repeater_with_retry") as mock_query,
|
||||
patch.object(module, "insert_metrics", return_value=3),
|
||||
):
|
||||
mock_run.return_value = (True, "OK", {}, None)
|
||||
mock_find.return_value = {"adv_name": "TestRepeater"}
|
||||
mock_query.return_value = (
|
||||
True,
|
||||
{"bat": 3850, "uptime": 86400, "nb_recv": 100},
|
||||
None,
|
||||
)
|
||||
|
||||
exit_code = await module.collect_repeater()
|
||||
|
||||
assert exit_code == 0
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_one_on_connection_failure(
|
||||
self, configured_env, async_context_manager_factory
|
||||
):
|
||||
"""Failed connection should return exit code 1."""
|
||||
module = load_collect_repeater()
|
||||
|
||||
mock_cb = MagicMock()
|
||||
mock_cb.is_open.return_value = False
|
||||
ctx_mock = async_context_manager_factory(None) # Connection returns None
|
||||
|
||||
with (
|
||||
patch.object(module, "get_repeater_circuit_breaker", return_value=mock_cb),
|
||||
patch.object(module, "connect_with_lock", return_value=ctx_mock),
|
||||
):
|
||||
exit_code = await module.collect_repeater()
|
||||
|
||||
assert exit_code == 1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_one_when_repeater_not_found(
|
||||
self, configured_env, monkeypatch, async_context_manager_factory
|
||||
):
|
||||
"""Should return 1 when repeater contact not found."""
|
||||
monkeypatch.setenv("REPEATER_NAME", "NonExistent")
|
||||
import meshmon.env
|
||||
|
||||
meshmon.env._config = None
|
||||
|
||||
module = load_collect_repeater()
|
||||
|
||||
mock_cb = MagicMock()
|
||||
mock_cb.is_open.return_value = False
|
||||
|
||||
mc = MagicMock()
|
||||
mc.commands = MagicMock()
|
||||
ctx_mock = async_context_manager_factory(mc)
|
||||
|
||||
with (
|
||||
patch.object(module, "get_repeater_circuit_breaker", return_value=mock_cb),
|
||||
patch.object(module, "connect_with_lock", return_value=ctx_mock),
|
||||
patch.object(module, "run_command") as mock_run,
|
||||
patch.object(module, "find_repeater_contact") as mock_find,
|
||||
):
|
||||
mock_run.return_value = (True, "OK", {}, None)
|
||||
mock_find.return_value = None # Not found
|
||||
|
||||
exit_code = await module.collect_repeater()
|
||||
|
||||
assert exit_code == 1
|
||||
|
||||
|
||||
class TestQueryRepeaterWithRetry:
|
||||
"""Test the retry wrapper for repeater queries."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_success_on_first_try(self, configured_env):
|
||||
"""Should return success when command succeeds immediately."""
|
||||
module = load_collect_repeater()
|
||||
|
||||
mc = MagicMock()
|
||||
contact = {"adv_name": "Test"}
|
||||
|
||||
async def successful_command():
|
||||
return {"bat": 3850}
|
||||
|
||||
with patch.object(module, "with_retries") as mock_retries:
|
||||
mock_retries.return_value = (True, {"bat": 3850}, None)
|
||||
|
||||
success, payload, err = await module.query_repeater_with_retry(
|
||||
mc, contact, "test_cmd", successful_command
|
||||
)
|
||||
|
||||
assert success is True
|
||||
assert payload == {"bat": 3850}
|
||||
assert err is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_failure_after_retries_exhausted(self, configured_env):
|
||||
"""Should return failure when all retries fail."""
|
||||
module = load_collect_repeater()
|
||||
|
||||
mc = MagicMock()
|
||||
contact = {"adv_name": "Test"}
|
||||
|
||||
async def failing_command():
|
||||
raise Exception("Timeout")
|
||||
|
||||
with patch.object(module, "with_retries") as mock_retries:
|
||||
mock_retries.return_value = (False, None, Exception("Timeout"))
|
||||
|
||||
success, payload, err = await module.query_repeater_with_retry(
|
||||
mc, contact, "test_cmd", failing_command
|
||||
)
|
||||
|
||||
assert success is False
|
||||
assert payload is None
|
||||
assert "Timeout" in err
|
||||
|
||||
|
||||
class TestMainEntryPoint:
|
||||
"""Test the main() entry point behavior."""
|
||||
|
||||
def test_main_calls_init_db(self, configured_env):
|
||||
"""main() should initialize database before collection."""
|
||||
module = load_collect_repeater()
|
||||
|
||||
with (
|
||||
patch.object(module, "init_db") as mock_init,
|
||||
patch.object(module, "collect_repeater", new=MagicMock(return_value=0)),
|
||||
patch.object(module, "asyncio") as mock_asyncio,
|
||||
patch.object(module, "sys"),
|
||||
):
|
||||
# Patch collect_repeater to return a non-coroutine to avoid unawaited coroutine warning
|
||||
mock_asyncio.run.return_value = 0
|
||||
module.main()
|
||||
|
||||
mock_init.assert_called_once()
|
||||
|
||||
def test_main_exits_with_collection_result(self, configured_env):
|
||||
"""main() should exit with the collection exit code."""
|
||||
module = load_collect_repeater()
|
||||
|
||||
with (
|
||||
patch.object(module, "init_db"),
|
||||
patch.object(module, "collect_repeater", new=MagicMock(return_value=1)),
|
||||
patch.object(module, "asyncio") as mock_asyncio,
|
||||
patch.object(module, "sys") as mock_sys,
|
||||
):
|
||||
# Patch collect_repeater to return a non-coroutine to avoid unawaited coroutine warning
|
||||
mock_asyncio.run.return_value = 1 # Collection failed
|
||||
module.main()
|
||||
|
||||
mock_sys.exit.assert_called_once_with(1)
|
||||
|
||||
|
||||
class TestDatabaseIntegration:
|
||||
"""Test that collection actually writes to database."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_writes_metrics_to_database(
|
||||
self, configured_env, initialized_db, monkeypatch, async_context_manager_factory
|
||||
):
|
||||
"""Collection should write metrics to database."""
|
||||
from meshmon.db import get_latest_metrics
|
||||
|
||||
monkeypatch.setenv("REPEATER_NAME", "TestRepeater")
|
||||
import meshmon.env
|
||||
|
||||
meshmon.env._config = None
|
||||
|
||||
module = load_collect_repeater()
|
||||
|
||||
mock_cb = MagicMock()
|
||||
mock_cb.is_open.return_value = False
|
||||
|
||||
mc = MagicMock()
|
||||
mc.commands = MagicMock()
|
||||
ctx_mock = async_context_manager_factory(mc)
|
||||
|
||||
with (
|
||||
patch.object(module, "get_repeater_circuit_breaker", return_value=mock_cb),
|
||||
patch.object(module, "connect_with_lock", return_value=ctx_mock),
|
||||
patch.object(module, "run_command") as mock_run,
|
||||
patch.object(module, "find_repeater_contact") as mock_find,
|
||||
patch.object(module, "query_repeater_with_retry") as mock_query,
|
||||
):
|
||||
mock_run.return_value = (True, "OK", {}, None)
|
||||
mock_find.return_value = {"adv_name": "TestRepeater"}
|
||||
mock_query.return_value = (
|
||||
True,
|
||||
{"bat": 3777, "uptime": 99999, "nb_recv": 1234, "nb_sent": 567},
|
||||
None,
|
||||
)
|
||||
|
||||
exit_code = await module.collect_repeater()
|
||||
|
||||
assert exit_code == 0
|
||||
|
||||
# Verify data was written to database
|
||||
latest = get_latest_metrics("repeater")
|
||||
assert latest is not None
|
||||
assert latest["bat"] == 3777
|
||||
assert latest["nb_recv"] == 1234
|
||||
|
||||
|
||||
class TestFindRepeaterContactEdgeCases:
|
||||
"""Test edge cases in find_repeater_contact."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_finds_contact_in_payload_dict(self, configured_env, monkeypatch):
|
||||
"""Should find contact in payload dict when mc.contacts is empty."""
|
||||
monkeypatch.setenv("REPEATER_NAME", "PayloadRepeater")
|
||||
import meshmon.env
|
||||
|
||||
meshmon.env._config = None
|
||||
|
||||
module = load_collect_repeater()
|
||||
|
||||
mc = MagicMock()
|
||||
mc.commands = MagicMock()
|
||||
mc.contacts = {} # Empty contacts attribute
|
||||
payload_dict = {"pk123": {"adv_name": "PayloadRepeater", "public_key": "pk123"}}
|
||||
|
||||
with (
|
||||
patch.object(module, "run_command") as mock_run,
|
||||
patch.object(module, "get_contact_by_name", return_value=None),
|
||||
):
|
||||
# Return contacts in payload
|
||||
mock_run.return_value = (True, "CONTACTS", payload_dict, None)
|
||||
# get_contact_by_name returns None, forcing manual search in payload
|
||||
contact = await module.find_repeater_contact(mc)
|
||||
|
||||
assert contact is not None
|
||||
assert contact["adv_name"] == "PayloadRepeater"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_finds_contact_by_key_prefix_manual_search(self, configured_env, monkeypatch):
|
||||
"""Should find contact by key prefix via manual search in payload."""
|
||||
monkeypatch.setenv("REPEATER_KEY_PREFIX", "abc")
|
||||
import meshmon.env
|
||||
|
||||
meshmon.env._config = None
|
||||
|
||||
module = load_collect_repeater()
|
||||
|
||||
mc = MagicMock()
|
||||
mc.commands = MagicMock()
|
||||
contacts_dict = {"abc123xyz": {"adv_name": "KeyPrefixNode"}}
|
||||
|
||||
with (
|
||||
patch.object(module, "run_command") as mock_run,
|
||||
patch.object(module, "get_contact_by_name", return_value=None),
|
||||
patch.object(module, "get_contact_by_key_prefix", return_value=None),
|
||||
):
|
||||
mock_run.return_value = (True, "CONTACTS", contacts_dict, None)
|
||||
# Both helper functions return None, forcing manual search
|
||||
contact = await module.find_repeater_contact(mc)
|
||||
|
||||
assert contact is not None
|
||||
assert contact["adv_name"] == "KeyPrefixNode"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_prints_available_contacts_when_not_found(self, configured_env, monkeypatch):
|
||||
"""Should print available contacts when repeater not found."""
|
||||
monkeypatch.setenv("REPEATER_NAME", "NonExistent")
|
||||
import meshmon.env
|
||||
|
||||
meshmon.env._config = None
|
||||
|
||||
module = load_collect_repeater()
|
||||
|
||||
mc = MagicMock()
|
||||
mc.commands = MagicMock()
|
||||
contacts_dict = {
|
||||
"key1": {"adv_name": "Node1", "name": "alt1"},
|
||||
"key2": {"adv_name": "Node2"},
|
||||
"key3": {}, # No name fields
|
||||
}
|
||||
|
||||
with (
|
||||
patch.object(module, "run_command") as mock_run,
|
||||
patch.object(module, "get_contact_by_name", return_value=None),
|
||||
patch.object(module, "log") as mock_log,
|
||||
):
|
||||
mock_run.return_value = (True, "CONTACTS", contacts_dict, None)
|
||||
contact = await module.find_repeater_contact(mc)
|
||||
|
||||
assert contact is None
|
||||
# Should have logged available contacts
|
||||
mock_log.info.assert_called()
|
||||
|
||||
|
||||
class TestLoginFunctionality:
|
||||
"""Test optional login functionality."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_attempts_login_when_password_set(
|
||||
self, configured_env, monkeypatch, async_context_manager_factory
|
||||
):
|
||||
"""Should attempt login when REPEATER_PASSWORD is set."""
|
||||
monkeypatch.setenv("REPEATER_NAME", "TestRepeater")
|
||||
monkeypatch.setenv("REPEATER_PASSWORD", "secret123")
|
||||
import meshmon.env
|
||||
|
||||
meshmon.env._config = None
|
||||
|
||||
module = load_collect_repeater()
|
||||
|
||||
mock_cb = MagicMock()
|
||||
mock_cb.is_open.return_value = False
|
||||
|
||||
mc = MagicMock()
|
||||
mc.commands = MagicMock()
|
||||
mc.commands.send_login = MagicMock()
|
||||
ctx_mock = async_context_manager_factory(mc)
|
||||
|
||||
with (
|
||||
patch.object(module, "get_repeater_circuit_breaker", return_value=mock_cb),
|
||||
patch.object(module, "connect_with_lock", return_value=ctx_mock),
|
||||
patch.object(module, "run_command") as mock_run,
|
||||
patch.object(module, "find_repeater_contact") as mock_find,
|
||||
patch.object(module, "extract_contact_info") as mock_extract,
|
||||
patch.object(module, "query_repeater_with_retry") as mock_query,
|
||||
patch.object(module, "insert_metrics", return_value=1),
|
||||
):
|
||||
# Return success for all commands
|
||||
mock_run.return_value = (True, "OK", {}, None)
|
||||
mock_find.return_value = {"adv_name": "TestRepeater"}
|
||||
mock_extract.return_value = {"adv_name": "TestRepeater"}
|
||||
mock_query.return_value = (True, {"bat": 3850}, None)
|
||||
|
||||
await module.collect_repeater()
|
||||
|
||||
# Verify login was attempted (run_command called with send_login)
|
||||
login_calls = [c for c in mock_run.call_args_list if c[0][2] == "send_login"]
|
||||
assert len(login_calls) == 1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_handles_login_exception(
|
||||
self, configured_env, monkeypatch, async_context_manager_factory
|
||||
):
|
||||
"""Should handle exception during login gracefully."""
|
||||
monkeypatch.setenv("REPEATER_NAME", "TestRepeater")
|
||||
monkeypatch.setenv("REPEATER_PASSWORD", "secret123")
|
||||
import meshmon.env
|
||||
|
||||
meshmon.env._config = None
|
||||
|
||||
module = load_collect_repeater()
|
||||
|
||||
mock_cb = MagicMock()
|
||||
mock_cb.is_open.return_value = False
|
||||
|
||||
mc = MagicMock()
|
||||
mc.commands = MagicMock()
|
||||
mc.commands.send_login = MagicMock(side_effect=Exception("Login not supported"))
|
||||
ctx_mock = async_context_manager_factory(mc)
|
||||
|
||||
call_count = 0
|
||||
|
||||
async def mock_run_command(mc, coro, name):
|
||||
nonlocal call_count
|
||||
call_count += 1
|
||||
if name == "send_login":
|
||||
raise Exception("Login not supported")
|
||||
return (True, "OK", {}, None)
|
||||
|
||||
with (
|
||||
patch.object(module, "get_repeater_circuit_breaker", return_value=mock_cb),
|
||||
patch.object(module, "connect_with_lock", return_value=ctx_mock),
|
||||
patch.object(module, "run_command", side_effect=mock_run_command),
|
||||
patch.object(module, "find_repeater_contact") as mock_find,
|
||||
patch.object(module, "extract_contact_info") as mock_extract,
|
||||
patch.object(module, "query_repeater_with_retry") as mock_query,
|
||||
patch.object(module, "insert_metrics", return_value=1),
|
||||
):
|
||||
mock_find.return_value = {"adv_name": "TestRepeater"}
|
||||
mock_extract.return_value = {"adv_name": "TestRepeater"}
|
||||
mock_query.return_value = (True, {"bat": 3850}, None)
|
||||
|
||||
# Should not raise - login failure should be handled
|
||||
exit_code = await module.collect_repeater()
|
||||
assert exit_code == 0
|
||||
|
||||
|
||||
class TestTelemetryCollection:
|
||||
"""Test telemetry collection when enabled."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_collects_telemetry_when_enabled(
|
||||
self, configured_env, monkeypatch, initialized_db, async_context_manager_factory
|
||||
):
|
||||
"""Should collect telemetry when TELEMETRY_ENABLED=1."""
|
||||
monkeypatch.setenv("REPEATER_NAME", "TestRepeater")
|
||||
monkeypatch.setenv("TELEMETRY_ENABLED", "1")
|
||||
import meshmon.env
|
||||
|
||||
meshmon.env._config = None
|
||||
|
||||
module = load_collect_repeater()
|
||||
|
||||
mock_cb = MagicMock()
|
||||
mock_cb.is_open.return_value = False
|
||||
|
||||
mc = MagicMock()
|
||||
mc.commands = MagicMock()
|
||||
ctx_mock = async_context_manager_factory(mc)
|
||||
|
||||
with (
|
||||
patch.object(module, "get_repeater_circuit_breaker", return_value=mock_cb),
|
||||
patch.object(module, "connect_with_lock", return_value=ctx_mock),
|
||||
patch.object(module, "run_command") as mock_run,
|
||||
patch.object(module, "find_repeater_contact") as mock_find,
|
||||
patch.object(module, "extract_contact_info") as mock_extract,
|
||||
patch.object(module, "query_repeater_with_retry") as mock_query,
|
||||
patch.object(
|
||||
module,
|
||||
"with_retries",
|
||||
new=AsyncMock(return_value=(True, {"lpp": b"\x00\x67\x01\x00"}, None)),
|
||||
),
|
||||
patch.object(module, "extract_lpp_from_payload") as mock_lpp,
|
||||
patch.object(module, "extract_telemetry_metrics") as mock_telem,
|
||||
):
|
||||
mock_run.return_value = (True, "OK", {}, None)
|
||||
mock_find.return_value = {"adv_name": "TestRepeater"}
|
||||
mock_extract.return_value = {"adv_name": "TestRepeater"}
|
||||
mock_query.return_value = (True, {"bat": 3850}, None)
|
||||
mock_lpp.return_value = {"temperature": [(0, 25.5)]}
|
||||
mock_telem.return_value = {"telemetry.temperature.0": 25.5}
|
||||
|
||||
exit_code = await module.collect_repeater()
|
||||
|
||||
assert exit_code == 0
|
||||
# Verify telemetry was processed
|
||||
mock_lpp.assert_called_once()
|
||||
mock_telem.assert_called_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_handles_telemetry_failure_gracefully(
|
||||
self, configured_env, monkeypatch, async_context_manager_factory
|
||||
):
|
||||
"""Should continue when telemetry collection fails."""
|
||||
monkeypatch.setenv("REPEATER_NAME", "TestRepeater")
|
||||
monkeypatch.setenv("TELEMETRY_ENABLED", "1")
|
||||
import meshmon.env
|
||||
|
||||
meshmon.env._config = None
|
||||
|
||||
module = load_collect_repeater()
|
||||
|
||||
mock_cb = MagicMock()
|
||||
mock_cb.is_open.return_value = False
|
||||
|
||||
mc = MagicMock()
|
||||
mc.commands = MagicMock()
|
||||
ctx_mock = async_context_manager_factory(mc)
|
||||
|
||||
with (
|
||||
patch.object(module, "get_repeater_circuit_breaker", return_value=mock_cb),
|
||||
patch.object(module, "connect_with_lock", return_value=ctx_mock),
|
||||
patch.object(module, "run_command") as mock_run,
|
||||
patch.object(module, "find_repeater_contact") as mock_find,
|
||||
patch.object(module, "extract_contact_info") as mock_extract,
|
||||
patch.object(module, "query_repeater_with_retry") as mock_query,
|
||||
patch.object(module, "insert_metrics", return_value=1),
|
||||
patch.object(
|
||||
module,
|
||||
"with_retries",
|
||||
new=AsyncMock(return_value=(False, None, Exception("Timeout"))),
|
||||
),
|
||||
):
|
||||
mock_run.return_value = (True, "OK", {}, None)
|
||||
mock_find.return_value = {"adv_name": "TestRepeater"}
|
||||
mock_extract.return_value = {"adv_name": "TestRepeater"}
|
||||
mock_query.return_value = (True, {"bat": 3850}, None)
|
||||
|
||||
# Should still succeed (status metrics were saved)
|
||||
exit_code = await module.collect_repeater()
|
||||
assert exit_code == 0
|
||||
|
||||
|
||||
class TestDatabaseErrorHandling:
|
||||
"""Test database error handling."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_one_on_status_db_error(
|
||||
self, configured_env, monkeypatch, async_context_manager_factory
|
||||
):
|
||||
"""Should return 1 when status metrics DB write fails."""
|
||||
monkeypatch.setenv("REPEATER_NAME", "TestRepeater")
|
||||
import meshmon.env
|
||||
|
||||
meshmon.env._config = None
|
||||
|
||||
module = load_collect_repeater()
|
||||
|
||||
mock_cb = MagicMock()
|
||||
mock_cb.is_open.return_value = False
|
||||
|
||||
mc = MagicMock()
|
||||
mc.commands = MagicMock()
|
||||
ctx_mock = async_context_manager_factory(mc)
|
||||
|
||||
with (
|
||||
patch.object(module, "get_repeater_circuit_breaker", return_value=mock_cb),
|
||||
patch.object(module, "connect_with_lock", return_value=ctx_mock),
|
||||
patch.object(module, "run_command") as mock_run,
|
||||
patch.object(module, "find_repeater_contact") as mock_find,
|
||||
patch.object(module, "extract_contact_info") as mock_extract,
|
||||
patch.object(module, "query_repeater_with_retry") as mock_query,
|
||||
patch.object(module, "insert_metrics", side_effect=Exception("DB error")),
|
||||
):
|
||||
mock_run.return_value = (True, "OK", {}, None)
|
||||
mock_find.return_value = {"adv_name": "TestRepeater"}
|
||||
mock_extract.return_value = {"adv_name": "TestRepeater"}
|
||||
mock_query.return_value = (True, {"bat": 3850}, None)
|
||||
|
||||
exit_code = await module.collect_repeater()
|
||||
assert exit_code == 1
|
||||
|
||||
|
||||
class TestExceptionHandling:
|
||||
"""Test general exception handling."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_records_failure_on_exception(
|
||||
self, configured_env, monkeypatch, async_context_manager_factory
|
||||
):
|
||||
"""Should record circuit breaker failure on unexpected exception."""
|
||||
monkeypatch.setenv("REPEATER_NAME", "TestRepeater")
|
||||
import meshmon.env
|
||||
|
||||
meshmon.env._config = None
|
||||
|
||||
module = load_collect_repeater()
|
||||
|
||||
mock_cb = MagicMock()
|
||||
mock_cb.is_open.return_value = False
|
||||
|
||||
mc = MagicMock()
|
||||
mc.commands = MagicMock()
|
||||
ctx_mock = async_context_manager_factory(mc)
|
||||
|
||||
with (
|
||||
patch.object(module, "get_repeater_circuit_breaker", return_value=mock_cb),
|
||||
patch.object(module, "connect_with_lock", return_value=ctx_mock),
|
||||
patch.object(module, "run_command") as mock_run,
|
||||
patch.object(module, "find_repeater_contact") as mock_find,
|
||||
patch.object(module, "extract_contact_info") as mock_extract,
|
||||
):
|
||||
mock_run.return_value = (True, "OK", {}, None)
|
||||
mock_find.return_value = {"adv_name": "TestRepeater"}
|
||||
mock_extract.side_effect = Exception("Unexpected error")
|
||||
|
||||
await module.collect_repeater()
|
||||
|
||||
# Circuit breaker should record failure
|
||||
mock_cb.record_failure.assert_called_once()
|
||||
Reference in New Issue
Block a user