From fec27fb245747254bc2ac06a1393cfa8b6f95c5c Mon Sep 17 00:00:00 2001 From: Aleksandar Stojanov Date: Fri, 17 Nov 2023 15:50:00 +0100 Subject: [PATCH 1/2] add some more tests --- go.mod | 6 ++ go.sum | 6 ++ schema.go | 28 +++---- schema_test.go | 108 +++++++++++++++++++++++++- testdata/{values_3.yaml => fail.yaml} | 0 5 files changed, 132 insertions(+), 16 deletions(-) rename testdata/{values_3.yaml => fail.yaml} (100%) diff --git a/go.mod b/go.mod index 0854c00..1d36cc6 100644 --- a/go.mod +++ b/go.mod @@ -6,3 +6,9 @@ require ( github.com/losisin/go-jsonschema-generator v0.1.0 gopkg.in/yaml.v3 v3.0.1 ) + +require ( + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/stretchr/testify v1.8.4 // indirect +) diff --git a/go.sum b/go.sum index a57cf2a..84e8bd1 100644 --- a/go.sum +++ b/go.sum @@ -1,8 +1,14 @@ +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI= github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/losisin/go-jsonschema-generator v0.1.0 h1:8gxoO92jZuVRmTlpiTthOvq32+IHRFRPw0QwHgVM/PY= github.com/losisin/go-jsonschema-generator v0.1.0/go.mod h1:H12PhYtGRM1BhF8nZ1L4Ml1l+Gjjr5tu3ybVnDlr8aM= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= diff --git a/schema.go b/schema.go index fd151b8..86db8cb 100644 --- a/schema.go +++ b/schema.go @@ -108,7 +108,7 @@ func parseFlags(progname string, args []string) (config *Config, output string, err = flags.Parse(args) if err != nil { - fmt.Println("usage: helm schema [-input STR] [-draft INT] [-output STR]") + fmt.Println("Usage: helm schema [-input STR] [-draft INT] [-output STR]") return nil, buf.String(), err } @@ -117,11 +117,10 @@ func parseFlags(progname string, args []string) (config *Config, output string, } // Generate JSON schema -func generateJsonSchema(config *Config) { +func generateJsonSchema(config *Config) error { // Check if the input flag is set if len(config.input) == 0 { - fmt.Fprintln(os.Stderr, "Input flag is required. Please provide input yaml files using the -input flag.") - os.Exit(2) + return errors.New("input flag is required. Please provide input yaml files using the -input flag") } var schemaUrl string @@ -137,8 +136,7 @@ func generateJsonSchema(config *Config) { case 2020: schemaUrl = "https://json-schema.org/draft/2020-12/schema" default: - fmt.Fprintln(os.Stderr, "Invalid draft version. Please use one of: 4, 6, 7, 2019, 2020.") - os.Exit(1) + return errors.New("invalid draft version. Please use one of: 4, 6, 7, 2019, 2020") } // Declare a map to hold the merged YAML data @@ -148,8 +146,8 @@ func generateJsonSchema(config *Config) { for _, filePath := range config.input { var currentMap map[string]interface{} if err := readAndUnmarshalYAML(filePath, ¤tMap); err != nil { - fmt.Printf("Error reading %s: %v\n", filePath, err) - continue + return errors.New("error reading YAML file(s)") + } // Merge the current YAML data with the mergedMap @@ -164,18 +162,22 @@ func generateJsonSchema(config *Config) { if err != nil { fmt.Printf("Error: %v\n", err) } + + return nil } func main() { conf, output, err := parseFlags(os.Args[0], os.Args[1:]) if err == flag.ErrHelp { fmt.Println(output) - os.Exit(0) + return } else if err != nil { - fmt.Println("got error:", err) - fmt.Println("output:\n", output) - os.Exit(1) + fmt.Println("Error:", output) + return } - generateJsonSchema(conf) + err = generateJsonSchema(conf) + if err != nil { + fmt.Println("Error:", err) + } } diff --git a/schema_test.go b/schema_test.go index 4b3c9f0..df7d9e5 100644 --- a/schema_test.go +++ b/schema_test.go @@ -1,14 +1,17 @@ package main import ( + "bytes" "flag" "fmt" + "io" "os" "reflect" "strings" "testing" "github.com/losisin/go-jsonschema-generator" + "github.com/stretchr/testify/assert" ) func TestMultiStringFlagString(t *testing.T) { @@ -225,7 +228,7 @@ func TestParseFlagsPass(t *testing.T) { for _, tt := range tests { t.Run(strings.Join(tt.args, " "), func(t *testing.T) { - conf, output, err := parseFlags("prog", tt.args) + conf, output, err := parseFlags("schema", tt.args) if err != nil { t.Errorf("err got %v, want nil", err) } @@ -244,7 +247,7 @@ func TestParseFlagsUsage(t *testing.T) { for _, arg := range usageArgs { t.Run(arg, func(t *testing.T) { - conf, output, err := parseFlags("prog", []string{arg}) + conf, output, err := parseFlags("schema", []string{arg}) if err != flag.ErrHelp { t.Errorf("err got %v, want ErrHelp", err) } @@ -270,7 +273,7 @@ func TestParseFlagsFail(t *testing.T) { for _, tt := range tests { t.Run(strings.Join(tt.args, " "), func(t *testing.T) { - conf, output, err := parseFlags("prog", tt.args) + conf, output, err := parseFlags("schema", tt.args) if conf != nil { t.Errorf("conf got %v, want nil", conf) } @@ -336,3 +339,102 @@ func TestGenerateJsonSchemaPass(t *testing.T) { }) } } + +func TestGenerateJsonSchemaFail(t *testing.T) { + testCases := []struct { + config *Config + expectedErr string + }{ + { + config: &Config{}, + expectedErr: "input flag is required. Please provide input yaml files using the -input flag", + }, + { + config: &Config{ + input: multiStringFlag{"testdata/values_1.yaml"}, + draft: 5, + }, + expectedErr: "invalid draft version. Please use one of: 4, 6, 7, 2019, 2020", + }, + { + config: &Config{ + input: multiStringFlag{"fake.yaml"}, + draft: 2019, + }, + expectedErr: "error reading YAML file(s)", + }, + } + + for _, testCase := range testCases { + err := generateJsonSchema(testCase.config) + if err == nil { + t.Errorf("Expected error, got nil") + } else if err.Error() != testCase.expectedErr { + t.Errorf("Expected error: %s, got: %s", testCase.expectedErr, err.Error()) + } + } +} + +func TestMain(t *testing.T) { + tests := []struct { + name string + args []string + expectedError string + expectedOut string + }{ + { + name: "HelpFlag", + args: []string{"schema", "-h"}, + expectedOut: "Usage of schema", + expectedError: "", + }, + { + name: "InvalidFlags", + args: []string{"schema", "-fail"}, + expectedOut: "", + expectedError: "flag provided but not defined", + }, + { + name: "SuccessfulRun", + args: []string{"schema", "-input", "testdata/values_1.yaml"}, + expectedOut: "", + expectedError: "", + }, + { + name: "GenerateError", + args: []string{"schema", "-input", "testdata/fail.yaml", "-draft", "2020"}, + expectedOut: "", + expectedError: "Error: error reading YAML file(s)", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + originalArgs := os.Args + originalStdout := os.Stdout + + r, w, _ := os.Pipe() + os.Stdout = w + + os.Args = tt.args + + go func() { + main() + w.Close() + }() + + var buf bytes.Buffer + io.Copy(&buf, r) + + os.Args = originalArgs + os.Stdout = originalStdout + + out := buf.String() + + assert.Contains(t, out, tt.expectedOut) + if tt.expectedError != "" { + assert.Contains(t, out, tt.expectedError) + } + }) + } +} diff --git a/testdata/values_3.yaml b/testdata/fail.yaml similarity index 100% rename from testdata/values_3.yaml rename to testdata/fail.yaml From 5166eb289396cca7060583532e2f558b52f2e84f Mon Sep 17 00:00:00 2001 From: Aleksandar Stojanov Date: Fri, 17 Nov 2023 16:00:51 +0100 Subject: [PATCH 2/2] fix lint errors --- go.mod | 2 +- schema_test.go | 17 +++++++++++++---- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/go.mod b/go.mod index 1d36cc6..af149a5 100644 --- a/go.mod +++ b/go.mod @@ -4,11 +4,11 @@ go 1.20 require ( github.com/losisin/go-jsonschema-generator v0.1.0 + github.com/stretchr/testify v1.8.4 gopkg.in/yaml.v3 v3.0.1 ) require ( github.com/davecgh/go-spew v1.1.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/stretchr/testify v1.8.4 // indirect ) diff --git a/schema_test.go b/schema_test.go index df7d9e5..22a1beb 100644 --- a/schema_test.go +++ b/schema_test.go @@ -303,9 +303,12 @@ func TestGenerateJsonSchemaPass(t *testing.T) { for _, tt := range tests { t.Run(fmt.Sprintf("%v", tt.conf), func(t *testing.T) { conf := &tt.conf - generateJsonSchema(conf) + err := generateJsonSchema(conf) + if err != nil { + t.Fatalf("generateJsonSchema() failed: %v", err) + } - _, err := os.Stat(conf.outputPath) + _, err = os.Stat(conf.outputPath) if os.IsNotExist(err) { t.Errorf("Expected file '%q' to be created, but it doesn't exist", conf.outputPath) } @@ -324,7 +327,10 @@ func TestGenerateJsonSchemaPass(t *testing.T) { }) t.Run(fmt.Sprintf("%v", tt.conf), func(t *testing.T) { conf := &tt.conf - generateJsonSchema(conf) + err := generateJsonSchema(conf) + if err != nil { + t.Fatalf("generateJsonSchema() failed: %v", err) + } outputJson, err := os.ReadFile(conf.outputPath) if err != nil { @@ -424,7 +430,10 @@ func TestMain(t *testing.T) { }() var buf bytes.Buffer - io.Copy(&buf, r) + _, err := io.Copy(&buf, r) + if err != nil { + t.Errorf("Error reading stdout: %v", err) + } os.Args = originalArgs os.Stdout = originalStdout