go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/analysis/internal/buildbucket/fake.go (about) 1 // Copyright 2022 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 buildbucket 16 17 import ( 18 "context" 19 20 "google.golang.org/grpc" 21 "google.golang.org/protobuf/proto" 22 23 bbpb "go.chromium.org/luci/buildbucket/proto" 24 "go.chromium.org/luci/common/errors" 25 "go.chromium.org/luci/common/proto/mask" 26 ) 27 28 // FakeClient is a fake implementation of bbpb.BuildsClient for testing. 29 type FakeClient struct { 30 Builds map[int64]*bbpb.Build 31 } 32 33 // UseFakeClient installs a fake buildbucket client into the context, 34 // with the given build data. 35 func UseFakeClient(ctx context.Context, builds map[int64]*bbpb.Build) context.Context { 36 return useBuildsClientForTesting(ctx, &FakeClient{Builds: builds}) 37 } 38 39 // GetBuild provides an implementation of the GetBuild RPC using an 40 // in-memory list of builds. 41 func (f *FakeClient) GetBuild(ctx context.Context, in *bbpb.GetBuildRequest, opts ...grpc.CallOption) (*bbpb.Build, error) { 42 if r, ok := f.Builds[in.Id]; ok { 43 // Incorrect field masks by callers are a common source of errors. 44 // Make sure the fake implementation applies the caller-specified 45 // mask to allow detection of incorrect masks in tests. 46 buildCopy := proto.Clone(r).(*bbpb.Build) 47 if in.Mask != nil { 48 mask, err := mask.FromFieldMask(in.Mask.Fields, &bbpb.Build{}, false, false) 49 if err != nil { 50 return nil, errors.Annotate(err, "invalid field mask").Err() 51 } 52 if err := mask.Trim(buildCopy); err != nil { 53 return nil, errors.Annotate(err, "apply field mask").Err() 54 } 55 } 56 return buildCopy, nil 57 } 58 return nil, errors.New("not found") 59 }