go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/buildbucket/appengine/internal/clients/fakepubsub.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 20 "cloud.google.com/go/pubsub" 21 "cloud.google.com/go/pubsub/pstest" 22 "google.golang.org/api/option" 23 "google.golang.org/grpc" 24 "google.golang.org/grpc/credentials/insecure" 25 ) 26 27 // SetupTestPubsub creates a new fake Pub/Sub server and the client connection 28 // to the server. It also adds the client into the context. 29 func SetupTestPubsub(ctx context.Context, cloudProject string) (context.Context, *pstest.Server, *pubsub.Client, error) { 30 srv := pstest.NewServer() 31 conn, err := grpc.Dial(srv.Addr, grpc.WithTransportCredentials(insecure.NewCredentials())) 32 if err != nil { 33 return ctx, nil, nil, err 34 } 35 36 client, err := pubsub.NewClient(ctx, cloudProject, option.WithGRPCConn(conn)) 37 if err != nil { 38 return ctx, nil, nil, err 39 } 40 41 mockClients, ok := ctx.Value(&mockPubsubClientKey).(map[string]*pubsub.Client) 42 if !ok { 43 mockClients = make(map[string]*pubsub.Client) 44 } 45 mockClients[cloudProject] = client 46 ctx = context.WithValue(ctx, &mockPubsubClientKey, mockClients) 47 return ctx, srv, client, nil 48 }