|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "log" |
| 7 | + "strings" |
| 8 | + "time" |
| 9 | + |
| 10 | + "github.com/jetstack/preflight/pkg/packagesources/local" |
| 11 | + "github.com/jetstack/preflight/pkg/packaging" |
| 12 | + "github.com/spf13/cobra" |
| 13 | +) |
| 14 | + |
| 15 | +var testParams = struct { |
| 16 | + verbose bool |
| 17 | + timeout time.Duration |
| 18 | +}{} |
| 19 | + |
| 20 | +var testCmd = &cobra.Command{ |
| 21 | + Use: "test", |
| 22 | + Short: "Test REGO inside a Preflight package", |
| 23 | + Long: `This uses OPA's engine to run all the test suites |
| 24 | +inside the package. |
| 25 | +
|
| 26 | +It only works with local packages. |
| 27 | +`, |
| 28 | + Run: func(cmd *cobra.Command, args []string) { |
| 29 | + if len(args) == 0 { |
| 30 | + // Fail if given no input |
| 31 | + log.Fatal("No packages provided for linting") |
| 32 | + } else { |
| 33 | + loadedPackages := make([]packaging.Package, 0) |
| 34 | + |
| 35 | + for _, packagePath := range args { |
| 36 | + pkgs, err := local.LoadLocalPackages(packagePath) |
| 37 | + if err != nil { |
| 38 | + log.Fatalf("Error loading packages from %s: %v", packagePath, err) |
| 39 | + } |
| 40 | + for _, p := range pkgs { |
| 41 | + loadedPackages = append(loadedPackages, p) |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + packagesWithErrors := make(map[string][]int) |
| 46 | + |
| 47 | + ctx, cancel := context.WithCancel(context.Background()) |
| 48 | + defer cancel() |
| 49 | + |
| 50 | + for _, pkg := range loadedPackages { |
| 51 | + log.Printf("Testing package %s", pkg.PolicyManifest().GlobalID()) |
| 52 | + numFailures, numTotal, err := packaging.TestPackage(ctx, pkg, testParams.verbose, testParams.timeout) |
| 53 | + |
| 54 | + if err != nil { |
| 55 | + log.Fatalf("Error testing package %s: %v", pkg.PolicyManifest().GlobalID(), err) |
| 56 | + } |
| 57 | + |
| 58 | + if numFailures != 0 { |
| 59 | + packagesWithErrors[pkg.PolicyManifest().GlobalID()] = []int{numFailures, numTotal} |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + if len(packagesWithErrors) > 0 { |
| 64 | + log.Fatalf("Encountered failed tests in these packages: %s", func() (s string) { |
| 65 | + pkgs := make([]string, 0) |
| 66 | + for k, v := range packagesWithErrors { |
| 67 | + pkgs = append(pkgs, fmt.Sprintf("%s (%d failures in %d tests)", k, v[0], v[1])) |
| 68 | + } |
| 69 | + return strings.Join(pkgs, ", ") |
| 70 | + }()) |
| 71 | + } else { |
| 72 | + log.Printf("All packages tests passed :)") |
| 73 | + } |
| 74 | + } |
| 75 | + }, |
| 76 | +} |
| 77 | + |
| 78 | +func init() { |
| 79 | + packageCmd.AddCommand(testCmd) |
| 80 | + |
| 81 | + testCmd.Flags().BoolVarP(&testParams.verbose, "verbose", "v", false, "set verbose reporting mode") |
| 82 | + testCmd.Flags().DurationVarP(&testParams.timeout, "timeout", "t", time.Second*10, "set test timeout") |
| 83 | +} |
0 commit comments