go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/buildbucket/appengine/internal/clients/fakebq.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 clients
    16  
    17  import (
    18  	"context"
    19  	"sync"
    20  
    21  	lucibq "go.chromium.org/luci/common/bq"
    22  )
    23  
    24  type FakeBqClient struct {
    25  	mu sync.RWMutex
    26  	// data persists all inserted rows.
    27  	data map[string][]*lucibq.Row
    28  }
    29  
    30  var FakeBqErrCtxKey = "used only in tests to make BQ return a fake error"
    31  
    32  func (f *FakeBqClient) Insert(ctx context.Context, dataset, table string, row *lucibq.Row) error {
    33  	if err, ok := ctx.Value(&FakeBqErrCtxKey).(error); ok {
    34  		return err
    35  	}
    36  	f.mu.Lock()
    37  	defer f.mu.Unlock()
    38  	key := dataset + "." + table
    39  	if f.data == nil {
    40  		f.data = make(map[string][]*lucibq.Row)
    41  	}
    42  	f.data[key] = append(f.data[key], row)
    43  	return nil
    44  }
    45  
    46  func (f *FakeBqClient) GetRows(dataset, table string) []*lucibq.Row {
    47  	f.mu.RLock()
    48  	defer f.mu.RUnlock()
    49  	return f.data[dataset+"."+table]
    50  }