Files
meshcore-stats/tests/client/test_contacts.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

276 lines
8.8 KiB
Python

"""Tests for contact lookup functions."""
from unittest.mock import MagicMock
class TestGetContactByName:
"""Tests for get_contact_by_name function."""
def test_returns_contact_when_found(self, mock_meshcore_client):
"""Returns contact when found by name."""
from meshmon.meshcore_client import get_contact_by_name
contact = MagicMock()
contact.adv_name = "TestNode"
mock_meshcore_client.get_contact_by_name.return_value = contact
result = get_contact_by_name(mock_meshcore_client, "TestNode")
assert result == contact
mock_meshcore_client.get_contact_by_name.assert_called_once_with("TestNode")
def test_returns_none_when_not_found(self, mock_meshcore_client):
"""Returns None when contact not found."""
from meshmon.meshcore_client import get_contact_by_name
mock_meshcore_client.get_contact_by_name.return_value = None
result = get_contact_by_name(mock_meshcore_client, "NonExistent")
assert result is None
def test_returns_none_when_method_not_available(self):
"""Returns None when get_contact_by_name method not available."""
from meshmon.meshcore_client import get_contact_by_name
mc = MagicMock(spec=[]) # No methods
result = get_contact_by_name(mc, "TestNode")
assert result is None
def test_returns_none_on_exception(self, mock_meshcore_client):
"""Returns None when method raises exception."""
from meshmon.meshcore_client import get_contact_by_name
mock_meshcore_client.get_contact_by_name.side_effect = RuntimeError("Connection lost")
result = get_contact_by_name(mock_meshcore_client, "TestNode")
assert result is None
class TestGetContactByKeyPrefix:
"""Tests for get_contact_by_key_prefix function."""
def test_returns_contact_when_found(self, mock_meshcore_client):
"""Returns contact when found by key prefix."""
from meshmon.meshcore_client import get_contact_by_key_prefix
contact = MagicMock()
contact.pubkey_prefix = "abc123"
mock_meshcore_client.get_contact_by_key_prefix.return_value = contact
result = get_contact_by_key_prefix(mock_meshcore_client, "abc123")
assert result == contact
mock_meshcore_client.get_contact_by_key_prefix.assert_called_once_with("abc123")
def test_returns_none_when_not_found(self, mock_meshcore_client):
"""Returns None when contact not found."""
from meshmon.meshcore_client import get_contact_by_key_prefix
mock_meshcore_client.get_contact_by_key_prefix.return_value = None
result = get_contact_by_key_prefix(mock_meshcore_client, "xyz789")
assert result is None
def test_returns_none_when_method_not_available(self):
"""Returns None when get_contact_by_key_prefix method not available."""
from meshmon.meshcore_client import get_contact_by_key_prefix
mc = MagicMock(spec=[]) # No methods
result = get_contact_by_key_prefix(mc, "abc123")
assert result is None
def test_returns_none_on_exception(self, mock_meshcore_client):
"""Returns None when method raises exception."""
from meshmon.meshcore_client import get_contact_by_key_prefix
mock_meshcore_client.get_contact_by_key_prefix.side_effect = RuntimeError("Connection lost")
result = get_contact_by_key_prefix(mock_meshcore_client, "abc123")
assert result is None
class TestExtractContactInfo:
"""Tests for extract_contact_info function."""
def test_extracts_from_dict_contact(self):
"""Extracts info from dict-based contact."""
from meshmon.meshcore_client import extract_contact_info
contact = {
"adv_name": "TestNode",
"name": "test",
"pubkey_prefix": "abc123",
"public_key": "abc123def456",
"type": 1,
"flags": 0,
}
result = extract_contact_info(contact)
assert result["adv_name"] == "TestNode"
assert result["name"] == "test"
assert result["pubkey_prefix"] == "abc123"
assert result["public_key"] == "abc123def456"
assert result["type"] == 1
assert result["flags"] == 0
def test_extracts_from_object_contact(self):
"""Extracts info from object-based contact."""
from meshmon.meshcore_client import extract_contact_info
contact = MagicMock()
contact.adv_name = "TestNode"
contact.name = "test"
contact.pubkey_prefix = "abc123"
contact.public_key = "abc123def456"
contact.type = 1
contact.flags = 0
result = extract_contact_info(contact)
assert result["adv_name"] == "TestNode"
assert result["name"] == "test"
assert result["pubkey_prefix"] == "abc123"
def test_converts_bytes_to_hex(self):
"""Converts bytes values to hex strings."""
from meshmon.meshcore_client import extract_contact_info
contact = {
"adv_name": "TestNode",
"public_key": bytes.fromhex("abc123def456"),
}
result = extract_contact_info(contact)
assert result["adv_name"] == "TestNode"
assert result["public_key"] == "abc123def456"
def test_converts_bytes_from_object(self):
"""Converts bytes values from object attributes to hex."""
from meshmon.meshcore_client import extract_contact_info
contact = MagicMock()
contact.adv_name = "TestNode"
contact.public_key = bytes.fromhex("deadbeef")
# Make sure other attributes return AttributeError when accessed
del contact.name
del contact.pubkey_prefix
del contact.type
del contact.flags
result = extract_contact_info(contact)
assert result["adv_name"] == "TestNode"
assert result["public_key"] == "deadbeef"
def test_skips_none_values(self):
"""Skips None values in contact."""
from meshmon.meshcore_client import extract_contact_info
contact = {
"adv_name": "TestNode",
"name": None,
"pubkey_prefix": None,
}
result = extract_contact_info(contact)
assert result["adv_name"] == "TestNode"
assert "name" not in result
assert "pubkey_prefix" not in result
def test_skips_missing_attributes(self):
"""Skips missing attributes in dict contact."""
from meshmon.meshcore_client import extract_contact_info
contact = {"adv_name": "TestNode"}
result = extract_contact_info(contact)
assert result == {"adv_name": "TestNode"}
def test_empty_contact_returns_empty_dict(self):
"""Empty contact returns empty dict."""
from meshmon.meshcore_client import extract_contact_info
result = extract_contact_info({})
assert result == {}
class TestListContactsSummary:
"""Tests for list_contacts_summary function."""
def test_returns_list_of_contact_info(self):
"""Returns list of extracted contact info."""
from meshmon.meshcore_client import list_contacts_summary
contacts = [
{"adv_name": "Node1", "type": 1},
{"adv_name": "Node2", "type": 2},
{"adv_name": "Node3", "type": 1},
]
result = list_contacts_summary(contacts)
assert len(result) == 3
assert result[0]["adv_name"] == "Node1"
assert result[1]["adv_name"] == "Node2"
assert result[2]["adv_name"] == "Node3"
def test_handles_mixed_contact_types(self):
"""Handles mix of dict and object contacts."""
from meshmon.meshcore_client import list_contacts_summary
obj_contact = MagicMock()
obj_contact.adv_name = "ObjectNode"
del obj_contact.name
del obj_contact.pubkey_prefix
del obj_contact.public_key
del obj_contact.type
del obj_contact.flags
contacts = [
{"adv_name": "DictNode"},
obj_contact,
]
result = list_contacts_summary(contacts)
assert len(result) == 2
assert result[0]["adv_name"] == "DictNode"
assert result[1]["adv_name"] == "ObjectNode"
def test_empty_list_returns_empty_list(self):
"""Empty contacts list returns empty list."""
from meshmon.meshcore_client import list_contacts_summary
result = list_contacts_summary([])
assert result == []
def test_preserves_order(self):
"""Preserves contact order in output."""
from meshmon.meshcore_client import list_contacts_summary
contacts = [
{"adv_name": "Zebra"},
{"adv_name": "Alpha"},
{"adv_name": "Middle"},
]
result = list_contacts_summary(contacts)
assert result[0]["adv_name"] == "Zebra"
assert result[1]["adv_name"] == "Alpha"
assert result[2]["adv_name"] == "Middle"