github.com/hugh712/snapd@v0.0.0-20200910133618-1a99902bd583/osutil/udev/netlink/conn_test.go (about)

     1  package netlink
     2  
     3  import (
     4  	"syscall"
     5  	"testing"
     6  	"time"
     7  )
     8  
     9  func TestConnect(t *testing.T) {
    10  	conn := new(UEventConn)
    11  	if err := conn.Connect(UdevEvent); err != nil {
    12  		t.Fatal("unable to subscribe to netlink uevent, err:", err)
    13  	}
    14  	defer conn.Close()
    15  
    16  	conn2 := new(UEventConn)
    17  	if err := conn2.Connect(UdevEvent); err == nil {
    18  		// see issue: https://github.com/pilebones/go-udev/issues/3 by @stolowski
    19  		t.Fatal("can't subscribing a second time to netlink socket with PID", conn2.Addr.Pid)
    20  	}
    21  	defer conn2.Close()
    22  }
    23  
    24  func TestMonitorStop(t *testing.T) {
    25  	conn := new(UEventConn)
    26  	if err := conn.Connect(UdevEvent); err != nil {
    27  		t.Fatal("unable to subscribe to netlink uevent, err:", err)
    28  	}
    29  	defer conn.Close()
    30  
    31  	stop := conn.Monitor(nil, nil, nil)
    32  	ok := stop(200 * time.Millisecond)
    33  	if !ok {
    34  		t.Fatal("stop timed out instead of working")
    35  	}
    36  }
    37  
    38  func TestMonitorSelectTimeoutIsHarmless(t *testing.T) {
    39  	conn := new(UEventConn)
    40  	if err := conn.Connect(UdevEvent); err != nil {
    41  		t.Fatal("unable to subscribe to netlink uevent, err:", err)
    42  	}
    43  	defer conn.Close()
    44  
    45  	selectCalled := 0
    46  	oldStopperSelectTimeout := stopperSelectTimeout
    47  	stopperSelectTimeout = func() *syscall.Timeval {
    48  		selectCalled += 1
    49  		return &syscall.Timeval{
    50  			Usec: 10 * 1000, // 10ms
    51  		}
    52  	}
    53  	defer func() {
    54  		stopperSelectTimeout = oldStopperSelectTimeout
    55  	}()
    56  
    57  	stop := conn.Monitor(nil, nil, nil)
    58  	time.Sleep(100 * time.Millisecond)
    59  	ok := stop(200 * time.Millisecond)
    60  	if !ok {
    61  		t.Fatal("stop timed out instead of working")
    62  	}
    63  	if selectCalled <= 1 {
    64  		t.Fatal("select->read->select should have been exercised at least once")
    65  	}
    66  }