1
16
17 package tail
18
19 import (
20 "bytes"
21 "os"
22 "strings"
23 "testing"
24 )
25
26 func TestReadAtMost(t *testing.T) {
27 file, err := os.CreateTemp("", "TestFileReadAtMost")
28 if err != nil {
29 t.Fatalf("unable to create temp file")
30 }
31 defer os.Remove(file.Name())
32
33 line := strings.Repeat("a", blockSize)
34 testBytes := []byte(line + "\n" +
35 line + "\n" +
36 line + "\n" +
37 line + "\n" +
38 line[blockSize/2:])
39
40 file.Write(testBytes)
41 testCases := []struct {
42 name string
43 max int64
44 longerThanMax bool
45 expected string
46 }{
47 {
48 name: "the max is negative",
49 max: -1,
50 longerThanMax: true,
51 expected: "",
52 },
53 {
54 name: "the max is zero",
55 max: 0,
56 longerThanMax: true,
57 expected: "",
58 },
59 {
60 name: "the file length is longer than max",
61 max: 1,
62 longerThanMax: true,
63 expected: "a",
64 },
65 {
66 name: "the file length is longer than max and contains newlines",
67 max: blockSize,
68 longerThanMax: true,
69 expected: strings.Repeat("a", blockSize/2-1) + "\n" + strings.Repeat("a", blockSize/2),
70 },
71 {
72 name: "the max is longer than file length ",
73 max: 4613,
74 longerThanMax: false,
75 expected: string(testBytes),
76 },
77 }
78
79 for _, test := range testCases {
80 readAtMostBytes, longerThanMax, err := ReadAtMost(file.Name(), test.max)
81 if err != nil {
82 t.Fatalf("Unexpected failure %v", err)
83 }
84 if test.longerThanMax != longerThanMax {
85 t.Fatalf("Unexpected result on whether the file length longer than the max, want: %t, got: %t", test.longerThanMax, longerThanMax)
86 }
87 if test.expected != string(readAtMostBytes) {
88 t.Fatalf("Unexpected most max bytes, want: %s, got: %s", test.expected, readAtMostBytes)
89 }
90 }
91 }
92
93 func TestTail(t *testing.T) {
94 line := strings.Repeat("a", blockSize)
95 testBytes := []byte(line + "\n" +
96 line + "\n" +
97 line + "\n" +
98 line + "\n" +
99 line[blockSize/2:])
100
101 for c, test := range []struct {
102 n int64
103 start int64
104 }{
105 {n: -1, start: 0},
106 {n: 0, start: int64(len(line)+1) * 4},
107 {n: 1, start: int64(len(line)+1) * 3},
108 {n: 9999, start: 0},
109 } {
110 t.Logf("TestCase #%d: %+v", c, test)
111 r := bytes.NewReader(testBytes)
112 s, err := FindTailLineStartIndex(r, test.n)
113 if err != nil {
114 t.Error(err)
115 }
116 if s != test.start {
117 t.Errorf("%d != %d", s, test.start)
118 }
119 }
120 }
121
View as plain text