github.com/ggiamarchi/terraform@v0.3.7-0.20150607194748-ed2a66a46a71/rpc/rpc_test.go (about)

     1  package rpc
     2  
     3  import (
     4  	"net"
     5  	"net/rpc"
     6  	"testing"
     7  
     8  	"github.com/hashicorp/terraform/terraform"
     9  )
    10  
    11  func testConn(t *testing.T) (net.Conn, net.Conn) {
    12  	l, err := net.Listen("tcp", "127.0.0.1:0")
    13  	if err != nil {
    14  		t.Fatalf("err: %s", err)
    15  	}
    16  
    17  	var serverConn net.Conn
    18  	doneCh := make(chan struct{})
    19  	go func() {
    20  		defer close(doneCh)
    21  		defer l.Close()
    22  		var err error
    23  		serverConn, err = l.Accept()
    24  		if err != nil {
    25  			t.Fatalf("err: %s", err)
    26  		}
    27  	}()
    28  
    29  	clientConn, err := net.Dial("tcp", l.Addr().String())
    30  	if err != nil {
    31  		t.Fatalf("err: %s", err)
    32  	}
    33  	<-doneCh
    34  
    35  	return clientConn, serverConn
    36  }
    37  
    38  func testClientServer(t *testing.T) (*rpc.Client, *rpc.Server) {
    39  	clientConn, serverConn := testConn(t)
    40  
    41  	server := rpc.NewServer()
    42  	go server.ServeConn(serverConn)
    43  
    44  	client := rpc.NewClient(clientConn)
    45  
    46  	return client, server
    47  }
    48  
    49  func testNewClientServer(t *testing.T) (*Client, *Server) {
    50  	clientConn, serverConn := testConn(t)
    51  
    52  	server := &Server{
    53  		ProviderFunc: testProviderFixed(new(terraform.MockResourceProvider)),
    54  		ProvisionerFunc: testProvisionerFixed(
    55  			new(terraform.MockResourceProvisioner)),
    56  	}
    57  	go server.ServeConn(serverConn)
    58  
    59  	client, err := NewClient(clientConn)
    60  	if err != nil {
    61  		t.Fatalf("err: %s", err)
    62  	}
    63  
    64  	return client, server
    65  }
    66  
    67  func testProviderFixed(p terraform.ResourceProvider) ProviderFunc {
    68  	return func() terraform.ResourceProvider {
    69  		return p
    70  	}
    71  }
    72  
    73  func testProvisionerFixed(p terraform.ResourceProvisioner) ProvisionerFunc {
    74  	return func() terraform.ResourceProvisioner {
    75  		return p
    76  	}
    77  }