|
| 1 | +package fecdecoder |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "oneway-filesync/pkg/structs" |
| 7 | + "strings" |
| 8 | + "testing" |
| 9 | + "time" |
| 10 | + |
| 11 | + "github.com/klauspost/reedsolomon" |
| 12 | + "github.com/sirupsen/logrus" |
| 13 | +) |
| 14 | + |
| 15 | +func createChunks(t *testing.T, required int, total int) []*structs.Chunk { |
| 16 | + fec, err := reedsolomon.New(required, total-required) |
| 17 | + if err != nil { |
| 18 | + t.Fatal(err) |
| 19 | + } |
| 20 | + shares, err := fec.Split(make([]byte, 400)) |
| 21 | + if err != nil { |
| 22 | + t.Fatal(err) |
| 23 | + } |
| 24 | + |
| 25 | + // Encode the parity set |
| 26 | + err = fec.Encode(shares) |
| 27 | + if err != nil { |
| 28 | + t.Fatal(err) |
| 29 | + } |
| 30 | + chunks := make([]*structs.Chunk, total) |
| 31 | + for i, sharedata := range shares { |
| 32 | + chunks[i] = &structs.Chunk{ |
| 33 | + ShareIndex: uint32(i), |
| 34 | + Data: sharedata, |
| 35 | + } |
| 36 | + } |
| 37 | + return chunks |
| 38 | + |
| 39 | +} |
| 40 | + |
| 41 | +func Test_worker(t *testing.T) { |
| 42 | + type args struct { |
| 43 | + required int |
| 44 | + total int |
| 45 | + input []*structs.Chunk |
| 46 | + } |
| 47 | + tests := []struct { |
| 48 | + name string |
| 49 | + args args |
| 50 | + wantErr bool |
| 51 | + expectedErr string |
| 52 | + }{ |
| 53 | + {"test-works", args{2, 4, createChunks(t, 2, 4)}, false, ""}, |
| 54 | + {"test-too-few-shards", args{4, 8, createChunks(t, 4, 8)[:3]}, true, "Error FEC decoding shares: too few shards given"}, |
| 55 | + {"test-invalid-fec1", args{2, 1, make([]*structs.Chunk, 4)}, true, "Error creating fec object: cannot create Encoder with less than one data shard or less than zero parity shards"}, |
| 56 | + {"test-invalid-fec2", args{0, 1, make([]*structs.Chunk, 4)}, true, "Error creating fec object: cannot create Encoder with less than one data shard or less than zero parity shards"}, |
| 57 | + } |
| 58 | + for _, tt := range tests { |
| 59 | + t.Run(tt.name, func(t *testing.T) { |
| 60 | + var memLog bytes.Buffer |
| 61 | + logrus.SetOutput(&memLog) |
| 62 | + |
| 63 | + input := make(chan []*structs.Chunk, 5) |
| 64 | + output := make(chan *structs.Chunk, 5) |
| 65 | + |
| 66 | + input <- tt.args.input |
| 67 | + |
| 68 | + conf := fecDecoderConfig{tt.args.required, tt.args.total, input, output} |
| 69 | + ctx, cancel := context.WithCancel(context.Background()) |
| 70 | + go func() { |
| 71 | + time.Sleep(2 * time.Second) |
| 72 | + cancel() |
| 73 | + }() |
| 74 | + // ch <- tt.args.file |
| 75 | + worker(ctx, &conf) |
| 76 | + |
| 77 | + if tt.wantErr { |
| 78 | + if !strings.Contains(memLog.String(), tt.expectedErr) { |
| 79 | + t.Fatalf("Expected not in log, '%v' not in '%v'", tt.expectedErr, memLog.String()) |
| 80 | + } |
| 81 | + } else { |
| 82 | + <-output |
| 83 | + } |
| 84 | + |
| 85 | + }) |
| 86 | + } |
| 87 | +} |
0 commit comments