github.com/grailbio/base@v0.0.11/security/keycrypt/keycrypt_test.go (about)

     1  // Copyright 2018 GRAIL, Inc. All rights reserved.
     2  // Use of this source code is governed by the Apache-2.0
     3  // license that can be found in the LICENSE file.
     4  
     5  package keycrypt
     6  
     7  import "testing"
     8  
     9  type testSecret struct {
    10  	path  string
    11  	value []byte
    12  }
    13  
    14  func (t *testSecret) Get() ([]byte, error) {
    15  	if len(t.value) == 0 {
    16  		return nil, ErrNoSuchSecret
    17  	}
    18  	return t.value, nil
    19  }
    20  
    21  func (t *testSecret) Put(v []byte) error {
    22  	t.value = make([]byte, len(v), len(v))
    23  	copy(t.value, v)
    24  	return nil
    25  }
    26  
    27  type testKeycrypt struct {
    28  	host    string
    29  	secrets map[string]*testSecret
    30  }
    31  
    32  func (t *testKeycrypt) Lookup(name string) Secret {
    33  	if t.secrets == nil {
    34  		t.secrets = make(map[string]*testSecret)
    35  	}
    36  	if t.secrets[name] == nil {
    37  		t.secrets[name] = &testSecret{path: name}
    38  	}
    39  	return t.secrets[name]
    40  }
    41  
    42  func TestMarshal(t *testing.T) {
    43  	kc := &testKeycrypt{}
    44  	type data struct {
    45  		A, B, C string
    46  	}
    47  	s := kc.Lookup("foo/bar")
    48  	put := data{"a", "b", "c"}
    49  	if err := PutJSON(s, &put); err != nil {
    50  		t.Fatal(err)
    51  	}
    52  	var get data
    53  	if err := GetJSON(s, &get); err != nil {
    54  		t.Fatal(err)
    55  	}
    56  	if got, want := get, put; got != want {
    57  		t.Fatalf("got %v, want %v", got, want)
    58  	}
    59  }
    60  
    61  func TestResolver(t *testing.T) {
    62  	RegisterFunc("test", func(host string) Keycrypt {
    63  		return &testKeycrypt{host: host}
    64  	})
    65  	defer unregister("test")
    66  	s, err := Lookup("test://host/path/to/blah")
    67  	if err != nil {
    68  		t.Fatal(err)
    69  	}
    70  	ts, ok := s.(*testSecret)
    71  	if !ok {
    72  		t.Fatal("bad secret type")
    73  	}
    74  	if want, got := "path/to/blah", ts.path; got != want {
    75  		t.Fatalf("got %q, want %q", got, want)
    76  	}
    77  }