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)
15 if err := os.WriteFile("emptyfile_test.txt", []byte{}, 0660); err != nil {
16 t.Fatalf("writing emptyfile_test.txt: %s", err)
18 defer os.Remove("emptyfile_test.txt")
19 mr := &MsgReader{prefix: []byte("hello"), path: "emptyfile_test.txt", size: int64(len("hello"))}
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")
27 if err := os.WriteFile("msgreader_test.txt", []byte(" world"), 0660); err != nil {
28 t.Fatalf("writing msgreader_test.txt: %s", err)
30 defer os.Remove("msgreader_test.txt")
31 mr = &MsgReader{prefix: []byte("hello"), path: "msgreader_test.txt", size: int64(len("hello world"))}
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")
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")
47 // Read with 1 byte at a time to exercise the offset/buffer-length calculations.
50 mr = &MsgReader{prefix: []byte("hello"), path: "msgreader_test.txt", size: int64(len("hello world"))}
52 n, err := mr.Read(buf)
54 result = append(result, buf...)
60 t.Fatalf("read: %s", err)
63 if string(result) != "hello world" {
64 t.Fatalf("got %q, want %q", result, "hello world")
67 if err := mr.Close(); err != nil {
68 t.Fatalf("close: %v", err)
71 f, err := os.Open("msgreader_test.txt")
73 t.Fatalf("open: %v", err)
75 mr = FileMsgReader([]byte("hello"), f)
77 if mr.Size() != int64(len("hello world")) {
78 t.Fatalf("size, got %d, expect %d", mr.Size(), len("hello world"))
81 if err := mr.Close(); err != nil {
82 t.Fatalf("close: %v", err)