Skip to content

[management] network map tests#5795

Merged
mlsmaycon merged 4 commits intomainfrom
nm/tests
Apr 8, 2026
Merged

[management] network map tests#5795
mlsmaycon merged 4 commits intomainfrom
nm/tests

Conversation

@mlsmaycon
Copy link
Copy Markdown
Collaborator

@mlsmaycon mlsmaycon commented Apr 3, 2026

Describe your changes

Network Map Test Inventory

Complete inventory of all tests under management/ that test network map functionality directly or indirectly.

Last verified: all tests passing on branch nm/tests.


DIRECT TESTS

Tests that call GetPeerNetworkMapFromComponents, GetPeerNetworkMapComponents, CalculateNetworkMapFromComponents, GetPeerNetworkMap, NewNetworkMapBuilder, or directly construct/validate NetworkMap structs.

management/server/types/networkmap_components_correctness_test.go (NEW — 46 tests)

Tests use scalableTestAccount() (with default allow policy) or scalableTestAccountWithoutDefaultPolicy() (isolated, feature-specific connectivity only).

# Test Features Covered
1 TestComponents_PeerVisibility Peers, visibility filtering, validated peers
2 TestComponents_PeerDoesNotSeeItself Peers, self-exclusion
3 TestComponents_IntraGroupConnectivity Peers, Groups, same-group visibility
4 TestComponents_CrossGroupConnectivity Peers, Groups, Policies, cross-group visibility (isolated)
5 TestComponents_BidirectionalPolicy Policies, bidirectional rules (isolated)
6 TestComponents_ExpiredPeerInOfflineList Expiration, OfflinePeers, Settings
7 TestComponents_ExpirationDisabledSetting Account Settings, Expiration toggle
8 TestComponents_LoginExpiration_PeerLevel Per-peer login expiration
9 TestComponents_NetworkSerial Network serial propagation
10 TestComponents_NonValidatedPeerExcluded Peer validation filtering
11 TestComponents_NonValidatedTargetPeerGetsEmptyMap Validation, empty map for non-validated target
12 TestComponents_NonExistentPeerGetsEmptyMap Nonexistent peer handling
13 TestComponents_FirewallRulesGenerated Firewall rules, Policies
14 TestComponents_DropPolicyGeneratesDropRules DROP action firewall rules
15 TestComponents_DisabledPolicyIgnored Disabled policies produce no rules/peers
16 TestComponents_PortPolicy Port-specific firewall rules
17 TestComponents_PortRangePolicy Port range firewall rules (requires peer >= 0.48.0)
18 TestComponents_FirewallRuleDirection IN/OUT direction on firewall rules
19 TestComponents_RoutesIncluded Routes in network map
20 TestComponents_DisabledRouteExcluded Disabled routes filtered out
21 TestComponents_RoutesFirewallRulesForACG Route firewall rules for AccessControlGroups
22 TestComponents_HARouteDeduplication HA routes deduplicated into single entry per HA group
23 TestComponents_NetworkResourceRoutes_RouterPeer Network resources, router peer sees source peers
24 TestComponents_NetworkResourceRoutes_SourcePeerSeesRouterPeer Source peer sees router peer
25 TestComponents_DisabledNetworkResourceIgnored Disabled network resources excluded
26 TestComponents_PostureCheckFiltering_PassingPeer Posture check pass (version >= min), has resource routes
27 TestComponents_PostureCheckFiltering_FailingPeer Posture check fail sees fewer peers than passing peer (isolated)
28 TestComponents_MultiplePostureChecks Multiple posture checks (version + OS), passing/failing verified (isolated)
29 TestComponents_DNSConfigEnabled DNS enabled, nameserver groups populated
30 TestComponents_DNSDisabledByManagementGroup DNS disabled via DisabledManagementGroups
31 TestComponents_DNSNameServerGroupDistribution NS groups distributed to correct groups only
32 TestComponents_DNSCustomZone Custom DNS zone records
33 TestComponents_SSHPolicy SSH policy enables SSH, AuthorizedGroups
34 TestComponents_SSHNotEnabledWithoutPolicy SSH disabled without explicit SSH policy
35 TestComponents_AllPeersGetValidMaps All 50 validated peers get non-nil maps with correct serial
36 TestComponents_LargeScaleMapGeneration 500/1000 peer map generation works with correct output
37 TestComponents_PeerAsSourceResource SourceResource.Type=Peer targets specific peer
38 TestComponents_PeerAsDestinationResource DestinationResource.Type=Peer targets specific peer (isolated)
39 TestComponents_MultipleRulesPerPolicy Policy with 2 rules generates both sets of firewall rules
40 TestComponents_SSHAuthorizedUsersContent AuthorizedUsers map has correct machine user mappings
41 TestComponents_SSHLegacyImpliedSSH ALL protocol + SSHEnabled peer implies SSH access
42 TestComponents_RouteDefaultPermit Route without ACG gets 0.0.0.0/0 default permit
43 TestComponents_MultipleRoutersPerNetwork Network resource with 2 routers, source sees both (isolated)
44 TestComponents_PeerIsNameserverExcludedFromNSGroup Peer serving as NS excluded from its own NS group
45 TestComponents_DomainNetworkResource Domain-type network resource, source sees router (isolated)
46 TestComponents_DisabledRuleInEnabledPolicy Enabled rule generates FW, disabled rule does not

management/server/types/networkmap_golden_test.go (existing — 6 tests + 4 benchmarks)

Test Features Covered
TestGetPeerNetworkMap_Golden Legacy vs builder golden file comparison (all features)
TestGetPeerNetworkMap_Golden_WithNewPeer Incremental peer add via builder
TestGetPeerNetworkMap_Golden_WithNewRoutingPeer Router peer add via builder
TestGetPeerNetworkMap_Golden_WithDeletedPeer Peer deletion, offline list
TestGetPeerNetworkMap_Golden_WithDeletedRouterPeer Router peer deletion
TestGetPeerNetworkMap_Golden_New_WithOnPeerAddedRouter_Batched Batched router add
BenchmarkGetPeerNetworkMap Old vs new builder, 100 peers
BenchmarkGetPeerNetworkMap_AfterPeerAdded After peer add
BenchmarkGetPeerNetworkMap_AfterRouterPeerAdded After router peer add
BenchmarkGetPeerNetworkMap_AfterPeerDeleted After peer deletion

management/server/types/networkmap_comparison_test.go (existing — 2 tests + 4 benchmarks)

Test Features Covered
TestNetworkMapComponents_CompareWithLegacy Legacy vs components structural comparison
TestNetworkMapComponents_GoldenFileComparison Golden file JSON comparison
BenchmarkLegacyNetworkMap Legacy, 100 peers
BenchmarkComponentsNetworkMap Components, 100 peers
BenchmarkComponentsCreation Components extraction only
BenchmarkCalculationFromComponents Calculation from components only

management/server/types/account_test.go (existing — 17 tests)

Test Features Covered
Test_GetResourceRoutersMap Resource routers map helper
Test_GetResourcePoliciesMap Resource policies map helper
Test_AddNetworksRoutingPeersAddsMissingPeers Router peer injection into peer list
Test_AddNetworksRoutingPeersIgnoresExistingPeers Router peer dedup
Test_AddNetworksRoutingPeersAddsExpiredPeers Expired router handling
Test_AddNetworksRoutingPeersExcludesSelf Self-exclusion in routing
Test_AddNetworksRoutingPeersHandlesNoMissingPeers No-op when all present
Test_NetworksNetMapGenWithNoPostureChecks Resources without posture checks
Test_NetworksNetMapGenWithPostureChecks Resources with posture check (pass)
Test_NetworksNetMapGenWithNoMatchedPostureChecks Resources with posture check (fail)
Test_NetworksNetMapGenWithTwoPoliciesAndPostureChecks Two policies + posture
Test_NetworksNetMapGenWithTwoPostureChecks Two posture checks on one resource
Test_NetworksNetMapGenShouldExcludeOtherRouters Router isolation between networks
Test_ExpandPortsAndRanges_SSHRuleExpansion SSH port expansion logic
Test_GetActiveGroupUsers Active group users map
Test_FilterZoneRecordsForPeers DNS zone record filtering
Test_filterPeerAppliedZones Zone application filtering

management/server/account_test.go (existing — 2 tests)

Test Features Covered
TestAccount_GetPeerNetworkMap Expiration, OfflinePeers, Settings
TestAccount_GetRoutesToSync Route sync, HA dedup

management/server/route_test.go (existing — 3 tests)

Test Features Covered
TestGetNetworkMap_RouteSyncPeerGroups Routes with peer groups in netmap
TestGetNetworkMap_RouteSync Route synchronization in netmap
TestAccount_GetPeerNetworkResourceFirewallRules Resource firewall rules

management/server/peer_test.go (existing — 1 test)

Test Features Covered
TestToSyncResponse Full proto conversion (Peers, Routes, DNS, SSH, FW rules, Settings)

management/server/types/networkmap_benchmark_test.go (NEW — 7 benchmarks)

All benchmarks are skipped in CI (skipCIBenchmark). Run locally with go test -bench=....

Benchmark Features Covered
BenchmarkNetworkMapGeneration_Components Components, 100-30k peers
BenchmarkNetworkMapGeneration_AllPeers All-peers update (components), 100-5k
BenchmarkNetworkMapGeneration_ComponentsCreation Components extraction, 100-30k
BenchmarkNetworkMapGeneration_ComponentsCalculation Calculation from components, 100-30k
BenchmarkNetworkMapGeneration_PrecomputeMaps ResourcePoliciesMap, ResourceRoutersMap, ActiveGroupUsers
BenchmarkNetworkMapGeneration_GroupScaling 1-500 groups at 1000 peers
BenchmarkNetworkMapGeneration_PeerScaling 50-30k peers at fixed ratio

INDIRECT TESTS

Tests that trigger network map generation through higher-level operations (LoginPeer, SyncPeer, AddPeer, UpdateAccountPeers, etc.).

management/server/peer_test.go

Test Trigger Features
TestAccountManager_GetNetworkMap GetNetworkMap Peers, Groups
TestAccountManager_GetNetworkMap_Experimental GetNetworkMap (experimental) Peers, Builder
TestAccountManager_GetNetworkMapWithPolicy GetNetworkMap + policies Peers, Groups, Policies
TestAccountManager_GetPeerNetwork GetPeerNetwork Network info
TestDefaultAccountManager_GetPeers GetPeers Peers, validation
TestPeerAccountPeersUpdate UpdatePeer -> UpdateAccountPeers Peers, Groups, Expiration
TestUpdateAccountPeers UpdateAccountPeers All features
TestUpdateAccountPeers_Experimental UpdateAccountPeers (experimental) Builder
Test_LoginPeer LoginPeer -> netmap Peers, DNS, Routes, SSH
Test_RegisterPeerByUser AddPeer -> netmap Peers, Groups
Test_RegisterPeerBySetupKey AddPeer -> netmap Peers, Groups, SetupKeys
Test_AddPeer AddPeer -> netmap Peers, Groups
TestAddPeer_UserPendingApprovalBlocked AddPeer + approval Peers, Approval
TestAddPeer_ApprovedUserCanAddPeers AddPeer + approval Peers, Approval
TestLoginPeer_UserPendingApprovalBlocked LoginPeer + approval Peers, Approval
TestLoginPeer_ApprovedUserCanLogin LoginPeer + approval Peers, Approval
TestHandleUserAddedPeer OnPeerAddedByUser Peers, Events
TestHandleSetupKeyAddedPeer OnPeerAddedBySetupKey Peers, SetupKeys
TestProcessPeerAddAuth AddPeer auth Peers, Auth
BenchmarkGetPeers GetPeers Peers (50-5000)
BenchmarkUpdateAccountPeers UpdateAccountPeers All features (50-5000)

management/server/account_test.go

Test Trigger Features
TestAccountManager_AddPeer AddPeer Peers, Groups
TestAccountManager_AddPeerWithUserID AddPeer Peers, UserID
TestAccountManager_NetworkUpdates_DeletePeer DeletePeer -> UpdateAccountPeers Peers, Deletion
TestAccountManager_NetworkUpdates_DeletePeer_Experimental DeletePeer (experimental) Peers, Builder
TestDefaultAccountManager_UpdatePeer_PeerLoginExpiration UpdatePeer -> expiration Peers, Expiration, Settings
TestDefaultAccountManager_UpdateAccountSettings_PeerLoginExpiration Settings -> expiration Settings, Expiration
TestDefaultAccountManager_UpdateAccountSettings_PeerApproval Settings -> approval Settings, Approval
TestDefaultAccountManager_UpdatePeerIP UpdatePeerIP Peers, IP
BenchmarkSyncAndMarkPeer SyncAndMarkPeer All features (50-5000)
BenchmarkLoginPeer_ExistingPeer LoginPeer (existing) All features (50-5000)
BenchmarkLoginPeer_NewPeer LoginPeer (new) All features (50-5000)

management/server/dns_test.go

Test Trigger Features
TestGetNetworkMap_DNSConfigSync GetNetworkMap with DNS updates DNS, Nameservers
TestDNSAccountPeersUpdate SaveDNSSettings -> UpdateAccountPeers DNS, Nameservers

management/server/route_test.go

Test Trigger Features
TestRouteAccountPeersUpdate SaveRoute -> UpdateAccountPeers Routes, Firewall

management/server/group_test.go

Test Trigger Features
TestGroupAccountPeersUpdate SaveGroup -> UpdateAccountPeers Groups, Policies

management/server/policy_test.go

Test Trigger Features
TestPolicyAccountPeersUpdate SavePolicy -> UpdateAccountPeers Policies, Firewall

management/server/nameserver_test.go

Test Trigger Features
TestNameServerAccountPeersUpdate SaveNameServerGroup -> UpdateAccountPeers DNS, Nameservers

management/server/setupkey_test.go

Test Trigger Features
TestSetupKeyAccountPeersUpdate SaveSetupKey -> UpdateAccountPeers SetupKeys, Groups

management/server/posture_checks_test.go

Test Trigger Features
TestPostureCheckAccountPeersUpdate SavePostureCheck -> UpdateAccountPeers PostureChecks

management/server/user_test.go

Test Trigger Features
TestUserAccountPeersUpdate SaveUser -> UpdateAccountPeers Users, Groups

management/server/management_test.go (gRPC integration)

Test Trigger Features
TestSyncNewPeerConfiguration gRPC Sync Peers, Config
TestSyncThreePeers gRPC Sync (3 peers) Peers, Groups
TestSyncNewPeerUpdate gRPC Sync + new peer Peers, Updates
TestSync10PeersGetUpdates gRPC Sync (10 peers) Peers, Policies, Routes
TestConcurrentPeersNoDuplicateIPs Concurrent gRPC Sync Peers, IP alloc, Concurrency

management/server/management_proto_test.go

Test Trigger Features
Test_LoginPerformance LoginPeer perf test Login, Peers

HTTP Handler Integration Tests (management/server/http/testing/integration/)

Test File Features
Test_Peers_GetAll peers_handler Peers
Test_Peers_GetById peers_handler Peers
Test_Peers_Update peers_handler Peers -> UpdateAccountPeers
Test_Peers_Delete peers_handler Peers -> UpdateAccountPeers
Test_Peers_GetAccessiblePeers peers_handler Peers, Access control
Test_Groups_GetAll groups_handler Groups
Test_Groups_Update groups_handler Groups -> UpdateAccountPeers
Test_Groups_Delete groups_handler Groups -> UpdateAccountPeers
Test_Routes_GetAll routes_handler Routes
Test_Routes_Create routes_handler Routes -> UpdateAccountPeers
Test_Routes_Update routes_handler Routes -> UpdateAccountPeers
Test_Routes_Delete routes_handler Routes -> UpdateAccountPeers
Test_Policies_GetAll policies_handler Policies
Test_Policies_Create policies_handler Policies -> UpdateAccountPeers
Test_Policies_Update policies_handler Policies -> UpdateAccountPeers
Test_Policies_Delete policies_handler Policies -> UpdateAccountPeers
Test_DnsSettings_Update dns_handler DNS -> UpdateAccountPeers
Test_Nameservers_GetAll dns_handler DNS, Nameservers
Test_Nameservers_Create dns_handler DNS -> UpdateAccountPeers
Test_Nameservers_Update dns_handler DNS -> UpdateAccountPeers
Test_Nameservers_Delete dns_handler DNS -> UpdateAccountPeers
Test_NetworkResources_* (6 tests) networks_handler Network Resources, CRUD
Test_NetworkRouters_* (6 tests) networks_handler Network Routers, CRUD

HTTP Handler Benchmarks (management/server/http/testing/benchmarks/) (require -tags=benchmark)

Benchmark Features
BenchmarkPeersHandler_* (Create/Update/GetOne/GetAll/Delete) Peers API (XS to XL: 5-25000 peers)
BenchmarkSetupKeysHandler_* SetupKeys API
BenchmarkUsersHandler_* Users API

Store Benchmarks (management/server/store/)

Benchmark Features
BenchmarkGetAccount Account loading (200 peers, 30 groups, 50 policies)
BenchmarkGetAccountPeers Peer querying
BenchmarkTest_StoreWrite / BenchmarkTest_StoreRead Store I/O

FEATURE COVERAGE MATRIX

Feature Direct Tests Indirect Tests Gaps
Peers (visibility, self-exclusion) 46+ tests 20+ tests None
Groups (intra/cross-group, isolated) 5 tests 10+ tests None
Policies (accept/drop, ports, ranges, direction, disabled rules) 9 tests 5+ tests None
Firewall Rules 9 tests 3+ tests None
Routes (enabled/disabled, HA dedup, ACG) 4 tests 3+ tests None
Route Firewall Rules 2 tests 1+ tests None
Network Resources (router, source, disabled) 3 tests 12+ tests None
Multiple Routers 1 test None None
Domain Resources 1 test None None
Posture Checks (pass/fail, multiple, isolated) 3 tests + 5 in account_test 1 test None
DNS (enabled/disabled, NS groups, custom zones) 4 tests 2+ tests None
Nameserver Self-Exclusion 1 test None None
SSH (policy, legacy, authorized users) 4 tests None None
Peer Expiration (login, per-peer, settings) 3 tests 3+ tests None
Account Settings (serial, expiration toggle) 2 tests 2+ tests None
Peer Validation (non-validated, nonexistent) 3 tests None None
Peer-as-Resource (source/destination) 2 tests None None
Multiple Rules per Policy 1 test None None
Disabled Rule in Enabled Policy 1 test None None
Route Default Permit (no ACG) 1 test None None
Cross-Peer Consistency 2 tests None None
ToSyncResponse (proto conversion) 1 test 5+ gRPC tests No benchmark at scale
ForwardingRules None None Populated by proxy controller, not components
Extra DNS Labels None None Minor, peer-level feature
Inactivity Expiration None None Handled by account manager, not components

SUMMARY

  • Direct tests: 77 (46 new correctness + 6 golden + 2 comparison + 17 types/account_test + 2 account_test + 3 route_test + 1 peer_test)
  • Direct benchmarks: 15 (7 new + 4 golden + 4 comparison)
  • Indirect tests: 65+
  • Grand total: 157+ tests exercising network map functionality

Test isolation notes

Tests marked "(isolated)" use scalableTestAccountWithoutDefaultPolicy() which omits the blanket
group-all allow rule, ensuring the test validates feature-specific connectivity rather than passing
vacuously through the catch-all policy. All new benchmarks use skipCIBenchmark() to avoid running
in CI environments.

Issue ticket number and link

Stack

Checklist

  • Is it a bug fix
  • Is a typo/documentation fix
  • Is a feature enhancement
  • It is a refactor
  • Created tests that fail without the change (if possible)

By submitting this pull request, you confirm that you have read and agree to the terms of the Contributor License Agreement.

Documentation

Select exactly one:

  • I added/updated documentation for this change
  • Documentation is not needed for this change (explain why)

Docs PR URL (required if "docs added" is checked)

Paste the PR link from https://github.com/netbirdio/docs here:

https://github.com/netbirdio/docs/pull/__

Summary by CodeRabbit

  • Tests
    • Added a comprehensive benchmark suite for network-map generation covering single-peer, all-peers, component creation, component calculation, precomputed maps, and scaling analyses across varied peer/group sizes.
    • Added extensive correctness tests with a scalable account builder exercising peer visibility, policies (firewall/SSH/routes), DNS/network resources, posture checks, login expiration, and components-vs-legacy output consistency.

@mlsmaycon mlsmaycon changed the title Nm/tests [management] network map tests Apr 3, 2026
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Apr 3, 2026

📝 Walkthrough

Walkthrough

Added two new test files: extensive correctness tests validating network-map component outputs and a suite of benchmarks measuring network-map generation and related sub-operations across multiple peer/group scales. Changes are limited to test code and introduce no production API changes. (43 words)

Changes

Cohort / File(s) Summary
Benchmarks
management/server/types/networkmap_benchmark_test.go
New benchmark suite introducing benchmarkScale, defaultScales, CI-skip helper, and multiple benchmarks measuring GetPeerNetworkMapFromComponents, component creation/calculation, precomputed map access, and scaling across peers/groups. Reports allocations and uses sub-benchmarks per scale.
Correctness Tests
management/server/types/networkmap_components_correctness_test.go
New comprehensive correctness tests and a scalable account builder validating peer visibility, login expiration, policies → firewall rules, routes and route ACLs, network resources/routers, posture-check gating, DNS behavior, SSH/AuthorizedUsers handling, and parity between component-based and legacy outputs.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • crn4
  • pascal-fischer

Poem

🐇 I hop through peers, groups, and time,

Benchmarks hum and tests align,
Components, builders, legacy too,
I nibble bugs and chase the view,
A carrot cheers each passing line.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 55.17% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title '[management] network map tests' clearly identifies the main change (adding network map tests to management module) and is specific enough to convey the primary purpose.
Description check ✅ Passed The PR description is comprehensive and well-structured, covering all required template sections including change description, documentation status, and contributor license agreement confirmation.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch nm/tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@management/server/types/networkmap_benchmark_test.go`:
- Around line 138-145: The benchmark currently reconstructs the
NetworkMapBuilder inside the timed loop; move the
types.NewNetworkMapBuilder(account, validatedPeers) call so it runs once before
b.ResetTimer() and reuse that builder within the for range b.N loop, calling
builder.GetPeerNetworkMap(ctx, peerID, nbdns.CustomZone{}, nil, validatedPeers,
nil) for each peerID; this makes the "builder/..." sub-benchmark measure only
generation cost (like the legacy branches) and leaves
BenchmarkNetworkMapGeneration_BuilderInit to measure initialization separately.
- Around line 243-258: The benchmark currently measures setup/teardown work
(creating NewNetworkMapBuilder, allocating/timestamping a Peer, and mutating
account/validatedPeers) rather than just OnPeerAddedIncremental; fix it by
moving all builder/peer/account setup and cleanup outside the timed section or
by bracketing only the call to builder.OnPeerAddedIncremental with
b.StopTimer()/b.StartTimer() (or ResetTimer) so the timer runs only for the
invocation of OnPeerAddedIncremental; reference NewNetworkMapBuilder,
OnPeerAddedIncremental, account, validatedPeers and builder to locate and adjust
the code.

In `@management/server/types/networkmap_components_correctness_test.go`:
- Around line 628-665: Tests TestComponents_PostureCheckFiltering_FailingPeer
and TestComponents_MultiplePostureChecks only assert NotNil, so add concrete
assertions comparing the network maps returned by componentsNetworkMap for a
passing peer ("peer-0") and a failing peer ("peer-1"): verify that nm0 (from
"peer-0") contains resource/router routes (e.g., nm0.Routes length > nm1.Routes,
presence of resource-specific entries in nm0.ResourceRoutes or route.TargetType
== "resource") and that nm1 lacks those same entries or has visibility flags
disabled (e.g., Router visibility false) to demonstrate posture gating removed
resource routes for the failing peer; update
TestComponents_PostureCheckFiltering_PassingPeer/TestComponents_PostureCheckFiltering_FailingPeer
to assert these concrete deltas between nm0 and nm1 after calling
componentsNetworkMap.
- Around line 83-90: The test fixture currently appends a blanket allow policy
(policies append of &types.Policy with ID "policy-all" containing PolicyRule ID
"rule-all" that references "group-all") which makes many targeted tests vacuous;
change the fixture to make this baseline policy optional by adding a disable
flag or option (e.g., disableDefaultPolicy/DisableBaselinePolicy) to the test
setup and avoid appending the &types.Policy{"policy-all"/"rule-all"/"group-all"}
when that option is set, then update the isolated tests (e.g.,
TestComponents_CrossGroupConnectivity, TestComponents_BidirectionalPolicy,
TestComponents_PeerAsDestinationResource,
TestComponents_MultipleRoutersPerNetwork, TestComponents_DomainNetworkResource)
to construct the fixture with the flag enabled so they run without the baseline
allow rule.
- Around line 548-573: The test TestComponents_HARouteDeduplication currently
only asserts at least one HA route exists, which won't catch duplicate-emission
regressions; update the test to assert the exact expected representation for the
haNetwork by verifying nm.Routes yields exactly one entry for haNetwork (e.g.
replace assert.GreaterOrEqual(t, haRoutes, 1) with an exact assertion like
assert.Equal(t, 1, haRoutes) or assert.Len for the filtered slice) and
optionally validate that the single emitted route's fields
(PeerID/Metric/PeerGroups) match the expected selection logic from
componentsNetworkMap so the deduplication behavior is enforced.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: dc4febdf-5894-46ba-ad5e-80bb200a11eb

📥 Commits

Reviewing files that changed from the base of the PR and between 28fbf96 and f914296.

📒 Files selected for processing (2)
  • management/server/types/networkmap_benchmark_test.go
  • management/server/types/networkmap_components_correctness_test.go

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
management/server/types/networkmap_components_correctness_test.go (2)

545-555: Assertion is vacuous when all routes are disabled.

If GetPeerNetworkMapFromComponents correctly excludes disabled routes, nm.Routes will be empty and the loop assertion never executes. Add an explicit emptiness check to verify the expected behavior.

♻️ Suggested fix
 func TestComponents_DisabledRouteExcluded(t *testing.T) {
 	account, validatedPeers := scalableTestAccount(50, 2)
 	for _, r := range account.Routes {
 		r.Enabled = false
 	}
 	nm := componentsNetworkMap(account, "peer-0", validatedPeers)
 	require.NotNil(t, nm)
-	for _, r := range nm.Routes {
-		assert.True(t, r.Enabled, "only enabled routes should appear")
-	}
+	assert.Empty(t, nm.Routes, "disabled routes should not appear in network map")
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@management/server/types/networkmap_components_correctness_test.go` around
lines 545 - 555, The test TestComponents_DisabledRouteExcluded currently
disables all routes and then loops over nm.Routes making assertions that only
run if nm.Routes is non-empty, which is vacuous; update the test (which builds
its input via scalableTestAccount and calls
componentsNetworkMap/GetPeerNetworkMapFromComponents) to explicitly assert that
nm.Routes is empty when all account.Routes are disabled (e.g., use require.Empty
or assert.Empty on nm.Routes) and keep the existing loop/true assertion only as
a secondary check if you change the setup to leave some routes enabled.

631-639: Test assertion does not verify disabled resources are ignored.

assert.NotNil(t, nm.Network) only confirms the network map was created, which will always succeed for a valid account. Consider asserting that resource-related routes or router peer visibility are absent when resources are disabled.

♻️ Suggested improvement
 func TestComponents_DisabledNetworkResourceIgnored(t *testing.T) {
-	account, validatedPeers := scalableTestAccount(50, 5)
+	// Use account without default policy so resource policies provide the only
+	// connectivity to router peers
+	account, validatedPeers := scalableTestAccountWithoutDefaultPolicy(50, 5)
+
+	// Capture router peer IDs before disabling resources
+	routerPeerIDs := make(map[string]bool)
+	for _, nr := range account.NetworkRouters {
+		routerPeerIDs[nr.Peer] = true
+	}
+
 	for _, nr := range account.NetworkResources {
 		nr.Enabled = false
 	}
 	nm := componentsNetworkMap(account, "peer-0", validatedPeers)
 	require.NotNil(t, nm)
-	assert.NotNil(t, nm.Network)
+
+	// With resources disabled, resource policies should not grant visibility
+	// to router peers (assuming no other policies connect them)
+	for _, p := range nm.Peers {
+		if routerPeerIDs[p.ID] {
+			// Router peer visible via resource policy would indicate disabled
+			// resources are not being properly ignored
+			t.Logf("Warning: router peer %s still visible despite disabled resources", p.ID)
+		}
+	}
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@management/server/types/networkmap_components_correctness_test.go` around
lines 631 - 639, The test TestComponents_DisabledNetworkResourceIgnored
currently only checks nm.Network is non-nil; change it to verify that disabled
resources produce no network artifacts by inspecting the generated map from
componentsNetworkMap: iterate account.NetworkResources (which you set
Enabled=false) and assert that nm.Network.Routes contains no routes referencing
any resource IDs and that nm.Network.Routers (or equivalent router/peer
visibility structures returned by componentsNetworkMap) do not include peers or
entries derived from those resource IDs; use explicit checks like
len(nm.Network.Routes)==0 or absence of resource.ID in route/peer lists to
ensure disabled resources are ignored.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@management/server/types/networkmap_components_correctness_test.go`:
- Around line 545-555: The test TestComponents_DisabledRouteExcluded currently
disables all routes and then loops over nm.Routes making assertions that only
run if nm.Routes is non-empty, which is vacuous; update the test (which builds
its input via scalableTestAccount and calls
componentsNetworkMap/GetPeerNetworkMapFromComponents) to explicitly assert that
nm.Routes is empty when all account.Routes are disabled (e.g., use require.Empty
or assert.Empty on nm.Routes) and keep the existing loop/true assertion only as
a secondary check if you change the setup to leave some routes enabled.
- Around line 631-639: The test TestComponents_DisabledNetworkResourceIgnored
currently only checks nm.Network is non-nil; change it to verify that disabled
resources produce no network artifacts by inspecting the generated map from
componentsNetworkMap: iterate account.NetworkResources (which you set
Enabled=false) and assert that nm.Network.Routes contains no routes referencing
any resource IDs and that nm.Network.Routers (or equivalent router/peer
visibility structures returned by componentsNetworkMap) do not include peers or
entries derived from those resource IDs; use explicit checks like
len(nm.Network.Routes)==0 or absence of resource.ID in route/peer lists to
ensure disabled resources are ignored.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: e3373bba-9d6a-4fec-a934-39b4ef45984f

📥 Commits

Reviewing files that changed from the base of the PR and between f914296 and 971e68d.

📒 Files selected for processing (2)
  • management/server/types/networkmap_benchmark_test.go
  • management/server/types/networkmap_components_correctness_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • management/server/types/networkmap_benchmark_test.go

…ased test coverage for clarity and scalability.
@sonarqubecloud
Copy link
Copy Markdown

sonarqubecloud bot commented Apr 4, 2026

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
management/server/types/networkmap_benchmark_test.go (2)

29-33: Harden CI benchmark skip detection.

Line 30 only skips when CI=="true". Some environments set CI=1 or uppercase variants, so benchmarks may run unintentionally.

♻️ Proposed tweak
 import (
 	"context"
 	"fmt"
 	"os"
+	"strconv"
 	"testing"
@@
 func skipCIBenchmark(b *testing.B) {
-	if os.Getenv("CI") == "true" {
+	if ci, err := strconv.ParseBool(os.Getenv("CI")); err == nil && ci {
 		b.Skip("Skipping benchmark in CI")
 	}
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@management/server/types/networkmap_benchmark_test.go` around lines 29 - 33,
The CI skip currently only checks for exact "true" in skipCIBenchmark, which
misses values like "1" or different case; update skipCIBenchmark to read
os.Getenv("CI"), normalize it (e.g., strings.ToLower or strings.EqualFold) and
treat "1" and "true" (case-insensitive) as true — if the value matches either,
call b.Skip("Skipping benchmark in CI"); reference the skipCIBenchmark function
and the use of os.Getenv("CI") when making the change.

77-80: Make peer iteration deterministic to reduce benchmark noise.

Line 77–80 collects peer IDs from map iteration, so order is randomized and can add variance across runs. Sorting once will make comparisons steadier.

♻️ Proposed tweak
 import (
 	"context"
 	"fmt"
 	"os"
+	"sort"
 	"testing"
@@
 		peerIDs := make([]string, 0, len(account.Peers))
 		for peerID := range account.Peers {
 			peerIDs = append(peerIDs, peerID)
 		}
+		sort.Strings(peerIDs)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@management/server/types/networkmap_benchmark_test.go` around lines 77 - 80,
The benchmark collects peer IDs from the map account.Peers into peerIDs, which
yields nondeterministic order and noise; after building peerIDs (the loop that
appends peerID), sort the slice (e.g., with sort.Strings(peerIDs)) so iteration
is deterministic and add the required import for sort; locate the peerIDs
variable and the for peerID := range account.Peers loop to apply this change.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@management/server/types/networkmap_benchmark_test.go`:
- Around line 29-33: The CI skip currently only checks for exact "true" in
skipCIBenchmark, which misses values like "1" or different case; update
skipCIBenchmark to read os.Getenv("CI"), normalize it (e.g., strings.ToLower or
strings.EqualFold) and treat "1" and "true" (case-insensitive) as true — if the
value matches either, call b.Skip("Skipping benchmark in CI"); reference the
skipCIBenchmark function and the use of os.Getenv("CI") when making the change.
- Around line 77-80: The benchmark collects peer IDs from the map account.Peers
into peerIDs, which yields nondeterministic order and noise; after building
peerIDs (the loop that appends peerID), sort the slice (e.g., with
sort.Strings(peerIDs)) so iteration is deterministic and add the required import
for sort; locate the peerIDs variable and the for peerID := range account.Peers
loop to apply this change.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 702b73c1-b5d5-469d-9130-298b640ff7f3

📥 Commits

Reviewing files that changed from the base of the PR and between 971e68d and 9a21ccc.

📒 Files selected for processing (2)
  • management/server/types/networkmap_benchmark_test.go
  • management/server/types/networkmap_components_correctness_test.go
✅ Files skipped from review due to trivial changes (1)
  • management/server/types/networkmap_components_correctness_test.go

@mlsmaycon mlsmaycon merged commit 099c493 into main Apr 8, 2026
47 checks passed
@mlsmaycon mlsmaycon deleted the nm/tests branch April 8, 2026 19:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants