Files
schemas/cmd/validate/main_test.go

77 lines
2.9 KiB
Go

package main
import (
"bytes"
"os"
"path/filepath"
"strings"
"testing"
)
func TestCommand(t *testing.T) {
for _, test := range []struct {
name string
args []string
code int
out string
err string
}{
{"valid", []string{"-root", "../..", "../../examples/party.yml"}, 0, "valid (maximumdirect.rpg.party.v1)", ""},
{"continue after failure", []string{"-root", "../..", "../../tests/invalid/semantic-duplicate-id.yml", "../../examples/weather.json"}, 1, "weather.json: valid", "semantic:"},
{"structural", []string{"-root", "../..", "../../tests/invalid/structure-missing-name.yml"}, 1, "", "structure:"},
{"decode", []string{"-root", "../..", "../../tests/invalid/decode-duplicate-key.yml"}, 1, "", "decode:"},
{"file missing", []string{"-root", "../..", filepath.Join(t.TempDir(), "missing.yml")}, 1, "", "missing.yml"},
{"no documents", nil, 2, "", "Usage:"},
{"bad flag", []string{"-unknown"}, 2, "", "flag provided"},
{"help", []string{"-h"}, 0, "", "Usage:"},
{"missing set", []string{"-root", t.TempDir(), "../../examples/party.yml"}, 2, "", "schema set:"},
} {
t.Run(test.name, func(t *testing.T) {
var stdout, stderr bytes.Buffer
code := run(test.args, &stdout, &stderr)
if code != test.code || !strings.Contains(stdout.String(), test.out) || !strings.Contains(stderr.String(), test.err) {
t.Fatalf("exit=%d, stdout=%q, stderr=%q", code, &stdout, &stderr)
}
})
}
}
func TestJSONSyntax(t *testing.T) {
file := filepath.Join(t.TempDir(), "document.json")
if err := os.WriteFile(file, []byte("schema_version: maximumdirect.rpg.campaign.v1\nid: sample"), 0600); err != nil {
t.Fatal(err)
}
var stdout, stderr bytes.Buffer
if run([]string{"-root", "../..", file}, &stdout, &stderr) != 1 || !strings.Contains(stderr.String(), "decode: expected JSON syntax") {
t.Fatalf("expected JSON syntax failure, got %q", &stderr)
}
}
func TestDocumentDecoding(t *testing.T) {
for _, test := range []struct {
file string
body string
code int
}{
{"escaped.json", `{"schema_version":"maximumdirect.rpg.campaign.v1","id":"weather","name":"Weather \ud83c\udf27"}`, 0},
{"malformed-float.yml", "schema_version: maximumdirect.rpg.campaign.v1\nid: weather\nreading: !!float e3\n", 1},
} {
t.Run(test.file, func(t *testing.T) {
file := filepath.Join(t.TempDir(), test.file)
if err := os.WriteFile(file, []byte(test.body), 0600); err != nil {
t.Fatal(err)
}
var stdout, stderr bytes.Buffer
if code := run([]string{"-root", "../..", file}, &stdout, &stderr); code != test.code {
t.Fatalf("want exit %d, got %d: stdout=%q stderr=%q", test.code, code, &stdout, &stderr)
}
if test.code == 0 && !strings.Contains(stdout.String(), "valid (maximumdirect.rpg.campaign.v1)") {
t.Fatalf("missing success report: %q", &stdout)
}
if test.code != 0 && !strings.Contains(stderr.String(), "decode:") {
t.Fatalf("missing decoding failure: %q", &stderr)
}
})
}
}