Skip to content

Commit c390ecc

Browse files
author
Konikz
committed
fix: make usrlocalsharelima.Dir() testable
This commit implements the following improvements:\n- Caches the executable path at package level using Must()\n- Makes the Dir() function testable\n- Adds a test to verify functionality Signed-off-by: Konikz <[email protected]>
1 parent 4c82f35 commit c390ecc

File tree

2 files changed

+53
-4
lines changed

2 files changed

+53
-4
lines changed

Diff for: pkg/usrlocalsharelima/usrlocalsharelima.go

+4-4
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,14 @@ import (
1313

1414
"github.com/lima-vm/lima/pkg/debugutil"
1515
"github.com/lima-vm/lima/pkg/limayaml"
16+
. "github.com/lima-vm/lima/pkg/must"
1617
"github.com/sirupsen/logrus"
1718
)
1819

20+
// Cache the executable path at package level.
21+
var self = Must(os.Executable())
22+
1923
func Dir() (string, error) {
20-
self, err := os.Executable()
21-
if err != nil {
22-
return "", err
23-
}
2424
selfSt, err := os.Stat(self)
2525
if err != nil {
2626
return "", err

Diff for: pkg/usrlocalsharelima/usrlocalsharelima_test.go

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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+
"testing"
10+
11+
"gotest.tools/v3/assert"
12+
)
13+
14+
func TestDir(t *testing.T) {
15+
// Create a temporary directory for testing
16+
tmpDir := t.TempDir()
17+
18+
// Create the expected directory structure
19+
shareDir := filepath.Join(tmpDir, "share", "lima")
20+
err := os.MkdirAll(shareDir, 0o755)
21+
assert.NilError(t, err)
22+
23+
// Create a dummy guest agent binary with the correct name format
24+
gaBinary := filepath.Join(shareDir, "lima-guestagent.Linux-x86_64")
25+
err = os.WriteFile(gaBinary, []byte("dummy content"), 0o755)
26+
assert.NilError(t, err)
27+
28+
// Create bin directory and limactl file
29+
binDir := filepath.Join(tmpDir, "bin")
30+
err = os.MkdirAll(binDir, 0o755)
31+
assert.NilError(t, err)
32+
limactlPath := filepath.Join(binDir, "limactl")
33+
err = os.WriteFile(limactlPath, []byte("dummy content"), 0o755)
34+
assert.NilError(t, err)
35+
36+
// Save original value of self
37+
originalSelf := self
38+
// Restore original value after test
39+
defer func() {
40+
self = originalSelf
41+
}()
42+
// Override self for the test
43+
self = limactlPath
44+
45+
// Test that Dir() returns the correct path
46+
dir, err := Dir()
47+
assert.NilError(t, err)
48+
assert.Equal(t, dir, shareDir)
49+
}

0 commit comments

Comments
 (0)