1
0
Fork 0
mirror of https://github.com/kyverno/kyverno.git synced 2025-03-10 09:56:55 +00:00
kyverno/cmd/cli/kubectl-kyverno/commands/test/compare.go
Tomas Aschan 8746a8ffbb
feat: Show textual diff when generate test fails (#11674)
* feat: Show textual diff when generate test fails

Signed-off-by: Tomas Aschan <tomasl@spotify.com>

* Tweak verbosity level for diff output

Signed-off-by: Tomas Aschan <tomasl@spotify.com>

* Display a rich diff of the expected and actual resources with --detailed-results

Signed-off-by: Tomas Aschan <tomasl@spotify.com>

---------

Signed-off-by: Tomas Aschan <tomasl@spotify.com>
2024-12-04 06:09:19 +00:00

51 lines
1.7 KiB
Go

package test
import (
"fmt"
"github.com/go-git/go-billy/v5"
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/log"
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/resource"
"github.com/sergi/go-diff/diffmatchpatch"
"gopkg.in/yaml.v2"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
)
func getAndCompareResource(actualResources []*unstructured.Unstructured, fs billy.Filesystem, path string) (bool, string, error) {
expectedResources, err := resource.GetResourceFromPath(fs, path)
if err != nil {
return false, "", fmt.Errorf("error: failed to load resource (%s)", err)
}
expectedResourcesMap := map[string]unstructured.Unstructured{}
for _, expectedResource := range expectedResources {
if expectedResource == nil {
continue
}
r := *expectedResource
resource.FixupGenerateLabels(r)
expectedResourcesMap[expectedResource.GetNamespace()+"/"+expectedResource.GetName()] = r
}
for _, actualResource := range actualResources {
if actualResource == nil {
continue
}
r := *actualResource
resource.FixupGenerateLabels(r)
equals, err := resource.Compare(r, expectedResourcesMap[r.GetNamespace()+"/"+r.GetName()], true)
if err != nil {
return false, "", fmt.Errorf("error: failed to compare resources (%s)", err)
}
if !equals {
log.Log.V(4).Info("Resource diff", "expected", expectedResourcesMap[r.GetNamespace()+"/"+r.GetName()], "actual", r)
es, _ := yaml.Marshal(expectedResourcesMap[r.GetNamespace()+"/"+r.GetName()])
as, _ := yaml.Marshal(r)
dmp := diffmatchpatch.New()
diffs := dmp.DiffMain(string(es), string(as), false)
log.Log.V(4).Info("\n" + dmp.DiffPrettyText(diffs) + "\n")
return false, dmp.DiffPrettyText(diffs), nil
}
}
return true, "", nil
}