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

     1  package buildinfo
     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_dockerfileAnalyzer_Analyze(t *testing.T) {
    16  	tests := []struct {
    17  		name      string
    18  		inputFile string
    19  		want      *analyzer.AnalysisResult
    20  		wantErr   string
    21  	}{
    22  		{
    23  			name:      "com.redhat.component",
    24  			inputFile: "testdata/dockerfile/Dockerfile-ubi8-8.3-227",
    25  			want: &analyzer.AnalysisResult{
    26  				BuildInfo: &types.BuildInfo{
    27  					Nvr:  "ubi8-container-8.3-227",
    28  					Arch: "x86_64",
    29  				},
    30  			},
    31  		},
    32  		{
    33  			name:      "BZcomponent",
    34  			inputFile: "testdata/dockerfile/Dockerfile-jboss-base-7-base-1.1-3",
    35  			want: &analyzer.AnalysisResult{
    36  				BuildInfo: &types.BuildInfo{
    37  					Nvr:  "jboss-base-7-docker-1.1-3",
    38  					Arch: "x86_64",
    39  				},
    40  			},
    41  		},
    42  		{
    43  			name:      "missing architecture",
    44  			inputFile: "testdata/dockerfile/Dockerfile.sad",
    45  			wantErr:   "no arch found",
    46  		},
    47  	}
    48  	for _, tt := range tests {
    49  		t.Run(tt.name, func(t *testing.T) {
    50  			f, err := os.Open(tt.inputFile)
    51  			require.NoError(t, err)
    52  			defer f.Close()
    53  
    54  			a := dockerfileAnalyzer{}
    55  			got, err := a.Analyze(context.Background(), analyzer.AnalysisInput{
    56  				FilePath: tt.inputFile,
    57  				Content:  f,
    58  			})
    59  
    60  			if tt.wantErr != "" {
    61  				require.Error(t, err)
    62  				assert.Equal(t, err.Error(), tt.wantErr)
    63  				return
    64  			}
    65  			assert.NoError(t, err)
    66  			assert.Equal(t, tt.want, got)
    67  		})
    68  	}
    69  }
    70  
    71  func Test_dockerfileAnalyzer_Required(t *testing.T) {
    72  	tests := []struct {
    73  		name     string
    74  		filePath string
    75  		want     bool
    76  	}{
    77  		{
    78  			name:     "happy path",
    79  			filePath: "root/buildinfo/Dockerfile-ubi8-8.3-227",
    80  			want:     true,
    81  		},
    82  		{
    83  			name:     "sad path",
    84  			filePath: "app/Dockerfile-ubi8-8.3-227",
    85  			want:     false,
    86  		},
    87  	}
    88  	for _, tt := range tests {
    89  		t.Run(tt.name, func(t *testing.T) {
    90  			a := dockerfileAnalyzer{}
    91  			got := a.Required(tt.filePath, nil)
    92  			assert.Equal(t, tt.want, got)
    93  		})
    94  	}
    95  }