From eaa4df6ce658fbbe5bb0dac261138efece57b1a2 Mon Sep 17 00:00:00 2001 From: Justin Abrahms Date: Thu, 30 Mar 2023 09:58:24 -0700 Subject: [PATCH] Error if invalid json is passed. Signed-off-by: Justin Abrahms --- decode.go | 7 ++++++- decode_test.go | 12 ++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/decode.go b/decode.go index fdf0529..508791c 100644 --- a/decode.go +++ b/decode.go @@ -21,6 +21,7 @@ import ( "encoding/json" "encoding/xml" "io" + "io/ioutil" ) type BOMDecoder interface { @@ -40,7 +41,11 @@ type jsonBOMDecoder struct { // Decode implements the BOMDecoder interface. func (j jsonBOMDecoder) Decode(bom *BOM) error { - return json.NewDecoder(j.reader).Decode(bom) + bytes, err := ioutil.ReadAll(j.reader) + if err != nil { + return err + } + return json.Unmarshal(bytes, bom) } type xmlBOMDecoder struct { diff --git a/decode_test.go b/decode_test.go index 9d10c03..efb3f72 100644 --- a/decode_test.go +++ b/decode_test.go @@ -30,6 +30,18 @@ func TestNewBOMDecoder(t *testing.T) { assert.IsType(t, &xmlBOMDecoder{}, NewBOMDecoder(nil, BOMFileFormatXML)) } +func TestXmlBOMDecoder_Decode_InvalidXML(t *testing.T) { + var bom BOM + err := NewBOMDecoder(strings.NewReader("invalid"), BOMFileFormatXML).Decode(&bom) + require.Error(t, err) +} + +func TestJsonBOMDecoder_Decode_InvalidJson(t *testing.T) { + var bom BOM + err := NewBOMDecoder(strings.NewReader("{}invalid"), BOMFileFormatJSON).Decode(&bom) + require.Error(t, err) +} + func TestXmlBOMDecoder_Decode(t *testing.T) { t.Run("ShouldSetSpecVersion", func(t *testing.T) { testCases := []struct {