Skip to content

Commit 23eebb0

Browse files
Replace parseOSRelease env var hack with mockable function variable
Signed-off-by: Karthik Vetrivel <[email protected]>
1 parent c5d513d commit 23eebb0

File tree

2 files changed

+21
-9
lines changed

2 files changed

+21
-9
lines changed

controllers/object_controls.go

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -966,19 +966,19 @@ func TransformGPUDiscoveryPlugin(obj *appsv1.DaemonSet, config *gpuv1.ClusterPol
966966
return nil
967967
}
968968

969-
// Read and parse os-release file
970-
func parseOSRelease() (map[string]string, error) {
971-
release := map[string]string{}
969+
// parseOSRelease can be overridden in tests for mocking filesystem access.
970+
// In production, it reads and parses /host-etc/os-release.
971+
var parseOSRelease = parseOSReleaseFromFile
972972

973-
// TODO: mock this call instead
974-
if os.Getenv("UNIT_TEST") == "true" {
975-
return release, nil
976-
}
973+
// parseOSReleaseFromFile reads and parses the os-release file from the host filesystem.
974+
func parseOSReleaseFromFile() (map[string]string, error) {
975+
release := map[string]string{}
977976

978977
f, err := os.Open("/host-etc/os-release")
979978
if err != nil {
980979
return nil, err
981980
}
981+
defer f.Close()
982982

983983
re := regexp.MustCompile(`^(?P<key>\w+)=(?P<value>.+)`)
984984

controllers/object_controls_test.go

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,18 @@ func getModuleRoot(dir string) (string, error) {
146146
return dir, nil
147147
}
148148

149+
// mockOSRelease returns a mock parseOSRelease function for testing.
150+
// It allows tests to simulate different operating systems without filesystem access.
151+
func mockOSRelease(osID, version string) func() (map[string]string, error) {
152+
return func() (map[string]string, error) {
153+
return map[string]string{
154+
"ID": osID,
155+
"VERSION_ID": version,
156+
"NAME": osID,
157+
}, nil
158+
}
159+
}
160+
149161
// setup creates a mock kubernetes cluster and client. Nodes are labeled with the minimum
150162
// required NFD labels to be detected as GPU nodes by the GPU Operator. A sample
151163
// ClusterPolicy resource is applied to the cluster. The ClusterPolicyController
@@ -158,8 +170,8 @@ func setup() error {
158170
boolTrue = new(bool)
159171
*boolTrue = true
160172

161-
// add env for calls that we cannot mock
162-
os.Setenv("UNIT_TEST", "true")
173+
// Mock parseOSRelease to avoid filesystem dependency in tests
174+
parseOSRelease = mockOSRelease("ubuntu", "20.04")
163175

164176
s := scheme.Scheme
165177
if err := gpuv1.AddToScheme(s); err != nil {

0 commit comments

Comments
 (0)