github.com/ethersphere/bee/v2@v2.2.0/pkg/file/loadsave/loadsave_test.go (about)

     1  // Copyright 2021 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 loadsave_test
     6  
     7  import (
     8  	"bytes"
     9  	"context"
    10  	"encoding/hex"
    11  	"errors"
    12  	"testing"
    13  
    14  	"github.com/ethersphere/bee/v2/pkg/file/loadsave"
    15  	"github.com/ethersphere/bee/v2/pkg/file/pipeline"
    16  	"github.com/ethersphere/bee/v2/pkg/file/pipeline/builder"
    17  	storage "github.com/ethersphere/bee/v2/pkg/storage"
    18  	"github.com/ethersphere/bee/v2/pkg/storage/inmemchunkstore"
    19  	"github.com/ethersphere/bee/v2/pkg/swarm"
    20  )
    21  
    22  var (
    23  	data    = []byte{0, 1, 2, 3}
    24  	expHash = "4f7e85bb4282fd468a9ce4e6e50b6c4b8e6a34aa33332b604c83fb9b2e55978a"
    25  )
    26  
    27  func TestLoadSave(t *testing.T) {
    28  	t.Parallel()
    29  
    30  	store := inmemchunkstore.New()
    31  	ls := loadsave.New(store, store, pipelineFn(store))
    32  	ref, err := ls.Save(context.Background(), data)
    33  
    34  	if err != nil {
    35  		t.Fatal(err)
    36  	}
    37  	if r := hex.EncodeToString(ref); r != expHash {
    38  		t.Fatalf("expected hash %s got %s", expHash, r)
    39  	}
    40  	b, err := ls.Load(context.Background(), ref)
    41  	if err != nil {
    42  		t.Fatal(err)
    43  	}
    44  	if !bytes.Equal(data, b) {
    45  		t.Fatal("wrong data in response")
    46  	}
    47  }
    48  
    49  func TestReadonlyLoadSave(t *testing.T) {
    50  	t.Parallel()
    51  
    52  	store := inmemchunkstore.New()
    53  	factory := pipelineFn(store)
    54  	ls := loadsave.NewReadonly(store)
    55  	_, err := ls.Save(context.Background(), data)
    56  	if !errors.Is(err, loadsave.ErrReadonlyLoadSave) {
    57  		t.Fatal("expected error but got none")
    58  	}
    59  
    60  	_, err = builder.FeedPipeline(context.Background(), factory(), bytes.NewReader(data))
    61  	if err != nil {
    62  		t.Fatal(err)
    63  	}
    64  
    65  	b, err := ls.Load(context.Background(), swarm.MustParseHexAddress(expHash).Bytes())
    66  	if err != nil {
    67  		t.Fatal(err)
    68  	}
    69  	if !bytes.Equal(data, b) {
    70  		t.Fatal("wrong data in response")
    71  	}
    72  }
    73  
    74  func pipelineFn(s storage.Putter) func() pipeline.Interface {
    75  	return func() pipeline.Interface {
    76  		return builder.NewPipelineBuilder(context.Background(), s, false, 0)
    77  	}
    78  }