|
| 1 | +package reader |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "io" |
| 6 | + "strings" |
| 7 | + "testing" |
| 8 | +) |
| 9 | + |
| 10 | +const testingLimit = 4 * 1024 * 1024 |
| 11 | + |
| 12 | +func TestLimitedLineReader(t *testing.T) { |
| 13 | + tests := []struct { |
| 14 | + desc string |
| 15 | + inputSize int |
| 16 | + }{ |
| 17 | + {"small size", 128}, |
| 18 | + {"under buf size", 4095}, |
| 19 | + {"buf size", 4096}, |
| 20 | + {"multiple of buf size ", 4096 * 2}, |
| 21 | + {"not multiple of buf size", 10 * 1024}, |
| 22 | + {"bufio.MaxScanTokenSize", bufio.MaxScanTokenSize}, |
| 23 | + {"over bufio.MaxScanTokenSize", bufio.MaxScanTokenSize + 1}, |
| 24 | + {"under limit", testingLimit - 1}, |
| 25 | + {"at limit", testingLimit}, |
| 26 | + {"just over limit", testingLimit + 1}, |
| 27 | + {"over limit", testingLimit + 128}, |
| 28 | + } |
| 29 | + |
| 30 | + for _, test := range tests { |
| 31 | + t.Run(test.desc, func(t *testing.T) { |
| 32 | + line1 := string(make([]byte, test.inputSize)) |
| 33 | + line2 := "other line" |
| 34 | + input := strings.NewReader(strings.Join([]string{line1, line2}, "\n")) |
| 35 | + r := NewLimitedLineReader(input, testingLimit) |
| 36 | + |
| 37 | + got, err := r.ReadLine() |
| 38 | + if err != nil { |
| 39 | + t.Fatalf("ReadLine() returned error %v", err) |
| 40 | + } |
| 41 | + |
| 42 | + want := line1 |
| 43 | + if len(line1) > testingLimit { |
| 44 | + want = want[:testingLimit] |
| 45 | + } |
| 46 | + if got != want { |
| 47 | + t.Fatalf("ReadLine() returned incorrect line, got len %d want len %d", len(got), len(want)) |
| 48 | + } |
| 49 | + |
| 50 | + got, err = r.ReadLine() |
| 51 | + if err != nil { |
| 52 | + t.Fatalf("ReadLine() returned error %v", err) |
| 53 | + } |
| 54 | + want = line2 |
| 55 | + if got != want { |
| 56 | + t.Fatalf("ReadLine() returned incorrect line, got len %d want len %d", len(got), len(want)) |
| 57 | + } |
| 58 | + |
| 59 | + got, err = r.ReadLine() |
| 60 | + if err != io.EOF { |
| 61 | + t.Fatalf("ReadLine() returned unexpected error, got %v want %v\n", err, io.EOF) |
| 62 | + } |
| 63 | + if got != "" { |
| 64 | + t.Fatalf("ReadLine() returned unexpected line, got %v want nothing\n", got) |
| 65 | + } |
| 66 | + }) |
| 67 | + } |
| 68 | +} |
0 commit comments