github.com/sunvim/utils@v0.1.0/netpoll/poll_test.go (about)

     1  // Copyright (c) 2020 Meng Huang (mhboy@outlook.com)
     2  // This package is licensed under a MIT license that can be found in the LICENSE file.
     3  
     4  package netpoll
     5  
     6  import (
     7  	"net"
     8  	"sync"
     9  	"syscall"
    10  	"testing"
    11  	"time"
    12  )
    13  
    14  func TestPoll(t *testing.T) {
    15  	p, err := Create()
    16  	defer p.Close()
    17  	if err != nil {
    18  		t.Error(err)
    19  	}
    20  	err = p.SetTimeout(0)
    21  	if err != ErrTimeout {
    22  		t.Error(err)
    23  	}
    24  	err = p.SetTimeout(time.Millisecond * 1)
    25  	if err != nil {
    26  		t.Error(err)
    27  	}
    28  
    29  	if n, err := p.Wait(make([]Event, len(p.events)+1)); err != nil {
    30  		t.Error(err)
    31  	} else if n != 0 {
    32  		t.Error(n)
    33  	}
    34  	network := "tcp"
    35  	addr := ":9999"
    36  	l, _ := net.Listen(network, addr)
    37  	ln, _ := l.(*net.TCPListener)
    38  	f, _ := ln.File()
    39  	epfd := int(f.Fd())
    40  	if err := syscall.SetNonblock(epfd, false); err != nil {
    41  		panic(err)
    42  	}
    43  	wg := sync.WaitGroup{}
    44  	wg.Add(1)
    45  	go func() {
    46  		defer wg.Done()
    47  		conn, _ := net.Dial(network, addr)
    48  		for {
    49  			conn.Read(make([]byte, 64))
    50  			break
    51  		}
    52  	}()
    53  	fd, _, err := syscall.Accept(epfd)
    54  	if err != nil {
    55  		t.Error(err)
    56  	}
    57  	p.Register(fd)
    58  	err = p.Write(fd)
    59  	if err != nil {
    60  		t.Error(err)
    61  	}
    62  	events := make([]Event, 128)
    63  	if n, err := p.Wait(events); err != nil {
    64  		t.Error(err)
    65  	} else if n != 1 {
    66  		t.Error(n)
    67  	} else if events[0].Mode != WRITE {
    68  		t.Error(events)
    69  	}
    70  	p.Unregister(fd)
    71  	syscall.Close(fd)
    72  	f.Close()
    73  	l.Close()
    74  	wg.Wait()
    75  }