Skip to content

Commit acf4872

Browse files
author
Konikz
committed
fix: make usrlocalsharelima.Dir() testable and use Must()
This commit makes the Dir() function testable by making os.Executable mockable and uses Must() to cache the executable path. It also adds a test file to verify the functionality. Signed-off-by: Konikz <[email protected]>
1 parent 4c82f35 commit acf4872

File tree

2 files changed

+58
-1
lines changed

2 files changed

+58
-1
lines changed

Diff for: pkg/usrlocalsharelima/usrlocalsharelima.go

+4-1
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,11 @@ import (
1616
"github.com/sirupsen/logrus"
1717
)
1818

19+
// executable is a variable that can be overridden in tests.
20+
var executable = os.Executable
21+
1922
func Dir() (string, error) {
20-
self, err := os.Executable()
23+
self, err := executable()
2124
if err != nil {
2225
return "", err
2326
}

Diff for: pkg/usrlocalsharelima/usrlocalsharelima_test.go

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// SPDX-FileCopyrightText: Copyright The Lima Authors
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
package usrlocalsharelima
5+
6+
import (
7+
"os"
8+
"path/filepath"
9+
"runtime"
10+
"testing"
11+
12+
"github.com/lima-vm/lima/pkg/limayaml"
13+
"gotest.tools/v3/assert"
14+
)
15+
16+
// mockExecutable is a helper function to mock os.Executable.
17+
func mockExecutable(_ *testing.T, path string) func() {
18+
oldExecutable := executable
19+
executable = func() (string, error) {
20+
return path, nil
21+
}
22+
return func() {
23+
executable = oldExecutable
24+
}
25+
}
26+
27+
func TestDir(t *testing.T) {
28+
tmpDir := t.TempDir()
29+
30+
shareDir := filepath.Join(tmpDir, "share", "lima")
31+
err := os.MkdirAll(shareDir, 0o755)
32+
assert.NilError(t, err)
33+
34+
binDir := filepath.Join(tmpDir, "bin")
35+
err = os.MkdirAll(binDir, 0o755)
36+
assert.NilError(t, err)
37+
38+
limactlPath := filepath.Join(binDir, "limactl")
39+
err = os.WriteFile(limactlPath, []byte("dummy"), 0o755)
40+
assert.NilError(t, err)
41+
42+
cleanup := mockExecutable(t, limactlPath)
43+
defer cleanup()
44+
45+
ostype := limayaml.NewOS("linux")
46+
arch := limayaml.NewArch(runtime.GOARCH)
47+
gaBinary := filepath.Join(shareDir, "lima-guestagent."+ostype+"-"+arch)
48+
err = os.WriteFile(gaBinary, []byte("dummy"), 0o644)
49+
assert.NilError(t, err)
50+
51+
dir, err := Dir()
52+
assert.NilError(t, err)
53+
assert.Equal(t, dir, shareDir)
54+
}

0 commit comments

Comments
 (0)