cmd: Add very basic parse cmd coverage

There was an issue a little while back where we had a panic in the
command but there is zero test coverage exercising it... so we never
noticed.

This at least will get us some bare-bones test coverage to ensure
it isn't crashing on some basic use-cases.

Signed-off-by: Patrick East <east.patrick@gmail.com>
This commit is contained in:
Patrick East
2020-03-20 16:53:03 -07:00
committed by Torin Sandall
parent 16b6e29a97
commit 4f323e0597
2 changed files with 66 additions and 6 deletions
+7 -6
View File
@@ -7,6 +7,7 @@ package cmd
import (
"encoding/json"
"fmt"
"io"
"os"
"github.com/spf13/cobra"
@@ -39,11 +40,11 @@ var parseCommand = &cobra.Command{
return nil
},
Run: func(cmd *cobra.Command, args []string) {
os.Exit(parse(args))
os.Exit(parse(args, os.Stdout, os.Stderr))
},
}
func parse(args []string) int {
func parse(args []string, stdout io.Writer, stderr io.Writer) int {
if len(args) == 0 {
return 0
}
@@ -53,22 +54,22 @@ func parse(args []string) int {
switch parseParams.format.String() {
case parseFormatJSON:
if err != nil {
pr.JSON(os.Stderr, pr.Output{Errors: pr.NewOutputErrors(err)})
pr.JSON(stderr, pr.Output{Errors: pr.NewOutputErrors(err)})
return 1
}
bs, err := json.MarshalIndent(result.Parsed, "", " ")
if err != nil {
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(stderr, err)
return 1
}
fmt.Println(string(bs))
default:
if err != nil {
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(stderr, err)
return 1
}
ast.Pretty(os.Stdout, result.Parsed)
ast.Pretty(stdout, result.Parsed)
}
return 0
+59
View File
@@ -0,0 +1,59 @@
package cmd
import (
"bytes"
"path/filepath"
"testing"
"github.com/open-policy-agent/opa/util/test"
)
func TestParseExit0(t *testing.T) {
files := map[string]string{
"x.rego": `package x
p = 1
`,
}
errc, _, stderr := testParse(t, files)
if errc != 0 {
t.Fatalf("Expected exit code 0, got %v", errc)
}
if len(stderr) > 0 {
t.Fatalf("Expected no stderr output, got:\n%s\n", string(stderr))
}
}
func TestParseExit1(t *testing.T) {
files := map[string]string{
"x.rego": `???`,
}
errc, _, stderr := testParse(t, files)
if errc != 1 {
t.Fatalf("Expected exit code 1, got %v", errc)
}
if len(stderr) == 0 {
t.Fatalf("Expected output in stderr")
}
}
// Runs parse and returns the exit code, stdout, and stderr contents
func testParse(t *testing.T, files map[string]string) (int, []byte, []byte) {
t.Helper()
stdout := new(bytes.Buffer)
stderr := new(bytes.Buffer)
var errc int
test.WithTempFS(files, func(path string) {
var args []string
for file := range files {
args = append(args, filepath.Join(path, file))
}
errc = parse(args, stdout, stderr)
})
return errc, stdout.Bytes(), stderr.Bytes()
}