From c390ecc5f537bb306d6f738bb0ec59b5efd0d114 Mon Sep 17 00:00:00 2001 From: Konikz Date: Wed, 16 Apr 2025 12:21:59 +0530 Subject: [PATCH] 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 --- pkg/usrlocalsharelima/usrlocalsharelima.go | 8 +-- .../usrlocalsharelima_test.go | 49 +++++++++++++++++++ 2 files changed, 53 insertions(+), 4 deletions(-) create mode 100644 pkg/usrlocalsharelima/usrlocalsharelima_test.go diff --git a/pkg/usrlocalsharelima/usrlocalsharelima.go b/pkg/usrlocalsharelima/usrlocalsharelima.go index fcaca4ad7f2..f9ba7b0d225 100644 --- a/pkg/usrlocalsharelima/usrlocalsharelima.go +++ b/pkg/usrlocalsharelima/usrlocalsharelima.go @@ -13,14 +13,14 @@ import ( "github.com/lima-vm/lima/pkg/debugutil" "github.com/lima-vm/lima/pkg/limayaml" + . "github.com/lima-vm/lima/pkg/must" "github.com/sirupsen/logrus" ) +// Cache the executable path at package level. +var self = Must(os.Executable()) + func Dir() (string, error) { - self, err := os.Executable() - if err != nil { - return "", err - } selfSt, err := os.Stat(self) if err != nil { return "", err diff --git a/pkg/usrlocalsharelima/usrlocalsharelima_test.go b/pkg/usrlocalsharelima/usrlocalsharelima_test.go new file mode 100644 index 00000000000..4c26e4b2a3e --- /dev/null +++ b/pkg/usrlocalsharelima/usrlocalsharelima_test.go @@ -0,0 +1,49 @@ +// SPDX-FileCopyrightText: Copyright The Lima Authors +// SPDX-License-Identifier: Apache-2.0 + +package usrlocalsharelima + +import ( + "os" + "path/filepath" + "testing" + + "gotest.tools/v3/assert" +) + +func TestDir(t *testing.T) { + // Create a temporary directory for testing + tmpDir := t.TempDir() + + // Create the expected directory structure + shareDir := filepath.Join(tmpDir, "share", "lima") + err := os.MkdirAll(shareDir, 0o755) + assert.NilError(t, err) + + // Create a dummy guest agent binary with the correct name format + gaBinary := filepath.Join(shareDir, "lima-guestagent.Linux-x86_64") + err = os.WriteFile(gaBinary, []byte("dummy content"), 0o755) + assert.NilError(t, err) + + // Create bin directory and limactl file + binDir := filepath.Join(tmpDir, "bin") + err = os.MkdirAll(binDir, 0o755) + assert.NilError(t, err) + limactlPath := filepath.Join(binDir, "limactl") + err = os.WriteFile(limactlPath, []byte("dummy content"), 0o755) + assert.NilError(t, err) + + // Save original value of self + originalSelf := self + // Restore original value after test + defer func() { + self = originalSelf + }() + // Override self for the test + self = limactlPath + + // Test that Dir() returns the correct path + dir, err := Dir() + assert.NilError(t, err) + assert.Equal(t, dir, shareDir) +}