| 1 |
/* |
| 2 |
Copyright 2026 The Kubernetes Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
package cpuset |
| 18 |
|
| 19 |
import ( |
| 20 |
"os" |
| 21 |
"path/filepath" |
| 22 |
"testing" |
| 23 |
) |
| 24 |
|
| 25 |
func TestNumCPU(t *testing.T) { |
| 26 |
orig := onlineCPUsPath |
| 27 |
t.Cleanup(func() { onlineCPUsPath = orig }) |
| 28 |
|
| 29 |
dir := t.TempDir() |
| 30 |
|
| 31 |
tests := []struct { |
| 32 |
name string |
| 33 |
content string |
| 34 |
want int |
| 35 |
wantErr bool |
| 36 |
}{ |
| 37 |
{name: "single", content: "0\n", want: 1}, |
| 38 |
{name: "range", content: "0-3\n", want: 4}, |
| 39 |
{name: "list and ranges", content: "0-1,4-7\n", want: 6}, |
| 40 |
{name: "no trailing newline", content: "0-15", want: 16}, |
| 41 |
{name: "malformed", content: "nope\n", wantErr: true}, |
| 42 |
} |
| 43 |
for _, tc := range tests { |
| 44 |
t.Run(tc.name, func(t *testing.T) { |
| 45 |
path := filepath.Join(dir, tc.name) |
| 46 |
if err := os.WriteFile(path, []byte(tc.content), 0o600); err != nil { |
| 47 |
t.Fatal(err) |
| 48 |
} |
| 49 |
onlineCPUsPath = path |
| 50 |
got, err := NumCPU() |
| 51 |
if tc.wantErr { |
| 52 |
if err == nil { |
| 53 |
t.Fatalf("NumCPU() = %d, want error", got) |
| 54 |
} |
| 55 |
return |
| 56 |
} |
| 57 |
if err != nil { |
| 58 |
t.Fatalf("NumCPU() unexpected error: %v", err) |
| 59 |
} |
| 60 |
if got != tc.want { |
| 61 |
t.Errorf("NumCPU() = %d, want %d", got, tc.want) |
| 62 |
} |
| 63 |
}) |
| 64 |
} |
| 65 |
|
| 66 |
t.Run("missing file", func(t *testing.T) { |
| 67 |
onlineCPUsPath = filepath.Join(dir, "absent") |
| 68 |
if _, err := NumCPU(); err == nil { |
| 69 |
t.Error("NumCPU() with missing file: want error, got nil") |
| 70 |
} |
| 71 |
}) |
| 72 |
} |