github.com/google/osv-scalibr@v0.4.1/binary/spdx/spdx_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 spdx_test 16 17 import ( 18 "os" 19 "path/filepath" 20 "runtime" 21 "strings" 22 "testing" 23 24 "github.com/google/go-cmp/cmp" 25 "github.com/google/osv-scalibr/binary/spdx" 26 "github.com/spdx/tools-golang/spdx/v2/v2_3" 27 ) 28 29 var doc = &v2_3.Document{ 30 SPDXVersion: "SPDX-2.3", 31 DataLicense: "CC0-1.0", 32 SPDXIdentifier: "DOCUMENT", 33 DocumentName: "Document name", 34 CreationInfo: &v2_3.CreationInfo{ 35 Created: "2006-01-02T15:04:05Z", 36 }, 37 } 38 39 func TestWrite23(t *testing.T) { 40 testDirPath := t.TempDir() 41 testCases := []struct { 42 desc string 43 format string 44 want string 45 }{ 46 { 47 desc: "tag-value", 48 format: "spdx23-tag-value", 49 want: "testdata/tag-value-format.spdx", 50 }, 51 { 52 desc: "yaml", 53 format: "spdx23-yaml", 54 want: "testdata/yaml-format", 55 }, 56 { 57 desc: "json", 58 format: "spdx23-json", 59 want: "testdata/json-format.spdx.json", 60 }, 61 } 62 63 for _, tc := range testCases { 64 t.Run(tc.desc, func(t *testing.T) { 65 fullPath := filepath.Join(testDirPath, "output") 66 err := spdx.Write23(doc, fullPath, tc.format) 67 if err != nil { 68 t.Fatalf("spdx.Write23(%v, %s, %s) returned an error: %v", doc, fullPath, tc.format, err) 69 } 70 71 got, err := os.ReadFile(fullPath) 72 if err != nil { 73 t.Fatalf("error while reading %s: %v", fullPath, err) 74 } 75 want, err := os.ReadFile(tc.want) 76 if err != nil { 77 t.Fatalf("error while reading %s: %v", tc.want, err) 78 } 79 wantStr := strings.TrimSpace(string(want)) 80 gotStr := strings.TrimSpace(string(got)) 81 if runtime.GOOS == "windows" { 82 wantStr = strings.ReplaceAll(wantStr, "\r", "") 83 gotStr = strings.ReplaceAll(gotStr, "\r", "") 84 } 85 86 if diff := cmp.Diff(wantStr, gotStr); diff != "" { 87 t.Errorf("spdx.Write23(%v, %s, %s) produced unexpected results, diff (-want +got):\n%s", doc, fullPath, tc.format, diff) 88 } 89 }) 90 } 91 } 92 93 func TestWrite_InvalidFormat(t *testing.T) { 94 testDirPath := t.TempDir() 95 fullPath := filepath.Join(testDirPath, "output") 96 format := "invalid-format" 97 if err := spdx.Write23(doc, fullPath, format); err == nil || 98 !strings.Contains(err.Error(), "invalid SPDX format") { 99 t.Errorf("spdx.Write23(%s, %s) didn't return an invalid extension error: %v", fullPath, format, err) 100 } 101 }