github.com/juju/juju@v0.0.0-20240430160146-1752b71fcf00/worker/uniter/runner/jujuc/jujuctesting/relations.go (about) 1 // Copyright 2015 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package jujuctesting 5 6 import ( 7 "fmt" 8 9 "github.com/juju/errors" 10 "github.com/juju/testing" 11 12 "github.com/juju/juju/core/life" 13 "github.com/juju/juju/worker/uniter/runner/jujuc" 14 ) 15 16 // Relations holds the values for the hook context. 17 type Relations struct { 18 Relations map[int]jujuc.ContextRelation 19 } 20 21 // Reset clears the Relations data. 22 func (r *Relations) Reset() { 23 r.Relations = nil 24 } 25 26 // SetRelation adds the relation to the set of known relations. 27 func (r *Relations) SetRelation(id int, relCtx jujuc.ContextRelation) { 28 if r.Relations == nil { 29 r.Relations = make(map[int]jujuc.ContextRelation) 30 } 31 r.Relations[id] = relCtx 32 } 33 34 // SetNewRelation adds the relation to the set of known relations. 35 func (r *Relations) SetNewRelation(id int, name string, stub *testing.Stub) *Relation { 36 return r.SetNewRelationWithLife(id, name, life.Alive, stub) 37 } 38 39 func (r *Relations) SetNewRelationWithLife(id int, name string, life life.Value, stub *testing.Stub) *Relation { 40 if name == "" { 41 name = fmt.Sprintf("relation-%d", id) 42 } 43 rel := &Relation{ 44 Id: id, 45 Name: name, 46 Life: life, 47 } 48 relCtx := &ContextRelation{info: rel} 49 relCtx.stub = stub 50 51 r.SetRelation(id, relCtx) 52 return rel 53 } 54 55 // SetRelated adds the provided unit information to the relation. 56 func (r *Relations) SetRelated(id int, unit string, settings Settings) { 57 relation := r.Relations[id].(*ContextRelation).info 58 relation.SetRelated(unit, settings) 59 } 60 61 // ContextRelations is a test double for jujuc.ContextRelations. 62 type ContextRelations struct { 63 contextBase 64 info *Relations 65 } 66 67 // Relation implements jujuc.ContextRelations. 68 func (c *ContextRelations) Relation(id int) (jujuc.ContextRelation, error) { 69 c.stub.AddCall("Relation", id) 70 71 r, ok := c.info.Relations[id] 72 var err error 73 if !ok { 74 err = errors.NotFoundf("relation") 75 } 76 return r, err 77 } 78 79 // RelationIds implements jujuc.ContextRelations. 80 func (c *ContextRelations) RelationIds() ([]int, error) { 81 c.stub.AddCall("RelationIds") 82 83 ids := []int{} 84 for id := range c.info.Relations { 85 ids = append(ids, id) 86 } 87 return ids, c.stub.NextErr() 88 }