github.com/ethersphere/bee/v2@v2.2.0/pkg/file/addresses/addresses_getter_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 addresses_test 6 7 import ( 8 "context" 9 "io" 10 "sync" 11 "testing" 12 "time" 13 14 "github.com/ethersphere/bee/v2/pkg/file" 15 "github.com/ethersphere/bee/v2/pkg/file/addresses" 16 "github.com/ethersphere/bee/v2/pkg/file/joiner" 17 filetest "github.com/ethersphere/bee/v2/pkg/file/testing" 18 "github.com/ethersphere/bee/v2/pkg/storage/inmemchunkstore" 19 "github.com/ethersphere/bee/v2/pkg/swarm" 20 ) 21 22 func TestAddressesGetterIterateChunkAddresses(t *testing.T) { 23 t.Parallel() 24 25 store := inmemchunkstore.New() 26 27 ctx, cancel := context.WithTimeout(context.Background(), time.Second) 28 defer cancel() 29 30 // create root chunk with 2 references and the referenced data chunks 31 rootChunk := filetest.GenerateTestRandomFileChunk(swarm.ZeroAddress, swarm.ChunkSize*2, swarm.SectionSize*2) 32 err := store.Put(ctx, rootChunk) 33 if err != nil { 34 t.Fatal(err) 35 } 36 37 firstAddress := swarm.NewAddress(rootChunk.Data()[8 : swarm.SectionSize+8]) 38 firstChunk := filetest.GenerateTestRandomFileChunk(firstAddress, swarm.ChunkSize, swarm.ChunkSize) 39 err = store.Put(ctx, firstChunk) 40 if err != nil { 41 t.Fatal(err) 42 } 43 44 secondAddress := swarm.NewAddress(rootChunk.Data()[swarm.SectionSize+8:]) 45 secondChunk := filetest.GenerateTestRandomFileChunk(secondAddress, swarm.ChunkSize, swarm.ChunkSize) 46 err = store.Put(ctx, secondChunk) 47 if err != nil { 48 t.Fatal(err) 49 } 50 51 createdAddresses := []swarm.Address{rootChunk.Address(), firstAddress, secondAddress} 52 53 foundAddresses := make(map[string]struct{}) 54 var foundAddressesMu sync.Mutex 55 56 addressIterFunc := func(addr swarm.Address) error { 57 foundAddressesMu.Lock() 58 defer foundAddressesMu.Unlock() 59 60 foundAddresses[addr.String()] = struct{}{} 61 return nil 62 } 63 64 addressesGetter := addresses.NewGetter(store, addressIterFunc) 65 66 j, _, err := joiner.New(ctx, addressesGetter, store, rootChunk.Address()) 67 if err != nil { 68 t.Fatal(err) 69 } 70 71 _, err = file.JoinReadAll(ctx, j, io.Discard) 72 if err != nil { 73 t.Fatal(err) 74 } 75 76 if len(createdAddresses) != len(foundAddresses) { 77 t.Fatalf("expected to find %d addresses, got %d", len(createdAddresses), len(foundAddresses)) 78 } 79 80 checkAddressFound := func(t *testing.T, foundAddresses map[string]struct{}, address swarm.Address) { 81 t.Helper() 82 83 if _, ok := foundAddresses[address.String()]; !ok { 84 t.Fatalf("expected address %s not found", address.String()) 85 } 86 } 87 88 for _, createdAddress := range createdAddresses { 89 checkAddressFound(t, foundAddresses, createdAddress) 90 } 91 }