github.com/nextlinux/gosbom@v0.81.1-0.20230627115839-1ff50c281391/gosbom/formats/cyclonedxjson/decoder_test.go (about)

     1  package cyclonedxjson
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"strings"
     7  	"testing"
     8  
     9  	"github.com/stretchr/testify/assert"
    10  )
    11  
    12  func Test_decodeJSON(t *testing.T) {
    13  	tests := []struct {
    14  		file     string
    15  		err      bool
    16  		distro   string
    17  		packages []string
    18  	}{
    19  		{
    20  			file:     "snapshot/TestCycloneDxDirectoryEncoder.golden",
    21  			distro:   "debian:1.2.3",
    22  			packages: []string{"package-1:1.0.1", "package-2:2.0.1"},
    23  		},
    24  		{
    25  			file:     "snapshot/TestCycloneDxImageEncoder.golden",
    26  			distro:   "debian:1.2.3",
    27  			packages: []string{"package-1:1.0.1", "package-2:2.0.1"},
    28  		},
    29  		{
    30  			file: "image-simple/Dockerfile",
    31  			err:  true,
    32  		},
    33  	}
    34  	for _, test := range tests {
    35  		t.Run(test.file, func(t *testing.T) {
    36  			reader, err := os.Open("test-fixtures/" + test.file)
    37  			assert.NoError(t, err)
    38  
    39  			if test.err {
    40  				err = Format().Validate(reader)
    41  				assert.Error(t, err)
    42  				return
    43  			}
    44  
    45  			bom, err := Format().Decode(reader)
    46  
    47  			assert.NoError(t, err)
    48  
    49  			split := strings.SplitN(test.distro, ":", 2)
    50  			name := split[0]
    51  			version := split[1]
    52  			assert.Equal(t, bom.Artifacts.LinuxDistribution.ID, name)
    53  			assert.Equal(t, bom.Artifacts.LinuxDistribution.Version, version)
    54  
    55  		pkgs:
    56  			for _, pkg := range test.packages {
    57  				split = strings.SplitN(pkg, ":", 2)
    58  				name = split[0]
    59  				version = split[1]
    60  				for p := range bom.Artifacts.Packages.Enumerate() {
    61  					if p.Name == name {
    62  						assert.Equal(t, version, p.Version)
    63  						continue pkgs
    64  					}
    65  				}
    66  				assert.Fail(t, fmt.Sprintf("package should be present: %s", pkg))
    67  			}
    68  		})
    69  	}
    70  }