Best Testcontainers-go code snippet using testcontainers.inspectContainer
docker.go
Source:docker.go  
...110	return host, nil111}112// MappedPort gets externally mapped port for a container port113func (c *DockerContainer) MappedPort(ctx context.Context, port nat.Port) (nat.Port, error) {114	inspect, err := c.inspectContainer(ctx)115	if err != nil {116		return "", err117	}118	if inspect.ContainerJSONBase.HostConfig.NetworkMode == "host" {119		return port, nil120	}121	ports, err := c.Ports(ctx)122	if err != nil {123		return "", err124	}125	for k, p := range ports {126		if k.Port() != port.Port() {127			continue128		}129		if port.Proto() != "" && k.Proto() != port.Proto() {130			continue131		}132		if len(p) == 0 {133			continue134		}135		return nat.NewPort(k.Proto(), p[0].HostPort)136	}137	return "", errors.New("port not found")138}139// Ports gets the exposed ports for the container.140func (c *DockerContainer) Ports(ctx context.Context) (nat.PortMap, error) {141	inspect, err := c.inspectContainer(ctx)142	if err != nil {143		return nil, err144	}145	return inspect.NetworkSettings.Ports, nil146}147// SessionID gets the current session id148func (c *DockerContainer) SessionID() string {149	return c.sessionID.String()150}151// Start will start an already created container152func (c *DockerContainer) Start(ctx context.Context) error {153	shortID := c.ID[:12]154	c.logger.Printf("Starting container id: %s image: %s", shortID, c.Image)155	if err := c.provider.client.ContainerStart(ctx, c.ID, types.ContainerStartOptions{}); err != nil {156		return err157	}158	// if a Wait Strategy has been specified, wait before returning159	if c.WaitingFor != nil {160		c.logger.Printf("Waiting for container id %s image: %s", shortID, c.Image)161		if err := c.WaitingFor.WaitUntilReady(ctx, c); err != nil {162			return err163		}164	}165	c.logger.Printf("Container is ready id: %s image: %s", shortID, c.Image)166	c.isRunning = true167	return nil168}169// Stop will stop an already started container170//171// In case the container fails to stop172// gracefully within a time frame specified by the timeout argument,173// it is forcefully terminated (killed).174//175// If the timeout is nil, the container's StopTimeout value is used, if set,176// otherwise the engine default. A negative timeout value can be specified,177// meaning no timeout, i.e. no forceful termination is performed.178func (c *DockerContainer) Stop(ctx context.Context, timeout *time.Duration) error {179	shortID := c.ID[:12]180	c.logger.Printf("Stopping container id: %s image: %s", shortID, c.Image)181	var options container.StopOptions182	if timeout != nil {183		timeoutSeconds := int(timeout.Seconds())184		options.Timeout = &timeoutSeconds185	}186	if err := c.provider.client.ContainerStop(ctx, c.ID, options); err != nil {187		return err188	}189	c.logger.Printf("Container is stopped id: %s image: %s", shortID, c.Image)190	c.isRunning = false191	return nil192}193// Terminate is used to kill the container. It is usually triggered by as defer function.194func (c *DockerContainer) Terminate(ctx context.Context) error {195	select {196	// close reaper if it was created197	case c.terminationSignal <- true:198	default:199	}200	err := c.provider.client.ContainerRemove(ctx, c.GetContainerID(), types.ContainerRemoveOptions{201		RemoveVolumes: true,202		Force:         true,203	})204	if err != nil {205		return err206	}207	if c.imageWasBuilt {208		_, err := c.provider.client.ImageRemove(ctx, c.Image, types.ImageRemoveOptions{209			Force:         true,210			PruneChildren: true,211		})212		if err != nil {213			return err214		}215	}216	if err := c.provider.client.Close(); err != nil {217		return err218	}219	c.sessionID = uuid.UUID{}220	c.isRunning = false221	return nil222}223// update container raw info224func (c *DockerContainer) inspectRawContainer(ctx context.Context) (*types.ContainerJSON, error) {225	inspect, err := c.provider.client.ContainerInspect(ctx, c.ID)226	if err != nil {227		return nil, err228	}229	c.raw = &inspect230	return c.raw, nil231}232func (c *DockerContainer) inspectContainer(ctx context.Context) (*types.ContainerJSON, error) {233	inspect, err := c.provider.client.ContainerInspect(ctx, c.ID)234	if err != nil {235		return nil, err236	}237	return &inspect, nil238}239// Logs will fetch both STDOUT and STDERR from the current container. Returns a240// ReadCloser and leaves it up to the caller to extract what it wants.241func (c *DockerContainer) Logs(ctx context.Context) (io.ReadCloser, error) {242	const streamHeaderSize = 8243	options := types.ContainerLogsOptions{244		ShowStdout: true,245		ShowStderr: true,246	}247	rc, err := c.provider.client.ContainerLogs(ctx, c.ID, options)248	if err != nil {249		return nil, err250	}251	pr, pw := io.Pipe()252	r := bufio.NewReader(rc)253	go func() {254		var (255			isPrefix    = true256			lineStarted = true257			line        []byte258		)259		for err == nil {260			line, isPrefix, err = r.ReadLine()261			if lineStarted && len(line) >= streamHeaderSize {262				line = line[streamHeaderSize:] // trim stream header263				lineStarted = false264			}265			if !isPrefix {266				lineStarted = true267			}268			_, errW := pw.Write(line)269			if errW != nil {270				return271			}272			if !isPrefix {273				_, errW := pw.Write([]byte("\n"))274				if errW != nil {275					return276				}277			}278			if err != nil {279				_ = pw.CloseWithError(err)280				return281			}282		}283	}()284	return pr, nil285}286// FollowOutput adds a LogConsumer to be sent logs from the container's287// STDOUT and STDERR288func (c *DockerContainer) FollowOutput(consumer LogConsumer) {289	if c.consumers == nil {290		c.consumers = []LogConsumer{291			consumer,292		}293	} else {294		c.consumers = append(c.consumers, consumer)295	}296}297// Name gets the name of the container.298func (c *DockerContainer) Name(ctx context.Context) (string, error) {299	inspect, err := c.inspectContainer(ctx)300	if err != nil {301		return "", err302	}303	return inspect.Name, nil304}305// State returns container's running state306func (c *DockerContainer) State(ctx context.Context) (*types.ContainerState, error) {307	inspect, err := c.inspectRawContainer(ctx)308	if err != nil {309		return c.raw.State, err310	}311	return inspect.State, nil312}313// Networks gets the names of the networks the container is attached to.314func (c *DockerContainer) Networks(ctx context.Context) ([]string, error) {315	inspect, err := c.inspectContainer(ctx)316	if err != nil {317		return []string{}, err318	}319	networks := inspect.NetworkSettings.Networks320	n := []string{}321	for k := range networks {322		n = append(n, k)323	}324	return n, nil325}326// ContainerIP gets the IP address of the primary network within the container.327func (c *DockerContainer) ContainerIP(ctx context.Context) (string, error) {328	inspect, err := c.inspectContainer(ctx)329	if err != nil {330		return "", err331	}332	ip := inspect.NetworkSettings.IPAddress333	if ip == "" {334		// use IP from "Networks" if only single network defined335		networks := inspect.NetworkSettings.Networks336		if len(networks) == 1 {337			for _, v := range networks {338				ip = v.IPAddress339			}340		}341	}342	return ip, nil343}344// ContainerIPs gets the IP addresses of all the networks within the container.345func (c *DockerContainer) ContainerIPs(ctx context.Context) ([]string, error) {346	ips := make([]string, 0)347	inspect, err := c.inspectContainer(ctx)348	if err != nil {349		return nil, err350	}351	networks := inspect.NetworkSettings.Networks352	for _, nw := range networks {353		ips = append(ips, nw.IPAddress)354	}355	return ips, nil356}357// NetworkAliases gets the aliases of the container for the networks it is attached to.358func (c *DockerContainer) NetworkAliases(ctx context.Context) (map[string][]string, error) {359	inspect, err := c.inspectContainer(ctx)360	if err != nil {361		return map[string][]string{}, err362	}363	networks := inspect.NetworkSettings.Networks364	a := map[string][]string{}365	for k := range networks {366		a[k] = networks[k].Aliases367	}368	return a, nil369}370func (c *DockerContainer) Exec(ctx context.Context, cmd []string) (int, io.Reader, error) {371	cli := c.provider.client372	response, err := cli.ContainerExecCreate(ctx, c.ID, types.ExecConfig{373		Cmd:          cmd,...compose_provider.go
Source:compose_provider.go  
...116	return host, nil117}118// MappedPort gets externally mapped port for a container port119func (c *DockerContainer) MappedPort(ctx context.Context, port nat.Port) (nat.Port, error) {120	inspect, err := c.inspectContainer(ctx)121	if err != nil {122		return "", err123	}124	if inspect.ContainerJSONBase.HostConfig.NetworkMode == "host" {125		return port, nil126	}127	ports, err := c.Ports(ctx)128	if err != nil {129		return "", err130	}131	for k, p := range ports {132		if k.Port() != port.Port() {133			continue134		}135		if port.Proto() != "" && k.Proto() != port.Proto() {136			continue137		}138		if len(p) == 0 {139			continue140		}141		return nat.NewPort(k.Proto(), p[0].HostPort)142	}143	return "", errors.New("port not found")144}145// Ports gets the exposed ports for the container.146func (c *DockerContainer) Ports(ctx context.Context) (nat.PortMap, error) {147	inspect, err := c.inspectContainer(ctx)148	if err != nil {149		return nil, err150	}151	return inspect.NetworkSettings.Ports, nil152}153func (c *DockerContainer) inspectContainer(ctx context.Context) (*types.ContainerJSON, error) {154	inspect, err := c.provider.client.ContainerInspect(ctx, c.ID)155	if err != nil {156		return nil, err157	}158	return &inspect, nil159}160// Logs will fetch both STDOUT and STDERR from the current container. Returns a161// ReadCloser and leaves it up to the caller to extract what it wants.162func (c *DockerContainer) Logs(ctx context.Context) (io.ReadCloser, error) {163	options := types.ContainerLogsOptions{164		ShowStdout: true,165		ShowStderr: true,166	}167	return c.provider.client.ContainerLogs(ctx, c.ID, options)168}169// FollowOutput adds a LogConsumer to be sent logs from the container's170// STDOUT and STDERR171func (c *DockerContainer) FollowOutput(consumer LogConsumer) {172	if c.consumers == nil {173		c.consumers = []LogConsumer{174			consumer,175		}176	} else {177		c.consumers = append(c.consumers, consumer)178	}179}180// Name gets the name of the container.181func (c *DockerContainer) Name(ctx context.Context) (string, error) {182	inspect, err := c.inspectContainer(ctx)183	if err != nil {184		return "", err185	}186	return inspect.Name, nil187}188// Networks gets the names of the networks the container is attached to.189func (c *DockerContainer) Networks(ctx context.Context) ([]string, error) {190	inspect, err := c.inspectContainer(ctx)191	if err != nil {192		return []string{}, err193	}194	networks := inspect.NetworkSettings.Networks195	n := []string{}196	for k := range networks {197		n = append(n, k)198	}199	return n, nil200}201// ContainerIP gets the IP address of the primary network within the container.202func (c *DockerContainer) ContainerIP(ctx context.Context) (string, error) {203	inspect, err := c.inspectContainer(ctx)204	if err != nil {205		return "", err206	}207	return inspect.NetworkSettings.IPAddress, nil208}209// NetworkAliases gets the aliases of the container for the networks it is attached to.210func (c *DockerContainer) NetworkAliases(ctx context.Context) (map[string][]string, error) {211	inspect, err := c.inspectContainer(ctx)212	if err != nil {213		return map[string][]string{}, err214	}215	networks := inspect.NetworkSettings.Networks216	a := map[string][]string{}217	for k := range networks {218		a[k] = networks[k].Aliases219	}220	return a, nil221}222func (c *DockerContainer) Exec(ctx context.Context, cmd []string) (int, error) {223	cli := c.provider.client224	response, err := cli.ContainerExecCreate(ctx, c.ID, types.ExecConfig{225		Cmd:    cmd,...inspectContainer
Using AI Code Generation
1import (2func main() {3	ctx := context.Background()4	req := testcontainers.ContainerRequest{5		ExposedPorts: []string{"8080/tcp"},6		WaitingFor:   wait.ForLog("listening on"),7	}8	c, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9	})10	if err != nil {11		log.Fatal(err)12	}13	id, err := c.ContainerID(ctx)14	if err != nil {15		log.Fatal(err)16	}17	ip, err := c.Host(ctx)18	if err != nil {19		log.Fatal(err)20	}21	port, err := c.MappedPort(ctx, "8080")22	if err != nil {23		log.Fatal(err)24	}25	state, err := c.State(ctx)26	if err != nil {27		log.Fatal(err)28	}29	name, err := c.Name(ctx)30	if err != nil {31		log.Fatal(err)32	}33	image, err := c.Image(ctx)34	if err != nil {35		log.Fatal(err)36	}37	startedAt, err := c.StartedAt(ctx)38	if err != nil {39		log.Fatal(err)40	}41	uptime, err := c.Uptime(ctx)42	if err != nil {43		log.Fatal(err)44	}45	logs, err := c.Logs(ctx)46	if err != nil {47		log.Fatal(err)48	}49	stats, err := c.Stats(ctx)50	if err != nil {51		log.Fatal(err)52	}53	health, err := c.HealthCheck(ctx)54	if err != nil {55		log.Fatal(err)56	}57	labels, err := c.Labels(ctx)58	if err != nil {59		log.Fatal(err)60	}61	network, err := c.NetworkSettings(ctx)62	if err != nil {63		log.Fatal(err)64	}inspectContainer
Using AI Code Generation
1import (2func main() {3	ctx := context.Background()4	req := testcontainers.ContainerRequest{5		ExposedPorts: []string{"22/tcp"},6		WaitingFor:   wait.ForListeningPort("22/tcp"),7	}8	ubuntuContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9	})10	if err != nil {11		log.Fatal(err)12	}13	inspect, err := ubuntuContainer.Inspect(ctx)14	if err != nil {15		log.Fatal(err)16	}17	fmt.Println("ContainerID: ", inspect.ContainerJSONBase.ID)18	fmt.Println("ContainerName: ", inspect.ContainerJSONBase.Name)19	fmt.Println("Image: ", inspect.Config.Image)20	fmt.Println("ImageID: ", inspect.ImageID)21	fmt.Println("NetworkSettings: ", inspect.NetworkSettings.Networks)22	fmt.Println("State: ", inspect.State)23	fmt.Println("HostPortinspectContainer
Using AI Code Generation
1import (2func main() {3	ctx := context.Background()4	req := testcontainers.ContainerRequest{5		ExposedPorts: []string{"80/tcp"},6		WaitingFor:   wait.ForLog("listening on port 80"),7	}8	provider, _ := testcontainers.NewDockerProvider()9	container, _ := testcontainers.GenericContainer(ctx, provider, req)10	defer container.Terminate(ctx)11	_, err := container.Start(ctx)12	if err != nil {13		panic(err)14	}15	inspect, _ := container.Inspect(ctx)16	fmt.Println(inspect.ContainerJSONBase.ID)17}18import (19func main() {20	ctx := context.Background()21	req := testcontainers.ContainerRequest{22		ExposedPorts: []string{"80/tcp"},23		WaitingFor:   wait.ForLog("listening on port 80"),24	}25	provider, _ := testcontainers.NewDockerProvider()26	container, _ := testcontainers.GenericContainer(ctx, provider, req)27	defer container.Terminate(ctx)28	_, err := container.Start(ctx)29	if err != nil {30		panic(err)31	}32	containerID, _ := container.Create(ctx)33	fmt.Println(containerID)34}inspectContainer
Using AI Code Generation
1import (2func main() {3	ctx := context.Background()4	req := testcontainers.ContainerRequest{5		Cmd:          []string{"sleep", "3000"},6		ExposedPorts: []string{"80/tcp"},7		WaitingFor:   wait.ForLog("listening"),8	}9	container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{10	})11	if err != nil {12		panic(err)13	}14	defer container.Terminate(ctx)15	inspect, err := container.Inspect(ctx)16	if err != nil {17		panic(err)18	}19	fmt.Println(inspect.Name)20	fmt.Println(inspect.ID)21	fmt.Println(inspect.State)22	fmt.Println(inspect.NetworkSettings)23	fmt.Println(inspect.Mounts)24	fmt.Println(inspect.Config)25	fmt.Println(inspect.Config.Hostname)26	fmt.Println(inspect.Image)27	fmt.Println(inspect.NetworkSettings.IPAddress)28	fmt.Println(inspect.NetworkSettings.Ports)29	fmt.Println(inspect.NetworkSettings.Ports["80/tcp"])30	fmt.Println(inspect.NetworkSettings.Ports["80/tcp"][0])31	fmt.Println(inspect.NetworkSettings.Ports["80/tcp"][0].HostPort)32	fmt.Println(inspect.NetworkSettings.Ports["80/tcp"][0].HostIP)33	fmt.Println(inspect.NetworkSettings.Ports["80/tcp"][0].HostPort)34	fmt.Println(inspect.NetworkSettings.Ports["80/tcp"][0].HostIP)35	fmt.Println(inspect.NetworkSettingsinspectContainer
Using AI Code Generation
1import (2func main() {3	ctx := context.Background()4	req := testcontainers.ContainerRequest{5		ExposedPorts: []string{"6379/tcp"},6		WaitingFor:   wait.ForListeningPort("6379/tcp"),7	}8	redisContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9	})10	if err != nil {11		panic(err)12	}13	id, err := redisContainer.ContainerID(ctx)14	if err != nil {15		panic(err)16	}17	fmt.Println(id)18	ip, err := redisContainer.Host(ctx)19	if err != nil {20		panic(err)21	}22	fmt.Println(ip)23	port, err := redisContainer.MappedPort(ctx, "6379/tcp")24	if err != nil {25		panic(err)26	}27	fmt.Println(port.Int())28	err = redisContainer.Terminate(ctx)29	if err != nil {30		panic(err)31	}32}inspectContainer
Using AI Code Generation
1import (2func main() {3	ctx := context.Background()4	req := testcontainers.ContainerRequest{5		Cmd:          []string{"echo", "hello world"},6		ExposedPorts: []string{"80/tcp"},7		WaitingFor:   wait.ForLog("hello world"),8	}9	container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{10	})11	if err != nil {12		panic(err)13	}14	id, err := container.ContainerID(ctx)15	if err != nil {16		panic(err)17	}18	fmt.Println(id)19	ip, err := container.Host(ctx)20	if err != nil {21		panic(err)22	}23	fmt.Println(ip)24	port, err := container.MappedPort(ctx, "80")25	if err != nil {26		panic(err)27	}28	fmt.Println(port.Int())29	logs, err := container.Logs(ctx)30	if err != nil {31		panic(err)32	}33	defer logs.Close()34	io.Copy(os.Stdout, logs)35	stats, err := container.Stats(ctx)36	if err != nil {37		panic(err)38	}39	fmt.Println(stats)40	top, err := container.Top(ctx)41	if err != nil {42		panic(err)43	}44	fmt.Println(top)45	inspect, err := container.Inspect(ctx)46	if err != nil {47		panic(err)48	}49	fmt.Println(inspect)50	err = container.Terminate(ctx)51	if err != nil {52		panic(err)53	}54	err = container.Remove(ctx)55	if err != nil {56		panic(err)57	}58}inspectContainer
Using AI Code Generation
1import (2func main() {3	ctx := context.Background()4	req := testcontainers.ContainerRequest{5		ExposedPorts: []string{"80/tcp"},6		WaitingFor:   wait.ForLog("listening on port 80"),7	}8	container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9	})10	if err != nil {11		panic(err)12	}13	ip, err := container.Host(ctx)14	if err != nil {15		panic(err)16	}17	port, err := container.MappedPort(ctx, "80")18	if err != nil {19		panic(err)20	}21	fmt.Printf("Container's IP: %s, Port: %s", ip, port.Port())22	err = container.Terminate(ctx)23	if err != nil {24		panic(err)25	}26}inspectContainer
Using AI Code Generation
1import (2func main() {3	cli, err := client.NewEnvClient()4	if err != nil {5		panic(err)6	}7	ctx := context.Background()8	req := testcontainers.ContainerRequest{9		Cmd:          []string{"sh", "-c", "while true; do sleep 1; done"},10		ExposedPorts: []string{"8080/tcp"},11		WaitingFor:   wait.ForLog("started"),12	}13	container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{14	})15	if err != nil {16		panic(err)17	}18	inspect, err := cli.ContainerInspect(ctx, container.GetContainerID())19	if err != nil {20		panic(err)21	}inspectContainer
Using AI Code Generation
1import (2func main() {3	containerID, err := testcontainers.InspectContainer("nginx")4	if err != nil {5		fmt.Println(err)6	} else {7		fmt.Println(containerID)8	}9}10import (11func main() {12	inspectContainer, err := testcontainers.InspectContainer("nginx")13	if err != nil {Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
