github.com/devseccon/trivy@v0.47.1-0.20231123133102-bd902a0bd996/pkg/fanal/analyzer/licensing/license_test.go (about)

     1  package licensing
     2  
     3  import (
     4  	"context"
     5  	"os"
     6  	"testing"
     7  
     8  	"github.com/stretchr/testify/assert"
     9  	"github.com/stretchr/testify/require"
    10  
    11  	"github.com/devseccon/trivy/pkg/fanal/analyzer"
    12  	"github.com/devseccon/trivy/pkg/fanal/types"
    13  )
    14  
    15  func Test_licenseAnalyzer_Analyze(t *testing.T) {
    16  	tests := []struct {
    17  		name     string
    18  		filePath string
    19  		want     *analyzer.AnalysisResult
    20  	}{
    21  		{
    22  			name:     "Licensed C file",
    23  			filePath: "testdata/licensed.c",
    24  			want: &analyzer.AnalysisResult{
    25  				Licenses: []types.LicenseFile{
    26  					{
    27  						Type:     types.LicenseTypeHeader,
    28  						FilePath: "testdata/licensed.c",
    29  						Findings: []types.LicenseFinding{
    30  							{
    31  								Name:       "AGPL-3.0",
    32  								Confidence: 1,
    33  								Link:       "https://spdx.org/licenses/AGPL-3.0.html",
    34  							},
    35  						},
    36  					},
    37  				},
    38  			},
    39  		},
    40  		{
    41  			name:     "Non human readable binary file",
    42  			filePath: "testdata/binaryfile",
    43  			want:     nil,
    44  		},
    45  	}
    46  
    47  	for _, tt := range tests {
    48  		t.Run(tt.name, func(t *testing.T) {
    49  			f, err := os.Open(tt.filePath)
    50  			require.NoError(t, err)
    51  			defer f.Close()
    52  
    53  			fi, err := f.Stat()
    54  			require.NoError(t, err)
    55  
    56  			a := licenseFileAnalyzer{}
    57  			got, err := a.Analyze(context.TODO(), analyzer.AnalysisInput{
    58  				FilePath: tt.filePath,
    59  				Content:  f,
    60  				Info:     fi,
    61  			})
    62  			require.NoError(t, err)
    63  			assert.Equal(t, tt.want, got)
    64  		})
    65  	}
    66  
    67  }
    68  
    69  func Test_licenseAnalyzer_Required(t *testing.T) {
    70  	tests := []struct {
    71  		name     string
    72  		filePath string
    73  		want     bool
    74  	}{
    75  		{
    76  			name:     "C file with license",
    77  			filePath: "testdata/licensed.c",
    78  			want:     true,
    79  		},
    80  		{
    81  			name:     "C file without license",
    82  			filePath: "testdata/unlicensed.c",
    83  			want:     true,
    84  		},
    85  		{
    86  			name:     "Unreadable file",
    87  			filePath: "testdata/binaryfile",
    88  			want:     false,
    89  		},
    90  	}
    91  	for _, tt := range tests {
    92  		t.Run(tt.name, func(t *testing.T) {
    93  			a := licenseFileAnalyzer{}
    94  			got := a.Required(tt.filePath, nil)
    95  			assert.Equal(t, tt.want, got)
    96  		})
    97  	}
    98  }