mirror of
https://github.com/kyverno/kyverno.git
synced 2025-03-09 09:26:54 +00:00
* feat: Add flags for target resources and add fake client initialization Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add fake discovery client and cluster bool in the policy processor Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use the full mutation engine policy response in the engine response Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Extract mutated targets from the policy responses and print them out Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add TargetResources field in the cli test schema Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Generate CLI crds Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: modify checkResult to take an arbitrary actual resource and resource name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: change getAndCompareResource to take a resource name and cascade it to GetResourceFromPath Signed-off-by: aerosouund <aerosound161@gmail.com> * test: Create a simple test to test mutate existing in the CLI Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Allow GetResourceFromPath to select a resource with a name from a multi resource yaml Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Modify the runTest command to return the TestResponse type - Create a fake client, load the target resources in it and use it in the PolicyProcessor. - Create the TestResponse which contains Trigger and Target fields, each is a map of gvk/name to the responses corresponding to that resource. Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Rewrite output.go to use the TestResponse type - Check for both target and trigger - Create logic for appending the resource array in case no resources are passed - Move row creation logic into a separate method to avoid code duplication - Extract the proper target resource based on rule type - Create a function to extract mutated target from the engine response Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Move tests to the correct folder Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use apiVersion/Kind/Name as the key in the test responses Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Use the apiVersion/Kind/name key schema in checking results and fix invalid resource name checking for generate policies Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use better variable names for rows Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Account for Generate resources being an array Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use generated resource name in checking the results and printing output Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Uncomment checks printing Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Remove bug in engine response creation Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Move the generate logic into an else block Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix namespace fetching bug in cel validator Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use pointer to int in the test counter Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Remove redundant method Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Skip resources not being found in the manifests Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Create another field in the engine to denote if this is a cluster engine or an offline engine Simply checking for the client being nil is no longer enough because for cli operations the client will be a fake client A pointer to bool is chosen because callers who don't necessarily know what to pass should be able to pass nil Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Add extra argument in fake client initiation Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: add extra argument in fuzz test Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Add extra arg Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Handle resources specified as ns/name as this schema will be deprecated in favor of apiVersion/Kind/Name Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Fix linter complaints Signed-off-by: ammar <ammar.yasser@vodafone.com> * fix: Use comma separation as array separators as kubernetes names don't support commas To avoid undefined array length on splitting on / using commas will result in a fixed length since all resources will have an apiVersion, kind, namespace and name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Change resource array type to an array of any instead of array of string To support the use of a string or a TestResourceSpec Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Expect the resource array to be an array of string or array of TestResourceSpec Assert that an array element is either of these types and match the resources in both cases according to the element type Expect that the key in responses is now separated by commas instead of slashes Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Expect that the resource array is now of type array of any and modify tests that use it Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Skip response check if the policy name isnt whats in the result Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Match the name if its specified as ns/name Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Create CLI CRDs Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Fix linter complaints Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Cleanup invalid code used in FixTest to adapt it to the schema changes Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Check if resource is nil before extracting Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: use the loadResources method to open targets in a directory Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Account for target resources with the same name but different namespaces Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Add CLI test for mutate existing with the same name Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Infer resource name and namespace from the actual resource and account for resources with the same name and namespace but different kinds Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: remove extra line Signed-off-by: aerosouund <aerosound161@gmail.com> * feat: Add printing mutate existing resources to the output or to a file Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Minor fixes Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: codegen Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Revert result back to error Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Use io discard to not print resources in the test command Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Update vague comments and remove outdated ones Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Integrate mutate existing changes with diff generation Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Move resource key generation into a function Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Add a mutate existing test that fails Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: fix linter complaint Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Remove redundant comment Signed-off-by: aerosouund <aerosound161@gmail.com> * refactor: Fix array of any assignment in cli test Signed-off-by: aerosouund <aerosound161@gmail.com> * fix: Dont check duplicate strings for field that is an array of any Signed-off-by: aerosouund <aerosound161@gmail.com> * bug: Fix appending to the wrong array Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: run fix tests Signed-off-by: aerosouund <aerosound161@gmail.com> * chore: Run fix tests Signed-off-by: aerosouund <aerosound161@gmail.com> --------- Signed-off-by: aerosouund <aerosound161@gmail.com> Signed-off-by: ammar <ammar.yasser@vodafone.com> Signed-off-by: Ammar Yasser <aerosound161@gmail.com> Co-authored-by: ammar <ammar.yasser@vodafone.com> Co-authored-by: shuting <shuting@nirmata.com>
205 lines
7.1 KiB
Go
205 lines
7.1 KiB
Go
package test
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"path/filepath"
|
|
|
|
"github.com/go-git/go-billy/v5"
|
|
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/apis/v1alpha1"
|
|
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/command"
|
|
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/deprecations"
|
|
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/output/color"
|
|
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/output/table"
|
|
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/report"
|
|
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/test/filter"
|
|
engineapi "github.com/kyverno/kyverno/pkg/engine/api"
|
|
"github.com/sergi/go-diff/diffmatchpatch"
|
|
"github.com/spf13/cobra"
|
|
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
|
)
|
|
|
|
func Command() *cobra.Command {
|
|
var testCase string
|
|
var fileName, gitBranch string
|
|
var registryAccess, failOnly, removeColor, detailedResults bool
|
|
cmd := &cobra.Command{
|
|
Use: "test [local folder or git repository]...",
|
|
Short: command.FormatDescription(true, websiteUrl, false, description...),
|
|
Long: command.FormatDescription(false, websiteUrl, false, description...),
|
|
Example: command.FormatExamples(examples...),
|
|
Args: cobra.MinimumNArgs(1),
|
|
SilenceUsage: true,
|
|
RunE: func(cmd *cobra.Command, dirPath []string) (err error) {
|
|
color.Init(removeColor)
|
|
return testCommandExecute(cmd.OutOrStdout(), dirPath, fileName, gitBranch, testCase, registryAccess, failOnly, detailedResults)
|
|
},
|
|
}
|
|
cmd.Flags().StringVarP(&fileName, "file-name", "f", "kyverno-test.yaml", "Test filename")
|
|
cmd.Flags().StringVarP(&gitBranch, "git-branch", "b", "", "Test github repository branch")
|
|
cmd.Flags().StringVarP(&testCase, "test-case-selector", "t", "policy=*,rule=*,resource=*", "Filter test cases to run")
|
|
cmd.Flags().BoolVar(®istryAccess, "registry", false, "If set to true, access the image registry using local docker credentials to populate external data")
|
|
cmd.Flags().BoolVar(&failOnly, "fail-only", false, "If set to true, display all the failing test only as output for the test command")
|
|
cmd.Flags().BoolVar(&removeColor, "remove-color", false, "Remove any color from output")
|
|
cmd.Flags().BoolVar(&detailedResults, "detailed-results", false, "If set to true, display detailed results")
|
|
return cmd
|
|
}
|
|
|
|
type resultCounts struct {
|
|
Skip int
|
|
Pass int
|
|
Fail int
|
|
}
|
|
|
|
func testCommandExecute(
|
|
out io.Writer,
|
|
dirPath []string,
|
|
fileName string,
|
|
gitBranch string,
|
|
testCase string,
|
|
registryAccess bool,
|
|
failOnly bool,
|
|
detailedResults bool,
|
|
) (err error) {
|
|
// check input dir
|
|
if len(dirPath) == 0 {
|
|
return fmt.Errorf("a directory is required")
|
|
}
|
|
// parse filter
|
|
filter, errors := filter.ParseFilter(testCase)
|
|
if len(errors) > 0 {
|
|
fmt.Fprintln(out)
|
|
fmt.Fprintln(out, "Filter errors:")
|
|
for _, e := range errors {
|
|
fmt.Fprintln(out, " Error:", e)
|
|
}
|
|
}
|
|
// load tests
|
|
tests, err := loadTests(dirPath, fileName, gitBranch)
|
|
if err != nil {
|
|
fmt.Fprintln(out)
|
|
fmt.Fprintln(out, "Error loading tests:", err)
|
|
return err
|
|
}
|
|
if len(tests) == 0 {
|
|
fmt.Fprintln(out)
|
|
fmt.Fprintln(out, "No test yamls available")
|
|
}
|
|
if errs := tests.Errors(); len(errs) > 0 {
|
|
fmt.Fprintln(out)
|
|
fmt.Fprintln(out, "Test errors:")
|
|
for _, e := range errs {
|
|
fmt.Fprintln(out, " Path:", e.Path)
|
|
fmt.Fprintln(out, " Error:", e.Err)
|
|
}
|
|
}
|
|
if len(tests) == 0 {
|
|
if len(errors) == 0 {
|
|
return nil
|
|
} else {
|
|
// TODO aggregate errors
|
|
return errors[0]
|
|
}
|
|
}
|
|
rc := &resultCounts{}
|
|
var fullTable table.Table
|
|
for _, test := range tests {
|
|
if test.Err == nil {
|
|
deprecations.CheckTest(out, test.Path, test.Test)
|
|
// filter results
|
|
var filteredResults []v1alpha1.TestResult
|
|
for _, res := range test.Test.Results {
|
|
if filter.Apply(res) {
|
|
filteredResults = append(filteredResults, res)
|
|
}
|
|
}
|
|
if len(filteredResults) == 0 {
|
|
continue
|
|
}
|
|
resourcePath := filepath.Dir(test.Path)
|
|
responses, err := runTest(out, test, registryAccess)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to run test (%w)", err)
|
|
}
|
|
fmt.Fprintln(out, " Checking results ...")
|
|
var resultsTable table.Table
|
|
if err := printTestResult(filteredResults, responses, rc, &resultsTable, test.Fs, resourcePath); err != nil {
|
|
return fmt.Errorf("failed to print test result (%w)", err)
|
|
}
|
|
if err := printCheckResult(test.Test.Checks, *responses, rc, &resultsTable); err != nil {
|
|
return fmt.Errorf("failed to print test result (%w)", err)
|
|
}
|
|
fullTable.AddFailed(resultsTable.RawRows...)
|
|
printer := table.NewTablePrinter(out)
|
|
fmt.Fprintln(out)
|
|
printer.Print(resultsTable.Rows(detailedResults))
|
|
fmt.Fprintln(out)
|
|
}
|
|
}
|
|
if !failOnly {
|
|
fmt.Fprintf(out, "\nTest Summary: %d tests passed and %d tests failed\n", rc.Pass+rc.Skip, rc.Fail)
|
|
} else {
|
|
fmt.Fprintf(out, "\nTest Summary: %d out of %d tests failed\n", rc.Fail, rc.Pass+rc.Skip+rc.Fail)
|
|
}
|
|
fmt.Fprintln(out)
|
|
if rc.Fail > 0 {
|
|
if !failOnly {
|
|
printFailedTestResult(out, fullTable, detailedResults)
|
|
}
|
|
return fmt.Errorf("%d tests failed", rc.Fail)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func checkResult(test v1alpha1.TestResult, fs billy.Filesystem, resoucePath string, response engineapi.EngineResponse, rule engineapi.RuleResponse, actualResource unstructured.Unstructured) (bool, string, string) {
|
|
expected := test.Result
|
|
// fallback to the deprecated field
|
|
if expected == "" {
|
|
expected = test.Status
|
|
}
|
|
// fallback on deprecated field
|
|
if test.PatchedResource != "" {
|
|
equals, diff, err := getAndCompareResource(actualResource, fs, filepath.Join(resoucePath, test.PatchedResource))
|
|
if err != nil {
|
|
return false, err.Error(), "Resource error"
|
|
}
|
|
if !equals {
|
|
dmp := diffmatchpatch.New()
|
|
legend := dmp.DiffPrettyText(dmp.DiffMain("only in expected", "only in actual", false))
|
|
return false, fmt.Sprintf("Patched resource didn't match the patched resource in the test result\n(%s)\n\n%s", legend, diff), "Resource diff"
|
|
}
|
|
}
|
|
if test.GeneratedResource != "" {
|
|
equals, diff, err := getAndCompareResource(actualResource, fs, filepath.Join(resoucePath, test.GeneratedResource))
|
|
if err != nil {
|
|
return false, err.Error(), "Resource error"
|
|
}
|
|
if !equals {
|
|
dmp := diffmatchpatch.New()
|
|
legend := dmp.DiffPrettyText(dmp.DiffMain("only in expected", "only in actual", false))
|
|
return false, fmt.Sprintf("Patched resource didn't match the generated resource in the test result\n(%s)\n\n%s", legend, diff), "Resource diff"
|
|
}
|
|
}
|
|
result := report.ComputePolicyReportResult(false, response, rule)
|
|
if result.Result != expected {
|
|
return false, result.Message, fmt.Sprintf("Want %s, got %s", expected, result.Result)
|
|
}
|
|
return true, result.Message, "Ok"
|
|
}
|
|
|
|
func lookupRuleResponses(test v1alpha1.TestResult, responses ...engineapi.RuleResponse) []engineapi.RuleResponse {
|
|
var matches []engineapi.RuleResponse
|
|
// Since there are no rules in case of validating admission policies, responses are returned without checking rule names.
|
|
if test.IsValidatingAdmissionPolicy {
|
|
matches = responses
|
|
} else {
|
|
for _, response := range responses {
|
|
rule := response.Name()
|
|
if rule != test.Rule && rule != "autogen-"+test.Rule && rule != "autogen-cronjob-"+test.Rule {
|
|
continue
|
|
}
|
|
matches = append(matches, response)
|
|
}
|
|
}
|
|
return matches
|
|
}
|