| 1 |
package compressor |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"errors" |
| 6 |
"io/ioutil" |
| 7 |
"testing" |
| 8 |
) |
| 9 |
|
| 10 |
func TestWriter_Write(t *testing.T) { |
| 11 |
tt := []struct { |
| 12 |
Input []byte |
| 13 |
Expected []byte |
| 14 |
}{ |
| 15 |
// nothing to compress |
| 16 |
{ |
| 17 |
[]byte("\x1B[38;2;249;38;114mre\x1B[0m\x1B[38;2;249;38;115mflow\x1B[0m"), |
| 18 |
[]byte("\x1B[38;2;249;38;114mre\x1B[0m\x1B[38;2;249;38;115mflow\x1B[0m"), |
| 19 |
}, |
| 20 |
// reset sequence before setting the same styles again |
| 21 |
{ |
| 22 |
[]byte("\x1B[38;2;249;38;114mre\x1B[0m\x1B[38;2;249;38;114mfl\x1B[0m\x1B[38;2;249;38;114mow\x1B[0m"), |
| 23 |
[]byte("\x1B[38;2;249;38;114mreflow\x1B[0m"), |
| 24 |
}, |
| 25 |
} |
| 26 |
|
| 27 |
for i, tc := range tt { |
| 28 |
forward := &bytes.Buffer{} |
| 29 |
w := &Writer{Forward: forward} |
| 30 |
|
| 31 |
n, err := w.Write(tc.Input) |
| 32 |
if err != nil { |
| 33 |
t.Fatalf("Test %d, err should be nil, but got %v", i, err) |
| 34 |
} |
| 35 |
if err := w.Close(); err != nil { |
| 36 |
t.Fatalf("Test %d, err should be nil, but got %v", i, err) |
| 37 |
} |
| 38 |
|
| 39 |
if l := len(tc.Input); n != l { |
| 40 |
t.Fatalf("Test %d, n should be %d, got %d", i, l, n) |
| 41 |
} |
| 42 |
|
| 43 |
if b := forward.Bytes(); !bytes.Equal(b, tc.Expected) { |
| 44 |
// fmt.Println(strings.ReplaceAll(string(tc.Expected), string(ansi.Marker), "")) |
| 45 |
// fmt.Println(strings.ReplaceAll(string(b), string(ansi.Marker), "")) |
| 46 |
|
| 47 |
t.Fatalf("Test %d, forward should be wrote by %v, but got %v", i, tc.Expected, b) |
| 48 |
} |
| 49 |
} |
| 50 |
} |
| 51 |
|
| 52 |
var fakeErr = errors.New("fake error") |
| 53 |
|
| 54 |
type fakeWriter struct{} |
| 55 |
|
| 56 |
func (fakeWriter) Write(_ []byte) (int, error) { |
| 57 |
return 0, fakeErr |
| 58 |
} |
| 59 |
|
| 60 |
func TestWriter_Write_Error(t *testing.T) { |
| 61 |
t.Parallel() |
| 62 |
|
| 63 |
w := &Writer{Forward: fakeWriter{}} |
| 64 |
|
| 65 |
_, err := w.Write([]byte("foo")) |
| 66 |
if err != fakeErr { |
| 67 |
t.Fatalf("err should be fakeErr, but got %v", err) |
| 68 |
} |
| 69 |
} |
| 70 |
|
| 71 |
// go test -bench=BenchmarkWriter_Write -benchmem -count=4 |
| 72 |
func BenchmarkWriter_Write(b *testing.B) { |
| 73 |
buf := []byte("\x1B[38;2;249;38;114mre\x1B[0m\x1B[38;2;249;38;114mfl\x1B[0m\x1B[38;2;249;38;114mow\x1B[0m") |
| 74 |
w := &Writer{Forward: ioutil.Discard} |
| 75 |
|
| 76 |
b.ReportAllocs() |
| 77 |
b.ResetTimer() |
| 78 |
for i := 0; i < b.N; i++ { |
| 79 |
_, _ = w.Write(buf) |
| 80 |
} |
| 81 |
} |