Repository navigation
refactor: reduce ExecuteDescribeStacks cyclomatic complexity 247→10 + near-100% unit test coverage - #2204
Conversation
terraform clean into testable pkg with adapter pattern
…verage helpers Co-authored-by: nitrocode <[email protected]>
terraform clean into testable pkg with adapter pattern
Dependency Review✅ No vulnerabilities or license issues found.Scanned FilesNone |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #2204 +/- ##
==========================================
+ Coverage 77.01% 77.19% +0.18%
==========================================
Files 1012 1013 +1
Lines 96029 95730 -299
==========================================
- Hits 73952 73903 -49
+ Misses 17813 17653 -160
+ Partials 4264 4174 -90
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
…be_stacks_component_processor Co-authored-by: nitrocode <[email protected]>
…blog Co-authored-by: nitrocode <[email protected]>
|
CodeRabbit (@coderabbitai) full review please. |
🧩 Analysis chain🏁 Script executed: Length of output: 58947
Round 4 Audit Status — Current Code
✅ Item 1 — Fixed
if p.includeEmptyStacks && (stackManifestName != "" || p.atmosConfig.Stacks.NameTemplate == "") {Ghost entry is correctly suppressed when ✅ Item 2 — Fixed
|
📝 WalkthroughWalkthroughRefactored Changes
Sequence DiagramsequenceDiagram
participant ExecuteDescribeStacks as ExecuteDescribeStacks
participant Processor as describeStacksProcessor
participant StackIterator as Stack File Iteration
participant ComponentIterator as Component Processing
participant Metadata as Metadata Resolution
participant Output as Final Output Map
ExecuteDescribeStacks->>Processor: newDescribeStacksProcessor(config, filters, ...)
ExecuteDescribeStacks->>StackIterator: iterate stack files
StackIterator->>Processor: processStackFile(fileName, stackMap)
Processor->>ComponentIterator: iterate component types
ComponentIterator->>Metadata: resolveStackName(manifest/template/pattern)
Metadata->>Metadata: applyTerraformMetadataInheritance (if enabled)
Metadata->>Output: extract/filter sections → finalStacksMap
ComponentIterator->>Output: add/merge component entry
Processor->>ExecuteDescribeStacks: return finalStacksMap
ExecuteDescribeStacks->>Output: filterEmptyFinalStacks (if !includeEmptyStacks)
Output-->>ExecuteDescribeStacks: processed output
Estimated code review effort🎯 4 (Complex) | ⏱️ ~55 minutes Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (4)
internal/exec/describe_stacks_test.go (1)
435-454: This test never provesincludeEmptyStacksworks.It only checks
NoErrorandNotNil, so it still passes if thetruepath returns exactly the same map as the default path. Please assert on a known empty-stack key from the fixture, or at least a count/key delta against anincludeEmptyStacks=falsecall.Based on learnings:
Test behavior, not implementation; never test stub functions (implement or remove); avoid tautological tests; make code testable via DI; no coverage theater; remove always-skipped tests; use errors.Is() for error checking.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/exec/describe_stacks_test.go` around lines 435 - 454, The test TestExecuteDescribeStacks_IncludeEmptyStacks currently only checks for no error and non-nil result and doesn't verify includeEmptyStacks behavior; update it to call ExecuteDescribeStacks twice (once with includeEmptyStacks=false and once with includeEmptyStacks=true) and assert the difference: either assert the known empty-stack key from the fixtures is present in the map returned when includeEmptyStacks=true (using the expected stack key from the fixtures) and absent when false, or assert that the map length increases when includeEmptyStacks=true (i.e., compare len(stacksMapFalse) < len(stacksMapTrue)); use the ExecuteDescribeStacks call sites in the test to obtain both maps and add the appropriate require/assert checks.internal/exec/describe_stacks_component_processor_test.go (3)
414-483: Consider consolidating into a table-driven test.These seven tests share identical structure. A single table-driven test would reduce boilerplate and make adding new cases easier.
Example consolidation
func TestHasStackExplicitComponents(t *testing.T) { tests := []struct { name string stack map[string]any want bool }{ {"with terraform", map[string]any{cfg.ComponentsSectionName: map[string]any{cfg.TerraformSectionName: map[string]any{"vpc": map[string]any{}}}}, true}, {"empty terraform", map[string]any{cfg.ComponentsSectionName: map[string]any{cfg.TerraformSectionName: map[string]any{}}}, false}, {"with helmfile", map[string]any{cfg.ComponentsSectionName: map[string]any{cfg.HelmfileSectionName: map[string]any{"chart": map[string]any{}}}}, true}, {"with packer", map[string]any{cfg.ComponentsSectionName: map[string]any{cfg.PackerSectionName: map[string]any{"ami": map[string]any{}}}}, true}, {"with ansible", map[string]any{cfg.ComponentsSectionName: map[string]any{cfg.AnsibleSectionName: map[string]any{"playbook": map[string]any{}}}}, true}, {"no components", map[string]any{}, false}, {"nil components", map[string]any{cfg.ComponentsSectionName: nil}, false}, {"wrong type", map[string]any{cfg.ComponentsSectionName: "not-a-map"}, false}, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { assert.Equal(t, tc.want, hasStackExplicitComponents(tc.stack)) }) } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/exec/describe_stacks_component_processor_test.go` around lines 414 - 483, Consolidate the seven individual tests into one table-driven test for hasStackExplicitComponents: create a slice of test cases each with name, stack (using cfg.ComponentsSectionName and the specific keys cfg.TerraformSectionName, cfg.HelmfileSectionName, cfg.PackerSectionName, cfg.AnsibleSectionName, nil and wrong-type cases) and expected bool, then iterate and call t.Run for each case and assert.Equal(t, tc.want, hasStackExplicitComponents(tc.stack)); keep the original case variants (empty terraform, with terraform, helmfile, packer, ansible, no components, nil components, wrong type) so behavior is preserved.
270-274: Consider ok-guarded assertions for clearer test failures.Direct type assertions here will panic if the map structure changes, producing a less informative failure message than a
require.True(t, ok)check would.Suggested improvement
- prodEntry := finalMap["prod"].(map[string]any) - comps := prodEntry[cfg.ComponentsSectionName].(map[string]any) - tf := comps["terraform"].(map[string]any) - assert.NotNil(t, tf["vpc"]) + prodEntry, ok := finalMap["prod"].(map[string]any) + require.True(t, ok, "prod entry should be map[string]any") + comps, ok := prodEntry[cfg.ComponentsSectionName].(map[string]any) + require.True(t, ok, "components section should be map[string]any") + tf, ok := comps["terraform"].(map[string]any) + require.True(t, ok, "terraform section should be map[string]any") + assert.NotNil(t, tf["vpc"])🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/exec/describe_stacks_component_processor_test.go` around lines 270 - 274, The test currently uses unchecked type assertions for prodEntry, comps and tf (prodEntry := finalMap["prod"].(map[string]any), comps := prodEntry[cfg.ComponentsSectionName].(map[string]any), tf := comps["terraform"].(map[string]any)) which will panic on structural changes; replace each direct assertion with an ok-guarded check (e.g., v, ok := finalMap["prod"].(map[string]any); require.True(t, ok) and similarly for comps using cfg.ComponentsSectionName and for tf using "terraform"), then continue to assert the presence of tf["vpc"] with require/ assert as appropriate so failures produce informative messages instead of panics.
14-17: File length exceeds 600 lines but cohesion is good.At 1553 lines, this exceeds the typical guideline. However, all tests cover a single processor with logical grouping via comment separators. Splitting would fragment related tests unnecessarily. Consider this acceptable for comprehensive processor coverage.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/exec/describe_stacks_component_processor_test.go` around lines 14 - 17, The test file is intentionally long because it comprehensively covers the extractDescribeComponentSections processor; do not split tests. Instead, keep the current structure and add a short package/top-of-file comment explaining that the 1500+ line length is deliberate because all tests target extractDescribeComponentSections and are grouped by logical comment separators to preserve cohesion and readability; ensure the comment references extractDescribeComponentSections so reviewers understand the rationale.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@internal/exec/describe_stacks_component_processor.go`:
- Around line 167-170: The code mutates shared componentSection maps before
filters run, allowing filtered-out components to alter shared stack state; fix
by either performing the filter fast-exit before any in-place edits or by
cloning the componentSection map prior to normalization/metadata inheritance so
modifications do not affect the original shared map. Concretely, in the
DescribeStacks component processing path (look for componentSection,
cfg.ComponentSectionName, componentName, applyTerraformMetadataInheritance, and
the callers FindStacksMap / ExecuteDescribeStacks), move the filter check ahead
of the block that sets the default component key and calls
applyTerraformMetadataInheritance, or create a shallow copy of componentSection
at the start of that processing and run normalization/mutation on the copy
instead.
- Around line 98-113: The pre-creation of an empty stack entry using initialName
(stackFileName / stackManifestName) leaks ghost stacks because the final logical
name (after atmosConfig.Stacks.NameTemplate evaluation) and filterByStack
decision are not known yet; instead, stop pre-creating p.finalStacksMap entries
here and only create the map entry after the stack's final name is resolved and
it passes filterByStack (i.e., move the creation logic to the code path where
NameTemplate is evaluated per component or add a guard that checks the evaluated
name and filterByStack before inserting into p.finalStacksMap); update uses of
p.includeEmptyStacks/p.atmosConfig.Stacks.NameTemplate/p.finalStacksMap/initialName/stackFileName/stackManifestName
so empty shells are not inserted before filterEmptyFinalStacks runs.
In `@pkg/describe/debug_stacks_test.go`:
- Around line 11-29: Remove the debug-only test TestDebugStackCounts from the
repo (pkg/describe/debug_stacks_test.go) because it prints diagnostics, ignores
errors from ExecuteDescribeStacks, and contains no assertions; delete the file
or replace it with a proper fixture-based test that calls ExecuteDescribeStacks,
checks returned error with errors.Is/require, and asserts expected stack
counts/contents instead of printing them (referencing TestDebugStackCounts and
ExecuteDescribeStacks to locate the code to remove or refactor).
In `@website/blog/2026-03-15-describe-stacks-complexity-reduction.mdx`:
- Around line 47-50: The blog post's complexity summary for
ExecuteDescribeStacks is inconsistent: update the reported cognitive complexity
for ExecuteDescribeStacks from 12 to 22 so it matches the other docs (and verify
the "Max complexity" numbers if they were derived from the same measurement);
edit the text in the post that lists ExecuteDescribeStacks and the overall Max
complexity values to reflect the corrected numbers and run a quick search for
other occurrences of those complexity values to keep all references
synchronized.
---
Nitpick comments:
In `@internal/exec/describe_stacks_component_processor_test.go`:
- Around line 414-483: Consolidate the seven individual tests into one
table-driven test for hasStackExplicitComponents: create a slice of test cases
each with name, stack (using cfg.ComponentsSectionName and the specific keys
cfg.TerraformSectionName, cfg.HelmfileSectionName, cfg.PackerSectionName,
cfg.AnsibleSectionName, nil and wrong-type cases) and expected bool, then
iterate and call t.Run for each case and assert.Equal(t, tc.want,
hasStackExplicitComponents(tc.stack)); keep the original case variants (empty
terraform, with terraform, helmfile, packer, ansible, no components, nil
components, wrong type) so behavior is preserved.
- Around line 270-274: The test currently uses unchecked type assertions for
prodEntry, comps and tf (prodEntry := finalMap["prod"].(map[string]any), comps
:= prodEntry[cfg.ComponentsSectionName].(map[string]any), tf :=
comps["terraform"].(map[string]any)) which will panic on structural changes;
replace each direct assertion with an ok-guarded check (e.g., v, ok :=
finalMap["prod"].(map[string]any); require.True(t, ok) and similarly for comps
using cfg.ComponentsSectionName and for tf using "terraform"), then continue to
assert the presence of tf["vpc"] with require/ assert as appropriate so failures
produce informative messages instead of panics.
- Around line 14-17: The test file is intentionally long because it
comprehensively covers the extractDescribeComponentSections processor; do not
split tests. Instead, keep the current structure and add a short
package/top-of-file comment explaining that the 1500+ line length is deliberate
because all tests target extractDescribeComponentSections and are grouped by
logical comment separators to preserve cohesion and readability; ensure the
comment references extractDescribeComponentSections so reviewers understand the
rationale.
In `@internal/exec/describe_stacks_test.go`:
- Around line 435-454: The test TestExecuteDescribeStacks_IncludeEmptyStacks
currently only checks for no error and non-nil result and doesn't verify
includeEmptyStacks behavior; update it to call ExecuteDescribeStacks twice (once
with includeEmptyStacks=false and once with includeEmptyStacks=true) and assert
the difference: either assert the known empty-stack key from the fixtures is
present in the map returned when includeEmptyStacks=true (using the expected
stack key from the fixtures) and absent when false, or assert that the map
length increases when includeEmptyStacks=true (i.e., compare len(stacksMapFalse)
< len(stacksMapTrue)); use the ExecuteDescribeStacks call sites in the test to
obtain both maps and add the appropriate require/assert checks.
🪄 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: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: e91f9ef7-c572-4771-99b6-ef4e0f8d6a61
📒 Files selected for processing (9)
docs/fixes/2026-03-20-executedescribestacks-refactor.mdinternal/exec/describe_stacks.gointernal/exec/describe_stacks_component_processor.gointernal/exec/describe_stacks_component_processor_test.gointernal/exec/describe_stacks_test.gopkg/describe/debug_stacks_test.gowebsite/blog/2026-03-15-describe-stacks-complexity-reduction.mdxwebsite/blog/authors.ymlwebsite/src/data/roadmap.js
- Extract getComponentDestMap with ok guards at all 4 levels, replacing the panicking single-line type assertion chain (item 3) - Sync info.ComponentSection after template processing so YAML functions see rendered values instead of raw template strings (item 6) - Add TestProcessStackFile_NameTemplate_NoGhostEntry covering the name_template + includeEmptyStacks=true ghost entry path (item 10) - Add 5 tests for getComponentDestMap covering all failure paths - Update fix doc with round 4 findings and resolutions Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Replace tautological NoError+NotNil assertions with a meaningful comparison: call with includeEmptyStacks=false as baseline, then assert includeEmptyStacks=true returns >= stacks. This proves the flag actually changes behavior. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Replace 8 individual test functions with a single table-driven test with named subtests. Same coverage, less boilerplate. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Replace unguarded .(map[string]any) assertions with ok-guarded require.True checks for clearer test failures on type mismatches. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- Extend ghost entry prevention to cover name_pattern (not just name_template): skip pre-creation when either NameTemplate or NamePattern is active without a manifest name - Add filterByStack early return in pre-creation path: non-matching stacks skip entry creation instead of creating empty shells - Add TestProcessStackFile_NoGhostEntry_NamePattern test - Add TestProcessStackFile_NoGhostEntry_FilterByStack test Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Shallow-clone the component section map before any mutations (setting defaults, metadata inheritance) so the shared FindStacksMap cache is not modified. Filtered-out components were mutating workspace pattern and component keys on the shared data, affecting subsequent calls. Update TestProcessComponentTypeSection_DefaultsComponentKey to verify the original map is NOT mutated (clone protection). Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Debug-only test with no assertions, ignores errors, only prints diagnostic output. Does not protect against regressions. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Clarify that cognitive 22 is from processComponentEntry (the most complex extracted helper), not ExecuteDescribeStacks itself. Remove the ambiguous cognitive 12 number for the orchestrator. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
TestDescribeStacksWithEmptyStacks and TestDescribeStacksWithVariousEmptyStacks failed because the fixture has no import-only stacks, so includeEmptyStacks=true returns the same count as false. The ghost-entry prevention fix correctly prevents phantom entries. - Change assert.Greater to assert.GreaterOrEqual for stack count comparison - Remove assertion requiring empty stacks (fixture has none) - Keep assertion for non-empty stacks (validates real behavior) - Add cross-platform path comments for buildComponentInfo assertions - Update fix doc with all findings and resolutions Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
These changes were released in v1.211.0-test.16. |
TestDescribeStacksWithEmptyStacks,TestDescribeStacksWithVariousEmptyStacks)includeEmptyStackstests are reliable on all platforms📱 Kick off Copilot coding agent tasks wherever you are with GitHub Mobile, available on iOS and Android.
Summary by CodeRabbit
Bug Fixes
NameTemplateis set with empty manifest names.Tests