github.com/hashicorp/terraform-plugin-sdk@v1.17.2/helper/resource/grpc_test_provider.go (about)

     1  package resource
     2  
     3  import (
     4  	"context"
     5  	"net"
     6  	"time"
     7  
     8  	"github.com/hashicorp/terraform-plugin-sdk/internal/helper/plugin"
     9  	"github.com/hashicorp/terraform-plugin-sdk/internal/providers"
    10  	proto "github.com/hashicorp/terraform-plugin-sdk/internal/tfplugin5"
    11  	tfplugin "github.com/hashicorp/terraform-plugin-sdk/plugin"
    12  	"github.com/hashicorp/terraform-plugin-sdk/terraform"
    13  	"google.golang.org/grpc"
    14  	"google.golang.org/grpc/test/bufconn"
    15  )
    16  
    17  // GRPCTestProvider takes a legacy ResourceProvider, wraps it in the new GRPC
    18  // shim and starts it in a grpc server using an inmem connection. It returns a
    19  // GRPCClient for this new server to test the shimmed resource provider.
    20  func GRPCTestProvider(rp terraform.ResourceProvider) providers.Interface {
    21  	listener := bufconn.Listen(256 * 1024)
    22  	grpcServer := grpc.NewServer()
    23  
    24  	p := plugin.NewGRPCProviderServerShim(rp)
    25  	proto.RegisterProviderServer(grpcServer, p)
    26  
    27  	go grpcServer.Serve(listener)
    28  
    29  	conn, err := grpc.Dial("", grpc.WithDialer(func(string, time.Duration) (net.Conn, error) {
    30  		return listener.Dial()
    31  	}), grpc.WithInsecure())
    32  	if err != nil {
    33  		panic(err)
    34  	}
    35  
    36  	var pp tfplugin.GRPCProviderPlugin
    37  	client, _ := pp.GRPCClient(context.Background(), nil, conn)
    38  
    39  	grpcClient := client.(*tfplugin.GRPCProvider)
    40  	grpcClient.TestServer = grpcServer
    41  
    42  	return grpcClient
    43  }