11package main
22
33import (
4- "errors"
4+ "os"
5+ "path/filepath"
56 "strings"
67 "testing"
78
89 "github.com/eraser-dev/eraser/api/unversioned"
9-
1010 "github.com/stretchr/testify/assert"
11+ "github.com/stretchr/testify/require"
1112)
1213
1314const (
@@ -174,36 +175,43 @@ func TestCLIArgs(t *testing.T) {
174175
175176// TestFindTrivyExecutable tests the findTrivyExecutable function in isolation.
176177func TestFindTrivyExecutable (t * testing.T ) {
177- // Store original function to restore after tests
178- originalLookPath := currentExecutingLookPath
179- defer func () { currentExecutingLookPath = originalLookPath }()
178+ // Save original PATH to restore after tests
179+ originalPath := os . Getenv ( "PATH" )
180+ defer func () { os . Setenv ( "PATH" , originalPath ) }()
180181
181182 testCases := []struct {
182183 name string
183- lookPathSetup func ()
184+ setupFunc func (t * testing. T ) string // returns tempdir path
184185 expectedPath string
185186 expectedError bool
186187 expectedErrorMatch string
187188 }{
188189 {
189190 name : "Trivy found in PATH only" ,
190- lookPathSetup : func () {
191- currentExecutingLookPath = func (file string ) (string , error ) {
192- if file == trivyExecutableName {
193- return trivyPathBin , nil
194- }
195- return "" , errors .New ("not found" )
196- }
191+ setupFunc : func (t * testing.T ) string {
192+ tempDir := t .TempDir ()
193+ trivyPath := filepath .Join (tempDir , "trivy" )
194+
195+ // Create executable file
196+ file , err := os .Create (trivyPath )
197+ require .NoError (t , err )
198+ file .Close ()
199+ err = os .Chmod (trivyPath , 0o755 )
200+ require .NoError (t , err )
201+
202+ // Set PATH to include temp directory
203+ os .Setenv ("PATH" , tempDir )
204+ return trivyPath
197205 },
198- expectedPath : trivyPathBin ,
199206 expectedError : false ,
200207 },
201208 {
202209 name : "Trivy not found anywhere" ,
203- lookPathSetup : func () {
204- currentExecutingLookPath = func (_ string ) (string , error ) {
205- return "" , errors .New ("executable file not found in $PATH" )
206- }
210+ setupFunc : func (t * testing.T ) string {
211+ // Set PATH to empty temp directory without trivy
212+ tempDir := t .TempDir ()
213+ os .Setenv ("PATH" , tempDir )
214+ return ""
207215 },
208216 expectedPath : "" ,
209217 expectedError : true ,
@@ -213,7 +221,10 @@ func TestFindTrivyExecutable(t *testing.T) {
213221
214222 for _ , tc := range testCases {
215223 t .Run (tc .name , func (t * testing.T ) {
216- tc .lookPathSetup ()
224+ expectedPath := tc .setupFunc (t )
225+ if expectedPath == "" {
226+ expectedPath = tc .expectedPath
227+ }
217228
218229 path , err := findTrivyExecutable ()
219230
@@ -223,7 +234,7 @@ func TestFindTrivyExecutable(t *testing.T) {
223234 assert .Empty (t , path )
224235 } else {
225236 assert .NoError (t , err )
226- assert .Equal (t , tc . expectedPath , path )
237+ assert .Equal (t , expectedPath , path )
227238 }
228239 })
229240 }
0 commit comments