github.com/google/osv-scalibr@v0.4.1/binary/cdx/cdx_test.go (about) 1 // Copyright 2025 Google LLC 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package cdx_test 16 17 import ( 18 "os" 19 "path/filepath" 20 "runtime" 21 "strings" 22 "testing" 23 24 "github.com/CycloneDX/cyclonedx-go" 25 "github.com/google/go-cmp/cmp" 26 "github.com/google/osv-scalibr/binary/cdx" 27 ) 28 29 var doc *cyclonedx.BOM 30 31 //nolint:gochecknoinits 32 func init() { 33 doc = cyclonedx.NewBOM() 34 doc.Metadata = &cyclonedx.Metadata{ 35 Timestamp: "2006-01-02T15:04:05Z", 36 Component: &cyclonedx.Component{ 37 Name: "BOM name", 38 }, 39 } 40 } 41 42 func TestWrite(t *testing.T) { 43 testDirPath := t.TempDir() 44 testCases := []struct { 45 desc string 46 format string 47 want string 48 }{ 49 { 50 desc: "xml", 51 format: "cdx-xml", 52 want: "testdata/doc.cyclonedx.xml", 53 }, 54 { 55 desc: "json", 56 format: "cdx-json", 57 want: "testdata/doc.cyclonedx.json", 58 }, 59 } 60 61 for _, tc := range testCases { 62 t.Run(tc.desc, func(t *testing.T) { 63 fullPath := filepath.Join(testDirPath, "output") 64 err := cdx.Write(doc, fullPath, tc.format) 65 if err != nil { 66 t.Fatalf("cdx.Write(%v, %s, %s) returned an error: %v", doc, fullPath, tc.format, err) 67 } 68 69 got, err := os.ReadFile(fullPath) 70 if err != nil { 71 t.Fatalf("error while reading %s: %v", fullPath, err) 72 } 73 want, err := os.ReadFile(tc.want) 74 if err != nil { 75 t.Fatalf("error while reading %s: %v", tc.want, err) 76 } 77 wantStr := strings.TrimSpace(string(want)) 78 gotStr := strings.TrimSpace(string(got)) 79 if runtime.GOOS == "windows" { 80 wantStr = strings.ReplaceAll(wantStr, "\r", "") 81 gotStr = strings.ReplaceAll(gotStr, "\r", "") 82 } 83 84 if diff := cmp.Diff(wantStr, gotStr); diff != "" { 85 t.Errorf("cdx.Write(%v, %s, %s) produced unexpected results, diff (-want +got):\n%s", doc, fullPath, tc.format, diff) 86 } 87 }) 88 } 89 } 90 91 func TestWrite_InvalidFormat(t *testing.T) { 92 testDirPath := t.TempDir() 93 fullPath := filepath.Join(testDirPath, "output") 94 format := "invalid-format" 95 if err := cdx.Write(doc, fullPath, format); err == nil || 96 !strings.Contains(err.Error(), "invalid CDX format") { 97 t.Errorf("cdx.Write(%s, %s) didn't return an invalid extension error: %v", fullPath, format, err) 98 } 99 }