github.com/google/trillian-examples@v0.0.0-20240520080811-0d40d35cef0e/clone/cmd/ctclone/ctclone_test.go (about) 1 // Copyright 2021 Google LLC. 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 main 16 17 import ( 18 "fmt" 19 "testing" 20 21 "github.com/google/go-cmp/cmp" 22 ) 23 24 func TestCertLeafFetcher(t *testing.T) { 25 for _, test := range []struct { 26 name string 27 start uint64 28 count uint 29 urls map[string]string 30 want []string 31 wantErr bool 32 }{ 33 { 34 name: "first leaf", 35 start: 0, 36 count: 1, 37 urls: map[string]string{"ct/v1/get-entries?start=0&end=0": `{"entries":[{"leaf_input": "dGhpcyBjb3VsZCBiZSBhIGNlcnQ="}]}`}, 38 want: []string{"this could be a cert"}, 39 }, 40 { 41 name: "three leaves", 42 start: 101, 43 count: 3, 44 urls: map[string]string{"ct/v1/get-entries?start=101&end=103": `{"entries":[{"leaf_input": "b25lIG9oIG9uZQ=="},{"leaf_input": "b25lIG9oIHR3bw=="},{"leaf_input": "b25lIG9oIHRocmVl"}]}`}, 45 want: []string{"one oh one", "one oh two", "one oh three"}, 46 }, 47 { 48 name: "too many returned", 49 start: 42, 50 count: 1, 51 urls: map[string]string{"ct/v1/get-entries?start=42&end=42": `{"entries":[{"leaf_input": "b25l"},{"leaf_input": "dHdv"}]}`}, 52 wantErr: true, 53 }, 54 { 55 name: "not enough returned", 56 start: 42, 57 count: 2, 58 urls: map[string]string{"ct/v1/get-entries?start=42&end=43": `{"entries":[{"leaf_input": "b25l"}]}`}, 59 wantErr: true, 60 }, 61 } { 62 t.Run(test.name, func(t *testing.T) { 63 clf := ctFetcher{&fakeFetcher{test.urls}} 64 leaves := make([][]byte, test.count) 65 _, err := clf.Batch(test.start, leaves) 66 switch { 67 case err != nil && !test.wantErr: 68 t.Fatalf("Got unexpected error %q", err) 69 case err == nil && test.wantErr: 70 t.Fatal("Got no error, but wanted error") 71 case err != nil && test.wantErr: 72 // expected error 73 default: 74 gotStrings := make([]string, len(leaves)) 75 for i, bs := range leaves { 76 gotStrings[i] = string(bs) 77 } 78 if d := cmp.Diff(gotStrings, test.want); len(d) != 0 { 79 t.Fatalf("Got different result: %s", d) 80 } 81 } 82 }) 83 } 84 } 85 86 type fakeFetcher struct { 87 values map[string]string 88 } 89 90 func (f *fakeFetcher) GetData(path string) ([]byte, error) { 91 res, ok := f.values[path] 92 if !ok { 93 return nil, fmt.Errorf("could not find '%s'", path) 94 } 95 return []byte(res), nil 96 }