Skip to content

Toxiproxy

Since v0.37.0

Introduction

The Testcontainers module for Toxiproxy.

Adding this module to your project dependencies

Please run the following command to add the Toxiproxy module to your Go dependencies:

go get github.com/testcontainers/testcontainers-go/modules/toxiproxy

Usage example

ctx := context.Background()

toxiproxyContainer, err := tctoxiproxy.Run(
    ctx,
    "ghcr.io/shopify/toxiproxy:2.12.0",
)
defer func() {
    if err := testcontainers.TerminateContainer(toxiproxyContainer); err != nil {
        log.Printf("failed to terminate container: %s", err)
    }
}()
if err != nil {
    log.Printf("failed to start container: %s", err)
    return
}

Module Reference

Run function

The Toxiproxy module exposes one entrypoint function to create the Toxiproxy container, and this function receives three parameters:

func Run(ctx context.Context, img string, opts ...testcontainers.ContainerCustomizer) (*Container, error)
  • context.Context, the Go context.
  • string, the Docker image to use.
  • testcontainers.ContainerCustomizer, a variadic argument for passing options.

Container Ports

The Toxiproxy container exposes the following ports:

  • 8474/tcp, the Toxiproxy control port, exported as toxiproxy.ControlPort.

Image

Use the second argument in the Run function to set a valid Docker image. In example: Run(context.Background(), "shopify/toxiproxy:2.12.0").

Container Options

When starting the Toxiproxy container, you can pass options in a variadic way to configure it.

WithProxy

The WithProxy option allows you to specify a proxy to be created on the Toxiproxy container. This option allocates a random port on the host and exposes it to the Toxiproxy container, allowing you to create a unique proxy for a given service, starting from the 8666/tcp port.

func WithProxy(name string, upstream string) Option

If this option is used in combination with the WithConfigFile option, the proxy defined in this option is added to the proxies defined in the config file.

Info

If you add proxies in a programmatic manner using the Toxiproxy client, then you need to manually add exposed ports in the Toxiproxy container.

WithConfigFile

The WithConfigFile option allows you to specify a config file for the Toxiproxy container, in the form of an io.Reader representing the JSON file with the Toxiproxy configuration, in the valid format of the Toxiproxy configuration file.

[
    {
        "name": "redis",
        "listen": "0.0.0.0:8666",
        "upstream": "redis:6379",
        "enabled": true
    }
]
func WithConfigFile(r io.Reader) testcontainers.CustomizeRequestOption

If this option is used in combination with the WithProxy option, the proxies defined in this option are added to the proxies defined with the WithProxy option.

The following options are exposed by the testcontainers package.

Basic Options

Lifecycle Options

Files & Mounts Options

Build Options

Logging Options

Image Options

Networking Options

Advanced Options

Experimental Options

Container Methods

The Toxiproxy container exposes the following methods:

ProxiedEndpoint

The ProxiedEndpoint method returns the host and port of the proxy for a given port. It's used to create new connections to the proxied service, and it returns an error in case the port has no proxy.

func (c *Container) ProxiedEndpoint(port int) (string, string, error)
proxiedRedisHost, proxiedRedisPort, err := toxiproxyContainer.ProxiedEndpoint(8666)
if err != nil {
    log.Printf("failed to get toxiproxy container port: %s", err)
    return
}
// Create a redis client that connects to the toxiproxy container.
// We are defining a read timeout of 2 seconds, because we are adding
// a latency toxic of 1.1 seconds to the request.
redisURI := fmt.Sprintf("redis://%s:%s?read_timeout=2s", proxiedRedisHost, proxiedRedisPort)

The above examples show how to get the proxied endpoint and use it to create a new connection to the proxied service, in this case a Redis client.

URI

The URI method returns the URI of the Toxiproxy container, used to create a new Toxiproxy client.

func (c *Container) URI() string
toxiURI, err := toxiproxyContainer.URI(ctx)
if err != nil {
    log.Printf("failed to get toxiproxy container uri: %s", err)
    return
}

toxiproxyClient := toxiproxy.NewClient(toxiURI)
  • the toxiproxy package comes from the github.com/Shopify/toxiproxy/v2/client package.
  • the toxiproxyContainer variable has been created by the Run function.

Examples

Programmatically create a proxy

const proxyPort = "8666"

// No need to create a proxy, as we are programmatically adding it below.
toxiproxyContainer, err := tctoxiproxy.Run(
    ctx,
    "ghcr.io/shopify/toxiproxy:2.12.0",
    network.WithNetwork([]string{"toxiproxy"}, nw),
    // explicitly expose the ports that will be proxied using the programmatic API
    // of the toxiproxy client. Otherwise, the ports will not be exposed and the
    // toxiproxy client will not be able to connect to the proxy.
    testcontainers.WithExposedPorts(proxyPort+"/tcp"),
)
defer func() {
    if err := testcontainers.TerminateContainer(toxiproxyContainer); err != nil {
        log.Printf("failed to terminate container: %s", err)
    }
}()
if err != nil {
    log.Printf("failed to start container: %s", err)
    return
}
// Create the proxy using the network alias of the redis container,
// as they run on the same network.
proxy, err := toxiproxyClient.CreateProxy("redis", "0.0.0.0:"+proxyPort, "redis:6379")
if err != nil {
    log.Printf("failed to create proxy: %s", err)
    return
}
// Create a redis client that connects to the toxiproxy container.
// We are defining a read timeout of 2 seconds, because we are adding
// a latency toxic of 1 second to the request, +/- 100ms jitter.
redisURI := fmt.Sprintf("redis://%s:%s?read_timeout=2s", toxiproxyProxyHostIP, toxiproxyProxyPort.Port())

options, err := redis.ParseURL(redisURI)
if err != nil {
    log.Printf("failed to parse url: %s", err)
    return
}

redisCli := redis.NewClient(options)
defer func() {
    if err := redisCli.FlushAll(ctx).Err(); err != nil {
        log.Printf("failed to flush redis: %s", err)
    }
}()
const (
    latency = 1_000
    jitter  = 200
)
// Add a latency toxic to the proxy
_, err = proxy.AddToxic("latency_down", "latency", "downstream", 1.0, toxiproxy.Attributes{
    "latency": latency,
    "jitter":  jitter,
})
if err != nil {
    log.Printf("failed to add toxic: %s", err)
    return
}