github.com/axw/juju@v0.0.0-20161005053422-4bd6544d08d4/apiserver/common/instanceidgetter_test.go (about) 1 // Copyright 2013 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package common_test 5 6 import ( 7 "fmt" 8 9 jc "github.com/juju/testing/checkers" 10 gc "gopkg.in/check.v1" 11 "gopkg.in/juju/names.v2" 12 13 "github.com/juju/juju/apiserver/common" 14 "github.com/juju/juju/apiserver/params" 15 apiservertesting "github.com/juju/juju/apiserver/testing" 16 "github.com/juju/juju/instance" 17 "github.com/juju/juju/state" 18 ) 19 20 type instanceIdGetterSuite struct{} 21 22 var _ = gc.Suite(&instanceIdGetterSuite{}) 23 24 type fakeInstanceIdGetter struct { 25 state.Entity 26 instanceId string 27 err string 28 fetchError 29 } 30 31 func (f *fakeInstanceIdGetter) InstanceId() (instance.Id, error) { 32 if f.err != "" { 33 return "", fmt.Errorf(f.err) 34 } 35 return instance.Id(f.instanceId), nil 36 } 37 38 func (*instanceIdGetterSuite) TestInstanceId(c *gc.C) { 39 st := &fakeState{ 40 entities: map[names.Tag]entityWithError{ 41 u("x/0"): &fakeInstanceIdGetter{instanceId: "foo"}, 42 u("x/1"): &fakeInstanceIdGetter{instanceId: "bar"}, 43 u("x/2"): &fakeInstanceIdGetter{instanceId: "baz", err: "x2 error"}, 44 u("x/3"): &fakeInstanceIdGetter{fetchError: "x3 error"}, 45 }, 46 } 47 getCanRead := func() (common.AuthFunc, error) { 48 x0 := u("x/0") 49 x2 := u("x/2") 50 x3 := u("x/3") 51 return func(tag names.Tag) bool { 52 return tag == x0 || tag == x2 || tag == x3 53 }, nil 54 } 55 ig := common.NewInstanceIdGetter(st, getCanRead) 56 entities := params.Entities{[]params.Entity{ 57 {"unit-x-0"}, {"unit-x-1"}, {"unit-x-2"}, {"unit-x-3"}, {"unit-x-4"}, 58 }} 59 results, err := ig.InstanceId(entities) 60 c.Assert(err, jc.ErrorIsNil) 61 c.Assert(results, jc.DeepEquals, params.StringResults{ 62 Results: []params.StringResult{ 63 {Result: "foo"}, 64 {Error: apiservertesting.ErrUnauthorized}, 65 {Error: ¶ms.Error{Message: "x2 error"}}, 66 {Error: ¶ms.Error{Message: "x3 error"}}, 67 {Error: apiservertesting.ErrUnauthorized}, 68 }, 69 }) 70 } 71 72 func (*instanceIdGetterSuite) TestInstanceIdError(c *gc.C) { 73 getCanRead := func() (common.AuthFunc, error) { 74 return nil, fmt.Errorf("pow") 75 } 76 ig := common.NewInstanceIdGetter(&fakeState{}, getCanRead) 77 _, err := ig.InstanceId(params.Entities{[]params.Entity{{"unit-x-0"}}}) 78 c.Assert(err, gc.ErrorMatches, "pow") 79 }