github.com/mhilton/juju-juju@v0.0.0-20150901100907-a94dd2c73455/worker/dependency/testing/stub.go (about) 1 // Copyright 2015 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package testing 5 6 import ( 7 "reflect" 8 9 "github.com/juju/errors" 10 11 "github.com/juju/juju/worker/dependency" 12 ) 13 14 // StubResource is used to define the behaviour of a StubGetResource func for a 15 // particular resource name. 16 type StubResource struct { 17 Output interface{} 18 Error error 19 } 20 21 // StubResources defines the complete behaviour of a StubGetResource func. 22 type StubResources map[string]StubResource 23 24 // StubGetResource returns a GetResourceFunc which will set outputs, or 25 // return errors, as defined by the supplied StubResources. Any unexpected 26 // usage of the result will return Errorf errors describing the problem; in 27 // particular, missing resources will not trigger dependency.ErrMissing unless 28 // specifically configured to do so. 29 func StubGetResource(resources StubResources) dependency.GetResourceFunc { 30 return func(name string, outPtr interface{}) error { 31 resource, found := resources[name] 32 if !found { 33 return errors.Errorf("unexpected resource name: %s", name) 34 } else if resource.Error != nil { 35 return resource.Error 36 } 37 if outPtr != nil { 38 outPtrV := reflect.ValueOf(outPtr) 39 if outPtrV.Kind() != reflect.Ptr { 40 return errors.Errorf("outPtr should be a pointer; is %#v", outPtr) 41 } 42 outV := outPtrV.Elem() 43 outT := outV.Type() 44 setV := reflect.ValueOf(resource.Output) 45 setT := setV.Type() 46 if !setT.ConvertibleTo(outT) { 47 return errors.Errorf("cannot set %#v into %T", resource.Output, outPtr) 48 } 49 outV.Set(setV.Convert(outT)) 50 } 51 return nil 52 } 53 }