okami.mom/ultraviolet

git clone https://git.nkp.pet/okami.mom/ultraviolet

David Gageottest: fix TestReader flake (#132)27c57c1

main
1.6 KiB75 linesraw
1//go:build !windows
2// +build !windows
3
4package uv
5
6import (
7	"os"
8	"testing"
9	"time"
10)
11
12func TestReader(t *testing.T) {
13	pr, pw, err := os.Pipe()
14	if err != nil {
15		t.Errorf("expected no error, but got %s", err)
16	}
17	defer pw.Close()
18	defer pr.Close()
19
20	pollReader, err := newPollReader(pr)
21	if err != nil {
22		t.Errorf("expected no error, but got %s", err)
23	}
24
25	// Don't write anything to the pipe yet so the read below blocks and
26	// cannot complete before the cancellation.
27	done := make(chan struct{})
28	var n int
29	go func() {
30		defer close(done)
31		p := make([]byte, 1)
32		n, err = pollReader.Read(p)
33	}()
34
35	if !pollReader.Cancel() {
36		t.Errorf("expected cancellation to be success")
37	}
38
39	select {
40	case <-done:
41	case <-time.After(100 * time.Millisecond):
42		t.Errorf("expected cancellation to unblock reader")
43	}
44	if n != 0 {
45		t.Errorf("expected 0 bytes read but got %d", n)
46	}
47	if err != ErrCanceled {
48		t.Errorf("expected cancel error but got %s", err)
49	}
50
51	// Test that read is still possible after cancellation.
52	pollReader, err = newPollReader(pr)
53	if err != nil {
54		t.Errorf("expected no error, but got %s", err)
55	}
56	msg := "hello"
57	n, err = pw.Write([]byte(msg))
58	if n != 5 {
59		t.Errorf("expected 5 bytes written but got %d", n)
60	}
61	if err != nil {
62		t.Errorf("expected no error, but got %s", err)
63	}
64	p := make([]byte, 5)
65	n, err = pollReader.Read(p)
66	if n != 5 {
67		t.Errorf("expected 5 bytes written but got %d", n)
68	}
69	if err != nil {
70		t.Errorf("expected no error, but got %s", err)
71	}
72	if string(p[:n]) != msg[:n] {
73		t.Errorf("expected to read %q but got %q", msg[:n], string(p[:n]))
74	}
75}