Best Testcontainers-go code snippet using testcontainers.TestContainerCreation
docker_test.go
Source:docker_test.go
...605 if resp.StatusCode != http.StatusOK {606 t.Errorf("Expected status code %d. Got %d.", http.StatusOK, resp.StatusCode)607 }608}609func TestContainerCreation(t *testing.T) {610 ctx := context.Background()611 nginxC, err := GenericContainer(ctx, GenericContainerRequest{612 ProviderType: providerType,613 ContainerRequest: ContainerRequest{614 Image: nginxAlpineImage,615 ExposedPorts: []string{616 nginxDefaultPort,617 },618 WaitingFor: wait.ForListeningPort(nginxDefaultPort),619 },620 Started: true,621 })622 require.NoError(t, err)623 terminateContainerOnEnd(t, ctx, nginxC)624 endpoint, err := nginxC.PortEndpoint(ctx, nginxDefaultPort, "http")625 require.NoError(t, err)626 resp, err := http.Get(endpoint)627 if err != nil {628 t.Fatal(err)629 }630 if resp.StatusCode != http.StatusOK {631 t.Errorf("Expected status code %d. Got %d.", http.StatusOK, resp.StatusCode)632 }633 networkIP, err := nginxC.ContainerIP(ctx)634 if err != nil {635 t.Fatal(err)636 }637 if len(networkIP) == 0 {638 t.Errorf("Expected an IP address, got %v", networkIP)639 }640 networkAliases, err := nginxC.NetworkAliases(ctx)641 if err != nil {642 t.Fatal(err)643 }644 if len(networkAliases) != 1 {645 fmt.Printf("%v", networkAliases)646 t.Errorf("Expected number of connected networks %d. Got %d.", 0, len(networkAliases))647 }648 if len(networkAliases["bridge"]) != 0 {649 t.Errorf("Expected number of aliases for 'bridge' network %d. Got %d.", 0, len(networkAliases["bridge"]))650 }651}652func TestContainerIPs(t *testing.T) {653 ctx := context.Background()654 networkName := "new-network"655 newNetwork, err := GenericNetwork(ctx, GenericNetworkRequest{656 ProviderType: providerType,657 NetworkRequest: NetworkRequest{658 Name: networkName,659 CheckDuplicate: true,660 },661 })662 if err != nil {663 t.Fatal(err)664 }665 t.Cleanup(func() {666 require.NoError(t, newNetwork.Remove(ctx))667 })668 nginxC, err := GenericContainer(ctx, GenericContainerRequest{669 ProviderType: providerType,670 ContainerRequest: ContainerRequest{671 Image: nginxAlpineImage,672 ExposedPorts: []string{673 nginxDefaultPort,674 },675 Networks: []string{676 "bridge",677 networkName,678 },679 WaitingFor: wait.ForListeningPort(nginxDefaultPort),680 },681 Started: true,682 })683 require.NoError(t, err)684 terminateContainerOnEnd(t, ctx, nginxC)685 ips, err := nginxC.ContainerIPs(ctx)686 if err != nil {687 t.Fatal(err)688 }689 if len(ips) != 2 {690 t.Errorf("Expected two IP addresses, got %v", len(ips))691 }692}693func TestContainerCreationWithName(t *testing.T) {694 ctx := context.Background()695 creationName := fmt.Sprintf("%s_%d", "test_container", time.Now().Unix())696 expectedName := "/" + creationName // inspect adds '/' in the beginning697 nginxC, err := GenericContainer(ctx, GenericContainerRequest{698 ProviderType: providerType,699 ContainerRequest: ContainerRequest{700 Image: nginxAlpineImage,701 ExposedPorts: []string{702 nginxDefaultPort,703 },704 WaitingFor: wait.ForListeningPort(nginxDefaultPort),705 Name: creationName,706 Networks: []string{"bridge"},707 },708 Started: true,709 })710 require.NoError(t, err)711 terminateContainerOnEnd(t, ctx, nginxC)712 name, err := nginxC.Name(ctx)713 if err != nil {714 t.Fatal(err)715 }716 if name != expectedName {717 t.Errorf("Expected container name '%s'. Got '%s'.", expectedName, name)718 }719 networks, err := nginxC.Networks(ctx)720 if err != nil {721 t.Fatal(err)722 }723 if len(networks) != 1 {724 t.Errorf("Expected networks 1. Got '%d'.", len(networks))725 }726 network := networks[0]727 switch providerType {728 case ProviderDocker:729 if network != Bridge {730 t.Errorf("Expected network name '%s'. Got '%s'.", Bridge, network)731 }732 case ProviderPodman:733 if network != Podman {734 t.Errorf("Expected network name '%s'. Got '%s'.", Podman, network)735 }736 }737 endpoint, err := nginxC.PortEndpoint(ctx, nginxDefaultPort, "http")738 require.NoError(t, err)739 resp, err := http.Get(endpoint)740 if err != nil {741 t.Fatal(err)742 }743 if resp.StatusCode != http.StatusOK {744 t.Errorf("Expected status code %d. Got %d.", http.StatusOK, resp.StatusCode)745 }746}747func TestContainerCreationAndWaitForListeningPortLongEnough(t *testing.T) {748 ctx := context.Background()749 // delayed-nginx will wait 2s before opening port750 nginxC, err := GenericContainer(ctx, GenericContainerRequest{751 ProviderType: providerType,752 ContainerRequest: ContainerRequest{753 Image: "docker.io/menedev/delayed-nginx:1.15.2",754 ExposedPorts: []string{755 nginxDefaultPort,756 },757 WaitingFor: wait.ForListeningPort(nginxDefaultPort), // default startupTimeout is 60s758 },759 Started: true,760 })761 require.NoError(t, err)762 terminateContainerOnEnd(t, ctx, nginxC)763 origin, err := nginxC.PortEndpoint(ctx, nginxDefaultPort, "http")764 if err != nil {765 t.Fatal(err)766 }767 resp, err := http.Get(origin)768 if err != nil {769 t.Fatal(err)770 }771 if resp.StatusCode != http.StatusOK {772 t.Errorf("Expected status code %d. Got %d.", http.StatusOK, resp.StatusCode)773 }774}775func TestContainerCreationTimesOut(t *testing.T) {776 ctx := context.Background()777 // delayed-nginx will wait 2s before opening port778 nginxC, err := GenericContainer(ctx, GenericContainerRequest{779 ProviderType: providerType,780 ContainerRequest: ContainerRequest{781 Image: "docker.io/menedev/delayed-nginx:1.15.2",782 ExposedPorts: []string{783 nginxDefaultPort,784 },785 WaitingFor: wait.ForListeningPort(nginxDefaultPort).WithStartupTimeout(1 * time.Second),786 },787 Started: true,788 })789 if err == nil {790 t.Error("Expected timeout")791 err := nginxC.Terminate(ctx)792 if err != nil {793 t.Fatal(err)794 }795 }796}797func TestContainerRespondsWithHttp200ForIndex(t *testing.T) {798 ctx := context.Background()799 // delayed-nginx will wait 2s before opening port800 nginxC, err := GenericContainer(ctx, GenericContainerRequest{801 ProviderType: providerType,802 ContainerRequest: ContainerRequest{803 Image: nginxAlpineImage,804 ExposedPorts: []string{805 nginxDefaultPort,806 },807 WaitingFor: wait.ForHTTP("/"),808 },809 Started: true,810 })811 require.NoError(t, err)812 terminateContainerOnEnd(t, ctx, nginxC)813 origin, err := nginxC.PortEndpoint(ctx, nginxDefaultPort, "http")814 if err != nil {815 t.Fatal(err)816 }817 resp, err := http.Get(origin)818 if err != nil {819 t.Error(err)820 }821 if resp.StatusCode != http.StatusOK {822 t.Errorf("Expected status code %d. Got %d.", http.StatusOK, resp.StatusCode)823 }824}825func TestContainerCreationTimesOutWithHttp(t *testing.T) {826 ctx := context.Background()827 // delayed-nginx will wait 2s before opening port828 nginxC, err := GenericContainer(ctx, GenericContainerRequest{829 ProviderType: providerType,830 ContainerRequest: ContainerRequest{831 Image: "docker.io/menedev/delayed-nginx:1.15.2",832 ExposedPorts: []string{833 nginxDefaultPort,834 },835 WaitingFor: wait.ForHTTP("/").WithStartupTimeout(1 * time.Second),836 },837 Started: true,838 })839 terminateContainerOnEnd(t, ctx, nginxC)840 if err == nil {841 t.Error("Expected timeout")842 }843}844func TestContainerCreationWaitsForLogContextTimeout(t *testing.T) {845 ctx := context.Background()846 req := ContainerRequest{847 Image: "docker.io/mysql:latest",848 ExposedPorts: []string{"3306/tcp", "33060/tcp"},849 Env: map[string]string{850 "MYSQL_ROOT_PASSWORD": "password",851 "MYSQL_DATABASE": "database",852 },853 WaitingFor: wait.ForLog("test context timeout").WithStartupTimeout(1 * time.Second),854 }855 _, err := GenericContainer(ctx, GenericContainerRequest{856 ProviderType: providerType,857 ContainerRequest: req,858 Started: true,859 })860 if err == nil {861 t.Error("Expected timeout")862 }863}864func TestContainerCreationWaitsForLog(t *testing.T) {865 ctx := context.Background()866 req := ContainerRequest{867 Image: "docker.io/mysql:latest",868 ExposedPorts: []string{"3306/tcp", "33060/tcp"},869 Env: map[string]string{870 "MYSQL_ROOT_PASSWORD": "password",871 "MYSQL_DATABASE": "database",872 },873 WaitingFor: wait.ForLog("port: 3306 MySQL Community Server - GPL"),874 }875 mysqlC, err := GenericContainer(ctx, GenericContainerRequest{876 ProviderType: providerType,877 ContainerRequest: req,878 Started: true,879 })880 require.NoError(t, err)881 terminateContainerOnEnd(t, ctx, mysqlC)882 host, _ := mysqlC.Host(ctx)883 p, _ := mysqlC.MappedPort(ctx, "3306/tcp")884 port := p.Int()885 connectionString := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?tls=skip-verify",886 "root", "password", host, port, "database")887 db, err := sql.Open("mysql", connectionString)888 defer db.Close()889 if err = db.Ping(); err != nil {890 t.Errorf("error pinging db: %+v\n", err)891 }892 _, err = db.Exec("CREATE TABLE IF NOT EXISTS a_table ( \n" +893 " `col_1` VARCHAR(128) NOT NULL, \n" +894 " `col_2` VARCHAR(128) NOT NULL, \n" +895 " PRIMARY KEY (`col_1`, `col_2`) \n" +896 ")")897 if err != nil {898 t.Errorf("error creating table: %+v\n", err)899 }900}901func Test_BuildContainerFromDockerfile(t *testing.T) {902 t.Log("getting context")903 ctx := context.Background()904 t.Log("got context, creating container request")905 req := ContainerRequest{906 FromDockerfile: FromDockerfile{907 Context: "./testresources",908 },909 ExposedPorts: []string{"6379/tcp"},910 WaitingFor: wait.ForLog("Ready to accept connections"),911 }912 t.Log("creating generic container request from container request")913 genContainerReq := GenericContainerRequest{914 ProviderType: providerType,915 ContainerRequest: req,916 Started: true,917 }918 t.Log("creating redis container")919 redisC, err := GenericContainer(ctx, genContainerReq)920 require.NoError(t, err)921 terminateContainerOnEnd(t, ctx, redisC)922 t.Log("created redis container")923 t.Log("getting redis container endpoint")924 endpoint, err := redisC.Endpoint(ctx, "")925 if err != nil {926 t.Fatal(err)927 }928 t.Log("retrieved redis container endpoint")929 client := redis.NewClient(&redis.Options{930 Addr: endpoint,931 })932 t.Log("pinging redis")933 pong, err := client.Ping(ctx).Result()934 require.NoError(t, err)935 t.Log("received response from redis")936 if pong != "PONG" {937 t.Fatalf("received unexpected response from redis: %s", pong)938 }939}940func Test_BuildContainerFromDockerfileWithBuildArgs(t *testing.T) {941 t.Log("getting ctx")942 ctx := context.Background()943 ba := "build args value"944 t.Log("got ctx, creating container request")945 req := ContainerRequest{946 FromDockerfile: FromDockerfile{947 Context: "./testresources",948 Dockerfile: "args.Dockerfile",949 BuildArgs: map[string]*string{950 "FOO": &ba,951 },952 },953 ExposedPorts: []string{"8080/tcp"},954 WaitingFor: wait.ForLog("ready"),955 }956 genContainerReq := GenericContainerRequest{957 ProviderType: providerType,958 ContainerRequest: req,959 Started: true,960 }961 c, err := GenericContainer(ctx, genContainerReq)962 require.NoError(t, err)963 terminateContainerOnEnd(t, ctx, c)964 ep, err := c.Endpoint(ctx, "http")965 if err != nil {966 t.Fatal(err)967 }968 resp, err := http.Get(ep + "/env")969 if err != nil {970 t.Fatal(err)971 }972 body, err := ioutil.ReadAll(resp.Body)973 if err != nil {974 t.Fatal(err)975 }976 assert.Equal(t, 200, resp.StatusCode)977 assert.Equal(t, ba, string(body))978}979func Test_BuildContainerFromDockerfileWithBuildLog(t *testing.T) {980 rescueStdout := os.Stderr981 r, w, _ := os.Pipe()982 os.Stderr = w983 t.Log("getting ctx")984 ctx := context.Background()985 t.Log("got ctx, creating container request")986 req := ContainerRequest{987 FromDockerfile: FromDockerfile{988 Context: "./testresources",989 Dockerfile: "buildlog.Dockerfile",990 PrintBuildLog: true,991 },992 }993 genContainerReq := GenericContainerRequest{994 ProviderType: providerType,995 ContainerRequest: req,996 Started: true,997 }998 c, err := GenericContainer(ctx, genContainerReq)999 require.NoError(t, err)1000 terminateContainerOnEnd(t, ctx, c)1001 _ = w.Close()1002 out, _ := ioutil.ReadAll(r)1003 os.Stdout = rescueStdout1004 temp := strings.Split(string(out), "\n")1005 if !regexp.MustCompile(`(?i)^Step\s*1/1\s*:\s*FROM docker.io/alpine$`).MatchString(temp[0]) {1006 t.Errorf("Expected stdout firstline to be %s. Got '%s'.", "Step 1/1 : FROM docker.io/alpine", temp[0])1007 }1008}1009func TestContainerCreationWaitsForLogAndPortContextTimeout(t *testing.T) {1010 ctx := context.Background()1011 req := ContainerRequest{1012 Image: "docker.io/mysql:latest",1013 ExposedPorts: []string{"3306/tcp", "33060/tcp"},1014 Env: map[string]string{1015 "MYSQL_ROOT_PASSWORD": "password",1016 "MYSQL_DATABASE": "database",1017 },1018 WaitingFor: wait.ForAll(1019 wait.ForLog("I love testcontainers-go"),1020 wait.ForListeningPort("3306/tcp"),1021 ),1022 }1023 _, err := GenericContainer(ctx, GenericContainerRequest{1024 ProviderType: providerType,1025 ContainerRequest: req,1026 Started: true,1027 })1028 if err == nil {1029 t.Fatal("Expected timeout")1030 }1031}1032func TestContainerCreationWaitingForHostPort(t *testing.T) {1033 ctx := context.Background()1034 req := ContainerRequest{1035 Image: nginxAlpineImage,1036 ExposedPorts: []string{nginxDefaultPort},1037 WaitingFor: wait.ForListeningPort(nginxDefaultPort),1038 }1039 nginx, err := GenericContainer(ctx, GenericContainerRequest{1040 ProviderType: providerType,1041 ContainerRequest: req,1042 Started: true,1043 })1044 require.NoError(t, err)1045 terminateContainerOnEnd(t, ctx, nginx)1046}1047func TestContainerCreationWaitingForHostPortWithoutBashThrowsAnError(t *testing.T) {1048 ctx := context.Background()1049 req := ContainerRequest{1050 Image: nginxAlpineImage,1051 ExposedPorts: []string{nginxDefaultPort},1052 WaitingFor: wait.ForListeningPort(nginxDefaultPort),1053 }1054 nginx, err := GenericContainer(ctx, GenericContainerRequest{1055 ProviderType: providerType,1056 ContainerRequest: req,1057 Started: true,1058 })1059 require.NoError(t, err)1060 terminateContainerOnEnd(t, ctx, nginx)1061}1062func TestContainerCreationWaitsForLogAndPort(t *testing.T) {1063 ctx := context.Background()1064 req := ContainerRequest{1065 Image: "docker.io/mysql:latest",1066 ExposedPorts: []string{"3306/tcp", "33060/tcp"},1067 Env: map[string]string{1068 "MYSQL_ROOT_PASSWORD": "password",1069 "MYSQL_DATABASE": "database",1070 },1071 WaitingFor: wait.ForAll(1072 wait.ForLog("port: 3306 MySQL Community Server - GPL"),1073 wait.ForListeningPort("3306/tcp"),1074 ),1075 }1076 mysqlC, err := GenericContainer(ctx, GenericContainerRequest{1077 ProviderType: providerType,1078 ContainerRequest: req,1079 Started: true,1080 })1081 require.NoError(t, err)1082 terminateContainerOnEnd(t, ctx, mysqlC)1083 host, _ := mysqlC.Host(ctx)1084 p, _ := mysqlC.MappedPort(ctx, "3306/tcp")1085 port := p.Int()1086 connectionString := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?tls=skip-verify",1087 "root", "password", host, port, "database")1088 db, err := sql.Open("mysql", connectionString)1089 if err != nil {1090 t.Fatal(err)1091 }1092 defer db.Close()1093 if err = db.Ping(); err != nil {1094 t.Errorf("error pinging db: %+v\n", err)1095 }1096}1097func TestCMD(t *testing.T) {1098 /*1099 echo a unique statement to ensure that we1100 can pass in a command to the ContainerRequest1101 and it will be run when we run the container1102 */1103 ctx := context.Background()1104 req := ContainerRequest{1105 Image: "docker.io/alpine",1106 WaitingFor: wait.ForAll(1107 wait.ForLog("command override!"),1108 ),1109 Cmd: []string{"echo", "command override!"},1110 }1111 c, err := GenericContainer(ctx, GenericContainerRequest{1112 ProviderType: providerType,1113 ContainerRequest: req,1114 Started: true,1115 })1116 require.NoError(t, err)1117 terminateContainerOnEnd(t, ctx, c)1118}1119func TestEntrypoint(t *testing.T) {1120 /*1121 echo a unique statement to ensure that we1122 can pass in an entrypoint to the ContainerRequest1123 and it will be run when we run the container1124 */1125 ctx := context.Background()1126 req := ContainerRequest{1127 Image: "docker.io/alpine",1128 WaitingFor: wait.ForAll(1129 wait.ForLog("entrypoint override!"),1130 ),1131 Entrypoint: []string{"echo", "entrypoint override!"},1132 }1133 c, err := GenericContainer(ctx, GenericContainerRequest{1134 ProviderType: providerType,1135 ContainerRequest: req,1136 Started: true,1137 })1138 require.NoError(t, err)1139 terminateContainerOnEnd(t, ctx, c)1140}1141func TestReadTCPropsFile(t *testing.T) {1142 t.Run("HOME is not set", func(t *testing.T) {1143 env.Patch(t, "HOME", "")1144 config := configureTC()1145 assert.Empty(t, config, "TC props file should not exist")1146 })1147 t.Run("HOME is not set - TESTCONTAINERS_ env is set", func(t *testing.T) {1148 env.Patch(t, "HOME", "")1149 env.Patch(t, "TESTCONTAINERS_RYUK_CONTAINER_PRIVILEGED", "true")1150 config := configureTC()1151 expected := TestContainersConfig{}1152 expected.RyukPrivileged = true1153 assert.Equal(t, expected, config)1154 })1155 t.Run("HOME does not contain TC props file", func(t *testing.T) {1156 tmpDir := fs.NewDir(t, os.TempDir())1157 env.Patch(t, "HOME", tmpDir.Path())1158 config := configureTC()1159 assert.Empty(t, config, "TC props file should not exist")1160 })1161 t.Run("HOME does not contain TC props file - TESTCONTAINERS_ env is set", func(t *testing.T) {1162 tmpDir := fs.NewDir(t, os.TempDir())1163 env.Patch(t, "HOME", tmpDir.Path())1164 env.Patch(t, "TESTCONTAINERS_RYUK_CONTAINER_PRIVILEGED", "true")1165 config := configureTC()1166 expected := TestContainersConfig{}1167 expected.RyukPrivileged = true1168 assert.Equal(t, expected, config)1169 })1170 t.Run("HOME contains TC properties file", func(t *testing.T) {1171 tests := []struct {1172 content string1173 env map[string]string1174 expected TestContainersConfig1175 }{1176 {1177 "docker.host = tcp://127.0.0.1:33293",1178 map[string]string{},1179 TestContainersConfig{1180 Host: "tcp://127.0.0.1:33293",1181 TLSVerify: 0,1182 CertPath: "",1183 },1184 },1185 {1186 "docker.host = tcp://127.0.0.1:33293",1187 map[string]string{},1188 TestContainersConfig{1189 Host: "tcp://127.0.0.1:33293",1190 TLSVerify: 0,1191 CertPath: "",1192 },1193 },1194 {1195 `docker.host = tcp://127.0.0.1:332931196 docker.host = tcp://127.0.0.1:47111197 `,1198 map[string]string{},1199 TestContainersConfig{1200 Host: "tcp://127.0.0.1:4711",1201 TLSVerify: 0,1202 CertPath: "",1203 },1204 },1205 {1206 `docker.host = tcp://127.0.0.1:332931207 docker.host = tcp://127.0.0.1:47111208 docker.host = tcp://127.0.0.1:12341209 docker.tls.verify = 11210 `,1211 map[string]string{},1212 TestContainersConfig{1213 Host: "tcp://127.0.0.1:1234",1214 TLSVerify: 1,1215 CertPath: "",1216 },1217 },1218 {1219 "",1220 map[string]string{},1221 TestContainersConfig{1222 Host: "",1223 TLSVerify: 0,1224 CertPath: "",1225 },1226 },1227 {1228 `foo = bar1229 docker.host = tcp://127.0.0.1:12341230 `,1231 map[string]string{},1232 TestContainersConfig{1233 Host: "tcp://127.0.0.1:1234",1234 TLSVerify: 0,1235 CertPath: "",1236 },1237 },1238 {1239 "docker.host=tcp://127.0.0.1:33293",1240 map[string]string{},1241 TestContainersConfig{1242 Host: "tcp://127.0.0.1:33293",1243 TLSVerify: 0,1244 CertPath: "",1245 },1246 },1247 {1248 `#docker.host=tcp://127.0.0.1:33293`,1249 map[string]string{},1250 TestContainersConfig{1251 Host: "",1252 TLSVerify: 0,1253 CertPath: "",1254 },1255 },1256 {1257 `#docker.host = tcp://127.0.0.1:332931258 docker.host = tcp://127.0.0.1:47111259 docker.host = tcp://127.0.0.1:12341260 docker.cert.path=/tmp/certs`,1261 map[string]string{},1262 TestContainersConfig{1263 Host: "tcp://127.0.0.1:1234",1264 TLSVerify: 0,1265 CertPath: "/tmp/certs",1266 },1267 },1268 {1269 `ryuk.container.privileged=true`,1270 map[string]string{},1271 TestContainersConfig{1272 Host: "",1273 TLSVerify: 0,1274 CertPath: "",1275 RyukPrivileged: true,1276 },1277 },1278 {1279 ``,1280 map[string]string{1281 "TESTCONTAINERS_RYUK_CONTAINER_PRIVILEGED": "true",1282 },1283 TestContainersConfig{1284 Host: "",1285 TLSVerify: 0,1286 CertPath: "",1287 RyukPrivileged: true,1288 },1289 },1290 {1291 `ryuk.container.privileged=true`,1292 map[string]string{1293 "TESTCONTAINERS_RYUK_CONTAINER_PRIVILEGED": "true",1294 },1295 TestContainersConfig{1296 Host: "",1297 TLSVerify: 0,1298 CertPath: "",1299 RyukPrivileged: true,1300 },1301 },1302 {1303 `ryuk.container.privileged=false`,1304 map[string]string{1305 "TESTCONTAINERS_RYUK_CONTAINER_PRIVILEGED": "true",1306 },1307 TestContainersConfig{1308 Host: "",1309 TLSVerify: 0,1310 CertPath: "",1311 RyukPrivileged: true,1312 },1313 },1314 {1315 `ryuk.container.privileged=true`,1316 map[string]string{1317 "TESTCONTAINERS_RYUK_CONTAINER_PRIVILEGED": "false",1318 },1319 TestContainersConfig{1320 Host: "",1321 TLSVerify: 0,1322 CertPath: "",1323 RyukPrivileged: false,1324 },1325 },1326 {1327 `ryuk.container.privileged=false`,1328 map[string]string{1329 "TESTCONTAINERS_RYUK_CONTAINER_PRIVILEGED": "false",1330 },1331 TestContainersConfig{1332 Host: "",1333 TLSVerify: 0,1334 CertPath: "",1335 RyukPrivileged: false,1336 },1337 },1338 {1339 `ryuk.container.privileged=false1340 docker.tls.verify = ERROR`,1341 map[string]string{1342 "TESTCONTAINERS_RYUK_CONTAINER_PRIVILEGED": "true",1343 },1344 TestContainersConfig{1345 Host: "",1346 TLSVerify: 0,1347 CertPath: "",1348 RyukPrivileged: true,1349 },1350 },1351 {1352 `ryuk.container.privileged=false`,1353 map[string]string{1354 "TESTCONTAINERS_RYUK_CONTAINER_PRIVILEGED": "foo",1355 },1356 TestContainersConfig{1357 Host: "",1358 TLSVerify: 0,1359 CertPath: "",1360 RyukPrivileged: false,1361 },1362 },1363 }1364 for i, tt := range tests {1365 t.Run(fmt.Sprintf("[%d]", i), func(t *testing.T) {1366 tmpDir := fs.NewDir(t, os.TempDir())1367 env.Patch(t, "HOME", tmpDir.Path())1368 for k, v := range tt.env {1369 env.Patch(t, k, v)1370 }1371 if err := ioutil.WriteFile(tmpDir.Join(".testcontainers.properties"), []byte(tt.content), 0o600); err != nil {1372 t.Errorf("Failed to create the file: %v", err)1373 return1374 }1375 config := configureTC()1376 assert.Equal(t, tt.expected, config, "Configuration doesn't not match")1377 })1378 }1379 })1380}1381func ExampleDockerProvider_CreateContainer() {1382 ctx := context.Background()1383 req := ContainerRequest{1384 Image: "docker.io/nginx:alpine",1385 ExposedPorts: []string{"80/tcp"},1386 WaitingFor: wait.ForHTTP("/"),1387 }1388 nginxC, _ := GenericContainer(ctx, GenericContainerRequest{1389 ContainerRequest: req,1390 Started: true,1391 })1392 defer nginxC.Terminate(ctx)1393}1394func ExampleContainer_Host() {1395 ctx := context.Background()1396 req := ContainerRequest{1397 Image: "docker.io/nginx:alpine",1398 ExposedPorts: []string{"80/tcp"},1399 WaitingFor: wait.ForHTTP("/"),1400 }1401 nginxC, _ := GenericContainer(ctx, GenericContainerRequest{1402 ContainerRequest: req,1403 Started: true,1404 })1405 defer nginxC.Terminate(ctx)1406 ip, _ := nginxC.Host(ctx)1407 println(ip)1408}1409func ExampleContainer_Start() {1410 ctx := context.Background()1411 req := ContainerRequest{1412 Image: "docker.io/nginx:alpine",1413 ExposedPorts: []string{"80/tcp"},1414 WaitingFor: wait.ForHTTP("/"),1415 }1416 nginxC, _ := GenericContainer(ctx, GenericContainerRequest{1417 ContainerRequest: req,1418 })1419 defer nginxC.Terminate(ctx)1420 _ = nginxC.Start(ctx)1421}1422func ExampleContainer_Stop() {1423 ctx := context.Background()1424 req := ContainerRequest{1425 Image: "docker.io/nginx:alpine",1426 ExposedPorts: []string{"80/tcp"},1427 WaitingFor: wait.ForHTTP("/"),1428 }1429 nginxC, _ := GenericContainer(ctx, GenericContainerRequest{1430 ContainerRequest: req,1431 })1432 defer nginxC.Terminate(ctx)1433 timeout := 10 * time.Second1434 _ = nginxC.Stop(ctx, &timeout)1435}1436func ExampleContainer_MappedPort() {1437 ctx := context.Background()1438 req := ContainerRequest{1439 Image: "docker.io/nginx:alpine",1440 ExposedPorts: []string{"80/tcp"},1441 WaitingFor: wait.ForHTTP("/"),1442 }1443 nginxC, _ := GenericContainer(ctx, GenericContainerRequest{1444 ContainerRequest: req,1445 Started: true,1446 })1447 defer nginxC.Terminate(ctx)1448 ip, _ := nginxC.Host(ctx)1449 port, _ := nginxC.MappedPort(ctx, "80")1450 _, _ = http.Get(fmt.Sprintf("http://%s:%s", ip, port.Port()))1451}1452func TestContainerCreationWithBindAndVolume(t *testing.T) {1453 absPath, err := filepath.Abs("./testresources/hello.sh")1454 if err != nil {1455 t.Fatal(err)1456 }1457 ctx, cnl := context.WithTimeout(context.Background(), 30*time.Second)1458 defer cnl()1459 // Create a Docker client.1460 dockerCli, _, _, err := NewDockerClient()1461 if err != nil {1462 t.Fatal(err)1463 }1464 // Create the volume.1465 vol, err := dockerCli.VolumeCreate(ctx, volume.VolumeCreateBody{1466 Driver: "local",...
TestContainerCreation
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 containerID, err := container.ContainerID(ctx)15 if err != nil {16 panic(err)17 }18 fmt.Println("Container ID is: ", containerID)19 containerIP, err := container.Host(ctx)20 if err != nil {21 panic(err)22 }23 fmt.Println("Container IP is: ", containerIP)24 containerPort, err := container.MappedPort(ctx, "80")25 if err != nil {26 panic(err)27 }28 fmt.Println("Container port is: ", containerPort.Int())
TestContainerCreation
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"80/tcp"},6 Cmd: []string{"top"},7 WaitingFor: wait.ForLog("listening on port 80"),8 }9 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{10 })11 if err != nil {12 panic(err)13 }14 ip, err := container.Host(ctx)15 if err != nil {16 panic(err)17 }18 port, err := container.MappedPort(ctx, "80")19 if err != nil {20 panic(err)21 }22 fmt.Printf("Container IP: %s, Port: %s", ip, port.Port())23}
TestContainerCreation
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"80/tcp"},6 WaitingFor: wait.ForLog("Serving HTTP on
TestContainerCreation
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"80/tcp"},6 WaitingFor: wait.ForListeningPort("80/tcp"),7 }
TestContainerCreation
Using AI Code Generation
1import (2func main() {3 container, err := testcontainers.GenericContainer(4 testcontainers.GenericContainerRequest{5 ContainerRequest: testcontainers.ContainerRequest{6 ExposedPorts: []string{"3306/tcp"},7 WaitingFor: wait.ForListeningPort("3306"),8 },9 },10 if err != nil {11 log.Fatal(err)12 }13 host, err := container.Host(context.Background())14 if err != nil {15 log.Fatal(err)16 }17 port, err := container.MappedPort(context.Background(), "3306")18 if err != nil {19 log.Fatal(err)20 }21 name, err := container.Name()22 if err != nil {23 log.Fatal(err)24 }25 id, err := container.ID()26 if err != nil {27 log.Fatal(err)28 }29 status, err := container.State(context.Background())30 if err != nil {31 log.Fatal(err)32 }33 network, err := container.Networks(context.Background())34 if err != nil {35 log.Fatal(err)36 }37 labels, err := container.Labels(context.Background())38 if err != nil {39 log.Fatal(err)40 }41 image, err := container.Image(context.Background())42 if err != nil {43 log.Fatal(err)44 }45 logs, err := container.Logs(context.Background())46 if err != nil {47 log.Fatal(err)48 }49 env, err := container.Env(context.Background())50 if err != nil {51 log.Fatal(err)52 }53 mounts, err := container.Mounts(context.Background())54 if err != nil {55 log.Fatal(err)56 }
TestContainerCreation
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"5432/tcp"},6 WaitingFor: wait.ForListeningPort("5432/tcp"),7 }8 postgresContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 defer postgresContainer.Terminate(ctx)14 port, err := postgresContainer.MappedPort(ctx, "5432")15 if err != nil {16 log.Fatal(err)17 }18 ip, err := postgresContainer.Host(ctx)19 if err != nil {20 log.Fatal(err)21 }22 fmt.Println(ip)23 fmt.Println(port.Int())24}
TestContainerCreation
Using AI Code Generation
1import (2func TestContainerCreation(t *testing.T) {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"9200/tcp", "9300/tcp"},6 WaitingFor: wait.ForLog("started"),7 }8 elasticContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 t.Fatal(err)12 }13 defer elasticContainer.Terminate(ctx)14 ip, err := elasticContainer.Host(ctx)15 if err != nil {16 t.Fatal(err)17 }18 port, err := elasticContainer.MappedPort(ctx, "9200")19 if err != nil {20 t.Fatal(err)21 }22", ip, port.Port())23}24import "testing"25func TestMain(m *testing.M) {26 m.Run()27}28require (
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!!