github.com/hashicorp/vault/sdk@v0.13.0/logical/testing.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package logical
     5  
     6  import (
     7  	"context"
     8  	"reflect"
     9  	"time"
    10  
    11  	log "github.com/hashicorp/go-hclog"
    12  	"github.com/hashicorp/vault/sdk/helper/logging"
    13  	testing "github.com/mitchellh/go-testing-interface"
    14  )
    15  
    16  // TestRequest is a helper to create a purely in-memory Request struct.
    17  func TestRequest(t testing.T, op Operation, path string) *Request {
    18  	return &Request{
    19  		Operation:  op,
    20  		Path:       path,
    21  		Data:       make(map[string]interface{}),
    22  		Storage:    new(InmemStorage),
    23  		Connection: &Connection{},
    24  	}
    25  }
    26  
    27  // TestStorage is a helper that can be used from unit tests to verify
    28  // the behavior of a Storage impl.
    29  func TestStorage(t testing.T, s Storage) {
    30  	keys, err := s.List(context.Background(), "")
    31  	if err != nil {
    32  		t.Fatalf("list error: %s", err)
    33  	}
    34  	if len(keys) > 0 {
    35  		t.Fatalf("should have no keys to start: %#v", keys)
    36  	}
    37  
    38  	entry := &StorageEntry{Key: "foo", Value: []byte("bar")}
    39  	if err := s.Put(context.Background(), entry); err != nil {
    40  		t.Fatalf("put error: %s", err)
    41  	}
    42  
    43  	actual, err := s.Get(context.Background(), "foo")
    44  	if err != nil {
    45  		t.Fatalf("get error: %s", err)
    46  	}
    47  	if !reflect.DeepEqual(actual, entry) {
    48  		t.Fatalf("wrong value. Expected: %#v\nGot: %#v", entry, actual)
    49  	}
    50  
    51  	keys, err = s.List(context.Background(), "")
    52  	if err != nil {
    53  		t.Fatalf("list error: %s", err)
    54  	}
    55  	if !reflect.DeepEqual(keys, []string{"foo"}) {
    56  		t.Fatalf("bad keys: %#v", keys)
    57  	}
    58  
    59  	if err := s.Delete(context.Background(), "foo"); err != nil {
    60  		t.Fatalf("put error: %s", err)
    61  	}
    62  
    63  	keys, err = s.List(context.Background(), "")
    64  	if err != nil {
    65  		t.Fatalf("list error: %s", err)
    66  	}
    67  	if len(keys) > 0 {
    68  		t.Fatalf("should have no keys to start: %#v", keys)
    69  	}
    70  }
    71  
    72  func TestSystemView() *StaticSystemView {
    73  	defaultLeaseTTLVal := time.Hour * 24
    74  	maxLeaseTTLVal := time.Hour * 24 * 2
    75  	return &StaticSystemView{
    76  		DefaultLeaseTTLVal: defaultLeaseTTLVal,
    77  		MaxLeaseTTLVal:     maxLeaseTTLVal,
    78  		VersionString:      "testVersionString",
    79  	}
    80  }
    81  
    82  func TestBackendConfig() *BackendConfig {
    83  	bc := &BackendConfig{
    84  		Logger: logging.NewVaultLogger(log.Trace),
    85  		System: TestSystemView(),
    86  		Config: make(map[string]string),
    87  	}
    88  
    89  	return bc
    90  }