packageconsulimport("context""fmt""github.com/testcontainers/testcontainers-go""github.com/testcontainers/testcontainers-go/wait")// consulContainer represents the consul container type used in the moduletypeconsulContainerstruct{testcontainers.Containerendpointstring}// setupConsul creates an instance of the consul container typefuncsetupConsul(ctxcontext.Context)(*consulContainer,error){req:=testcontainers.ContainerRequest{Image:"consul:latest",ExposedPorts:[]string{"8500/tcp","8600/udp"},Name:"badger",Cmd:[]string{"agent","-server","-ui","-node=server-1","-bootstrap-expect=1","-client=0.0.0.0"},WaitingFor:wait.ForListeningPort("8500/tcp"),}container,err:=testcontainers.GenericContainer(ctx,testcontainers.GenericContainerRequest{ContainerRequest:req,Started:true,})iferr!=nil{returnnil,err}mappedPort,err:=container.MappedPort(ctx,"8500")iferr!=nil{returnnil,err}host,err:=container.Host(ctx)iferr!=nil{returnnil,err}return&consulContainer{Container:container,endpoint:fmt.Sprintf("%s:%s",host,mappedPort.Port())},nil}
packageconsulimport("bytes""context""testing""github.com/hashicorp/consul/api")funcTestConsul(t*testing.T){ctx:=context.Background()container,err:=setupConsul(ctx)iferr!=nil{t.Fatal(err)}// Clean up the container after the test is completet.Cleanup(func(){iferr:=container.Terminate(ctx);err!=nil{t.Fatalf("failed to terminate container: %s",err)}})// perform assertionscfg:=api.DefaultConfig()cfg.Address=container.endpointclient,err:=api.NewClient(cfg)ifnil!=err{t.Fatal(err)}bs:=[]byte("apple")_,err=client.KV().Put(&api.KVPair{Key:"fruit",Value:bs,},nil)ifnil!=err{t.Fatal(err)}pair,_,err:=client.KV().Get("fruit",nil)iferr!=nil{t.Fatal(err)}ifpair.Key!="fruit"||!bytes.Equal(pair.Value,[]byte("apple")){t.Errorf("get KV: %v %s,expect them to be: 'fruit' and 'apple'\n",pair.Key,pair.Value)}}