github.com/mutagen-io/mutagen@v0.18.0-rc1/pkg/ipc/ipc_test.go (about)

     1  package ipc
     2  
     3  import (
     4  	"context"
     5  	"encoding/gob"
     6  	"path/filepath"
     7  	"testing"
     8  )
     9  
    10  // TestDialContextNoEndpoint tests that DialContext fails if there is no
    11  // endpoint at the specified path.
    12  func TestDialTimeoutNoEndpoint(t *testing.T) {
    13  	// Compute the IPC endpoint path.
    14  	endpoint := filepath.Join(t.TempDir(), "test.sock")
    15  
    16  	// Attempt to dial the listener and ensure that doing so fails.
    17  	if c, err := DialContext(context.Background(), endpoint); err == nil {
    18  		c.Close()
    19  		t.Error("IPC connection succeeded unexpectedly")
    20  	}
    21  }
    22  
    23  // TODO: Add TestDialContextNoListener to test cases where a stale socket has
    24  // been left on disk, ensuring that DialContext fails to connect.
    25  
    26  // testIPCMessage is a structure used to test IPC messaging.
    27  type testIPCMessage struct {
    28  	// Name represents a person's name.
    29  	Name string
    30  	// Age represents a person's age.
    31  	Age uint
    32  }
    33  
    34  // TestIPC tests that an IPC connection can be established between a listener
    35  // and a dialer.
    36  func TestIPC(t *testing.T) {
    37  	// Create a test message.
    38  	expected := testIPCMessage{"George", 67}
    39  
    40  	// Compute the IPC endpoint path.
    41  	endpoint := filepath.Join(t.TempDir(), "test.sock")
    42  
    43  	// Create a listener and defer its closure.
    44  	listener, err := NewListener(endpoint)
    45  	if err != nil {
    46  		t.Fatal("unable to create listener:", err)
    47  	}
    48  	defer listener.Close()
    49  
    50  	// Perform dialing and message sending in a separate Goroutine.
    51  	go func() {
    52  		// Dial and defer connection closure.
    53  		connection, err := DialContext(context.Background(), endpoint)
    54  		if err != nil {
    55  			return
    56  		}
    57  		defer connection.Close()
    58  
    59  		// Create an encoder.
    60  		encoder := gob.NewEncoder(connection)
    61  
    62  		// Send a test message.
    63  		encoder.Encode(expected)
    64  	}()
    65  
    66  	// Accept a connection and defer its closure.
    67  	connection, err := listener.Accept()
    68  	if err != nil {
    69  		t.Fatal("unable to accept connection:", err)
    70  	}
    71  	defer connection.Close()
    72  
    73  	// Create a decoder.
    74  	decoder := gob.NewDecoder(connection)
    75  
    76  	// Receive and validate test message.
    77  	var received testIPCMessage
    78  	if err := decoder.Decode(&received); err != nil {
    79  		t.Fatal("unable to receive test message:", err)
    80  	} else if received != expected {
    81  		t.Error("received message does not match expected:", received, "!=", expected)
    82  	}
    83  }