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