Inject errors into os.Lstat call from devices.go
Since the caller of os.Lstat in devices.go is a function (not a method), we use a variable to allow os.Lstat to be substituted during testing. In this case the variable osLstat is private to the devices package to prevent abuse. So the testcase needs to reside in the same package. This commit includes a simple test of GetDevices() using osLstat to simulate an error being returned from os.Lstat. In this case, the behaviour of GetDevices() in the error case is trivial, but this may change. This is just the beginning of error injection. In future, it may be necessary to pull out repetitive code sequences into a common file. Signed-off-by: Steve Powell <spowell@pivotal.io>
This commit is contained in:
parent
318d845931
commit
28e964bac6
|
@ -17,6 +17,11 @@ var (
|
|||
ErrNotADeviceNode = errors.New("not a device node")
|
||||
)
|
||||
|
||||
// Testing dependencies
|
||||
var (
|
||||
osLstat = os.Lstat
|
||||
)
|
||||
|
||||
type Device struct {
|
||||
Type rune `json:"type,omitempty"`
|
||||
Path string `json:"path,omitempty"` // It is fine if this is an empty string in the case that you are using Wildcards
|
||||
|
@ -42,7 +47,7 @@ func (device *Device) GetCgroupAllowString() string {
|
|||
|
||||
// Given the path to a device and it's cgroup_permissions(which cannot be easilly queried) look up the information about a linux device and return that information as a Device struct.
|
||||
func GetDevice(path, cgroupPermissions string) (*Device, error) {
|
||||
fileInfo, err := os.Lstat(path)
|
||||
fileInfo, err := osLstat(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
|
@ -0,0 +1,21 @@
|
|||
package devices
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGetDeviceLstatFailure(t *testing.T) {
|
||||
testError := errors.New("test error")
|
||||
|
||||
// Override os.Lstat to inject error.
|
||||
osLstat = func(path string) (os.FileInfo, error) {
|
||||
return nil, testError
|
||||
}
|
||||
|
||||
_, err := GetDevice("", "")
|
||||
if err != testError {
|
||||
t.Fatalf("Unexpected error %v, expected %v", err, testError)
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue