github.com/ethersphere/bee/v2@v2.2.0/pkg/addressbook/addressbook_test.go (about)

     1  // Copyright 2020 The Swarm Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package addressbook_test
     6  
     7  import (
     8  	"errors"
     9  	"testing"
    10  
    11  	"github.com/ethereum/go-ethereum/common"
    12  	"github.com/ethersphere/bee/v2/pkg/addressbook"
    13  	"github.com/ethersphere/bee/v2/pkg/bzz"
    14  	"github.com/ethersphere/bee/v2/pkg/crypto"
    15  	"github.com/ethersphere/bee/v2/pkg/statestore/mock"
    16  	"github.com/ethersphere/bee/v2/pkg/swarm"
    17  
    18  	ma "github.com/multiformats/go-multiaddr"
    19  )
    20  
    21  type bookFunc func() (book addressbook.Interface)
    22  
    23  func TestInMem(t *testing.T) {
    24  	t.Parallel()
    25  
    26  	run(t, func() addressbook.Interface {
    27  		store := mock.NewStateStore()
    28  		book := addressbook.New(store)
    29  		return book
    30  	})
    31  }
    32  
    33  func run(t *testing.T, f bookFunc) {
    34  	t.Helper()
    35  
    36  	store := f()
    37  	addr1 := swarm.NewAddress([]byte{0, 1, 2, 3})
    38  	addr2 := swarm.NewAddress([]byte{0, 1, 2, 4})
    39  	trxHash := common.HexToHash("0x1").Bytes()
    40  	multiaddr, err := ma.NewMultiaddr("/ip4/1.1.1.1")
    41  	if err != nil {
    42  		t.Fatal(err)
    43  	}
    44  
    45  	pk, err := crypto.GenerateSecp256k1Key()
    46  	if err != nil {
    47  		t.Fatal(err)
    48  	}
    49  
    50  	bzzAddr, err := bzz.NewAddress(crypto.NewDefaultSigner(pk), multiaddr, addr1, 1, trxHash)
    51  	if err != nil {
    52  		t.Fatal(err)
    53  	}
    54  
    55  	err = store.Put(addr1, *bzzAddr)
    56  	if err != nil {
    57  		t.Fatal(err)
    58  	}
    59  
    60  	v, err := store.Get(addr1)
    61  	if err != nil {
    62  		t.Fatal(err)
    63  	}
    64  
    65  	if !bzzAddr.Equal(v) {
    66  		t.Fatalf("expectted: %s, want %s", v, multiaddr)
    67  	}
    68  
    69  	notFound, err := store.Get(addr2)
    70  	if !errors.Is(err, addressbook.ErrNotFound) {
    71  		t.Fatal(err)
    72  	}
    73  
    74  	if notFound != nil {
    75  		t.Fatalf("expected nil got %s", v)
    76  	}
    77  
    78  	overlays, err := store.Overlays()
    79  	if err != nil {
    80  		t.Fatal(err)
    81  	}
    82  
    83  	if len(overlays) != 1 {
    84  		t.Fatalf("expected overlay len %v, got %v", 1, len(overlays))
    85  	}
    86  
    87  	addresses, err := store.Addresses()
    88  	if err != nil {
    89  		t.Fatal(err)
    90  	}
    91  
    92  	if len(addresses) != 1 {
    93  		t.Fatalf("expected addresses len %v, got %v", 1, len(addresses))
    94  	}
    95  }