google.golang.org/grpc@v1.72.2/xds/bootstrap/bootstrap_test.go (about) 1 /* 2 * 3 * Copyright 2022 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 package bootstrap 19 20 import ( 21 "encoding/json" 22 "testing" 23 24 "google.golang.org/grpc/credentials" 25 ) 26 27 const testCredsBuilderName = "test_creds" 28 29 var builder = &testCredsBuilder{} 30 31 func init() { 32 RegisterCredentials(builder) 33 } 34 35 type testCredsBuilder struct { 36 config json.RawMessage 37 } 38 39 func (t *testCredsBuilder) Build(config json.RawMessage) (credentials.Bundle, func(), error) { 40 t.config = config 41 return nil, nil, nil 42 } 43 44 func (t *testCredsBuilder) Name() string { 45 return testCredsBuilderName 46 } 47 48 func TestRegisterNew(t *testing.T) { 49 c := GetCredentials(testCredsBuilderName) 50 if c == nil { 51 t.Fatalf("GetCredentials(%q) credential = nil", testCredsBuilderName) 52 } 53 54 const sampleConfig = "sample_config" 55 rawMessage := json.RawMessage(sampleConfig) 56 if _, _, err := c.Build(rawMessage); err != nil { 57 t.Errorf("Build(%v) error = %v, want nil", rawMessage, err) 58 } 59 60 if got, want := string(builder.config), sampleConfig; got != want { 61 t.Errorf("Build config = %v, want %v", got, want) 62 } 63 } 64 65 func TestCredsBuilders(t *testing.T) { 66 tests := []struct { 67 typename string 68 builder Credentials 69 }{ 70 {"google_default", &googleDefaultCredsBuilder{}}, 71 {"insecure", &insecureCredsBuilder{}}, 72 {"tls", &tlsCredsBuilder{}}, 73 } 74 75 for _, test := range tests { 76 t.Run(test.typename, func(t *testing.T) { 77 if got, want := test.builder.Name(), test.typename; got != want { 78 t.Errorf("%T.Name = %v, want %v", test.builder, got, want) 79 } 80 81 _, stop, err := test.builder.Build(nil) 82 if err != nil { 83 t.Fatalf("%T.Build failed: %v", test.builder, err) 84 } 85 stop() 86 }) 87 } 88 } 89 90 func TestTlsCredsBuilder(t *testing.T) { 91 tls := &tlsCredsBuilder{} 92 _, stop, err := tls.Build(json.RawMessage(`{}`)) 93 if err != nil { 94 t.Fatalf("tls.Build() failed with error %s when expected to succeed", err) 95 } 96 stop() 97 98 if _, stop, err := tls.Build(json.RawMessage(`{"ca_certificate_file":"/ca_certificates.pem","refresh_interval": "asdf"}`)); err == nil { 99 t.Errorf("tls.Build() succeeded with an invalid refresh interval, when expected to fail") 100 stop() 101 } 102 }