Skip to content

Commit

Permalink
Merge pull request #19 from losisin/chore/add-unit-tests
Browse files Browse the repository at this point in the history
add some more tests
  • Loading branch information
losisin committed Nov 17, 2023
2 parents 533eaba + 5166eb2 commit 843eadf
Show file tree
Hide file tree
Showing 5 changed files with 144 additions and 19 deletions.
6 changes: 6 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +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
)
6 changes: 6 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -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=
Expand Down
28 changes: 15 additions & 13 deletions schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand All @@ -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
Expand All @@ -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
Expand All @@ -148,8 +146,8 @@ func generateJsonSchema(config *Config) {
for _, filePath := range config.input {
var currentMap map[string]interface{}
if err := readAndUnmarshalYAML(filePath, &currentMap); 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
Expand All @@ -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)
}
}
123 changes: 117 additions & 6 deletions schema_test.go
Original file line number Diff line number Diff line change
@@ -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) {
Expand Down Expand Up @@ -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)
}
Expand All @@ -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)
}
Expand All @@ -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)
}
Expand Down Expand Up @@ -300,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)
}
Expand All @@ -321,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 {
Expand All @@ -336,3 +345,105 @@ 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
_, err := io.Copy(&buf, r)
if err != nil {
t.Errorf("Error reading stdout: %v", err)
}

os.Args = originalArgs
os.Stdout = originalStdout

out := buf.String()

assert.Contains(t, out, tt.expectedOut)
if tt.expectedError != "" {
assert.Contains(t, out, tt.expectedError)
}
})
}
}
File renamed without changes.

0 comments on commit 843eadf

Please sign in to comment.