github.com/ethersphere/bee/v2@v2.2.0/pkg/manifest/mantaray/persist_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 mantaray_test
     6  
     7  import (
     8  	"bytes"
     9  	"context"
    10  	"crypto/sha256"
    11  	"sync"
    12  	"testing"
    13  
    14  	"github.com/ethersphere/bee/v2/pkg/manifest/mantaray"
    15  )
    16  
    17  func TestPersistIdempotence(t *testing.T) {
    18  	t.Parallel()
    19  
    20  	n := mantaray.New()
    21  	paths := [][]byte{
    22  		[]byte("aa"),
    23  		[]byte("b"),
    24  		[]byte("aaaaaa"),
    25  		[]byte("aaaaab"),
    26  		[]byte("abbbb"),
    27  		[]byte("abbba"),
    28  		[]byte("bbbbba"),
    29  		[]byte("bbbaaa"),
    30  		[]byte("bbbaab"),
    31  	}
    32  	ctx := context.Background()
    33  	var ls mantaray.LoadSaver = newMockLoadSaver()
    34  	for i := 0; i < len(paths); i++ {
    35  		c := paths[i]
    36  		err := n.Save(ctx, ls)
    37  		if err != nil {
    38  			t.Fatalf("expected no error, got %v", err)
    39  		}
    40  		var v [32]byte
    41  		copy(v[:], c)
    42  		err = n.Add(ctx, c, v[:], nil, ls)
    43  		if err != nil {
    44  			t.Fatalf("expected no error, got %v", err)
    45  		}
    46  	}
    47  	err := n.Save(ctx, ls)
    48  	if err != nil {
    49  		t.Fatalf("expected no error, got %v", err)
    50  	}
    51  	for i := 0; i < len(paths); i++ {
    52  		c := paths[i]
    53  		m, err := n.Lookup(ctx, c, ls)
    54  		if err != nil {
    55  			t.Fatalf("expected no error, got %v", err)
    56  		}
    57  		var v [32]byte
    58  		copy(v[:], c)
    59  		if !bytes.Equal(m, v[:]) {
    60  			t.Fatalf("expected value %x, got %x", v[:], m)
    61  		}
    62  	}
    63  }
    64  
    65  type addr [32]byte
    66  type mockLoadSaver struct {
    67  	mtx   sync.Mutex
    68  	store map[addr][]byte
    69  }
    70  
    71  func newMockLoadSaver() *mockLoadSaver {
    72  	return &mockLoadSaver{
    73  		store: make(map[addr][]byte),
    74  	}
    75  }
    76  
    77  func (m *mockLoadSaver) Save(_ context.Context, b []byte) ([]byte, error) {
    78  	var a addr
    79  	hasher := sha256.New()
    80  	_, err := hasher.Write(b)
    81  	if err != nil {
    82  		return nil, err
    83  	}
    84  	copy(a[:], hasher.Sum(nil))
    85  	m.mtx.Lock()
    86  	defer m.mtx.Unlock()
    87  	m.store[a] = b
    88  	return a[:], nil
    89  }
    90  
    91  func (m *mockLoadSaver) Load(_ context.Context, ab []byte) ([]byte, error) {
    92  	var a addr
    93  	copy(a[:], ab)
    94  	m.mtx.Lock()
    95  	defer m.mtx.Unlock()
    96  	b, ok := m.store[a]
    97  	if !ok {
    98  		return nil, mantaray.ErrNotFound
    99  	}
   100  	return b, nil
   101  }