go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/cv/internal/common/tree/treetest/fake.go (about) 1 // Copyright 2021 The LUCI Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 // Package treetest implements fake Tree for testing in CV. 16 package treetest 17 18 import ( 19 "context" 20 "sync" 21 22 "go.chromium.org/luci/common/clock" 23 24 "go.chromium.org/luci/cv/internal/common/tree" 25 ) 26 27 // Fake simulates Tree status app in test. 28 type Fake struct { 29 // TreeStatus represents the current status of this fake Tree. 30 TreeStatus tree.Status 31 // Error forces FetchLatest to fail when set. 32 Error error 33 // mu protects access/mutation to this fake Tree. 34 mu sync.RWMutex 35 } 36 37 // NewFake returns a fake Tree. 38 func NewFake(ctx context.Context, state tree.State) *Fake { 39 return &Fake{ 40 TreeStatus: tree.Status{ 41 State: state, 42 Since: clock.Now(ctx).UTC(), 43 }, 44 } 45 } 46 47 // Client returns a client of this Fake Tree. 48 func (f *Fake) Client() tree.Client { 49 return &client{f} 50 } 51 52 // InjectErr causes Fake tree status app to return error. 53 // 54 // Passing nil error will bring tree status app to normal. 55 func (f *Fake) InjectErr(err error) { 56 f.mu.Lock() 57 defer f.mu.Unlock() 58 f.Error = err 59 } 60 61 // ModifyState changes the state of this fake Tree. 62 func (f *Fake) ModifyState(ctx context.Context, newState tree.State) { 63 f.mu.Lock() 64 defer f.mu.Unlock() 65 if f.TreeStatus.State != newState { 66 f.TreeStatus.State = newState 67 f.TreeStatus.Since = clock.Now(ctx).UTC() 68 } 69 } 70 71 type client struct { 72 fake *Fake 73 } 74 75 var _ tree.Client = (*client)(nil) 76 77 func (c *client) FetchLatest(ctx context.Context, endpoint string) (tree.Status, error) { 78 c.fake.mu.RLock() 79 defer c.fake.mu.RUnlock() 80 if c.fake.Error != nil { 81 return tree.Status{}, c.fake.Error 82 } 83 return c.fake.TreeStatus, nil 84 }