github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/apiserver/common/life_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/state"
    17  )
    18  
    19  type lifeSuite struct{}
    20  
    21  var _ = gc.Suite(&lifeSuite{})
    22  
    23  type fakeLifer struct {
    24  	state.Entity
    25  	life state.Life
    26  	fetchError
    27  }
    28  
    29  func (l *fakeLifer) Life() state.Life {
    30  	return l.life
    31  }
    32  
    33  func (*lifeSuite) TestLife(c *gc.C) {
    34  	st := &fakeState{
    35  		entities: map[names.Tag]entityWithError{
    36  			u("x/0"): &fakeLifer{life: state.Alive},
    37  			u("x/1"): &fakeLifer{life: state.Dying},
    38  			u("x/2"): &fakeLifer{life: state.Dead},
    39  			u("x/3"): &fakeLifer{fetchError: "x3 error"},
    40  		},
    41  	}
    42  	getCanRead := func() (common.AuthFunc, error) {
    43  		x0 := u("x/0")
    44  		x2 := u("x/2")
    45  		x3 := u("x/3")
    46  		return func(tag names.Tag) bool {
    47  			return tag == x0 || tag == x2 || tag == x3
    48  		}, nil
    49  	}
    50  	lg := common.NewLifeGetter(st, getCanRead)
    51  	entities := params.Entities{[]params.Entity{
    52  		{"unit-x-0"}, {"unit-x-1"}, {"unit-x-2"}, {"unit-x-3"}, {"unit-x-4"},
    53  	}}
    54  	results, err := lg.Life(entities)
    55  	c.Assert(err, jc.ErrorIsNil)
    56  	c.Assert(results, gc.DeepEquals, params.LifeResults{
    57  		Results: []params.LifeResult{
    58  			{Life: params.Alive},
    59  			{Error: apiservertesting.ErrUnauthorized},
    60  			{Life: params.Dead},
    61  			{Error: &params.Error{Message: "x3 error"}},
    62  			{Error: apiservertesting.ErrUnauthorized},
    63  		},
    64  	})
    65  }
    66  
    67  func (*lifeSuite) TestLifeError(c *gc.C) {
    68  	getCanRead := func() (common.AuthFunc, error) {
    69  		return nil, fmt.Errorf("pow")
    70  	}
    71  	lg := common.NewLifeGetter(&fakeState{}, getCanRead)
    72  	_, err := lg.Life(params.Entities{[]params.Entity{{"x0"}}})
    73  	c.Assert(err, gc.ErrorMatches, "pow")
    74  }
    75  
    76  func (*lifeSuite) TestLifeNoArgsNoError(c *gc.C) {
    77  	getCanRead := func() (common.AuthFunc, error) {
    78  		return nil, fmt.Errorf("pow")
    79  	}
    80  	lg := common.NewLifeGetter(&fakeState{}, getCanRead)
    81  	result, err := lg.Life(params.Entities{})
    82  	c.Assert(err, jc.ErrorIsNil)
    83  	c.Assert(result.Results, gc.HasLen, 0)
    84  }