github.com/ethersphere/bee/v2@v2.2.0/pkg/file/pipeline/encryption/encryption_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 encryption_test 6 7 import ( 8 "bytes" 9 "encoding/binary" 10 "testing" 11 12 mockenc "github.com/ethersphere/bee/v2/pkg/encryption/mock" 13 "github.com/ethersphere/bee/v2/pkg/file/pipeline" 14 "github.com/ethersphere/bee/v2/pkg/file/pipeline/encryption" 15 mock "github.com/ethersphere/bee/v2/pkg/file/pipeline/mock" 16 ) 17 18 var ( 19 addr = []byte{0xaa, 0xbb, 0xcc} 20 key = []byte("abcd") 21 data = []byte("hello world") 22 encryptedSpan, encryptedData []byte 23 ) 24 25 // nolint:gochecknoinits 26 func init() { 27 mockEncrypter := mockenc.New(mockenc.WithXOREncryption(key)) 28 var err error 29 encryptedData, err = mockEncrypter.Encrypt(data) 30 if err != nil { 31 panic(err) 32 } 33 span := make([]byte, 8) 34 binary.BigEndian.PutUint64(span, uint64(len(data))) 35 encryptedSpan, err = mockEncrypter.Encrypt(span) 36 if err != nil { 37 panic(err) 38 } 39 } 40 41 // TestEncyrption tests that the encryption writer works correctly. 42 func TestEncryption(t *testing.T) { 43 t.Parallel() 44 45 mockChainWriter := mock.NewChainWriter() 46 writer := encryption.NewEncryptionWriter(mockenc.NewChunkEncrypter(key), mockChainWriter) 47 48 args := pipeline.PipeWriteArgs{Ref: addr, Data: data} 49 err := writer.ChainWrite(&args) 50 if err != nil { 51 t.Fatal(err) 52 } 53 if !bytes.Equal(encryptedData, args.Data) { 54 t.Fatalf("data mismatch. got %v want %v", args.Data, encryptedData) 55 } 56 57 if calls := mockChainWriter.ChainWriteCalls(); calls != 1 { 58 t.Errorf("wanted 1 ChainWrite call, got %d", calls) 59 } 60 } 61 62 // TestSum tests that calling Sum on the store writer results in Sum on the next writer in the chain. 63 func TestSum(t *testing.T) { 64 t.Parallel() 65 66 mockChainWriter := mock.NewChainWriter() 67 writer := encryption.NewEncryptionWriter(nil, mockChainWriter) 68 69 _, err := writer.Sum() 70 if err != nil { 71 t.Fatal(err) 72 } 73 if calls := mockChainWriter.SumCalls(); calls != 1 { 74 t.Fatalf("wanted 1 Sum call but got %d", calls) 75 } 76 }