Commit graph

1457 commits

Author SHA1 Message Date
rcourtman
13f5ca4018 test: Add CheckHost tests (49.6%→98.3%)
Add comprehensive TestCheckHostComprehensive with 17 test cases covering:
- Empty host ID early return
- Alerts disabled early return
- DisableAllHosts clears existing alerts
- Override with Disabled clears alerts
- CPU/Memory/Disk threshold nil clears alerts
- RAID degraded/rebuilding/healthy states
- RAID with failed devices triggers critical alert
- RAID resync triggers rebuilding alert
- Existing RAID alert not duplicated (preserves start time)
- Override thresholds applied correctly
- Multiple disks handling
- Offline alert cleared when host comes online
- Tags included in metadata

Alerts package coverage: 78.6%→80.0%
2025-12-02 11:34:20 +00:00
rcourtman
53a2c2a587 fix: Prevent agent type badge flapping in UnifiedAgents view
Track previously seen host types and preserve them when one data source
temporarily has no entry for a hostname. This prevents the "Host" or
"Docker" type badge from disappearing and reappearing when websocket
updates cause momentary state inconsistencies.

The fix only preserves types if the corresponding source array has any
data at all, ensuring that intentional host removal (both arrays empty
for that host) still works correctly.

Related to #773
2025-12-02 11:29:03 +00:00
rcourtman
f4e3f625e7 test: Add CheckGuest tests (41.4%→97.4%)
Cover all CheckGuest branches:
- Early return when alerts disabled
- Early return when all guests disabled
- VM and Container type handling
- Unsupported guest type returns early
- pulse-no-alerts tag suppresses alerts
- Stopped guest triggers powered-off check
- DisableAllGuestsOffline clears tracking
- Paused guest clears powered-off alert
- Non-running guest clears metric alerts
- Running guest clears powered-off alert
- Disabled thresholds clear existing alerts
- CPU, memory, disk metric checks
- Individual disk checks (mountpoint, device, index fallback)
- Skips disk with zero total or negative usage
- I/O metrics (diskRead, diskWrite, networkIn, networkOut)
- pulse-relaxed tag applies relaxed thresholds

Alerts package coverage: 76.0%→78.6%
2025-12-02 11:27:32 +00:00
rcourtman
4ceb4f9a35 test: Add CheckNode tests (31%→100%)
Cover all CheckNode branches:
- Early return when alerts disabled
- DisableAllNodes clears existing alerts
- DisableNodesOffline clears tracking
- Offline/connection error/failed triggers offline check
- Online node clears offline alert
- Online node triggers metric checks
- Offline node skips metric checks
- Override thresholds applied correctly
- Temperature with package temp and max fallback
- Temperature skipped when unavailable/nil/no threshold
- Memory and disk metric checks

Alerts package coverage: 75.2%→76.0%
2025-12-02 11:24:04 +00:00
rcourtman
9791fc07cb test: Add suppressGuestAlerts and guestHasMonitorOnlyAlerts tests
Coverage improvements:
- suppressGuestAlerts: 37% -> 96.3%
- guestHasMonitorOnlyAlerts: 40% -> 90%

Tests cover:
- No alerts returns false
- Exact ResourceID match clears
- Prefix match (e.g., "vm100/disk1") clears
- All auxiliary maps cleared (pending, recent, suppressed, rateLimit)
- Multiple alerts cleared
- Monitor-only detection via metadata (bool and string types)
2025-12-02 11:14:30 +00:00
rcourtman
f661c5a6a8 test: Add applyThresholdOverride tests
Coverage for applyThresholdOverride: 50% -> 93.2%

Tests cover:
- Empty override returns base unchanged
- Disabled/DisableConnectivity flag overrides
- Modern CPU threshold override
- Legacy CPU threshold conversion
- Modern takes precedence over legacy
- Multiple metrics override
- Note override, clearing, trimming
- All legacy metric types (Memory, Disk, etc.)
- Temperature and Usage override
- ensureHysteresisThreshold Clear value filling
2025-12-02 11:08:58 +00:00
rcourtman
ed118c973f test: Add ClearActiveAlerts test with existing alerts
Coverage for ClearActiveAlerts: 16% -> 92%

Tests verify all internal maps are properly cleared when alerts exist:
- activeAlerts, pendingAlerts, recentAlerts
- suppressedUntil, alertRateLimit
- nodeOfflineCount, offlineConfirmations
- dockerOfflineCount, dockerStateConfirm
- ackState, recentlyResolved
2025-12-02 11:01:54 +00:00
rcourtman
219c568649 test: Add CheckDiskHealth normal path tests
Coverage for CheckDiskHealth: 51% -> 98%

Tests cover:
- Healthy disk (PASSED/OK) creates no alert
- Failed non-Samsung disk creates critical alert
- Alert cleared when disk health recovers
- Low wearout (<10%) creates warning alert
- Wearout alert updates on subsequent checks
- Wearout alert cleared when wearout >= 10%
- Empty/UNKNOWN health creates no alert
2025-12-02 10:59:48 +00:00
rcourtman
c04d559700 test: Add Docker container restart loop alert tests
Coverage for checkDockerContainerRestartLoop: 53.5% -> 95.3%

Tests cover:
- First check initializes tracking without alert
- Stable restart count doesn't alert
- Restarts under threshold (<=3) don't alert
- Restart loop threshold (>3) triggers critical alert
- Recovery after window expires clears alert
- Incremental restart accumulation
- Alert StartTime preservation on updates
2025-12-02 10:54:51 +00:00
rcourtman
b6624e32cf test: Add Docker container health and OOM kill alert tests
Coverage improvements:
- checkDockerContainerHealth: 21.1% -> 94.7%
- checkDockerContainerOOMKill: 19.2% -> 96.2%

Tests cover:
- Health states (healthy, empty, none, starting, unhealthy, degraded)
- Health alert recovery when container becomes healthy
- OOM kill detection (exit code 137)
- OOM alert deduplication (repeated 137 doesn't re-alert)
- OOM alert clearing when container recovers or exits with different code
2025-12-02 10:49:42 +00:00
rcourtman
1ed8b18c12 fix: Deadlock in CancelByAlertIDs and add tests
Fixed deadlock where CancelByAlertIDs held nq.mu.Lock() and then called
UpdateStatus() which also tried to acquire the same lock. Now uses
direct SQL while holding the lock.

Tests added for CancelByAlertIDs:
- No matching notifications (notification stays pending)
- Matching notification cancelled
- Multiple alerts with partial match (any match cancels)

Coverage: CancelByAlertIDs 65.7% -> 81.1%
2025-12-02 10:40:07 +00:00
rcourtman
5ef4587767 test: Add queue IncrementAttempt and GetQueueStats tests
Coverage improvements:
- IncrementAttempt: 0% -> 85.7%
- GetQueueStats: 0% -> 87.5%

Tests verify attempt counter increments correctly and queue stats
aggregate notification counts by status.
2025-12-02 10:31:00 +00:00
rcourtman
e27717f1a2 test: Add secure webhook client tests for redirect handling
Tests SSRF protection in webhook client:
- Redirect limit enforcement (max 3)
- Blocking redirects to private networks (10.x, 192.168.x, 172.16.x)
- Blocking redirects to link-local addresses (169.254.x)
- Allowing valid redirects to allowlisted servers

Coverage: createSecureWebhookClient 18.2% -> 100%
2025-12-02 10:26:34 +00:00
rcourtman
9118344355 fix: Isolate alerts tests with temp directories to prevent flaky failures
Tests using NewManager() were sharing /etc/pulse/alerts, causing race
conditions when running in parallel. Added newTestManager(t) helper that
creates isolated temp directories for each test.
2025-12-02 10:21:03 +00:00
rcourtman
350d21c80d test: Add diagnostics function tests for error handling
Add comprehensive tests for untested diagnostics functions:

- fingerprintPublicKey: 14 test cases covering empty/whitespace input,
  invalid key formats, truncated/malformed keys, and valid ED25519 keys

- countLegacySSHKeys: 8 test cases covering non-existent directories,
  empty directories, files without id_ prefix, multiple key types,
  and directory filtering (subdirectories not counted)

- resolveUserName: 4 test cases covering UID 0 (root), current user,
  non-existent UID fallback, and max uint32 boundary

- resolveGroupName: 4 test cases covering GID 0 (root/wheel), current
  group, non-existent GID fallback, and max uint32 boundary

Coverage: fingerprintPublicKey 0% -> 100%, countLegacySSHKeys 0% -> 100%,
resolveUserName 0% -> 100%, resolveGroupName 0% -> 100%
2025-12-02 03:39:52 +00:00
rcourtman
b053a2848b fix: Update TestPublicURLDetectionUsesForwardedHeaders for proxy hardening
The test was failing after commit d6cbfc23 added security hardening
that requires authentication and trusted proxy configuration for
X-Forwarded-* headers to be read during public URL detection.

- Add API token authentication to the test request
- Configure 127.0.0.1 as trusted proxy for the test
- Add export_test.go with ResetTrustedProxyConfigForTests() to allow
  external tests to reset the trusted proxy configuration
2025-12-02 03:16:52 +00:00
rcourtman
201f613ac3 test: Add sendNotificationsDirect email and apprise tests
Test email enabled and apprise enabled code paths.
Coverage: 66.7% → 100.0%
2025-12-02 03:08:35 +00:00
rcourtman
37ec6c3a93 test: Add scanNotification DLQ timestamp test
Test scanNotification with CompletedAt and LastAttempt populated
via DLQ path. Coverage: 61.9% → 81.0%
2025-12-02 03:04:37 +00:00
rcourtman
99a6debd3a fix: Update Channel setting not persisting after save
The Update Channel dropdown reverted to "stable" after saving because the
frontend was overwriting the user's saved preference with the running
version's channel. Now the saved setting takes priority over the detected
channel.

Related to #738
2025-12-02 03:03:51 +00:00
rcourtman
ae54cfad8c test: Add processNotification tests for all code paths
Test cancelled notification, no processor, success, and failure paths.
Coverage: 50.0% → 80.0%
2025-12-02 03:01:17 +00:00
rcourtman
ca7da7c18f test: Add CancelByAlertIDs empty input and no-match tests
Test early return for empty alertIDs and happy path with empty queue.
Coverage: 62.9% → 65.7%
2025-12-02 02:58:10 +00:00
rcourtman
7a1c9ff53f test: Add SaveNodesConfigAllowEmpty test and document deadlock
Add test for SaveNodesConfigAllowEmpty which permits explicit
deletion of all nodes. Document deadlock bug in saveNodesConfig
where empty config protection tries to call LoadNodesConfig
while holding write lock.
2025-12-02 02:54:49 +00:00
rcourtman
d0fc62d45f test: Add LoadNodesConfig PBS/PMG migration tests
Test PBS and PMG token clearing and host normalization migrations.
Coverage: 61.4% → 76.3%
2025-12-02 02:46:47 +00:00
rcourtman
6d1eb44f7b test: Add LoadEmailConfig encrypted round-trip test
Test Save+Load with encryption enabled to cover success path
after decryption. Coverage: 58.8% → 88.2%
2025-12-02 02:43:49 +00:00
rcourtman
3c1ae26166 test: Add LoadWebhooks migration and error path tests
Cover unencrypted .enc file migration fallback and legacy file
with invalid JSON graceful handling.
Coverage: 67.9% → 75.0%
2025-12-02 02:39:04 +00:00
rcourtman
9eb7c59a4d test: Add SaveAlertConfig host defaults normalization tests
Cover nil HostDefaults initialization (CPU/Memory/Disk) and clear
threshold computation when clear=0 but trigger is set.
Coverage: 68.2% → 75.3%
2025-12-02 02:37:01 +00:00
rcourtman
9027ab359b test: Add StageFile transaction tests
Cover success path, already committed error, replacing existing staged
file, and empty basename edge case.
2025-12-02 02:34:20 +00:00
rcourtman
6cb12bd048 test: Add ImportConfig error path tests
Cover empty passphrase, invalid base64, wrong passphrase decryption
failure, and invalid JSON content error paths.
Coverage: 66.7% → 73.7%
2025-12-02 02:32:06 +00:00
rcourtman
0d482f9d63 test: Add DiscoveryConfig UnmarshalJSON tests
Cover invalid JSON error path, modern field parsing, legacy field
parsing, and empty object default handling.
Coverage: 60% → 88.9%
2025-12-02 02:29:38 +00:00
rcourtman
071ccc44ec test: Add ProcessQueuedNotification error path tests
Cover invalid config JSON for email, webhook, and apprise types,
plus unknown notification type handling.
Coverage: 63.3% → 83.3%
2025-12-02 02:26:25 +00:00
rcourtman
904b088d5d test: Add Disk UnmarshalJSON RPM and error path tests
Cover RPM field handling (numeric, string, SSD, N/A, null, invalid),
invalid JSON error path, and unexpected type fallbacks for both
wearout and RPM fields.
Coverage: 50% → 95.5%
2025-12-02 02:23:44 +00:00
rcourtman
7a63cf3be9 test: Add sendNotificationsDirect tests
Cover disabled paths: all channels disabled, webhook disabled,
multiple webhooks with mixed enabled state.
Coverage: 44.4% → 66.7%
2025-12-02 02:21:46 +00:00
rcourtman
ea04e4faae test: Add sendHTMLEmailWithError tests
Cover email sending paths: empty To uses From as recipient,
nil email manager creates new one, existing manager config updates.
Coverage: 57.9% → 89.5%
2025-12-02 02:19:49 +00:00
rcourtman
9768316e07 test: Add sendGroupedApprise error path tests
Add 3 tests for Apprise notification error handling:
- No alerts returns error
- Not enabled returns error
- Empty payload (all nil alerts) returns error

Coverage: 56.2% → 75.0%
2025-12-02 02:14:13 +00:00
rcourtman
42e7359506 test: Add describeInstancesForScheduler tests
Add 6 tests for instance descriptor generation:
- No clients returns nil
- PVE only with sorted order
- PBS only
- PMG only
- All types combined
- Nil scheduler/stalenessTracker safety

Coverage: 60.7% → 62.5%
2025-12-02 02:11:14 +00:00
rcourtman
de90519b21 test: Add handleHealth method tests
Add 2 tests for health endpoint:
- POST/PUT/DELETE/PATCH return 405 Method Not Allowed
- HEAD is allowed (same as GET)

Coverage: 50% → 83.3%
2025-12-02 02:09:04 +00:00
rcourtman
2d09c28129 test: Add recordTaskResult tests
Add 6 tests for polling task result recording:
- Nil monitor safety check
- Success case resets counters
- Failure case increments counters
- Consecutive failures tracking
- Success resets failure state
- Nil internal maps don't panic

Coverage: 53.7% → 97.6%
2025-12-02 02:06:08 +00:00
rcourtman
67d322c456 test: Add ApplyHostReport error path tests
Add 4 tests for error and edge cases:
- Missing hostname returns error
- Whitespace-only hostname returns error
- Nil hostTokenBindings map is initialized
- Fallback identifier generation

Coverage: 63.7% → 70.8%
2025-12-02 02:03:03 +00:00
rcourtman
7c94f3001e test: Add ApplyDockerReport error path tests
Add 4 tests for error conditions:
- Missing identifier (no agent ID or hostname)
- Removed host rejection
- Token bound to different agent
- Missing hostname

Coverage: 63.0% → 69.5%
2025-12-02 02:00:06 +00:00
rcourtman
781f72c953 test: Add RemoveHostAgent error path tests
Add 4 tests for uncovered branches:
- Empty/whitespace hostID returns error
- Host not found returns synthetic host
- No token binding (token exists but not bound)
- Nil alertManager doesn't panic

Coverage: 64.3% → 78.6%
2025-12-02 01:56:50 +00:00
rcourtman
5ff69a7e35 test: Add adminBypassEnabled tests
Add 5 tests to cover all branches:
- Not requested (ALLOW_ADMIN_BYPASS != "1")
- Enabled with PULSE_DEV=true
- Enabled with NODE_ENV=development
- Case-insensitive NODE_ENV check
- Declined when outside dev mode

Coverage: 40% → 100%
2025-12-02 01:53:55 +00:00
rcourtman
7ed8ef2074 test: Add loadTrustedProxyCIDRs tests
Cover invalid CIDR, invalid IP, IPv6, and empty entry handling (48% to 100%)
2025-12-02 01:48:41 +00:00
rcourtman
24fbce1281 test: Add LogAuditEvent tests
Cover success and failure logging branches (66.7% to 100%)
2025-12-02 01:46:27 +00:00
rcourtman
8f42156781 test: Add SecurityHeadersWithConfig tests
Cover all CSP/X-Frame-Options embedding configurations (57.1% to 100%)
2025-12-02 01:44:22 +00:00
rcourtman
07997b3516 test: Add filesystem error tests for SessionStore
Cover saveUnsafe (57.9% to 89.5%) and load (55.6% to 74.1%) error paths
2025-12-02 01:40:54 +00:00
rcourtman
21b69607f0 test: Add filesystem error tests for CSRFTokenStore
Cover saveUnsafe (57.9% to 89.5%) and load (50.0% to 67.9%) error paths
2025-12-02 01:38:49 +00:00
rcourtman
999f19beed test: Add filesystem error tests for RecoveryTokenStore.saveUnsafe
Cover MkdirAll, WriteFile, and Rename error paths (46.7% to 86.7%)
2025-12-02 01:36:21 +00:00
rcourtman
1ec59037b9 test: Add invalid user format tests for NewClient
Test error handling for password authentication user format validation:
- Missing realm separator (no @)
- Empty user string
- Multiple @ symbols

Improves NewClient coverage from 74.2% to 83.9%.
2025-12-02 01:25:11 +00:00
rcourtman
f86ea20069 test: Add invalid value tests for VMFileSystem.UnmarshalJSON
Test error handling for JSON parsing edge cases:
- Invalid JSON syntax
- Unsupported field types (bool, array)
- Unparseable string values for total-bytes and used-bytes

Improves coverage from 83.3% to 94.4%.
2025-12-02 01:22:42 +00:00
rcourtman
67553e0098 test: Add invalid value tests for MemoryStatus.UnmarshalJSON
Test error handling for JSON parsing edge cases:
- Invalid JSON syntax
- Unsupported field types (bool, array, object)
- Unparseable string values

Improves coverage from 70.0% to 83.3%.
2025-12-02 01:20:15 +00:00