okami.mom/ultraviolet

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

Ayman Bagabasfeat: add new poll reader for cross-platform I/O polling (#71)04a6149

upstream
1.8 KiB88 linesraw
1package uv
2
3import (
4	"bytes"
5	"fmt"
6	"io"
7	"sync"
8	"testing"
9)
10
11type blockingReader struct {
12	sync.Mutex
13	read      bool
14	unblockCh chan bool
15	startedCh chan bool
16}
17
18func (r *blockingReader) Read([]byte) (int, error) {
19	defer func() {
20		r.Lock()
21		defer r.Unlock()
22		r.read = true
23	}()
24	r.startedCh <- true
25	<-r.unblockCh
26	return 0, fmt.Errorf("this error should be ignored")
27}
28
29func TestFallbackReaderConcurrentCancel(t *testing.T) {
30	doneCh := make(chan bool, 1)
31	startedCh := make(chan bool, 1)
32	unblockCh := make(chan bool, 1)
33	r := blockingReader{
34		startedCh: startedCh,
35		unblockCh: unblockCh,
36	}
37	pr, err := newFallbackReader(&r)
38	if err != nil {
39		t.Errorf("expected no error, but got %s", err)
40	}
41
42	go func() {
43		defer func() { doneCh <- true }()
44		if _, err := io.ReadAll(pr); err != ErrCanceled {
45			t.Errorf("expected canceled error, got %v", err)
46		}
47	}()
48
49	// make sure the read started before canceling the reader
50	<-startedCh
51	pr.Cancel()
52	unblockCh <- true
53
54	// wait for the read to end to ensure its assertions were made
55	<-doneCh
56
57	// make sure that it waited for the reader
58	if !r.read {
59		t.Error("seems like the reader was canceled before the read, this shouldn't happen")
60	}
61}
62
63func TestFallbackReader(t *testing.T) {
64	var r bytes.Buffer
65	pr, err := newFallbackReader(&r)
66	if err != nil {
67		t.Errorf("expected no error, but got %s", err)
68	}
69
70	txt := "first"
71	_, _ = r.WriteString(txt)
72	first, err := io.ReadAll(pr)
73	if err != nil {
74		t.Errorf("expected no error, but got %s", err)
75	}
76	if string(first) != txt {
77		t.Errorf("expected output to be %q, got %q", txt, string(first))
78	}
79
80	pr.Cancel()
81	second, err := io.ReadAll(pr)
82	if err != ErrCanceled {
83		t.Errorf("expected ErrCanceled, got %v", err)
84	}
85	if len(second) > 0 {
86		t.Errorf("expected an empty read, got %q", string(second))
87	}
88}