Skip to content

Commit

Permalink
fix: ensure that unmarshalling errors properly
Browse files Browse the repository at this point in the history
Signed-off-by: Gareth Jones <[email protected]>
  • Loading branch information
G-Rath committed Oct 21, 2024
1 parent 11fadcf commit 57a2599
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
10 changes: 9 additions & 1 deletion packages/go/ecosystem/ecosystem.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package ecosystem

import (
"encoding/json"
"strings"

"github.com/ossf/osv-schema/packages/go/constants"
Expand All @@ -23,7 +24,14 @@ type Parsed struct {
//
//goland:noinspection GoMixedReceiverTypes
func (p *Parsed) UnmarshalJSON(data []byte) error {
*p = Parse(strings.Trim(string(data), "\""))
var str string
err := json.Unmarshal(data, &str)

if err != nil {
return err
}

*p = Parse(str)

return nil
}
Expand Down
36 changes: 36 additions & 0 deletions packages/go/ecosystem/ecosystem_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,42 @@ func TestParsed_UnmarshalJSON(t *testing.T) {
}
}

func TestParsed_UnmarshalJSON_Errors(t *testing.T) {
t.Parallel()

tests := []struct {
input string
err string
}{
{"1", "json: cannot unmarshal number into Go value of type string"},
{"{}", "json: cannot unmarshal object into Go value of type string"},
{"{\"ecosystem\": \"npm\"}", "json: cannot unmarshal object into Go value of type string"},
{"{\"ecosystem\": \"npm\", \"suffix\": \"\"}", "json: cannot unmarshal object into Go value of type string"},
{"{\"Ecosystem\": \"npm\", \"Suffix\": \"\"}", "json: cannot unmarshal object into Go value of type string"},
{"[]", "json: cannot unmarshal array into Go value of type string"},
}
for _, tt := range tests {
t.Run(tt.input, func(t *testing.T) {
t.Parallel()

var got ecosystem.Parsed
err := json.Unmarshal([]byte(tt.input), &got)

if err == nil {
t.Fatalf("Unmarshal() = %v; want an error", err)
}

if err.Error() != tt.err {
t.Fatalf("Unmarshal() = %v; want %v", err.Error(), tt.err)
}

if got != (ecosystem.Parsed{}) {
t.Fatalf("Unmarshal() = %v; want %v", got, ecosystem.Parsed{})
}
})
}
}

func TestParsed_MarshalJSON(t *testing.T) {
t.Parallel()

Expand Down

0 comments on commit 57a2599

Please sign in to comment.