Skip to content

Commit

Permalink
non existing device will return nil device (#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
MathiasFM authored Oct 1, 2024
1 parent 33548d3 commit 918c079
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
8 changes: 6 additions & 2 deletions zenoss/zenoss.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,14 +163,18 @@ func (z *client) ReadDevice(ctx context.Context, uid string) (*Device, error) {
return nil, fmt.Errorf("unable to read device: %w", err)
}

if !dev.Result.Success || dev.Result.Count > 1 {
return nil, fmt.Errorf("error reading device or more devices returned")
if dev.Result.Count > 1 {
return nil, fmt.Errorf("error multiple devices returned")
}

if dev.Result.Count == 0 || len(dev.Result.Devices) == 0 {
return nil, nil
}

if !dev.Result.Success {
return nil, fmt.Errorf("error reading device")
}

return &dev.Result.Devices[0], nil
}

Expand Down
30 changes: 30 additions & 0 deletions zenoss/zenoss_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,23 @@ func TestReadDevice(t *testing.T) {
assert.Equal(t, "oaas1.k8s.jysk.netic.dk", device.Name)
}

func TestReadDeviceNotFound(t *testing.T) {
api, server := newStubAPI(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
if req.URL.Path == "/zport/dmd/device_router" {
buf := new(strings.Builder)
io.Copy(buf, req.Body)
assert.Equal(t, `{"action":"DeviceRouter","method":"getDevices","data":[{"uid":"/zport/dmd/Devices/VirtualDevices/jysk-k8s/devices/oaas1.k8s.jysk.netic.dk"}],"tid":1}`, buf.String())
assert.Equal(t, "POST", req.Method)
rw.Write([]byte(readDeviceResponseNotFound))
}
}))
defer server.Close()

device, err := api.ReadDevice(context.Background(), "/zport/dmd/Devices/VirtualDevices/jysk-k8s/devices/oaas1.k8s.jysk.netic.dk")
assert.NoError(t, err)
assert.Nil(t, device)
}

func TestCreateDevice(t *testing.T) {
api, server := newStubAPI(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
assert.Equal(t, "POST", req.Method)
Expand Down Expand Up @@ -307,6 +324,19 @@ const readDeviceResponse = `{
"method": "getDevices"
}`

const readDeviceResponseNotFound = `{
"uuid": "f353184f-59f4-4057-9cc6-8614dd7cc91e",
"action": "DeviceRouter",
"result": {
"totalCount": 0,
"hash": "",
"success": false
},
"tid": 1,
"type": "rpc",
"method": "getDevices"
}`

const readDeviceResponseEmpty = `{
"uuid": "b2033e78-0cb5-42b7-878e-062386b777c7",
"action": "DeviceRouter",
Expand Down

0 comments on commit 918c079

Please sign in to comment.