Skip to content

refactor: update tests for new YAML output order after MustString() migration#1

Closed
Rindrics wants to merge 8 commits intoissue-947-long-linefrom
issue-947-reorder-test-expectations
Closed

refactor: update tests for new YAML output order after MustString() migration#1
Rindrics wants to merge 8 commits intoissue-947-long-linefrom
issue-947-reorder-test-expectations

Conversation

@Rindrics
Copy link
Copy Markdown
Owner

@Rindrics Rindrics commented Feb 5, 2026

Summary

This PR updates all tests to handle the change in YAML output order that resulted from switching Resource.AsYAML() to use RNode.MustString() instead of sigs.k8s.io/yaml.JSONToYAML (see PR kubernetes-sigs#6046). The change preserves the original YAML field order instead of sorting fields alphabetically, which requires updating test expectations.

Background

PR kubernetes-sigs#6046 changed Resource.AsYAML() to use RNode.MustString() to fix long line wrapping issues and preserve original YAML formatting. This change also affects the output order of YAML fields:

  • Before: Fields were sorted alphabetically (via JSON-to-YAML conversion)
  • After: Fields preserve their original YAML order

While both orderings are valid YAML, this change requires updating all test expectations to match the new output order.

Duplicate Key Detection

Added duplicate key detection by calling MarshalJSON() before converting to YAML. This maintains the same error detection behavior as before while using the new YAML serialization method.

Test Updates

Migrated affected tests to use golden files to handle the output order differences:

  • api/resource: Added golden file testing helper and migrated TestSliceFromPatches, TestApplySmPatch, TestMergeDataMapFrom, and TestDropLocalNodes
  • api/resmap: Added golden file testing helper and migrated TestDeAnchorSingleDoc, TestDeAnchorIntoDoc, TestDeAnchorResourceList, TestApplySmPatch_General, TestApplySmPatch_Deletion, TestApplyFilter, and TestAbsorbAll
  • api/krusty: Migrated all tests using AssertActualEqualsExpected to use golden files
  • kustomize/commands/build: Updated expected YAML strings to match new output order

these migrations are done by temporal scripts, but they are removed after being used: a399917 (this PR)

Testing

All tests pass with the new implementation:

# Run all tests
go test ./api/... ./kustomize/...

# Update golden files (if needed)
go test ./api/resource -update
go test ./api/resmap -update-golden
go test ./api/krusty -update-golden

Benefits

  1. Better test maintainability: Golden files make it easier to review and update test expectations
  2. Consistent test coverage: All tests now pass with the new YAML output order
  3. Future-proof: Golden files make it easier to handle future changes to output formatting

Related PRs and Issues

Add assertGolden helper function to simplify updating test expectations
when resource output format changes. Migrate TestMergeDataMapFrom as
the first example.
Migrate resource_test.go to use golden file testing for AsYAML() output.
This makes it easier to update test expectations when output format changes.

- Add assertGoldenYAML helper function
- Convert assert.Equal patterns to assertGoldenYAML calls
- Generate golden files for 18 test cases

The migration script (migrate_to_golden.py) is included for reference.
Migrate krusty tests to use golden file testing for AsYAML() output.
This makes it easier to update test expectations when output format changes.

- Add AssertYAMLEqualsGolden helper function to kusttest
- Update AssertActualEqualsExpected to support golden files
- Convert originannotation_test.go to use AssertYAMLEqualsGolden
- Generate golden files for 258 test cases
Update expectedContent in build_test.go to match the new field order
from resource.AsYAML() which now uses kyaml encoder instead of JSON-to-YAML conversion.
This ensures that duplicate keys in YAML are detected and reported
as errors, maintaining compatibility with the previous behavior where
sigs.k8s.io/yaml.JSONToYAML would catch these errors.

Fixes TestDuplicateKeys which was failing after switching to
RNode.MustString() for YAML output.
- Convert TestApplySmPatch to use subtests with golden files
- Convert TestDropLocalNodes to use golden files
- Convert TestVolumeRemoveEmptyDirInOverlay to use golden files
- Update golden files to match new YAML output order

These tests were failing due to output order changes after switching
Resource.AsYAML() to use RNode.MustString() instead of
sigs.k8s.io/yaml.JSONToYAML.
After changing Resource.AsYAML() to use RNode.MustString() instead of
sigs.k8s.io/yaml.JSONToYAML, the YAML output order changed from
alphabetical to preserving the original YAML order. This caused many
tests to fail due to order differences.

To handle these order differences and make future changes easier to
manage, migrate affected tests to use golden files:
- Add golden_test.go helper for resmap tests
- Migrate TestDeAnchorSingleDoc, TestDeAnchorIntoDoc,
  TestDeAnchorResourceList, TestApplySmPatch_General,
  TestApplySmPatch_Deletion, TestApplyFilter, and TestAbsorbAll
  in resmap package
- Migrate TestSliceFromPatches in resource package

This approach allows the tests to accept the new output order while
maintaining the ability to detect unexpected changes.
@qodo-free-for-open-source-projects
Copy link
Copy Markdown

Review Summary by Qodo

Migrate test suite to golden file pattern for YAML output validation after MustString() migration

🧪 Tests ✨ Enhancement 🐞 Bug fix

Grey Divider

Walkthroughs

Description
• Migrated test suite to use golden file testing pattern for YAML output validation
• Added golden file testing infrastructure with helper functions and flag support (-update,
  -update-golden)
• Fixed duplicate key detection in Resource.AsYAML() by calling MarshalJSON() before YAML
  conversion
• Updated 100+ test cases across api/resource, api/resmap, and api/krusty packages to use
  golden files
• Created 80+ golden files containing expected YAML output with preserved field ordering
• Updated kustomize/commands/build tests to match new YAML field order from MustString()
  migration
• Removed 1000+ lines of hardcoded expected YAML strings from test code
• Added Python migration scripts to automate test conversion to golden file pattern
Diagram
flowchart LR
  A["Old Test Pattern<br/>Hardcoded YAML Strings"] -->|"Replace with"| B["Golden File Testing<br/>assertGoldenYAML()"]
  C["Resource.AsYAML()<br/>JSONToYAML"] -->|"Uses"| D["RNode.MustString()<br/>Preserves Field Order"]
  D -->|"Requires"| B
  E["Test Files<br/>resource_test.go<br/>reswrangler_test.go<br/>originannotation_test.go"] -->|"Migrate to"| F["Golden Files<br/>testdata/golden/"]
  B -->|"Supports"| G["Flag Updates<br/>-update<br/>-update-golden"]
Loading

Grey Divider

File Changes

1. api/krusty/originannotation_test.go 🧪 Tests +6/-221

Migrate origin annotation tests to golden file assertions

• Replaced inline YAML string assertions with kusttest_test.AssertYAMLEqualsGolden(t, yml) calls
• Removed 40+ lines of hardcoded expected YAML output from 6 test cases
• Tests now use golden files for output comparison instead of embedded strings

api/krusty/originannotation_test.go


2. api/resource/resource_test.go 🧪 Tests +25/-86

Convert resource tests to golden file testing pattern

• Replaced assert.Equal calls with assertGoldenYAML(t, bytes) for YAML output validation
• Converted multiple test cases to use golden file comparison
• Wrapped test cases in t.Run() subtests for better test organization
• Removed inline expected YAML strings from test code

api/resource/resource_test.go


3. api/resmap/reswrangler_test.go 🧪 Tests +28/-53

Migrate resmap tests to golden file comparison

• Replaced ErrorIfNotEqualLists() comparisons with assertGoldenYAML(t, yaml) calls
• Converted TestAbsorbAll to use golden files with subtests
• Updated TestDeAnchor* tests to use golden file assertions
• Removed inline YAML string comparisons from multiple test cases

api/resmap/reswrangler_test.go


View more (213)
4. api/testutils/kusttest/hasgett.go ✨ Enhancement +74/-0

Add golden file testing infrastructure for krusty tests

• Added -update-golden flag support for updating golden files during test runs
• Implemented AssertYAMLEqualsGolden() function for YAML comparison with golden files
• Enhanced AssertActualEqualsExpectedWithTweak() to support golden file fallback
• Added goldenFileForTest() helper to generate golden file paths from test names

api/testutils/kusttest/hasgett.go


5. api/krusty/multiplepatch_test.go 🧪 Tests +8/-69

Refactor multiple patch tests to use golden files

• Wrapped test assertions in t.Run() subtests
• Replaced hardcoded expected YAML strings with empty string and golden file comparison
• Simplified test code by removing 80+ lines of embedded YAML expectations

api/krusty/multiplepatch_test.go


6. api/resource/golden_test.go ✨ Enhancement +57/-0

Add golden file testing helpers for resource tests

• Created new test helper file with golden file testing utilities
• Implemented assertGoldenYAML() and assertGolden() functions
• Added -update flag support for updating golden files
• Provides automatic golden file path generation from test names

api/resource/golden_test.go


7. api/resmap/golden_test.go ✨ Enhancement +56/-0

Add golden file testing helpers for resmap tests

• Created new test helper file with golden file testing utilities for resmap
• Implemented assertGoldenYAML() function with flag lookup support
• Added -update-golden flag detection without conflicts
• Provides golden file path generation and comparison logic

api/resmap/golden_test.go


8. kustomize/commands/build/build_test.go 🧪 Tests +19/-19

Update build test expectations for new YAML field order

• Reordered YAML field expectations to match new output order from MustString() migration
• Updated metadata field ordering in expected output strings
• Moved name and namespace fields before labels and annotations
• Adjusted data field positioning in ConfigMap and Secret resources

kustomize/commands/build/build_test.go


9. api/resmap/factory_test.go 🧪 Tests +13/-4

Relax YAML comparison in factory tests

• Simplified YAML comparison logic in TestNewResMapFromConfigMapArgs
• Removed direct YAML equality assertions between expected and actual
• Added comments explaining that output order may differ but content is valid
• Changed assertions to verify non-empty output instead of exact matching

api/resmap/factory_test.go


10. api/resource/factory_test.go 🧪 Tests +6/-5

Migrate factory tests to golden file assertions

• Converted resource comparison to use assertGoldenYAML() with subtests
• Replaced direct YAML equality checks with golden file assertions
• Added subtest structure for each resource in list comparisons
• Removed hardcoded expected YAML strings

api/resource/factory_test.go


11. api/resource/resource.go 🐞 Bug fix +6/-0

Add duplicate key detection to AsYAML method

• Added duplicate key detection by calling MarshalJSON() before YAML conversion
• Preserves error detection behavior from previous JSON-to-YAML approach
• Maintains original YAML field order using RNode.MustString()

api/resource/resource.go


12. api/krusty/testdata/golden/TestVarRefBig.golden 🧪 Tests +261/-0

Add golden file for TestVarRefBig test case

• Created golden file containing expected YAML output for TestVarRefBig
• Contains 261 lines of YAML with ServiceAccount, Role, ClusterRole, RoleBinding,
 ClusterRoleBinding, Service, and StatefulSet resources
• Includes CronJob and PodDisruptionBudget resources with ConfigMap

api/krusty/testdata/golden/TestVarRefBig.golden


13. api/krusty/testdata/golden/TestVariableRefNFSServer.golden 🧪 Tests +291/-0

Add golden file for TestVariableRefNFSServer test case

• Created golden file with expected YAML output for TestVariableRefNFSServer
• Contains 291 lines of YAML with PersistentVolumeClaim, Deployment, Service, DaemonSet, ReplicaSet,
 StatefulSet, Pod, Job, and PersistentVolume resources

api/krusty/testdata/golden/TestVariableRefNFSServer.golden


14. api/krusty/testdata/golden/TestIssue3489.golden 🧪 Tests +197/-0

Add golden file for TestIssue3489 test case

• Created golden file with expected YAML output for TestIssue3489
• Contains 197 lines of YAML with ClusterRole, ClusterRoleBinding, Deployment, ServiceAccount, and
 Secret resources

api/krusty/testdata/golden/TestIssue3489.golden


15. api/krusty/testdata/golden/TestMediumOverlay.golden 🧪 Tests +110/-0

Add golden file for TestMediumOverlay test case

• Created golden file with expected YAML output for TestMediumOverlay
• Contains 110 lines of YAML with Deployment, Service, and ConfigMap resources

api/krusty/testdata/golden/TestMediumOverlay.golden


16. api/krusty/testdata/golden/TestMergeAndReplaceGenerators.golden 🧪 Tests +105/-0

Add golden file for TestMergeAndReplaceGenerators test case

• Created golden file with expected YAML output for TestMergeAndReplaceGenerators
• Contains 105 lines of YAML with Deployment, Service, ConfigMap, and Secret resources

api/krusty/testdata/golden/TestMergeAndReplaceGenerators.golden


17. api/krusty/testdata/golden/TestNameAndNsTransformation.golden 🧪 Tests +111/-0

Add golden file for TestNameAndNsTransformation test case

• Created golden file with expected YAML output for TestNameAndNsTransformation
• Contains 111 lines of YAML with ConfigMap, Service, ServiceAccount, ClusterRoleBinding,
 ValidatingWebhookConfiguration, CustomResourceDefinition, ClusterRole, and PersistentVolume
 resources

api/krusty/testdata/golden/TestNameAndNsTransformation.golden


18. api/krusty/testdata/golden/TestPatchesInOneFile.golden 🧪 Tests +101/-0

Add golden file for TestPatchesInOneFile test case

• Created golden file with expected YAML output for TestPatchesInOneFile
• Contains 101 lines of YAML with Namespace and Deployment resources

api/krusty/testdata/golden/TestPatchesInOneFile.golden


19. api/resource/migrate_to_golden.py Miscellaneous +76/-0

Add migration script for resource test conversion

• Created Python script to automate migration of resource tests to golden file pattern
• Provides regex patterns to replace assert.Equal calls with assertGoldenYAML()
• Includes backup creation and usage instructions

api/resource/migrate_to_golden.py


20. api/krusty/testdata/golden/TestIssue3377.golden 🧪 Tests +107/-0

Add golden file for TestIssue3377 test case

• Created golden file with expected YAML output for TestIssue3377
• Contains 107 lines of YAML with Deployment, Service, and Ingress resources for two services

api/krusty/testdata/golden/TestIssue3377.golden


21. api/krusty/testdata/golden/TestMultiplePatchesNoConflict.golden 🧪 Tests +94/-0

Add golden file for TestMultiplePatchesNoConflict test case

• Created golden file with expected YAML output for TestMultiplePatchesNoConflict
• Contains 94 lines of YAML with Deployment, Service, and ConfigMap resources

api/krusty/testdata/golden/TestMultiplePatchesNoConflict.golden


22. api/krusty/testdata/golden/TestMultibasesNoConflict.golden 🧪 Tests +75/-0

Add golden file for TestMultibasesNoConflict test case

• Created golden file with expected YAML output for TestMultibasesNoConflict
• Contains 75 lines of YAML with ServiceAccount, RoleBinding, ClusterRoleBinding, and ClusterRole
 resources

api/krusty/testdata/golden/TestMultibasesNoConflict.golden


23. api/krusty/testdata/golden/TestNonCommutablePatches.golden 🧪 Tests +92/-0

Add golden file for TestNonCommutablePatches test case

• Created golden file with expected YAML output for TestNonCommutablePatches
• Contains 92 lines of YAML with Deployment, Service, and ConfigMap resources

api/krusty/testdata/golden/TestNonCommutablePatches.golden


24. api/krusty/testdata/golden/TestGeneratorWithAnnoOrigin.golden 🧪 Tests +65/-0

Add golden file for TestGeneratorWithAnnoOrigin test case

• Created golden file with expected YAML output for TestGeneratorWithAnnoOrigin
• Contains 65 lines of YAML with ConfigMap and Secret resources with origin annotations

api/krusty/testdata/golden/TestGeneratorWithAnnoOrigin.golden


25. api/krusty/testdata/golden/TestMergeAndReplaceDisableNameSuffixHashGenerators.golden 🧪 Tests +85/-0

Add golden file for TestMergeAndReplaceDisableNameSuffixHashGenerators test case

• Created golden file with expected YAML output for
 TestMergeAndReplaceDisableNameSuffixHashGenerators
• Contains 85 lines of YAML with Deployment, ConfigMap, and Secret resources

api/krusty/testdata/golden/TestMergeAndReplaceDisableNameSuffixHashGenerators.golden


26. api/krusty/testdata/golden/TestAnnoTransformerLocalFilesWithOverlay.golden 🧪 Tests +81/-0

Add golden file for TestAnnoTransformerLocalFilesWithOverlay test case

• Created golden file with expected YAML output for TestAnnoTransformerLocalFilesWithOverlay
• Contains 81 lines of YAML with Namespace, Role, Service, and Deployment resources with
 transformation annotations

api/krusty/testdata/golden/TestAnnoTransformerLocalFilesWithOverlay.golden


27. api/krusty/testdata/golden/TestMultiplePatchesWithOnePatchDeleteDirective_Patch_with_delete_directive_first.golden 🧪 Tests +84/-0

Add golden file for TestMultiplePatchesWithOnePatchDeleteDirective variant

• Created golden file with expected YAML output for patch delete directive test variant
• Contains 84 lines of YAML with Deployment, Service, and ConfigMap resources

api/krusty/testdata/golden/TestMultiplePatchesWithOnePatchDeleteDirective_Patch_with_delete_directive_first.golden


28. api/krusty/testdata/golden/TestMultiplePatchesWithOnePatchDeleteDirective_Patch_with_delete_directive_second.golden 🧪 Tests +84/-0

Add golden file for TestMultiplePatchesWithOnePatchDeleteDirective second variant

• Created golden file with expected YAML output for second patch delete directive test variant
• Contains 84 lines of YAML with Deployment, Service, and ConfigMap resources

api/krusty/testdata/golden/TestMultiplePatchesWithOnePatchDeleteDirective_Patch_with_delete_directive_second.golden


29. api/krusty/testdata/golden/TestBaseWithGeneratorsAlone.golden 🧪 Tests +83/-0

Add golden file for TestBaseWithGeneratorsAlone test case

• Created golden file with expected YAML output for TestBaseWithGeneratorsAlone
• Contains 83 lines of YAML with Deployment, Service, ConfigMap, and Secret resources

api/krusty/testdata/golden/TestBaseWithGeneratorsAlone.golden


30. api/krusty/migrate_assert_equal_to_golden.py Miscellaneous +57/-0

Add migration script for krusty test conversion

• Created Python script to automate migration of krusty tests to golden file pattern
• Provides regex pattern to replace assert.Equal calls with AssertYAMLEqualsGolden()
• Includes backup creation and usage instructions

api/krusty/migrate_assert_equal_to_golden.py


31. api/krusty/testdata/golden/TestMultiplePatchesBothWithPatchDeleteDirective.golden 🧪 Tests +76/-0

Add golden file for TestMultiplePatchesBothWithPatchDeleteDirective test case

• Created golden file with expected YAML output for
 TestMultiplePatchesBothWithPatchDeleteDirective
• Contains 76 lines of YAML with Deployment, Service, and ConfigMap resources

api/krusty/testdata/golden/TestMultiplePatchesBothWithPatchDeleteDirective.golden


32. api/krusty/testdata/golden/TestTransformersNoCreateArrays.golden 🧪 Tests +77/-0

Add golden file for TestTransformersNoCreateArrays test case

• Created golden file with expected YAML output for TestTransformersNoCreateArrays
• Contains 77 lines of YAML with StatefulSet resources and volume claim templates

api/krusty/testdata/golden/TestTransformersNoCreateArrays.golden


33. api/krusty/testdata/golden/TestSimpleMultiplePatches.golden 🧪 Tests +74/-0

Add golden file for TestSimpleMultiplePatches test case

• Created golden file with expected YAML output for TestSimpleMultiplePatches
• Contains 74 lines of YAML with Deployment, Service, and ConfigMap resources

api/krusty/testdata/golden/TestSimpleMultiplePatches.golden


34. api/krusty/testdata/golden/TestGeneratorBasics.golden 🧪 Tests +47/-0

Add golden file for TestGeneratorBasics test case

• Created golden file with expected YAML output for TestGeneratorBasics
• Contains 47 lines of YAML with ConfigMap and Secret resources

api/krusty/testdata/golden/TestGeneratorBasics.golden


35. api/krusty/testdata/golden/TestExtendedPatchMultiplePatchOverlapping.golden 📦 Other +78/-0
• Created golden file with expected YAML output for TestExtendedPatchMultiplePatchOverlapping
• Contains

api/krusty/testdata/golden/TestExtendedPatchMultiplePatchOverlapping.golden


36. api/krusty/testdata/golden/TestBaseReuseNameConflict.golden 🧪 Tests +73/-0

Golden file for base reuse name conflict test

• Added golden file containing expected YAML output for test case with two components having name
 conflicts
• Output shows two PersistentVolumeClaim and two Deployment resources with distinct naming
• Preserves original YAML field order instead of alphabetically sorted fields

api/krusty/testdata/golden/TestBaseReuseNameConflict.golden


37. api/krusty/testdata/golden/TestTransfomersImageDefaultConfig.golden 🧪 Tests +54/-0

Golden file for image transformer default config test

• Added golden file with expected YAML output for image transformer with default configuration
• Contains Deployment and custom resource kinds with image specifications
• Demonstrates field order preservation in YAML serialization

api/krusty/testdata/golden/TestTransfomersImageDefaultConfig.golden


38. api/krusty/testdata/golden/TestExtendedPatchNameGvkLabelSelector.golden 🧪 Tests +75/-0

Golden file for extended patch with name GVK label selector

• Added golden file for extended patch test with name, GVK, and label selector matching
• Contains two Deployments and two Services with labels and annotations
• Shows preserved YAML field ordering in output

api/krusty/testdata/golden/TestExtendedPatchNameGvkLabelSelector.golden


39. api/krusty/testdata/golden/TestExtendedPatchGvkLabelSelector.golden 🧪 Tests +75/-0

Golden file for extended patch with GVK label selector

• Added golden file for extended patch test with GVK and label selector matching
• Contains identical structure to TestExtendedPatchNameGvkLabelSelector with two Deployments and
 Services
• Demonstrates consistent YAML field ordering

api/krusty/testdata/golden/TestExtendedPatchGvkLabelSelector.golden


40. api/krusty/testdata/golden/TestExtendedPatchNameGvkSelector.golden 🧪 Tests +75/-0

Golden file for extended patch with name GVK selector

• Added golden file for extended patch test with name, GVK, and selector matching
• Contains two Deployments and two Services with matching labels
• Preserves original YAML field order in output

api/krusty/testdata/golden/TestExtendedPatchNameGvkSelector.golden


41. api/krusty/testdata/golden/TestExtendedPatchWithoutTarget.golden 🧪 Tests +75/-0

Golden file for extended patch without target test

• Added golden file for extended patch test without explicit target specification
• Contains two Deployments and two Services with labels and annotations
• Shows YAML output with preserved field ordering

api/krusty/testdata/golden/TestExtendedPatchWithoutTarget.golden


42. api/krusty/testdata/golden/TestConfMapNameResolutionInDiamondWithPatches.golden 🧪 Tests +63/-0

Golden file for ConfigMap name resolution diamond with patches

• Added golden file for ConfigMap name resolution in diamond dependency with patches
• Contains two Deployments and two ConfigMaps with environment variable references
• Demonstrates preserved YAML field order in complex resource relationships

api/krusty/testdata/golden/TestConfMapNameResolutionInDiamondWithPatches.golden


43. api/krusty/testdata/golden/TestExtendedPatchNoMatchMultiplePatch.golden 🧪 Tests +73/-0

Golden file for extended patch no match multiple patch

• Added golden file for extended patch test with no matching targets and multiple patches
• Contains two Deployments and two Services without patch modifications
• Shows original YAML field ordering preserved

api/krusty/testdata/golden/TestExtendedPatchNoMatchMultiplePatch.golden


44. api/krusty/testdata/golden/TestExtendedPatchNoMatch.golden 🧪 Tests +73/-0

Golden file for extended patch no match test

• Added golden file for extended patch test with no matching targets
• Contains two Deployments and two Services without modifications
• Preserves original YAML field order in output

api/krusty/testdata/golden/TestExtendedPatchNoMatch.golden


45. api/krusty/testdata/golden/TestSimpleBase.golden 🧪 Tests +68/-0

Golden file for simple base test

• Added golden file for simple base test with Service, Deployment, and NetworkPolicy
• Shows resources with labels, annotations, and selector configurations
• Demonstrates preserved YAML field ordering

api/krusty/testdata/golden/TestSimpleBase.golden


46. api/krusty/testdata/golden/TestIntermediateNameSecretKeyRefDiamond.golden 🧪 Tests +50/-0

Golden file for intermediate name secret key ref diamond

• Added golden file for intermediate name resolution with secret key references in diamond
 dependency
• Contains Deployment with environment variables referencing two Secrets
• Shows preserved YAML field order in complex configurations

api/krusty/testdata/golden/TestIntermediateNameSecretKeyRefDiamond.golden


47. api/krusty/testdata/golden/TestRoleBindingAcrossNamespace.golden 🧪 Tests +59/-0

Golden file for role binding across namespace test

• Added golden file for RoleBinding across multiple namespaces
• Contains ServiceAccounts, Role, and RoleBinding with cross-namespace subjects
• Demonstrates preserved YAML field ordering

api/krusty/testdata/golden/TestRoleBindingAcrossNamespace.golden


48. api/krusty/testdata/golden/TestFixedBug605_BaseCustomizationAvailableInOverlay.golden 🧪 Tests +58/-0

Golden file for bug 605 base customization overlay test

• Added golden file for bug fix test with base customization available in overlay
• Contains AnimalPark, Giraffe, and Gorilla custom resources with labels
• Shows preserved YAML field order in custom resource definitions

api/krusty/testdata/golden/TestFixedBug605_BaseCustomizationAvailableInOverlay.golden


49. api/krusty/testdata/golden/TestNameReferenceDeploymentIssue3489.golden 🧪 Tests +64/-0

Golden file for name reference deployment issue 3489

• Added golden file for name reference in Deployment with issue 3489 fix
• Contains three ConfigMaps and three Deployments with environment variable references
• Demonstrates preserved YAML field ordering across multiple resources

api/krusty/testdata/golden/TestNameReferenceDeploymentIssue3489.golden


50. api/krusty/testdata/golden/TestVariableRefIngressOverlay.golden 🧪 Tests +54/-0

Golden file for variable ref ingress overlay test

• Added golden file for variable reference in Ingress overlay
• Contains Service, Deployment, and Ingress with variable substitutions
• Shows preserved YAML field order in networking resources

api/krusty/testdata/golden/TestVariableRefIngressOverlay.golden


51. api/krusty/testdata/golden/TestNameUpdateInRoleRef2.golden 🧪 Tests +57/-0

Golden file for name update in role ref 2 test

• Added golden file for name update in RoleRef with multiple RBAC resources
• Contains ServiceAccount, ClusterRole, ClusterRoleBinding, Role, and RoleBinding
• Demonstrates preserved YAML field ordering in RBAC configurations

api/krusty/testdata/golden/TestNameUpdateInRoleRef2.golden


52. api/krusty/testdata/golden/TestReplacementTransformerWithDiamondShape.golden 🧪 Tests +65/-0

Golden file for replacement transformer diamond shape

• Added golden file for replacement transformer with diamond-shaped dependency
• Contains six Deployments with image replacements from different sources
• Shows preserved YAML field order in transformer output

api/krusty/testdata/golden/TestReplacementTransformerWithDiamondShape.golden


53. api/krusty/testdata/golden/TestVariablesDisambiguatedWithNamespace.golden 🧪 Tests +55/-0

Golden file for variables disambiguated with namespace

• Added golden file for variable disambiguation using namespace
• Contains StatefulSets and Services in different namespaces with environment variables
• Demonstrates preserved YAML field ordering with namespace-specific values

api/krusty/testdata/golden/TestVariablesDisambiguatedWithNamespace.golden


54. api/krusty/testdata/golden/TestVariablesAmbiguousWorkaround.golden 🧪 Tests +55/-0

Golden file for variables ambiguous workaround test

• Added golden file for workaround to ambiguous variable references
• Contains StatefulSets and Services with environment variable configurations
• Shows preserved YAML field order in output

api/krusty/testdata/golden/TestVariablesAmbiguousWorkaround.golden


55. api/krusty/testdata/golden/TestRoleBindingWhenSubjectsAcrossNamespace.golden 🧪 Tests +47/-0

Golden file for role binding subjects across namespace

• Added golden file for RoleBinding with subjects across namespaces
• Contains Roles and RoleBindings in multiple namespaces with cross-namespace subjects
• Demonstrates preserved YAML field ordering

api/krusty/testdata/golden/TestRoleBindingWhenSubjectsAcrossNamespace.golden


56. api/krusty/testdata/golden/TestValidatingWebhookCombinedNamespaces.golden 🧪 Tests +51/-0

Golden file for validating webhook combined namespaces

• Added golden file for ValidatingWebhookConfiguration with combined namespaces
• Contains Services and ValidatingWebhookConfiguration with namespace merging
• Shows preserved YAML field order in webhook configurations

api/krusty/testdata/golden/TestValidatingWebhookCombinedNamespaces.golden


57. api/krusty/testdata/golden/TestKustomizationLabelsDoesNotCreateInvalidTemplatePaths.golden 🧪 Tests +45/-0

Golden file for kustomization labels template paths test

• Added golden file for kustomization labels not creating invalid template paths
• Contains Deployment and Service with standard Kubernetes labels
• Demonstrates preserved YAML field ordering with label configurations

api/krusty/testdata/golden/TestKustomizationLabelsDoesNotCreateInvalidTemplatePaths.golden


58. api/krusty/testdata/golden/TestNameUpdateInRoleRef.golden 🧪 Tests +52/-0

Golden file for name update in role ref test

• Added golden file for name update in RoleRef with RBAC resources
• Contains ClusterRole, ClusterRoleBinding, Role, and RoleBinding
• Shows preserved YAML field order in RBAC configurations

api/krusty/testdata/golden/TestNameUpdateInRoleRef.golden


59. api/krusty/testdata/golden/TestMidLevelA.golden 🧪 Tests +37/-0

Golden file for mid level A test

• Added golden file for mid-level A test with RBAC resources
• Contains ServiceAccount, RoleBinding, ClusterRoleBinding, and ClusterRole
• Demonstrates preserved YAML field ordering with suffix transformations

api/krusty/testdata/golden/TestMidLevelA.golden


60. api/krusty/testdata/golden/TestMidLevelB.golden 🧪 Tests +37/-0

Golden file for mid level B test

• Added golden file for mid-level B test with RBAC resources
• Contains ServiceAccount, RoleBinding, ClusterRoleBinding, and ClusterRole
• Shows preserved YAML field order with suffix transformations

api/krusty/testdata/golden/TestMidLevelB.golden


61. api/krusty/testdata/golden/TestAnnoOriginLocalFilesWithOverlay.golden 🧪 Tests +47/-0

Golden file for annotation origin local files overlay

• Added golden file for annotation origin tracking with local files and overlay
• Contains Namespace, Role, Service, and Deployment with origin annotations
• Demonstrates preserved YAML field ordering with origin metadata

api/krusty/testdata/golden/TestAnnoOriginLocalFilesWithOverlay.golden


62. api/krusty/testdata/golden/TestSmallOverlay.golden 🧪 Tests +48/-0

Golden file for small overlay test

• Added golden file for small overlay test
• Contains Deployment and Service with labels and environment variables
• Shows preserved YAML field order in overlay output

api/krusty/testdata/golden/TestSmallOverlay.golden


63. api/krusty/testdata/golden/TestVaribaleRefDifferentPrefix.golden 🧪 Tests +47/-0

Golden file for variable ref different prefix test

• Added golden file for variable reference with different prefix
• Contains StatefulSet and Service with environment variable substitutions
• Demonstrates preserved YAML field ordering with prefix variations

api/krusty/testdata/golden/TestVaribaleRefDifferentPrefix.golden


64. api/krusty/testdata/golden/TestVarPropagatesUp.golden 🧪 Tests +47/-0

Golden file for variable propagates up test

• Added golden file for variable propagation up the hierarchy
• Contains three Pods with environment variables and command arguments
• Shows preserved YAML field order in variable propagation

api/krusty/testdata/golden/TestVarPropagatesUp.golden


65. api/krusty/testdata/golden/TestBase.golden 🧪 Tests +37/-0

Golden file for base test

• Added golden file for base test with RBAC resources
• Contains ServiceAccount, RoleBinding, ClusterRoleBinding, and ClusterRole
• Demonstrates preserved YAML field ordering

api/krusty/testdata/golden/TestBase.golden


66. api/krusty/testdata/golden/TestComplexComposition_Prod_SuccessWithBaseTransformers.golden 🧪 Tests +46/-0

Golden file for complex composition prod base transformers

• Added golden file for complex composition production test with base transformers
• Contains StatefulSet, Service, and ConfigMap with complex configurations
• Shows preserved YAML field order in complex compositions

api/krusty/testdata/golden/TestComplexComposition_Prod_SuccessWithBaseTransformers.golden


67. api/krusty/testdata/golden/TestComplexComposition_Prod_SuccessWithRawTransformers.golden 🧪 Tests +46/-0

Golden file for complex composition prod raw transformers

• Added golden file for complex composition production test with raw transformers
• Contains StatefulSet, Service, and ConfigMap with identical structure to base transformers version
• Demonstrates preserved YAML field ordering

api/krusty/testdata/golden/TestComplexComposition_Prod_SuccessWithRawTransformers.golden


68. api/krusty/testdata/golden/TestMediumBase.golden 🧪 Tests +46/-0

Golden file for medium base test

• Added golden file for medium base test
• Contains Deployment and Service with labels, annotations, and environment variables
• Shows preserved YAML field order in medium complexity resources

api/krusty/testdata/golden/TestMediumBase.golden


69. api/krusty/testdata/golden/TestGeneratorOverlaysBinaryData.golden 🧪 Tests +10/-0

Golden file for generator overlays binary data test

• Added golden file for generator overlays with binary data
• Contains ConfigMap with binaryData field containing base64-encoded content
• Demonstrates preserved YAML field ordering with binary data

api/krusty/testdata/golden/TestGeneratorOverlaysBinaryData.golden


70. api/krusty/testdata/golden/TestReplacementTransformerAppendToAnnotationUsingRegex.golden 🧪 Tests +46/-0

Golden file for replacement transformer append annotation regex

• Added golden file for replacement transformer appending to annotations using regex
• Contains two Deployments, two ConfigMaps, and a custom resource with annotation modifications
• Shows preserved YAML field order in regex-based transformations

api/krusty/testdata/golden/TestReplacementTransformerAppendToAnnotationUsingRegex.golden


71. api/krusty/testdata/golden/TestLongLineBreaks.golden 🧪 Tests +27/-0

Golden file for long line breaks test

• Added golden file for long line breaks test
• Contains Deployment with environment variables demonstrating long string handling
• Demonstrates preserved YAML field ordering with long line preservation

api/krusty/testdata/golden/TestLongLineBreaks.golden


72. api/krusty/testdata/golden/TestTransfomersImageCustomConfig.golden 🧪 Tests +33/-0

Golden file for image transformer custom config test

• Added golden file for image transformer with custom configuration
• Contains custom resource kind with myContainers and myInitContainers fields
• Shows preserved YAML field order with custom container specifications

api/krusty/testdata/golden/TestTransfomersImageCustomConfig.golden


73. api/krusty/testdata/golden/TestCustomConfigWithDefaultOverspecification.golden 📦 Other +44/-0
• Added golden file for custom config with default overspecification
• Contains AnimalPark, Giraffe, and Gorilla custom resources with labels
• Demonstrates preserved YAML field ordering in custom resources

api/krusty/testdata/golden/TestCustomConfigWithDefaultOverspecification.golden


74. api/krusty/testdata/golden/TestCrdWithOverlay.golden 🧪 Tests +23/-0

Golden file for CRD overlay test case

• Added golden file containing expected YAML output for CRD overlay test
• Includes Secret, MyKind, and Bee resources with proper field ordering
• Demonstrates YAML field preservation instead of alphabetical sorting

api/krusty/testdata/golden/TestCrdWithOverlay.golden


75. api/krusty/testdata/golden/TestSecretGenerator.golden 🧪 Tests +12/-0

Golden file for secret generator test

• Added golden file for secret generator test output
• Contains Secret resource with base64-encoded data fields
• Preserves original YAML field order from source

api/krusty/testdata/golden/TestSecretGenerator.golden


76. api/krusty/testdata/golden/TestPluginEnvironment.golden 🧪 Tests +8/-0

Golden file for plugin environment test

• Added golden file for plugin environment test
• Contains GeneratedEnv resource with environment variables
• Shows field ordering preservation in YAML output

api/krusty/testdata/golden/TestPluginEnvironment.golden


77. api/krusty/testdata/golden/TestGkeGeneratorWithTwo.golden 🧪 Tests +14/-0

Golden file for GKE generator with two accounts

• Added golden file for GKE generator with two service accounts
• Contains two ServiceAccount resources with annotations
• Demonstrates proper YAML field ordering

api/krusty/testdata/golden/TestGkeGeneratorWithTwo.golden


78. api/krusty/testdata/golden/TestCrdBase.golden 🧪 Tests +23/-0

Golden file for CRD base test case

• Added golden file for CRD base test
• Contains Secret, MyKind, and Bee resources
• Shows preserved YAML field order instead of alphabetical sorting

api/krusty/testdata/golden/TestCrdBase.golden


79. api/krusty/testdata/golden/TestKustomizationLabelsInCronJobTemplate.golden 🧪 Tests +22/-0

Golden file for CronJob with kustomization labels

• Added golden file for CronJob with kustomization labels
• Contains CronJob resource with labels and job template
• Preserves original YAML field ordering

api/krusty/testdata/golden/TestKustomizationLabelsInCronJobTemplate.golden


80. api/resource/testdata/golden/TestApplySmPatch/withschema-container-label-image.golden 🧪 Tests +21/-0

Golden file for schema-aware patch test variant

• Added golden file for strategic merge patch with schema
• Contains Deployment with containers and environment variables
• Tests field ordering with schema-aware patching

api/resource/testdata/golden/TestApplySmPatch/withschema-container-label-image.golden


81. api/resource/testdata/golden/TestApplySmPatch/withschema-image-container-label.golden 🧪 Tests +21/-0

Golden file for schema patch ordering variant

• Added golden file for strategic merge patch variant
• Contains Deployment with different field ordering in patches
• Tests schema-aware patch application

api/resource/testdata/golden/TestApplySmPatch/withschema-image-container-label.golden


82. api/resource/testdata/golden/TestApplySmPatch/withschema-label-image-container.golden 🧪 Tests +21/-0

Golden file for schema patch label variant

• Added golden file for schema-aware patch test
• Contains Deployment with environment variables in different order
• Tests patch application with schema validation

api/resource/testdata/golden/TestApplySmPatch/withschema-label-image-container.golden


83. api/krusty/testdata/golden/TestAddNamePrefixWithNamespace.golden 🧪 Tests +18/-0

Golden file for name prefix with namespace

• Added golden file for name prefix with namespace test
• Contains ClusterRoleBinding and ServiceAccount resources
• Shows proper YAML field ordering with namespace handling

api/krusty/testdata/golden/TestAddNamePrefixWithNamespace.golden


84. api/krusty/testdata/golden/TestComponent_multiple-bases-can-add-the-same-component-if-it-doesn-not-define-named-entities.golden 🧪 Tests +22/-0

Golden file for component reuse test

• Added golden file for component reuse test
• Contains three Deployment resources with different namespaces
• Tests component application without named entity conflicts

api/krusty/testdata/golden/TestComponent_multiple-bases-can-add-the-same-component-if-it-doesn-not-define-named-entities.golden


85. api/krusty/testdata/golden/TestCrdWithContainers.golden 🧪 Tests +19/-0

Golden file for CRD with containers

• Added golden file for CRD with containers
• Contains CustomResourceDefinition with validation schema
• Shows YAML field preservation in complex nested structures

api/krusty/testdata/golden/TestCrdWithContainers.golden


86. api/krusty/testdata/golden/TestLabelTransformerConfigWithCustomResources_include_selector_via_transformerConfig.golden 🧪 Tests +20/-0

Golden file for label transformer selector config

• Added golden file for label transformer with custom resources
• Contains SampleResource with labels and selectors
• Tests label transformation on custom resource types

api/krusty/testdata/golden/TestLabelTransformerConfigWithCustomResources_include_selector_via_transformerConfig.golden


87. api/krusty/testdata/golden/TestLabelTransformerConfigWithCustomResources_include_template_via_transformerConfig.golden 🧪 Tests +20/-0

Golden file for label transformer template config

• Added golden file for label transformer with template config
• Contains SampleResource with template metadata labels
• Tests label application to template sections

api/krusty/testdata/golden/TestLabelTransformerConfigWithCustomResources_include_template_via_transformerConfig.golden


88. api/resmap/testdata/golden/TestDeAnchorIntoDoc.golden 🧪 Tests +21/-0

Golden file for YAML anchor de-anchoring

• Added golden file for YAML anchor de-anchoring test
• Contains Deployment with probe configuration
• Tests removal of YAML anchors and aliases

api/resmap/testdata/golden/TestDeAnchorIntoDoc.golden


89. api/krusty/testdata/golden/TestIssue4682_NameReferencesToSelfInAnnotations.golden 🧪 Tests +19/-0

Golden file for name reference annotations

• Added golden file for name reference in annotations test
• Contains ConfigMap and Namespace with self-referential annotations
• Tests variable substitution in annotation values

api/krusty/testdata/golden/TestIssue4682_NameReferencesToSelfInAnnotations.golden


90. api/krusty/testdata/golden/TestDeploymentAnnotations.golden 🧪 Tests +23/-0

Golden file for deployment annotations

• Added golden file for deployment annotations test
• Contains Deployment and ConfigMap with annotations
• Tests annotation propagation to pod templates

api/krusty/testdata/golden/TestDeploymentAnnotations.golden


91. api/krusty/testdata/golden/TestNameReferenceAfterGvknChange.golden 🧪 Tests +22/-0

Golden file for name reference after GVKN change

• Added golden file for name reference after GVKN change
• Contains ConfigMap and Deployment with environment references
• Tests name resolution after resource renaming

api/krusty/testdata/golden/TestNameReferenceAfterGvknChange.golden


92. api/krusty/testdata/golden/TestRemoveEmptyDirWithPatchesAtSameLevel.golden 🧪 Tests +19/-0

Golden file for empty directory removal

• Added golden file for empty directory removal with patches
• Contains Deployment with volumes and containers
• Tests patch application for volume removal

api/krusty/testdata/golden/TestRemoveEmptyDirWithPatchesAtSameLevel.golden


93. api/krusty/testdata/golden/TestIssue1281_JsonPatchAndImageTag.golden 🧪 Tests +22/-0

Golden file for JSON patch and image tag

• Added golden file for JSON patch with image tag test
• Contains two Deployments with different image specifications
• Tests JSON patch application with image updates

api/krusty/testdata/golden/TestIssue1281_JsonPatchAndImageTag.golden


94. api/krusty/testdata/golden/TestReplacementTransformerWithSuffixTransformerAndRejectUsingRegex.golden 🧪 Tests +18/-0

Golden file for replacement with regex rejection

• Added golden file for replacement with suffix and regex rejection
• Contains Deployment and ConfigMap with name transformations
• Tests combined transformer operations with regex filtering

api/krusty/testdata/golden/TestReplacementTransformerWithSuffixTransformerAndRejectUsingRegex.golden


95. api/krusty/testdata/golden/TestComponent_missing-optional-component-api-version.golden 🧪 Tests +21/-0

Golden file for missing component API version

• Added golden file for component with missing API version
• Contains Deployment and ConfigMap resources
• Tests component handling without explicit API version

api/krusty/testdata/golden/TestComponent_missing-optional-component-api-version.golden


96. api/krusty/testdata/golden/TestCustomNamePrefixer.golden 🧪 Tests +23/-0

Golden file for custom name prefixer

• Added golden file for custom name prefixer test
• Contains Deployment, Role, and Service with custom prefixes
• Tests custom name transformation logic

api/krusty/testdata/golden/TestCustomNamePrefixer.golden


97. api/krusty/testdata/golden/TestReplacementTransformerWithOriginalName.golden 🧪 Tests +21/-0

Golden file for replacement with original name

• Added golden file for replacement transformer with original names...

These Python scripts were used to automate the migration to golden file
testing. Since the migration is complete, they are no longer needed.
@qodo-free-for-open-source-projects
Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (4) 📘 Rule violations (1) 📎 Requirement gaps (0)

Grey Divider


Action required

1. Golden collision subtests 🐞 Bug ✓ Correctness
Description
TestVolumeRemoveEmptyDirInOverlay now runs two assertions in subtests but reuses a Harness
  created with the parent *testing.T.
• The harness assertion derives the golden filename from t.Name(); since th holds the parent
  t, both subtests map to the same golden file.
• The repo contains only TestVolumeRemoveEmptyDirInOverlay.golden (overlay output), so the base
  assertion will compare against the wrong golden and fail (or overwrite when -update-golden is
  used).
Code

api/krusty/multiplepatch_test.go[R443-449]

+	t.Run("base", func(t *testing.T) {
+		m := th.Run("base", th.MakeDefaultOptions())
+		th.AssertActualEqualsExpected(m, "")
+	})

	th.WriteK("overlay", `
patchesStrategicMerge:
Evidence
The test introduces t.Run subtests but keeps using th.AssertActualEqualsExpected, which uses the
Harness’s stored t (not the subtest t). Golden filenames are based on t.Name(), so both
base/overlay assertions target the same TestVolumeRemoveEmptyDirInOverlay.golden. That golden file
content matches the overlay output, so the base assertion cannot pass against it.

api/krusty/multiplepatch_test.go[412-479]
api/testutils/kusttest/harness.go[18-40]
api/testutils/kusttest/hasgett.go[81-87]
api/krusty/testdata/golden/TestVolumeRemoveEmptyDirInOverlay.golden[1-37]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`TestVolumeRemoveEmptyDirInOverlay` asserts two different outputs (base and overlay) but, after converting to subtests, both assertions still use the same `Harness` instance created with the parent `*testing.T`. Since golden filenames are based on `t.Name()`, both assertions target the same golden file, causing failures or overwrites.

### Issue Context
The existing golden file `TestVolumeRemoveEmptyDirInOverlay.golden` contains the overlay output, so the base assertion will not match.

### Fix Focus Areas
- api/krusty/multiplepatch_test.go[412-479]
- api/testutils/kusttest/harness.go[18-40]
- api/testutils/kusttest/hasgett.go[81-87]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

2. AsYAML() returns raw error 📘 Rule violation ⛯ Reliability
Description
Resource.AsYAML() calls r.MarshalJSON() but returns the error directly without adding
  operation context (e.g., that the failure occurred during duplicate-key detection prior to YAML
  serialization).
• This makes failures harder to diagnose because callers only see the underlying marshal error, not
  where/why it was triggered in the YAML path.
Code

api/resource/resource.go[R383-388]

+	// Check for duplicate keys by attempting to marshal to JSON first.
+	// This will detect duplicate keys that would cause issues.
+	_, err := r.MarshalJSON()
+	if err != nil {
+		return nil, err
+	}
Evidence
The robust error-handling requirement calls for actionable, contextual errors. The new AsYAML()
logic introduces a new failure point (MarshalJSON() for duplicate-key detection) but returns err
without additional context.

Rule 3: Generic: Robust Error Handling and Edge Case Management
api/resource/resource.go[383-388]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`Resource.AsYAML()` introduces a new failure point by calling `r.MarshalJSON()` for duplicate-key detection, but it returns the raw error without adding context. This makes debugging harder for callers because the error does not indicate it occurred during the YAML conversion path.

## Issue Context
The compliance requirement expects errors to include actionable context about what failed and why.

## Fix Focus Areas
- api/resource/resource.go[383-388]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Golden read error masked 🐞 Bug ⛯ Reliability
Description
AssertActualEqualsExpectedWithTweak tries to read a golden file, but it only takes the golden
  path when os.ReadFile returns err == nil.
• Any other read error (permissions, transient FS issues, partial checkout) silently falls back to
  the inline expected string.
• This can hide golden-file problems and produce confusing behavior where tests pass/fail depending
  on the inline expected value, not the golden file state.
Code

api/testutils/kusttest/hasgett.go[R66-78]

+	// Try to read golden file first
+	if goldenBytes, err := os.ReadFile(goldenPath); err == nil {
+		// Golden file exists, use it
+		if string(goldenBytes) != string(actual) {
+			reportDiffAndFail(t, actual, string(goldenBytes))
+		}
+		return
+	}
+
+	// Fall back to expected string (backward compatibility)
	if string(actual) != expected {
		reportDiffAndFail(t, actual, expected)
	}
Evidence
The implementation only checks err == nil and otherwise proceeds to compare against the inline
expected value. This means errors other than ‘file does not exist’ are not surfaced.

api/testutils/kusttest/hasgett.go[66-78]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
Golden file read errors other than &#x27;not found&#x27; are silently ignored, and the assertion falls back to inline expected content. This can mask golden file corruption/permission issues.

### Issue Context
You want backwards compatibility when the golden file doesn&#x27;t exist, but you still want to fail loudly on unexpected I/O errors.

### Fix Focus Areas
- api/testutils/kusttest/hasgett.go[66-78]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


4. AsYAML extra serialization 🐞 Bug ➹ Performance
Description
Resource.AsYAML() now calls r.MarshalJSON() and then serializes again via r.MustString().
• MarshalJSON() for an RNode converts the node to a string, unmarshals it into a Go structure,
  then marshals it to JSON, adding substantial CPU/memory work.
• This is on an important path (e.g., ResMap.AsYaml() loops over all resources and calls
  res.AsYAML()), so it risks a noticeable performance regression during builds/printing.
Code

api/resource/resource.go[R383-391]

+	// Check for duplicate keys by attempting to marshal to JSON first.
+	// This will detect duplicate keys that would cause issues.
+	_, err := r.MarshalJSON()
+	if err != nil {
+		return nil, err
+	}
	// Use kyaml's encoder directly to preserve original formatting
	// and avoid line wrapping issues with sigs.k8s.io/yaml.JSONToYAML.
	// See https://github.com/kubernetes-sigs/kustomize/issues/947
Evidence
Resource.AsYAML now triggers MarshalJSON, which performs stringify + YAML unmarshal + JSON
marshal. ResMap.AsYaml() calls res.AsYAML() for each resource when producing build output; the
extra work scales with resource count.

api/resource/resource.go[380-393]
kyaml/yaml/rnode.go[974-1000]
api/resmap/reswrangler.go[284-305]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`Resource.AsYAML()` now does a full `MarshalJSON()` (stringify + unmarshal + json.Marshal) and then immediately serializes again via `MustString()`. This introduces extra overhead in build/output code paths.

### Issue Context
`ResMap.AsYaml()` calls `res.AsYAML()` per resource, so this overhead scales with the size of the build.

### Fix Focus Areas
- api/resource/resource.go[380-393]
- kyaml/yaml/rnode.go[974-1000]
- api/resmap/reswrangler.go[284-305]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View more (1)
5. Factory test weakened 🐞 Bug ⛯ Reliability
Description
TestNewResMapFromConfigMapArgs no longer compares actual YAML output to the expected ResMap
  output.
• The test now only asserts the YAML is non-empty, which allows content regressions to slip through.
• If output-order instability is the concern, it would be better to compare semantically (e.g.,
  parsed nodes) or use a golden file instead of dropping equality checks entirely.
Code

api/resmap/factory_test.go[R227-236]

+		// Compare with actual output from expected ResMap
+		// Both use the same AsYaml() which now preserves original YAML order
		tc.expected.RemoveBuildAnnotations()
-		expYaml, err := tc.expected.AsYaml()
+		_, err = tc.expected.AsYaml()
		require.NoError(t, err, tc.description)
-		assert.Equal(t, expYaml, rYaml)
+		// The output order may differ due to how resources are constructed
+		// (NewResMapFromConfigMapArgs vs NewRmBuilder), but both are valid YAML
+		// Use the actual output as the expected value since it's the correct one
+		// The actual output from NewResMapFromConfigMapArgs is the authoritative source
+		assert.NotEmpty(t, rYaml, tc.description)
Evidence
The equality assertion against the expected YAML is replaced by assert.NotEmpty, which does not
validate correctness of content.

api/resmap/factory_test.go[222-237]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
The test currently only checks that YAML output is non-empty, which weakens regression protection.

### Issue Context
If the original reason for removing equality is ordering differences, prefer semantic comparison or golden testing rather than `NotEmpty`.

### Fix Focus Areas
- api/resmap/factory_test.go[222-237]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

ⓘ The new review experience is currently in Beta. Learn more

Grey Divider

Qodo Logo

@Rindrics Rindrics closed this Feb 9, 2026
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.

1 participant