Skip to content

Commit

Permalink
Use tenntenn/jsonschema
Browse files Browse the repository at this point in the history
  • Loading branch information
tenntenn committed Mar 5, 2019
1 parent e23ec37 commit 0d5f7f3
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 2 deletions.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ module github.com/gcpug/hake
require (
cloud.google.com/go v0.35.1
github.com/golang/protobuf v1.2.0
github.com/tenntenn/jsonschema v0.0.1
github.com/tenntenn/jsonschema v0.0.2
github.com/xeipuuv/gojsonschema v1.1.0
google.golang.org/genproto v0.0.0-20190201180003-4b09977fb922
)
3 changes: 2 additions & 1 deletion json_row.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ func (rs JSONRows) toJSONRowSlice() []*JSONRow {
for i := range rs {
rows[i] = rs.At(i)
}

return rows
}

Expand All @@ -141,5 +142,5 @@ func (rs JSONRows) MarshalJSON() ([]byte, error) {

// Schema writes JSON Schema of the rows to writer w.
func (rs JSONRows) JSONSchema(w io.Writer, options ...jsonschema.Option) error {
return jsonschema.Generate(w, rs, options...)
return jsonschema.Generate(w, rs.toJSONRowSlice(), options...)
}
55 changes: 55 additions & 0 deletions json_row_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,58 @@ func TestJSONRow_JSONSchema(t *testing.T) {
})
}
}

func TestJSONRows_JSONSchema(t *testing.T) {

type T struct {
N int
S string
}

type NT struct {
T T
}

cases := []struct {
name string
rows []*spanner.Row
isErr bool
}{
{"int", rows(t, []R{{"col1", 100}}), false},
{"int int", rows(t, []R{{"col1", 100}, {"col1", 200}}), false},
{"int string", rows(t, []R{{"col1", 100, "col2", "string"}}), false},
{"nested struct", rows(t, []R{{"col1", 100, "col2", T{N: 100, S: ""}}}), false},
{"timestamp", rows(t, []R{{"col1", 100, "col2", timestamp(t, "2002-10-02T10:00:00Z")}}), false},
{"bytes", rows(t, []R{{"col1", []byte("test")}}), false},
}

for _, tt := range cases {
tt := tt
t.Run(tt.name, func(t *testing.T) {
var got bytes.Buffer
err := JSONRows(tt.rows).JSONSchema(&got)
switch {
case tt.isErr && err == nil:
t.Errorf("expected error does not occur")
case !tt.isErr && err != nil:
t.Errorf("unexpected error %v", err)
}

l := gojsonschema.NewStringLoader(got.String())
s, err := gojsonschema.NewSchema(l)
if err != nil {
t.Fatalf("unexpected error %v", err)
}

rowJSON := toJSON(t, JSONRows(tt.rows))
r, err := s.Validate(gojsonschema.NewStringLoader(rowJSON))
if err != nil {
t.Fatalf("unexpected error %v", err)
}

if !r.Valid() {
t.Errorf("invalid JSON Schema: %s", got.String())
}
})
}
}

0 comments on commit 0d5f7f3

Please sign in to comment.