github.com/letsencrypt/trillian@v1.1.2-0.20180615153820-ae375a99d36a/crypto/keys/handlers_test.go (about) 1 // Copyright 2017 Google Inc. All Rights Reserved. 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 keys_test 16 17 import ( 18 "context" 19 "crypto" 20 "errors" 21 "testing" 22 23 "github.com/golang/protobuf/proto" 24 "github.com/golang/protobuf/ptypes/empty" 25 . "github.com/google/trillian/crypto/keys" 26 "github.com/google/trillian/crypto/keys/pem" 27 "github.com/google/trillian/testonly" 28 ) 29 30 func fakeHandler(signer crypto.Signer, err error) ProtoHandler { 31 return func(ctx context.Context, pb proto.Message) (crypto.Signer, error) { 32 return signer, err 33 } 34 } 35 36 func TestNewSigner(t *testing.T) { 37 wantSigner, err := pem.UnmarshalPrivateKey(testonly.DemoPrivateKey, testonly.DemoPrivateKeyPass) 38 if err != nil { 39 t.Fatalf("Error unmarshaling test private key: %v", err) 40 } 41 42 ctx := context.Background() 43 44 for _, test := range []struct { 45 desc string 46 keyProto proto.Message 47 handler ProtoHandler 48 wantErr bool 49 }{ 50 { 51 desc: "KeyProto with handler", 52 keyProto: &empty.Empty{}, 53 handler: fakeHandler(wantSigner, nil), 54 }, 55 { 56 desc: "Invalid KeyProto with handler", 57 keyProto: &empty.Empty{}, 58 handler: fakeHandler(nil, errors.New("invalid KeyProto")), 59 wantErr: true, 60 }, 61 { 62 desc: "KeyProto with no handler", 63 keyProto: &empty.Empty{}, 64 wantErr: true, 65 }, 66 { 67 desc: "Nil KeyProto", 68 wantErr: true, 69 }, 70 } { 71 if test.handler != nil { 72 RegisterHandler(test.keyProto, test.handler) 73 } 74 75 gotSigner, err := NewSigner(ctx, test.keyProto) 76 switch gotErr := err != nil; { 77 case gotErr != test.wantErr: 78 t.Errorf("%v: NewSigner() = (_, %q), want err? %v", test.desc, err, test.wantErr) 79 case !gotErr && gotSigner != wantSigner: 80 t.Errorf("%v: NewSigner() = (%#v, _), want (%#v, _)", test.desc, gotSigner, wantSigner) 81 } 82 83 if test.handler != nil { 84 UnregisterHandler(test.keyProto) 85 } 86 } 87 }