Skip to content

Commit

Permalink
feat: set SpecVersion when decoding from xml
Browse files Browse the repository at this point in the history
`SpecVersion` as a field is only used in the json format, but when working with `BOM` instances it is useful to know what spec version one is dealing with.

Signed-off-by: nscuro <nscuro@protonmail.com>
  • Loading branch information
nscuro committed Sep 26, 2022
1 parent 5f10aea commit 1655b7d
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 1 deletion.
14 changes: 13 additions & 1 deletion decode.go
Expand Up @@ -49,5 +49,17 @@ type xmlBOMDecoder struct {

// Decode implements the BOMDecoder interface.
func (x xmlBOMDecoder) Decode(bom *BOM) error {
return xml.NewDecoder(x.reader).Decode(bom)
err := xml.NewDecoder(x.reader).Decode(bom)
if err != nil {
return err
}

for specVersion, xmlNs := range xmlNamespaces {
if xmlNs == bom.XMLNS {
bom.SpecVersion = specVersion
break
}
}

return nil
}
45 changes: 45 additions & 0 deletions decode_test.go
Expand Up @@ -18,12 +18,57 @@
package cyclonedx

import (
"strings"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestNewBOMDecoder(t *testing.T) {
assert.IsType(t, &jsonBOMDecoder{}, NewBOMDecoder(nil, BOMFileFormatJSON))
assert.IsType(t, &xmlBOMDecoder{}, NewBOMDecoder(nil, BOMFileFormatXML))
}

func TestXmlBOMDecoder_Decode(t *testing.T) {
t.Run("ShouldSetSpecVersion", func(t *testing.T) {
testCases := []struct {
bomContent string
specVersion SpecVersion
}{
{
bomContent: `<?xml version="1.0"?><bom version="1" xmlns="http://cyclonedx.org/schema/bom/1.0"></bom>`,
specVersion: SpecVersion1_0,
},
{
bomContent: `<?xml version="1.0"?><bom version="1" xmlns="http://cyclonedx.org/schema/bom/1.1"></bom>`,
specVersion: SpecVersion1_1,
},
{
bomContent: `<?xml version="1.0"?><bom version="1" xmlns="http://cyclonedx.org/schema/bom/1.2"></bom>`,
specVersion: SpecVersion1_2,
},
{
bomContent: `<?xml version="1.0"?><bom version="1" xmlns="http://cyclonedx.org/schema/bom/1.3"></bom>`,
specVersion: SpecVersion1_3,
},
{
bomContent: `<?xml version="1.0"?><bom version="1" xmlns="http://cyclonedx.org/schema/bom/1.4"></bom>`,
specVersion: SpecVersion1_4,
},
{
bomContent: `<?xml version="1.0"?><bom version="1" xmlns="http://cyclonedx.org/schema/bom/666"></bom>`,
specVersion: SpecVersion(0),
},
}

for _, tc := range testCases {
t.Run(tc.specVersion.String(), func(t *testing.T) {
var bom BOM
err := NewBOMDecoder(strings.NewReader(tc.bomContent), BOMFileFormatXML).Decode(&bom)
require.NoError(t, err)
require.Equal(t, tc.specVersion, bom.SpecVersion)
})
}
})
}

0 comments on commit 1655b7d

Please sign in to comment.