1717package plugin
1818
1919import (
20+ "context"
2021 "testing"
2122
2223 "github.com/stretchr/testify/require"
@@ -25,8 +26,88 @@ import (
2526 v1 "github.com/NVIDIA/k8s-device-plugin/api/config/v1"
2627 "github.com/NVIDIA/k8s-device-plugin/internal/cdi"
2728 "github.com/NVIDIA/k8s-device-plugin/internal/imex"
29+ "github.com/NVIDIA/k8s-device-plugin/internal/rm"
2830)
2931
32+ func TestAllocate (t * testing.T ) {
33+ testCases := []struct {
34+ description string
35+ request * pluginapi.AllocateRequest
36+ expectedError error
37+ expectedResponse * pluginapi.AllocateResponse
38+ }{
39+ {
40+ description : "single device" ,
41+ request : & pluginapi.AllocateRequest {
42+ ContainerRequests : []* pluginapi.ContainerAllocateRequest {
43+ {
44+ DevicesIDs : []string {"foo" },
45+ },
46+ },
47+ },
48+ expectedResponse : & pluginapi.AllocateResponse {
49+ ContainerResponses : []* pluginapi.ContainerAllocateResponse {
50+ {
51+ Envs : map [string ]string {
52+ "NVIDIA_VISIBLE_DEVICES" : "foo" ,
53+ },
54+ },
55+ },
56+ },
57+ },
58+ {
59+ description : "duplicate device IDs" ,
60+ request : & pluginapi.AllocateRequest {
61+ ContainerRequests : []* pluginapi.ContainerAllocateRequest {
62+ {
63+ DevicesIDs : []string {"foo" , "bar" , "foo" },
64+ },
65+ },
66+ },
67+ expectedResponse : & pluginapi.AllocateResponse {
68+ ContainerResponses : []* pluginapi.ContainerAllocateResponse {
69+ {
70+ Envs : map [string ]string {
71+ "NVIDIA_VISIBLE_DEVICES" : "foo,bar" ,
72+ },
73+ },
74+ },
75+ },
76+ },
77+ }
78+
79+ for _ , tc := range testCases {
80+ t .Run (tc .description , func (t * testing.T ) {
81+ plugin := nvidiaDevicePlugin {
82+ rm : & rm.ResourceManagerMock {
83+ ValidateRequestFunc : func (annotatedIDs rm.AnnotatedIDs ) error {
84+ return nil
85+ },
86+ },
87+ config : & v1.Config {
88+ Flags : v1.Flags {
89+ CommandLineFlags : v1.CommandLineFlags {
90+ Plugin : & v1.PluginCommandLineFlags {
91+ DeviceIDStrategy : ptr (v1 .DeviceIDStrategyUUID ),
92+ },
93+ },
94+ },
95+ },
96+ cdiHandler : & cdi.InterfaceMock {
97+ QualifiedNameFunc : func (c string , s string ) string {
98+ return "nvidia.com/" + c + "=" + s
99+ },
100+ },
101+ deviceListStrategies : v1.DeviceListStrategies {"envvar" : true },
102+ }
103+
104+ response , err := plugin .Allocate (context .TODO (), tc .request )
105+ require .EqualValues (t , tc .expectedError , err )
106+ require .EqualValues (t , tc .expectedResponse , response )
107+ })
108+ }
109+ }
110+
30111func TestCDIAllocateResponse (t * testing.T ) {
31112 testCases := []struct {
32113 description string
@@ -169,3 +250,7 @@ func TestCDIAllocateResponse(t *testing.T) {
169250 })
170251 }
171252}
253+
254+ func ptr [T any ](x T ) * T {
255+ return & x
256+ }
0 commit comments