github.com/angryronald/go-kit@v0.0.0-20240505173814-ff2bd9c79dbf/test/docker/vault/vault.dockertest.sample_test.go (about)

     1  package vault
     2  
     3  /*
     4  There is an issue with dockertest which seems to be able to pull the image and spin it up, but it turns out the container never created
     5  */
     6  
     7  import (
     8  	"fmt"
     9  	"log"
    10  	"net/http"
    11  	"testing"
    12  
    13  	"github.com/ory/dockertest/v3"
    14  	"github.com/stretchr/testify/assert"
    15  )
    16  
    17  func TestVaultContainer(t *testing.T) {
    18  	pool, err := dockertest.NewPool("")
    19  	if err != nil {
    20  		log.Fatalf("Could not connect to Docker: %v", err)
    21  	}
    22  
    23  	// Specify the complete image name including the registry
    24  	imageName := "docker.io/hashicorp/vault"
    25  
    26  	resource, err := pool.Run(imageName, "latest", nil)
    27  	if err != nil {
    28  		log.Fatalf("Could not start resource: %v", err)
    29  	}
    30  	defer func() {
    31  		if err := pool.Purge(resource); err != nil {
    32  			log.Fatalf("Could not purge resource: %v", err)
    33  		}
    34  	}()
    35  
    36  	if err := pool.Retry(func() error {
    37  		// Your logic to check if the container is ready
    38  		// This can be connecting to a port, checking logs, etc.
    39  
    40  		// Example: Check if Vault is responsive on the specified port
    41  		port := resource.GetPort("8200/tcp")
    42  		if port == "" {
    43  			return fmt.Errorf("container does not expose port 8200/tcp")
    44  		}
    45  
    46  		vaultURL := fmt.Sprintf("http://localhost:%s", port)
    47  		resp, err := http.Get(vaultURL)
    48  		if err != nil {
    49  			return fmt.Errorf("error making HTTP request to Vault: %v", err)
    50  		}
    51  		defer resp.Body.Close()
    52  
    53  		if resp.StatusCode != http.StatusOK {
    54  			return fmt.Errorf("Vault is not responsive, status code: %d", resp.StatusCode)
    55  		}
    56  
    57  		return nil
    58  	}); err != nil {
    59  		log.Fatalf("Could not connect to Docker: %v", err)
    60  	}
    61  
    62  	// Your test logic here
    63  	// For example, use assert statements to verify container behavior
    64  
    65  	assert.True(t, true, "Sample assertion")
    66  
    67  	fmt.Println("Test completed successfully")
    68  }