Commit graph

4826 commits

Author SHA1 Message Date
rcourtman
0254fc7397 Add unit tests for discovery config functions (config)
Add tests for CloneDiscoveryConfig and NormalizeDiscoveryConfig:
- CloneDiscoveryConfig: 7 tests verifying deep copy, slice independence
- NormalizeDiscoveryConfig: 16 tests covering defaults, validation,
  sanitization, edge cases

Total: 23 test cases for discovery config handling.
2025-11-30 10:49:03 +00:00
rcourtman
760f24dc5e Add unit tests for alert utility functions (alerts)
Test coverage for isMonitorOnlyAlert, quietHoursCategoryForAlert, and
ensureValidHysteresis functions that were previously untested. Improves
internal/alerts coverage from 46.4% to 46.8%.
2025-11-30 10:35:22 +00:00
rcourtman
82231877d5 Add unit tests for host alert utility functions (alerts)
Test hostResourceID, hostDisplayName, hostInstanceName,
sanitizeHostComponent, sanitizeRAIDDevice, and hostDiskResourceID.
2025-11-30 10:20:26 +00:00
rcourtman
9a5894b7a2 Add unit tests for hasLegacyThresholds function (diagnostics)
Covers all legacy threshold field detection paths including
CPU, Memory, Disk, DiskRead, DiskWrite, NetworkIn, NetworkOut,
and mixed modern/legacy configurations.
2025-11-30 10:05:33 +00:00
rcourtman
9476de40a6 Add pagination to backup list for large backup counts
- Add pagination (100 items per page) to prevent UI lockup with 2500+ backups
- Show year in date labels for non-current year backups
- Reset to page 1 when filters change
- Add First/Previous/Next/Last navigation controls

Fixes #541
2025-11-30 09:55:01 +00:00
rcourtman
8360ed8916 Add unit tests for dockeragent runtime detection functions
Test coverage for:
- detectRuntime: 11 test cases covering podman/docker detection via
  endpoint path, InitBinary, ServerVersion, DriverStatus, SecurityOptions
- buildRuntimeCandidates: 6 test cases verifying candidate ordering,
  deduplication, and preference-based filtering
- randomDuration: 5 test cases for boundary conditions and randomness
- determineSelfUpdateArch: validates architecture detection output

Coverage increased from 17.5% to 21.4%.
2025-11-30 08:47:46 +00:00
rcourtman
5c90fb102b Add unit tests for pulse-agent utility functions (unified agent)
53 test cases covering 4 functions:
- gatherTags: environment/flag tag merging (18 cases)
- parseLogLevel: log level parsing (30 cases)
- defaultLogLevel: default value resolution (10 cases)
- multiValue: flag.Value interface for repeatable flags (6 cases)

Key difference from pulse-host-agent: parseLogLevel in unified agent delegates
directly to zerolog.ParseLevel without range validation, so trace/fatal/panic
levels are accepted (unlike pulse-host-agent which restricts to debug-error).

First test file for cmd/pulse-agent package.
2025-11-30 08:34:09 +00:00
rcourtman
048708b2c7 Add unit tests for pulse-host-agent utility functions
60 test cases for gatherTags, parseLogLevel, defaultLogLevel, multiValue.
First test file for cmd/pulse-host-agent package.
2025-11-30 08:17:18 +00:00
rcourtman
0e25712d8e Add unit tests for notification security utilities (notifications)
Test 7 security-related functions with 118 test cases:
- formatWebhookDuration: webhook payload duration formatting
- isNumeric: Telegram chat_id validation helper
- extractTelegramChatID: Telegram webhook URL parsing
- isPrivateIP: SSRF protection (private IP detection)
- isNumericIP: HTTPS IP address detection
- isEmptyInterface: custom field validation
- ensurePushoverCustomFieldAliases: Pushover legacy field aliasing
2025-11-30 08:05:04 +00:00
rcourtman
2857a87c91 Add unit tests for notification template functions (notifications)
Test GetEmailProviders and GetWebhookTemplates functions covering:
- Provider/template uniqueness, required fields, valid values
- Known provider settings (Gmail, SendGrid, custom)
- Known webhook services (Discord, Slack, Telegram, PagerDuty)
- Payload template validation for required alert fields
2025-11-30 07:48:53 +00:00
rcourtman
18d3722fb8 Add unit tests for sanitizeCIDRList (config) 2025-11-30 07:35:52 +00:00
rcourtman
0a9669928a Add unit tests for config utility functions (config)
Test coverage for IsPasswordHashed, IsValidDiscoveryEnvironment, and
splitAndTrim functions. 63 test cases covering bcrypt hash validation,
discovery environment validation, and comma-separated string parsing.
2025-11-30 07:27:59 +00:00
rcourtman
79896d41a5 Add unit tests for RateTracker.CalculateRates (monitoring) 2025-11-30 07:07:18 +00:00
rcourtman
a3b64d4c00 Add unit tests for parseLogLevel and splitStringList (dockeragent) 2025-11-30 06:50:09 +00:00
rcourtman
d2f6d89c96 Add unit tests for alert utility functions (alerts)
Test coverage for pure utility functions:
- sanitizeAlertKey: string normalization for alert IDs
- abs: absolute value for float64
- isQueueOutlier: queue anomaly detection logic
- scaleThreshold: threshold scaling with ceiling
- calculateMedianInt: integer median calculation

78 test cases added, coverage improved from 45.3% to 46.2%.
2025-11-30 06:34:55 +00:00
rcourtman
0231743e4a Add unit tests for adaptive scheduler interval selection (scheduler)
46 test cases covering:
- clampFloat helper (9 cases: range checks, boundary conditions)
- Staleness score impact (5 cases: 0/0.25/0.5/0.75/1 scores)
- Error penalty (5 cases: 0 to 10 errors, min clamping)
- Queue depth stretching (5 cases: 1 to 50 depth, max clamping)
- EMA smoothing (convergence behavior with alpha=0.6)
- Jitter (bounds checking, deterministic tests with seeded RNG)
- Boundary conditions (6 cases: zero/negative intervals, max<min)
- Combined factors (3 cases: all factors interacting)
- State persistence (per-instance EMA state isolation)

First unit test file for scheduler.go (previously only had integration tests).
2025-11-30 06:11:22 +00:00
rcourtman
1fc4807a07 Add unit tests for Docker swarm utility functions (dockeragent)
Test coverage for serviceMode, buildContainerIndex, lookupContainer,
copyStringMap, and isTaskCompletedState. 52 test cases covering service
mode detection, container index building/lookup, and task state classification.
Coverage improved from 14.7% to 17.5%.
2025-11-30 05:32:52 +00:00
rcourtman
f0ead101d3 Add unit tests for Alert clone and metadata utility functions (alerts)
Tests for:
- normalizePoweredOffSeverity: Verifies severity normalization to warning/critical
- cloneMetadata: Deep copy functionality for metadata maps
- cloneMetadataValue: Type-specific cloning for various slice and map types
- Alert.Clone: Full alert cloning with pointer field independence

46 test cases covering nil handling, deep copy verification, slice/map
independence, and all supported metadata value types.

Coverage improved from 44.8% to 45.3%.
2025-11-30 05:19:38 +00:00
rcourtman
943c2b5082 Add unit tests for extractPodmanMetadata and detectHostRemovedError (dockeragent)
- TestExtractPodmanMetadata: 14 test cases covering pod metadata, infra
  containers, compose metadata, auto-update settings, user namespace
  handling, whitespace trimming, and precedence rules
- TestDetectHostRemovedError: 11 test cases covering JSON parsing,
  case-insensitive matching, error code validation, and edge cases

Coverage improved from 11.7% to 14.7% for internal/dockeragent.
2025-11-30 05:03:31 +00:00
rcourtman
f9a4df2e5a Add unit tests for sanitizeNodeLabel (pulse-sensor-proxy/metrics.go) 2025-11-30 04:50:51 +00:00
rcourtman
533050f721 Add unit tests for RateLimiter (internal/api/ratelimit.go)
16 test cases covering:
- Basic rate limiting with Allow() (limit enforcement, different IPs)
- Sliding window behavior (time-based expiry, partial expiry)
- Edge cases (zero limit, large limit, empty IP)
- Cleanup routine (full cleanup, partial cleanup)
- Concurrent access (thread safety with 100 parallel attempts)
- Middleware integration (allowed/denied paths, X-Forwarded-For)

First test file for internal/api package.
2025-11-30 04:33:59 +00:00
rcourtman
d054c20cd4 Add unit tests for temperature utility functions
Add focused unit tests for four utility functions in temperature.go:
- extractTempInput: 16 test cases for sensor value extraction
- extractCoreNumber: 18 test cases for core number parsing
- extractHostname: 21 test cases for URL hostname extraction
- normalizeSMARTEntries: 15 test cases for SMART data normalization

70 test cases total covering type conversions, edge cases,
boundary conditions, and error handling paths.
2025-11-30 04:20:28 +00:00
rcourtman
db7adea2a1 Add unit tests for InstallShAdapter utility functions
- Test parseProgress: 23 test cases for progress parsing from install.sh output
- Test readLastLines: 11 test cases including edge cases
- Test version pattern validation: 45 test cases for command injection prevention
- Test DockerUpdater and AURUpdater basic functionality
- Fix bug in readLastLines: handle n<=0 to prevent slice bounds panic

Coverage increased from 35.9% to 38.2%
2025-11-30 04:04:27 +00:00
rcourtman
28140707b1 Add unit tests for agentupdate utility functions
Tests for:
- verifyBinaryMagic: ELF/Mach-O/PE magic byte validation
- determineArch: platform architecture detection
- unraidPersistentPath: Unraid persistence path generation
- isUnraid: Unraid environment detection
- New(): updater initialization with various configs
- Config defaults and constants

Coverage: 12.9% -> 13.4%
2025-11-30 03:48:50 +00:00
rcourtman
deb5c3cd23 Add unit tests for pulse-sensor-proxy capability functions
Test Capability.Has, parseCapabilityList, capabilityNames, and
constant values. 54 test cases covering bitmask operations, parsing,
case insensitivity, whitespace handling, unknown values, and round-trip
consistency.
2025-11-30 03:32:53 +00:00
rcourtman
5be678f88d Add unit tests for notification queue utility functions
Test coverage for calculateBackoff (exponential backoff calculation),
NotificationQueueStatus constants, and QueuedNotification struct fields.
15 test cases covering backoff timing, cap behavior, and struct defaults.
2025-11-30 03:19:23 +00:00
rcourtman
efafbe8e31 Add unit tests for PMG flexible JSON type parsers
Tests for flexibleFloat and flexibleInt custom JSON unmarshalers that
handle PMG API responses where numeric values may arrive as numbers,
strings, or nulls. 64 test cases covering:

- JSON numbers (integers, floats, scientific notation, negatives)
- String values (numeric strings, empty, whitespace, "null")
- JSON null values
- Error cases (invalid strings, arrays, objects, booleans)
- Boundary values (max/min float64)
- Real PMG response patterns (mail stats, queue status)
- Struct embedding behavior
2025-11-30 03:04:12 +00:00
rcourtman
597c1f4850 Add unit tests for HTTP metrics utility functions
83 test cases covering classifyStatus, isNumeric, looksLikeUUID,
normalizeSegment, and normalizeRoute functions used for Prometheus
metrics aggregation. Tests cover status code classification, numeric
string validation, UUID format detection, URL segment normalization,
and route path normalization with query param stripping.
2025-11-30 02:48:05 +00:00
rcourtman
92c2d198b1 Add unit tests for Proxmox replication utility functions
Comprehensive test coverage for JSON parsing helpers used in
replication job status parsing: stringFromAny, intFromAny,
boolFromAny, floatFromAny, parseReplicationTime, parseDurationSeconds,
parseHHMMSSToSeconds, and parseReplicationJob.

Coverage increased from 22.6% to 35.5%.
2025-11-30 02:35:11 +00:00
rcourtman
316161f989 Add unit tests for coerceUint64 and FlexInt.UnmarshalJSON
45 test cases covering:
- FlexInt: integer/float/string parsing, truncation behavior, error cases
- coerceUint64: nil, float64 (including NaN/Inf), int/int32/int64,
  uint32/uint64, json.Number, string parsing (whitespace, null, quotes,
  commas, scientific notation), unsupported types

Coverage: 20.5% -> 22.6%
2025-11-30 02:17:52 +00:00
rcourtman
6e45073207 Add unit tests for version utility functions
Test coverage for pure functions in internal/updates/version.go:
- Version.String() - 6 test cases
- Version.Compare() - 14 test cases (major/minor/patch/prerelease)
- Version.IsNewerThan() - 4 test cases
- Version.IsPrerelease() - 4 test cases
- compareInts() - 7 test cases
- extractRCNumber() - 12 test cases
- envBool() - 17 test cases
- sanitizePrereleaseIdentifier() - 14 test cases

Coverage: 35.2% -> 35.9%
2025-11-30 02:03:35 +00:00
rcourtman
e108dc3180 Add unit tests for config encryption functions
Tests encryptWithPassphrase and decryptWithPassphrase:
- Roundtrip encryption/decryption with various data types
- Unique output verification (random salt/nonce)
- Wrong passphrase rejection
- Tampered ciphertext detection
- Minimum size validation
- Base64 roundtrip (matching export/import flow)
2025-11-30 01:48:20 +00:00
rcourtman
ef4e39f175 Add unit tests for hostagent utility functions
Test normalisePlatform (darwin->macos normalization, case handling,
whitespace trimming) and isLoopback (case-insensitive flag matching).
Package had no tests previously.
2025-11-30 01:34:55 +00:00
rcourtman
59971e0862 Add unit tests for email template utility functions
Test coverage for titleCase, formatDuration, pluralize, formatMetricValue,
and formatMetricThreshold functions. 71 test cases covering edge cases,
boundary conditions, and all metric type variants.
2025-11-30 01:03:05 +00:00
rcourtman
ca229240eb Add unit tests for discovery config_override utility functions
Tests for parseCIDRs, parseCIDRMap, environmentFromOverride,
shouldPruneContainerNetworks, isLikelyContainerPhase, filterPhasesForEnvironment,
and ApplyConfigToProfile. Coverage increased from 29.0% to 51.0%.
2025-11-30 00:50:07 +00:00
rcourtman
27b1188368 Add unit tests for websocket utility functions
Test coverage for pure utility functions:
- isValidPrivateOrigin: validates private network origins (security)
- normalizeForwardedProto: normalizes ws/wss to http/https for proxies
- sanitizeValue: handles NaN/Inf values in JSON data
- cloneMetadata/cloneMetadataValue: deep copies metadata maps/slices
- cloneAlert/cloneAlertData: deep copies alert structures

Coverage increased from 20.9% to 37.3% (80 test cases).
2025-11-30 00:34:38 +00:00
rcourtman
7147795e96 Add unit tests for diagnostics utility functions
Test coverage for 9 pure functions in internal/api/diagnostics.go:
- isFallbackMemorySource: 13 cases covering fallback and non-fallback sources
- copyStringSlice: 4 cases including nil handling and copy verification
- normalizeHostForComparison: 16 cases for URL normalization
- normalizeVersionLabel: 11 cases for version prefix handling
- contains: 8 cases for string slice membership
- containsFold: 11 cases for case-insensitive matching
- interfaceToStringSlice: 9 cases for type conversion
- preferredDockerHostName: 5 cases for name preference hierarchy
- formatTimeMaybe: 3 cases for time formatting
2025-11-30 00:18:41 +00:00
rcourtman
b1bc704e3a Consolidate duplicate normalizeVersion functions into shared utility
- Move normalizeVersion to utils.NormalizeVersion for single source of truth
- Update agentupdate and dockeragent packages to use shared function
- Add 14 test cases for version normalization

This prevents bugs like issue #773 where a fix applied to one copy
but not the other caused an update loop.
2025-11-29 22:57:33 +00:00
rcourtman
eff4ac0d21 Remove CPU capacity marker and highlight high container restarts
- Remove load average marker from CPU progress bar (confusing, not useful)
- Keep load average in tooltip only
- Highlight container restart count in red when >5 (indicates instability)
2025-11-29 22:37:17 +00:00
rcourtman
97d3f30a7f Add unit tests for dockeragent utility functions
Tests for calculateCPUPercent, calculateMemoryUsage, safeFloat,
parseTime, trimLeadingSlash, and summarizeBlockIO. 28 test cases
covering edge cases like zero deltas, cache handling, NaN/Inf,
and case-insensitive op matching.

Coverage improved from 8.0% to 11.7%.
2025-11-29 22:18:10 +00:00
rcourtman
b84b0383ca Fix redactSecretsFromURL matching params with prefixed names
The function was using substring matching for sensitive param names,
causing parameters like "extra_token" or "myapikey" to be incorrectly
redacted when they matched "token=" or "apikey=" as substrings.

Now checks for proper boundary characters (? or &) before matching,
so only actual parameter names are redacted.

Related to ADA knowledge entry: "Query param redaction uses substring matching"
2025-11-29 22:03:15 +00:00
rcourtman
84c41c1527 Match original sublabel style for CPU core count display 2025-11-29 21:49:00 +00:00
rcourtman
1eb286d900 Show CPU core count on EnhancedCPUBar progress bar 2025-11-29 21:47:22 +00:00
rcourtman
43f8a80ae0 Add unit tests for TaskQueue Upsert and Remove methods 2025-11-29 21:38:33 +00:00
rcourtman
00cce0ba75 Use left-aligned headers consistently in Docker table 2025-11-29 21:31:44 +00:00
rcourtman
f34a42f774 Center CPU and Memory cells in Docker container/service rows 2025-11-29 21:27:25 +00:00
rcourtman
8219ab80c2 Center CPU and Memory column headers in Docker table 2025-11-29 21:25:08 +00:00
rcourtman
87e19adac1 Convert data tables from CSS Grid to HTML tables
- Replace CSS Grid with native <table> elements across all data tables
- HTML tables naturally align columns based on widest content in each column
- Add min-width on CPU/Memory/Disk columns for proper progress bar display
- Remove responsive column header abbreviations (show full labels always)
- Remove icon components from NodeSummaryTable headers
- Simplify TemperatureGauge to text-only display (no progress bar)

Tables converted: Dashboard guest table, NodeSummaryTable, HostsOverview,
DockerUnifiedTable, DockerHostSummaryTable
2025-11-29 21:20:02 +00:00
rcourtman
dcc691b095 Add unit tests for HandleLookup hostname matching
Tests cover the hostname lookup paths in HandleLookup:
- Exact hostname match (case-insensitive)
- DisplayName match (case-insensitive)
- Short hostname match (before first dot)
- Priority of exact over short match
- Sorted iteration order behavior
- Not-found cases

12 test cases covering all hostname matching code paths.
2025-11-29 20:20:15 +00:00
rcourtman
0a623bee41 ADA: Add unit tests for isDirectLoopbackRequest 2025-11-29 20:07:59 +00:00