github.com/ks888/tgo@v0.0.0-20190130135156-80bf89407292/service/service_test.go (about)

     1  package service
     2  
     3  import (
     4  	"fmt"
     5  	"net"
     6  	"os/exec"
     7  	"runtime"
     8  	"testing"
     9  	"time"
    10  
    11  	"github.com/ks888/tgo/testutils"
    12  )
    13  
    14  func TestAttachAndDetach(t *testing.T) {
    15  	cmd := exec.Command(testutils.ProgramInfloop)
    16  	_ = cmd.Start()
    17  
    18  	tracer := &Tracer{}
    19  	args := AttachArgs{
    20  		Pid:                    cmd.Process.Pid,
    21  		InitialStartTracePoint: uintptr(testutils.InfloopAddrMain),
    22  		ProgramPath:            testutils.ProgramInfloop,
    23  		GoVersion:              runtime.Version(),
    24  	}
    25  	if err := tracer.Attach(args, nil); err != nil {
    26  		t.Errorf("failed to attach: %v", err)
    27  	}
    28  
    29  	if err := tracer.Detach(struct{}{}, nil); err != nil {
    30  		t.Errorf("failed to detach: %v", err)
    31  	}
    32  
    33  	cmd.Process.Kill()
    34  	cmd.Process.Wait()
    35  }
    36  
    37  func TestServe(t *testing.T) {
    38  	unusedPort, err := findUnusedPort()
    39  	if err != nil {
    40  		t.Fatalf("failed to find unused port: %v", err)
    41  	}
    42  	addr := fmt.Sprintf(":%d", unusedPort)
    43  
    44  	errCh := make(chan error)
    45  	go func() {
    46  		errCh <- Serve(addr)
    47  	}()
    48  
    49  	conn, err := connect(addr)
    50  	if err != nil {
    51  		t.Fatalf("failed to connect: %v", err)
    52  	}
    53  	conn.Close()
    54  
    55  	err = <-errCh
    56  	if err != nil {
    57  		t.Fatalf("failed to serve: %v", err)
    58  	}
    59  }
    60  
    61  func findUnusedPort() (int, error) {
    62  	listener, err := net.ListenTCP("tcp", &net.TCPAddr{})
    63  	if err != nil {
    64  		return 0, err
    65  	}
    66  	defer listener.Close()
    67  
    68  	return listener.Addr().(*net.TCPAddr).Port, nil
    69  }
    70  
    71  func connect(addr string) (net.Conn, error) {
    72  	const numRetries = 5
    73  	interval := 100 * time.Millisecond
    74  	var err error
    75  	for i := 0; i < numRetries; i++ {
    76  		conn, err := net.Dial("tcp", addr)
    77  		if err == nil {
    78  			return conn, nil
    79  		}
    80  
    81  		time.Sleep(interval)
    82  		interval *= 2
    83  	}
    84  	return nil, fmt.Errorf("can't connect to the server (addr: %s): %v", addr, err)
    85  }