Skip to content

Commit 340bb46

Browse files
committed
Fix nil pointer runtime error, adds more tests
1 parent cf2eedc commit 340bb46

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

spaceapi_validator.go

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,10 @@ func Validate(document string) (ValidationResult, error) {
3636
documentLoader := gojsonschema.NewStringLoader(document)
3737

3838
suppliedVersion := spaceAPIVersion{}
39-
json.Unmarshal([]byte(document), &suppliedVersion)
39+
err := json.Unmarshal([]byte(document), &suppliedVersion)
40+
if err != nil {
41+
return myResult, err
42+
}
4043

4144
schemaString, ok := SpaceAPISchemas[strings.Replace(suppliedVersion.API, "0.", "", 1)]
4245
if !ok {
@@ -45,8 +48,11 @@ func Validate(document string) (ValidationResult, error) {
4548
var schema = gojsonschema.NewStringLoader(schemaString)
4649

4750
result, err := gojsonschema.Validate(schema, documentLoader)
51+
if err != nil {
52+
return myResult, err
53+
}
4854

49-
var myErrors = []ResultError{}
55+
var myErrors []ResultError
5056
for _, bar := range result.Errors() {
5157
myErrors = append(myErrors, ResultError{
5258
bar.Field(),

spaceapi_validator_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"testing"
55
)
66

7+
var wrongVersion = `{ "api": "0.5" }`
78
var invalid13 = `{ "api": "0.13" }`
89
var valid13 = `{ "api": "0.13", "open": true, "space": "example", "url": "https://example.com", "logo": "https://example.com/logo.png", "location": { "lon": 42, "lat": 23 }, "state": { "open": true }, "contact": {}, "issue_report_channels": [ "email" ] }`
910

@@ -26,4 +27,14 @@ func TestValidate(t *testing.T) {
2627
if len(validErrors) != 0 {
2728
t.Error("Schema should have got no errors, got", len(validErrors))
2829
}
30+
31+
validResult, err := Validate("")
32+
if err == nil {
33+
t.Error("Should provide an error on faulty json")
34+
}
35+
36+
invalidResult, _ = Validate(wrongVersion)
37+
if invalidResult.Valid == true {
38+
t.Error("Expected validation to be false, got", invalidResult.Valid)
39+
}
2940
}

0 commit comments

Comments
 (0)