1 /* 2 * 3 * Copyright 2023 gRPC authors. 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 * 17 */ 18 19 package testutils 20 21 import ( 22 "google.golang.org/grpc/internal" 23 "google.golang.org/grpc/internal/pretty" 24 "google.golang.org/grpc/resolver" 25 "google.golang.org/grpc/serviceconfig" 26 ) 27 28 // Logger wraps the logging methods from testing.T. 29 type Logger interface { 30 Log(args ...any) 31 Logf(format string, args ...any) 32 Errorf(format string, args ...any) 33 } 34 35 // ResolverClientConn is a fake implementation of the resolver.ClientConn 36 // interface to be used in tests. 37 type ResolverClientConn struct { 38 resolver.ClientConn // Embedding the interface to avoid implementing deprecated methods. 39 40 Logger Logger // Tests should pass testing.T for this. 41 UpdateStateF func(resolver.State) error // Invoked when resolver pushes a state update. 42 ReportErrorF func(err error) // Invoked when resolver pushes an error. 43 } 44 45 // UpdateState invokes the test specified callback with the update received from 46 // the resolver. If the callback returns a non-nil error, the same will be 47 // propagated to the resolver. 48 func (t *ResolverClientConn) UpdateState(s resolver.State) error { 49 t.Logger.Logf("testutils.ResolverClientConn: UpdateState(%s)", pretty.ToJSON(s)) 50 51 if t.UpdateStateF != nil { 52 return t.UpdateStateF(s) 53 } 54 return nil 55 } 56 57 // ReportError pushes the error received from the resolver on to ErrorCh. 58 func (t *ResolverClientConn) ReportError(err error) { 59 t.Logger.Logf("testutils.ResolverClientConn: ReportError(%v)", err) 60 61 if t.ReportErrorF != nil { 62 t.ReportErrorF(err) 63 } 64 } 65 66 // ParseServiceConfig parses the provided service by delegating the work to the 67 // implementation in the grpc package. 68 func (t *ResolverClientConn) ParseServiceConfig(jsonSC string) *serviceconfig.ParseResult { 69 return internal.ParseServiceConfig.(func(string) *serviceconfig.ParseResult)(jsonSC) 70 } 71