Skip to content

Instantly share code, notes, and snippets.

@anxiousmodernman
Created January 9, 2018 00:14
Show Gist options
  • Save anxiousmodernman/cc3a5b99f218cf4fdad813e72170eaa2 to your computer and use it in GitHub Desktop.
Save anxiousmodernman/cc3a5b99f218cf4fdad813e72170eaa2 to your computer and use it in GitHub Desktop.
helper function for grpc golang tests
func grpcListenerClientCleanup() (*grpc.Server, server.ProxyClient, func()) {
    // Proxy, our concrent implementation
    dir, _ := ioutil.TempDir("", "co-chair-test")
    dbPath := filepath.Join(dir, "co-chair-test.db")
    px, _ := NewProxy(dbPath)
    // grpc server setup
    gs := grpc.NewServer()
    server.RegisterProxyServer(gs, px)
    // tcp listener on a random high port
    lis, err := net.Listen("tcp", "127.0.0.1:0")
    if err != nil {
        panic(err)
    }
    go func() { gs.Serve(lis) }()
    // grpc client setup; use the address of server to make new conn
    addr := lis.Addr().String()
    conn, err := grpc.Dial(addr, grpc.WithInsecure(), grpc.WithBlock(),
        grpc.WithTimeout(3*time.Second))
    if err != nil {
        panic(err)
    }
    // ProxyClient, our generated client interface
    pc := server.NewProxyClient(conn)
    // stop grpc server, remove the Proxy's temp db
    cleanup := func() {
        gs.Stop()
        os.RemoveAll(dir)
    }
    return gs, pc, cleanup
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment