github.com/qri-io/qri@v0.10.1-0.20220104210721-c771715036cb/auth/key/store_test.go (about)

     1  package key_test
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"io/ioutil"
     7  	"path/filepath"
     8  	"testing"
     9  
    10  	"github.com/google/go-cmp/cmp"
    11  	"github.com/qri-io/qri/auth/key"
    12  	testkeys "github.com/qri-io/qri/auth/key/test"
    13  )
    14  
    15  func TestLocalStore(t *testing.T) {
    16  	ctx := context.Background()
    17  	path, err := ioutil.TempDir("", "keys")
    18  	if err != nil {
    19  		t.Fatalf("error creating tmp directory: %s", err.Error())
    20  	}
    21  	t.Logf("store: %s", path)
    22  	// defer os.RemoveAll(path)
    23  
    24  	ks, err := key.NewLocalStore(filepath.Join(path, "keystore_test.json"))
    25  	if err != nil {
    26  		t.Fatal(err)
    27  	}
    28  
    29  	kd0 := testkeys.GetKeyData(0)
    30  
    31  	if err = ks.AddPubKey(ctx, key.ID("this_must_fail"), kd0.PrivKey.GetPublic()); err == nil {
    32  		t.Error("expected adding public key with mismatching ID to fail. got nil")
    33  	} else if !errors.Is(err, key.ErrKeyAndIDMismatch) {
    34  		t.Errorf("mismatched ID error must wrap exported pacakge error, got: %s", err)
    35  	}
    36  
    37  	if err = ks.AddPubKey(ctx, kd0.PeerID, kd0.PrivKey.GetPublic()); err != nil {
    38  		t.Fatal(err)
    39  	}
    40  
    41  	if err = ks.AddPrivKey(ctx, kd0.PeerID, kd0.PrivKey); err != nil {
    42  		t.Fatal(err)
    43  	}
    44  
    45  	if err = ks.AddPrivKey(ctx, key.ID("this_must_fail"), kd0.PrivKey); err == nil {
    46  		t.Error("expected adding private key with mismatching ID to fail. got nil")
    47  	} else if !errors.Is(err, key.ErrKeyAndIDMismatch) {
    48  		t.Errorf("mismatched ID error must wrap exported pacakge error, got: %s", err)
    49  	}
    50  
    51  	golden := "testdata/keystore.json"
    52  	path = filepath.Join(path, "keystore_test.json")
    53  	f1, err := ioutil.ReadFile(golden)
    54  	if err != nil {
    55  		t.Errorf("error reading golden file: %s", err.Error())
    56  	}
    57  	f2, err := ioutil.ReadFile(path)
    58  	if err != nil {
    59  		t.Errorf("error reading written file: %s", err.Error())
    60  	}
    61  
    62  	if diff := cmp.Diff(f1, f2); diff != "" {
    63  		t.Errorf("result mismatch (-want +got):\n%s", diff)
    64  	}
    65  }