1package store
2
3import (
4 "io"
5 "os"
6 "testing"
7)
8
9func TestMsgreader(t *testing.T) {
10 _, err := io.Copy(io.Discard, &MsgReader{prefix: []byte("hello"), path: "bogus.txt", size: int64(len("hello"))})
11 if err == nil || !os.IsNotExist(err) {
12 t.Fatalf("expected error for non-existing file, got %s", err)
13 }
14
15 if err := os.WriteFile("emptyfile_test.txt", []byte{}, 0660); err != nil {
16 t.Fatalf("writing emptyfile_test.txt: %s", err)
17 }
18 defer os.Remove("emptyfile_test.txt")
19 mr := &MsgReader{prefix: []byte("hello"), path: "emptyfile_test.txt", size: int64(len("hello"))}
20 defer mr.Close()
21 if buf, err := io.ReadAll(mr); err != nil {
22 t.Fatalf("readall: %s", err)
23 } else if string(buf) != "hello" {
24 t.Fatalf("got %q, expected %q", buf, "hello")
25 }
26
27 if err := os.WriteFile("msgreader_test.txt", []byte(" world"), 0660); err != nil {
28 t.Fatalf("writing msgreader_test.txt: %s", err)
29 }
30 defer os.Remove("msgreader_test.txt")
31 mr = &MsgReader{prefix: []byte("hello"), path: "msgreader_test.txt", size: int64(len("hello world"))}
32 defer mr.Close()
33 if buf, err := io.ReadAll(mr); err != nil {
34 t.Fatalf("readall: %s", err)
35 } else if string(buf) != "hello world" {
36 t.Fatalf("got %q, expected %q", buf, "hello world")
37 }
38
39 mr.Reset()
40 buf := make([]byte, 32)
41 if n, err := mr.ReadAt(buf, 1); err != nil && err != io.EOF {
42 t.Fatalf("readat: n %d, s %q, err %s", n, buf[:n], err)
43 } else if n != len("ello world") || string(buf[:n]) != "ello world" {
44 t.Fatalf("readat: got %d bytes (%q), expected %d (%q)", n, buf, int64(len("ello world")), "ello world")
45 }
46
47 // Read with 1 byte at a time to exercise the offset/buffer-length calculations.
48 buf = make([]byte, 1)
49 var result []byte
50 mr = &MsgReader{prefix: []byte("hello"), path: "msgreader_test.txt", size: int64(len("hello world"))}
51 for {
52 n, err := mr.Read(buf)
53 if n > 0 {
54 result = append(result, buf...)
55 }
56 if err == io.EOF {
57 break
58 }
59 if err != nil {
60 t.Fatalf("read: %s", err)
61 }
62 }
63 if string(result) != "hello world" {
64 t.Fatalf("got %q, want %q", result, "hello world")
65 }
66
67 if err := mr.Close(); err != nil {
68 t.Fatalf("close: %v", err)
69 }
70
71 f, err := os.Open("msgreader_test.txt")
72 if err != nil {
73 t.Fatalf("open: %v", err)
74 }
75 mr = FileMsgReader([]byte("hello"), f)
76
77 if mr.Size() != int64(len("hello world")) {
78 t.Fatalf("size, got %d, expect %d", mr.Size(), len("hello world"))
79 }
80
81 if err := mr.Close(); err != nil {
82 t.Fatalf("close: %v", err)
83 }
84}
85