Skip to content

Commit

Permalink
Add more keys to GetSize test
Browse files Browse the repository at this point in the history
  • Loading branch information
didaunesp committed Apr 19, 2024
1 parent 12786ad commit 70daa78
Showing 1 changed file with 78 additions and 9 deletions.
87 changes: 78 additions & 9 deletions p2p/peerManager/peerdb/datastore_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package peerdb
import (
"context"
"encoding/json"
"sync"
"testing"

datastore "github.com/ipfs/go-datastore"
Expand Down Expand Up @@ -113,23 +114,91 @@ func TestQuery(t *testing.T) {

func TestGetSize(t *testing.T) {
ps, teardown := setupDB(t)
t.Cleanup(teardown)
defer teardown()

peer := createPeers(t, 1)[0]
peers := createPeers(t, 5)

key := datastore.NewKey(peer.AddrInfo.ID.String())
keys := make([]datastore.Key, len(peers))

cases := []struct {
i int
Entropy uint64
PubKey []byte
}{
{
i: 0,
Entropy: uint64(12345),
PubKey: []byte(""),
},
{
i: 1,
Entropy: uint64(1234567890),
PubKey: []byte("pub"),
},
{
i: 2,
Entropy: uint64(1),
PubKey: []byte("pubkey"),
},
{
i: 3,
Entropy: uint64(0),
PubKey: []byte("pubkey1234567890"),
},
{
i: 4,
Entropy: uint64(12345678901234),
PubKey: []byte("pubkey12345678901234567890"),
},
}

var wg sync.WaitGroup

// Add value to keys and test first time
for i, peer := range peers {
wg.Add(1)
go func(peer *PeerInfo, i int) {
defer wg.Done()
keys[i] = datastore.NewKey(peer.AddrInfo.ID.String())
value, err := json.Marshal(peer)
require.NoError(t, err)

err = ps.Put(context.Background(), keys[i], value)
require.NoError(t, err)
size, err := ps.GetSize(context.Background(), keys[i])
require.NoError(t, err)
require.Equal(t, len(value), size)
}(peer, i)
}
wg.Wait()

// Update keys is parallel and check if size is updated
for i, peer := range peers {
wg.Add(1)
go func(peer *PeerInfo, i int) {
defer wg.Done()
peer.Entropy = cases[i].Entropy
testSize(t, ps, peer, keys[i])

peer.PubKey = cases[i].PubKey
testSize(t, ps, peer, keys[i])
}(peer, i)
}
wg.Wait()

//Test with non existent key
size, err := ps.GetSize(context.Background(), datastore.NewKey("non-existent-key"))
require.Error(t, err)
require.Equal(t, 0, size)
}

func testSize(t *testing.T, ps *PeerDB, peer *PeerInfo, key datastore.Key) {
value, err := json.Marshal(peer)
require.NoError(t, err)

err = ps.Put(context.Background(), key, value)
require.NoError(t, err)

size, err := ps.GetSize(context.Background(), key)
require.NoError(t, err)
require.Equal(t, len(value), size)

//Test with non existent key
size, err = ps.GetSize(context.Background(), datastore.NewKey("non-existent-key"))
require.Error(t, err)
require.Equal(t, 0, size)
}

0 comments on commit 70daa78

Please sign in to comment.