How to use TestCheck method of host Package

Best Syzkaller code snippet using host.TestCheck

resource_docker_container_test.go

Source:resource_docker_container_test.go Github

copy

Full Screen

...40 ProviderFactories: providerFactories,41 Steps: []resource.TestStep{42 {43 Config: fmt.Sprintf(loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerPrivateImage"), registry, dockerConfig, image),44 Check: resource.ComposeTestCheckFunc(45 testAccContainerRunning("docker_container.foo", &c),46 ),47 },48 },49 CheckDestroy: func(state *terraform.State) error {50 return checkAndRemoveImages(ctx, state)51 },52 })53}54func TestAccDockerContainer_basic(t *testing.T) {55 resourceName := "docker_container.foo"56 var c types.ContainerJSON57 resource.Test(t, resource.TestCase{58 PreCheck: func() { testAccPreCheck(t) },59 ProviderFactories: providerFactories,60 Steps: []resource.TestStep{61 {62 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerConfig"),63 Check: resource.ComposeTestCheckFunc(64 testAccContainerRunning(resourceName, &c),65 ),66 },67 {68 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerUpdateConfig"),69 Check: resource.ComposeTestCheckFunc(70 testAccContainerRunning(resourceName, &c),71 ),72 },73 {74 ResourceName: "docker_container.foo",75 ImportState: true,76 ImportStateVerify: true,77 ImportStateVerifyIgnore: []string{78 "attach",79 "log_driver",80 "logs",81 "must_run",82 "restart",83 "rm",84 "start",85 "container_logs",86 "destroy_grace_seconds",87 "upload",88 "remove_volumes",89 "init",90 // TODO mavogel: Will be done in #74 (import resources)91 "volumes",92 "network_alias",93 "networks",94 "network_advanced",95 "container_read_refresh_timeout_milliseconds",96 },97 },98 },99 })100}101func TestAccDockerContainer_init(t *testing.T) {102 resourceName := "docker_container.fooinit"103 var c types.ContainerJSON104 resource.Test(t, resource.TestCase{105 PreCheck: func() { testAccPreCheck(t) },106 ProviderFactories: providerFactories,107 Steps: []resource.TestStep{108 {109 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerInitConfig"),110 Check: resource.ComposeTestCheckFunc(111 testAccContainerRunning(resourceName, &c),112 ),113 },114 {115 ResourceName: "docker_container.fooinit",116 ImportState: true,117 ImportStateVerify: true,118 ImportStateVerifyIgnore: []string{119 "attach",120 "log_driver",121 "logs",122 "must_run",123 "restart",124 "rm",125 "start",126 "container_logs",127 "destroy_grace_seconds",128 "upload",129 "remove_volumes",130 // TODO mavogel: Will be done in #74 (import resources)131 "volumes",132 "network_alias",133 "networks",134 "network_advanced",135 "container_read_refresh_timeout_milliseconds",136 },137 },138 },139 })140}141func TestAccDockerContainer_basic_network(t *testing.T) {142 var c types.ContainerJSON143 resource.Test(t, resource.TestCase{144 PreCheck: func() { testAccPreCheck(t) },145 ProviderFactories: providerFactories,146 Steps: []resource.TestStep{147 {148 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerWith2BridgeNetworkConfig"),149 Check: resource.ComposeTestCheckFunc(150 testAccContainerRunning("docker_container.foo", &c),151 resource.TestCheckResourceAttr("docker_container.foo", "bridge", ""),152 resource.TestCheckResourceAttrSet("docker_container.foo", "ip_address"),153 resource.TestCheckResourceAttrSet("docker_container.foo", "ip_prefix_length"),154 resource.TestCheckResourceAttrSet("docker_container.foo", "gateway"),155 resource.TestCheckResourceAttr("docker_container.foo", "network_data.#", "2"),156 resource.TestCheckResourceAttrSet("docker_container.foo", "network_data.0.network_name"),157 resource.TestCheckResourceAttrSet("docker_container.foo", "network_data.0.ip_address"),158 resource.TestCheckResourceAttrSet("docker_container.foo", "network_data.0.ip_prefix_length"),159 resource.TestCheckResourceAttrSet("docker_container.foo", "network_data.0.gateway"),160 resource.TestCheckResourceAttrSet("docker_container.foo", "network_data.1.network_name"),161 resource.TestCheckResourceAttrSet("docker_container.foo", "network_data.1.ip_address"),162 resource.TestCheckResourceAttrSet("docker_container.foo", "network_data.1.ip_prefix_length"),163 resource.TestCheckResourceAttrSet("docker_container.foo", "network_data.1.gateway"),164 ),165 },166 },167 })168}169func TestAccDockerContainer_2networks_withmode(t *testing.T) {170 var c types.ContainerJSON171 resource.Test(t, resource.TestCase{172 PreCheck: func() { testAccPreCheck(t) },173 ProviderFactories: providerFactories,174 Steps: []resource.TestStep{175 {176 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainer2NetworksConfig"),177 Check: resource.ComposeTestCheckFunc(178 testAccContainerRunning("docker_container.foo", &c),179 resource.TestCheckResourceAttr("docker_container.foo", "bridge", ""),180 resource.TestCheckResourceAttrSet("docker_container.foo", "ip_address"),181 resource.TestCheckResourceAttrSet("docker_container.foo", "ip_prefix_length"),182 resource.TestCheckResourceAttrSet("docker_container.foo", "gateway"),183 resource.TestCheckResourceAttr("docker_container.foo", "network_data.#", "2"),184 resource.TestCheckResourceAttrSet("docker_container.foo", "network_data.0.network_name"),185 resource.TestCheckResourceAttrSet("docker_container.foo", "network_data.0.ip_address"),186 resource.TestCheckResourceAttrSet("docker_container.foo", "network_data.0.ip_prefix_length"),187 resource.TestCheckResourceAttrSet("docker_container.foo", "network_data.0.gateway"),188 resource.TestCheckResourceAttrSet("docker_container.foo", "network_data.1.network_name"),189 resource.TestCheckResourceAttrSet("docker_container.foo", "network_data.1.ip_address"),190 resource.TestCheckResourceAttrSet("docker_container.foo", "network_data.1.ip_prefix_length"),191 resource.TestCheckResourceAttrSet("docker_container.foo", "network_data.1.gateway"),192 resource.TestCheckResourceAttr("docker_container.bar", "network_alias.#", "1"),193 resource.TestCheckResourceAttr("docker_container.bar", "bridge", ""),194 resource.TestCheckResourceAttrSet("docker_container.bar", "ip_address"),195 resource.TestCheckResourceAttrSet("docker_container.bar", "ip_prefix_length"),196 resource.TestCheckResourceAttrSet("docker_container.bar", "gateway"),197 resource.TestCheckResourceAttr("docker_container.bar", "network_data.#", "1"),198 resource.TestCheckResourceAttrSet("docker_container.bar", "network_data.0.network_name"),199 resource.TestCheckResourceAttrSet("docker_container.bar", "network_data.0.ip_address"),200 resource.TestCheckResourceAttrSet("docker_container.bar", "network_data.0.ip_prefix_length"),201 resource.TestCheckResourceAttrSet("docker_container.bar", "network_data.0.gateway"),202 ),203 },204 },205 })206}207func TestAccDockerContainer_volume(t *testing.T) {208 var c types.ContainerJSON209 testCheck := func(*terraform.State) error {210 if len(c.Mounts) != 1 {211 return fmt.Errorf("Incorrect number of mounts: expected 1, got %d", len(c.Mounts))212 }213 for _, v := range c.Mounts {214 if v.Name != "testAccDockerContainerVolume_volume" {215 continue216 }217 if v.Destination != "/tmp/volume" {218 return fmt.Errorf("Bad destination on mount: expected /tmp/volume, got %q", v.Destination)219 }220 if v.Mode != "rw" {221 return fmt.Errorf("Bad mode on mount: expected rw, got %q", v.Mode)222 }223 return nil224 }225 return fmt.Errorf("Mount for testAccDockerContainerVolume_volume not found")226 }227 resource.Test(t, resource.TestCase{228 PreCheck: func() { testAccPreCheck(t) },229 ProviderFactories: providerFactories,230 Steps: []resource.TestStep{231 {232 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerVolumeConfig"),233 Check: resource.ComposeTestCheckFunc(234 testAccContainerRunning("docker_container.foo", &c),235 testCheck,236 ),237 },238 },239 })240}241func TestAccDockerContainer_mounts(t *testing.T) {242 var c types.ContainerJSON243 testCheck := func(*terraform.State) error {244 if len(c.Mounts) != 2 {245 return fmt.Errorf("Incorrect number of mounts: expected 2, got %d", len(c.Mounts))246 }247 for _, v := range c.Mounts {248 if v.Destination != "/mount/test" && v.Destination != "/mount/tmpfs" {249 return fmt.Errorf("Bad destination on mount: expected /mount/test or /mount/tmpfs, got %q", v.Destination)250 }251 }252 return nil253 }254 resource.Test(t, resource.TestCase{255 PreCheck: func() { testAccPreCheck(t) },256 ProviderFactories: providerFactories,257 Steps: []resource.TestStep{258 {259 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerMountsConfig"),260 Check: resource.ComposeTestCheckFunc(261 testAccContainerRunning("docker_container.foo_mounts", &c),262 testCheck,263 ),264 },265 },266 })267}268func TestAccDockerContainer_tmpfs(t *testing.T) {269 var c types.ContainerJSON270 testCheck := func(*terraform.State) error {271 if len(c.HostConfig.Tmpfs) != 1 {272 return fmt.Errorf("Incorrect number of tmpfs: expected 1, got %d", len(c.HostConfig.Tmpfs))273 }274 for mountPath := range c.HostConfig.Tmpfs {275 if mountPath != "/mount/tmpfs" {276 return fmt.Errorf("Bad destination on tmpfs: expected /mount/tmpfs, got %q", mountPath)277 }278 }279 return nil280 }281 resource.Test(t, resource.TestCase{282 PreCheck: func() { testAccPreCheck(t) },283 ProviderFactories: providerFactories,284 Steps: []resource.TestStep{285 {286 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerTmpfsConfig"),287 Check: resource.ComposeTestCheckFunc(288 testAccContainerRunning("docker_container.foo", &c),289 testCheck,290 ),291 },292 },293 })294}295func TestAccDockerContainer_sysctls(t *testing.T) {296 var c types.ContainerJSON297 testCheck := func(*terraform.State) error {298 if len(c.HostConfig.Sysctls) != 1 {299 return fmt.Errorf("Incorrect number of sysctls: expected 1, got %d", len(c.HostConfig.Sysctls))300 }301 if ctl, ok := c.HostConfig.Sysctls["net.ipv4.ip_forward"]; ok {302 if ctl != "1" {303 return fmt.Errorf("Bad value for sysctl net.ipv4.ip_forward: expected 1, got %s", ctl)304 }305 } else {306 return fmt.Errorf("net.ipv4.ip_forward not found in Sysctls")307 }308 return nil309 }310 resource.Test(t, resource.TestCase{311 PreCheck: func() { testAccPreCheck(t) },312 ProviderFactories: providerFactories,313 Steps: []resource.TestStep{314 {315 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerSysctlsConfig"),316 Check: resource.ComposeTestCheckFunc(317 testAccContainerRunning("docker_container.foo", &c),318 testCheck,319 ),320 },321 },322 })323}324func TestAccDockerContainer_groupadd_id(t *testing.T) {325 var c types.ContainerJSON326 testCheck := func(*terraform.State) error {327 if len(c.HostConfig.GroupAdd) != 1 || c.HostConfig.GroupAdd[0] != "100" {328 return fmt.Errorf("Wrong group add: %s", c.HostConfig.GroupAdd)329 }330 return nil331 }332 resource.Test(t, resource.TestCase{333 PreCheck: func() { testAccPreCheck(t) },334 ProviderFactories: providerFactories,335 Steps: []resource.TestStep{336 {337 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerGroupAddIdConfig"),338 Check: resource.ComposeTestCheckFunc(339 testAccContainerRunning("docker_container.foo", &c),340 testCheck,341 ),342 },343 },344 })345}346func TestAccDockerContainer_groupadd_name(t *testing.T) {347 var c types.ContainerJSON348 testCheck := func(*terraform.State) error {349 if len(c.HostConfig.GroupAdd) != 1 || c.HostConfig.GroupAdd[0] != "users" {350 return fmt.Errorf("Wrong group add: %s", c.HostConfig.GroupAdd)351 }352 return nil353 }354 resource.Test(t, resource.TestCase{355 PreCheck: func() { testAccPreCheck(t) },356 ProviderFactories: providerFactories,357 Steps: []resource.TestStep{358 {359 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerGroupAddNameConfig"),360 Check: resource.ComposeTestCheckFunc(361 testAccContainerRunning("docker_container.foo", &c),362 testCheck,363 ),364 },365 },366 })367}368func TestAccDockerContainer_groupadd_multiple(t *testing.T) {369 var c types.ContainerJSON370 testCheck := func(*terraform.State) error {371 if len(c.HostConfig.GroupAdd) != 3 {372 return fmt.Errorf("Wrong group add: %s", c.HostConfig.GroupAdd)373 }374 return nil375 }376 resource.Test(t, resource.TestCase{377 PreCheck: func() { testAccPreCheck(t) },378 ProviderFactories: providerFactories,379 Steps: []resource.TestStep{380 {381 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerGroupAddMultipleConfig"),382 Check: resource.ComposeTestCheckFunc(383 testAccContainerRunning("docker_container.foo", &c),384 testCheck,385 ),386 },387 },388 })389}390func TestAccDockerContainer_tty(t *testing.T) {391 var c types.ContainerJSON392 testCheck := func(*terraform.State) error {393 if !c.Config.Tty {394 return fmt.Errorf("Tty not enabled")395 }396 return nil397 }398 resource.Test(t, resource.TestCase{399 PreCheck: func() { testAccPreCheck(t) },400 ProviderFactories: providerFactories,401 Steps: []resource.TestStep{402 {403 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerTTYConfig"),404 Check: resource.ComposeTestCheckFunc(405 testAccContainerRunning("docker_container.foo", &c),406 testCheck,407 ),408 },409 },410 })411}412func TestAccDockerContainer_STDIN_Enabled(t *testing.T) {413 var c types.ContainerJSON414 testCheck := func(*terraform.State) error {415 if !c.Config.OpenStdin {416 return fmt.Errorf("STDIN not enabled")417 }418 return nil419 }420 resource.Test(t, resource.TestCase{421 PreCheck: func() { testAccPreCheck(t) },422 ProviderFactories: providerFactories,423 Steps: []resource.TestStep{424 {425 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerSTDIN_Config"),426 Check: resource.ComposeTestCheckFunc(427 testAccContainerRunning("docker_container.foo", &c),428 testCheck,429 ),430 },431 },432 })433}434func TestAccDockerContainer_customized(t *testing.T) {435 var c types.ContainerJSON436 testCheck := func(*terraform.State) error {437 if len(c.Config.Entrypoint) < 3 ||438 (c.Config.Entrypoint[0] != "/bin/bash" &&439 c.Config.Entrypoint[1] != "-c" &&440 c.Config.Entrypoint[2] != "ping localhost") {441 return fmt.Errorf("Container wrong entrypoint: %s", c.Config.Entrypoint)442 }443 if c.Config.User != "root:root" {444 return fmt.Errorf("Container wrong user: %s", c.Config.User)445 }446 if c.HostConfig.RestartPolicy.Name == "on-failure" {447 if c.HostConfig.RestartPolicy.MaximumRetryCount != 5 {448 return fmt.Errorf("Container has wrong restart policy max retry count: %d", c.HostConfig.RestartPolicy.MaximumRetryCount)449 }450 } else {451 return fmt.Errorf("Container has wrong restart policy: %s", c.HostConfig.RestartPolicy.Name)452 }453 if c.HostConfig.Memory != (512 * 1024 * 1024) {454 return fmt.Errorf("Container has wrong memory setting: %d", c.HostConfig.Memory)455 }456 if c.HostConfig.MemorySwap != (2048 * 1024 * 1024) {457 return fmt.Errorf("Container has wrong memory swap setting: %d\n\r\tPlease check that you machine supports memory swap (you can do that by running 'docker info' command).", c.HostConfig.MemorySwap)458 }459 if c.HostConfig.ShmSize != (128 * 1024 * 1024) {460 return fmt.Errorf("Container has wrong shared memory setting: %d", c.HostConfig.ShmSize)461 }462 if c.HostConfig.CPUShares != 32 {463 return fmt.Errorf("Container has wrong cpu shares setting: %d", c.HostConfig.CPUShares)464 }465 if c.HostConfig.CpusetCpus != "0-1" {466 return fmt.Errorf("Container has wrong cpu set setting: %s", c.HostConfig.CpusetCpus)467 }468 if len(c.HostConfig.DNS) != 1 {469 return fmt.Errorf("Container does not have the correct number of dns entries: %d", len(c.HostConfig.DNS))470 }471 if c.HostConfig.DNS[0] != "8.8.8.8" {472 return fmt.Errorf("Container has wrong dns setting: %v", c.HostConfig.DNS[0])473 }474 if len(c.HostConfig.DNSOptions) != 1 {475 return fmt.Errorf("Container does not have the correct number of dns option entries: %d", len(c.HostConfig.DNS))476 }477 if c.HostConfig.DNSOptions[0] != "rotate" {478 return fmt.Errorf("Container has wrong dns option setting: %v", c.HostConfig.DNS[0])479 }480 if len(c.HostConfig.DNSSearch) != 1 {481 return fmt.Errorf("Container does not have the correct number of dns search entries: %d", len(c.HostConfig.DNS))482 }483 if c.HostConfig.DNSSearch[0] != "example.com" {484 return fmt.Errorf("Container has wrong dns search setting: %v", c.HostConfig.DNS[0])485 }486 if len(c.HostConfig.CapAdd) != 1 {487 return fmt.Errorf("Container does not have the correct number of Capabilities in ADD: %d", len(c.HostConfig.CapAdd))488 }489 if c.HostConfig.CapAdd[0] != "ALL" {490 return fmt.Errorf("Container has wrong CapAdd setting: %v", c.HostConfig.CapAdd[0])491 }492 if len(c.HostConfig.CapDrop) != 1 {493 return fmt.Errorf("Container does not have the correct number of Capabilities in Drop: %d", len(c.HostConfig.CapDrop))494 }495 if c.HostConfig.CapDrop[0] != "SYS_ADMIN" {496 return fmt.Errorf("Container has wrong CapDrop setting: %v", c.HostConfig.CapDrop[0])497 }498 if c.HostConfig.CPUShares != 32 {499 return fmt.Errorf("Container has wrong cpu shares setting: %d", c.HostConfig.CPUShares)500 }501 if c.HostConfig.CPUShares != 32 {502 return fmt.Errorf("Container has wrong cpu shares setting: %d", c.HostConfig.CPUShares)503 }504 if c.Config.Labels["env"] != "prod" || c.Config.Labels["role"] != "test" {505 return fmt.Errorf("Container does not have the correct labels")506 }507 if c.HostConfig.LogConfig.Type != "json-file" {508 return fmt.Errorf("Container does not have the correct log config: %s", c.HostConfig.LogConfig.Type)509 }510 if c.HostConfig.LogConfig.Config["max-size"] != "10m" {511 return fmt.Errorf("Container does not have the correct max-size log option: %v", c.HostConfig.LogConfig.Config["max-size"])512 }513 if c.HostConfig.LogConfig.Config["max-file"] != "20" {514 return fmt.Errorf("Container does not have the correct max-file log option: %v", c.HostConfig.LogConfig.Config["max-file"])515 }516 if len(c.HostConfig.ExtraHosts) != 2 {517 return fmt.Errorf("Container does not have correct number of extra host entries, got %d", len(c.HostConfig.ExtraHosts))518 }519 if c.HostConfig.ExtraHosts[0] != "testhost:10.0.1.0" {520 return fmt.Errorf("Container has incorrect extra host string at 0: %q", c.HostConfig.ExtraHosts[0])521 }522 if c.HostConfig.ExtraHosts[1] != "testhost2:10.0.2.0" {523 return fmt.Errorf("Container has incorrect extra host string at 1: %q", c.HostConfig.ExtraHosts[1])524 }525 if _, ok := c.NetworkSettings.Networks["test"]; !ok {526 return fmt.Errorf("Container is not connected to the right user defined network: test")527 }528 if len(c.HostConfig.Ulimits) != 2 {529 return fmt.Errorf("Container doesn't have 2 ulimits")530 }531 if c.HostConfig.Ulimits[1].Name != "nproc" {532 return fmt.Errorf("Container doesn't have a nproc ulimit")533 }534 if c.HostConfig.Ulimits[1].Hard != 1024 {535 return fmt.Errorf("Container doesn't have a correct nproc hard limit")536 }537 if c.HostConfig.Ulimits[1].Soft != 512 {538 return fmt.Errorf("Container doesn't have a correct mem nproc limit")539 }540 if c.HostConfig.Ulimits[0].Name != "nofile" {541 return fmt.Errorf("Container doesn't have a nofile ulimit")542 }543 if c.HostConfig.Ulimits[0].Hard != 262144 {544 return fmt.Errorf("Container doesn't have a correct nofile hard limit")545 }546 if c.HostConfig.Ulimits[0].Soft != 200000 {547 return fmt.Errorf("Container doesn't have a correct nofile soft limit")548 }549 if c.HostConfig.PidMode != "host" {550 return fmt.Errorf("Container doesn't have a correct pid mode")551 }552 if c.HostConfig.UsernsMode != "testuser:231072:65536" {553 return fmt.Errorf("Container doesn't have a correct userns mode")554 }555 if c.Config.WorkingDir != "/tmp" {556 return fmt.Errorf("Container doesn't have a correct working dir")557 }558 if c.HostConfig.IpcMode != "private" {559 return fmt.Errorf("Container doesn't have a correct ipc mode")560 }561 // Disabled for tests due to562 // --storage-opt is supported only for overlay over xfs with 'pquota' mount option563 // see https://github.com/kreuzwerker/terraform-provider-docker/issues/177564 // if c.HostConfig.StorageOpt["size"] != "100Mi" {565 // return fmt.Errorf("Container does not have the correct size storage option: %v", c.HostConfig.StorageOpt["size"])566 // }567 return nil568 }569 resource.Test(t, resource.TestCase{570 PreCheck: func() { testAccPreCheck(t); testAccCheckSwapLimit(t) },571 ProviderFactories: providerFactories,572 Steps: []resource.TestStep{573 {574 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerCustomizedConfig"),575 Check: resource.ComposeTestCheckFunc(576 testAccContainerRunning("docker_container.foo", &c),577 testCheck,578 testCheckLabelMap("docker_container.foo", "labels", map[string]string{"env": "prod", "role": "test", "maintainer": "NGINX Docker Maintainers <docker-maint@nginx.com>"}),579 ),580 },581 },582 })583}584func testAccCheckSwapLimit(t *testing.T) {585 ctx := context.Background()586 client := testAccProvider.Meta().(*ProviderConfig).DockerClient587 info, err := client.Info(ctx)588 if err != nil {589 t.Fatalf("Failed to check swap limit capability: %s", err)590 }591 if !info.SwapLimit {592 t.Skip("Swap limit capability not available, skipping test")593 }594}595func TestAccDockerContainer_upload(t *testing.T) {596 var c types.ContainerJSON597 ctx := context.Background()598 testCheck := func(*terraform.State) error {599 client := testAccProvider.Meta().(*ProviderConfig).DockerClient600 srcPath := "/terraform/test.txt"601 r, _, err := client.CopyFromContainer(ctx, c.ID, srcPath)602 if err != nil {603 return fmt.Errorf("Unable to download a file from container: %s", err)604 }605 tr := tar.NewReader(r)606 if header, err := tr.Next(); err != nil {607 return fmt.Errorf("Unable to read content of tar archive: %s", err)608 } else {609 mode := strconv.FormatInt(header.Mode, 8)610 if !strings.HasSuffix(mode, "744") {611 return fmt.Errorf("File permissions are incorrect: %s", mode)612 }613 }614 fbuf := new(bytes.Buffer)615 if _, err := fbuf.ReadFrom(tr); err != nil {616 return err617 }618 content := fbuf.String()619 if content != "foo" {620 return fmt.Errorf("file content is invalid")621 }622 return nil623 }624 resource.Test(t, resource.TestCase{625 PreCheck: func() { testAccPreCheck(t) },626 ProviderFactories: providerFactories,627 Steps: []resource.TestStep{628 {629 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerUploadConfig"),630 Check: resource.ComposeTestCheckFunc(631 testAccContainerRunning("docker_container.foo", &c),632 testCheck,633 resource.TestCheckResourceAttr("docker_container.foo", "name", "tf-test"),634 resource.TestCheckResourceAttr("docker_container.foo", "upload.#", "1"),635 resource.TestCheckResourceAttr("docker_container.foo", "upload.0.content", "foo"),636 resource.TestCheckResourceAttr("docker_container.foo", "upload.0.content_base64", ""),637 resource.TestCheckResourceAttr("docker_container.foo", "upload.0.executable", "true"),638 resource.TestCheckResourceAttr("docker_container.foo", "upload.0.file", "/terraform/test.txt"),639 ),640 },641 },642 })643}644func TestAccDockerContainer_uploadSource(t *testing.T) {645 var c types.ContainerJSON646 ctx := context.Background()647 wd, _ := os.Getwd()648 testFile := strings.ReplaceAll(filepath.Join(wd, "..", "..", "scripts", "testing", "testingFile"), "\\", "\\\\")649 testFileContent, _ := ioutil.ReadFile(testFile)650 testCheck := func(*terraform.State) error {651 client := testAccProvider.Meta().(*ProviderConfig).DockerClient652 srcPath := "/terraform/test.txt"653 r, _, err := client.CopyFromContainer(ctx, c.ID, srcPath)654 if err != nil {655 return fmt.Errorf("Unable to download a file from container: %s", err)656 }657 tr := tar.NewReader(r)658 if header, err := tr.Next(); err != nil {659 return fmt.Errorf("Unable to read content of tar archive: %s", err)660 } else {661 mode := strconv.FormatInt(header.Mode, 8)662 if !strings.HasSuffix(mode, "744") {663 return fmt.Errorf("File permissions are incorrect: %s", mode)664 }665 }666 fbuf := new(bytes.Buffer)667 if _, err := fbuf.ReadFrom(tr); err != nil {668 return err669 }670 content := fbuf.String()671 if content != string(testFileContent) {672 return fmt.Errorf("file content is invalid")673 }674 // we directly exec the container and print the creation timestamp675 // which is easier to use the native docker sdk, by creating, running and attaching a reader to the command.676 execReponse, err := exec.Command("docker", "exec", "-t", "tf-test", "find", "/terraform", "-maxdepth", "1", "-name", "test.txt", "-printf", "%CY-%Cm-%Cd").Output()677 if err != nil {678 return fmt.Errorf("Unable to exec command: %s", err)679 }680 fileCreationTime, err := time.Parse("2006-01-02", string(execReponse))681 if err != nil {682 return fmt.Errorf("Unable to parse file creation time into format: %s", err)683 }684 if fileCreationTime.IsZero() {685 return fmt.Errorf("file creation time is zero: %s", err)686 }687 return nil688 }689 resource.Test(t, resource.TestCase{690 PreCheck: func() { testAccPreCheck(t) },691 ProviderFactories: providerFactories,692 Steps: []resource.TestStep{693 {694 Config: fmt.Sprintf(loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerUploadSourceConfig"), testFile),695 Check: resource.ComposeTestCheckFunc(696 testAccContainerRunning("docker_container.foo", &c),697 testCheck,698 resource.TestCheckResourceAttr("docker_container.foo", "name", "tf-test"),699 resource.TestCheckResourceAttr("docker_container.foo", "upload.#", "1"),700 // TODO mavogel: should be content of the source be written to this attribute?701 // resource.TestCheckResourceAttr("docker_container.foo", "upload.0.content", "foo"),702 resource.TestCheckResourceAttr("docker_container.foo", "upload.0.content_base64", ""),703 resource.TestCheckResourceAttr("docker_container.foo", "upload.0.executable", "true"),704 resource.TestCheckResourceAttr("docker_container.foo", "upload.0.file", "/terraform/test.txt"),705 ),706 },707 },708 })709}710func TestAccDockerContainer_uploadSourceHash(t *testing.T) {711 var c types.ContainerJSON712 var firstRunId string713 wd, _ := os.Getwd()714 testFile := strings.ReplaceAll(filepath.Join(wd, "..", "..", "scripts", "testing", "testingFile"), "\\", "\\\\")715 hash, _ := ioutil.ReadFile(testFile + ".base64")716 grabFirstCheck := func(*terraform.State) error {717 firstRunId = c.ID718 return nil719 }720 testCheck := func(*terraform.State) error {721 if c.ID == firstRunId {722 return fmt.Errorf("Container should have been recreated due to changed hash")723 }724 return nil725 }726 resource.Test(t, resource.TestCase{727 PreCheck: func() { testAccPreCheck(t) },728 ProviderFactories: providerFactories,729 Steps: []resource.TestStep{730 {731 Config: fmt.Sprintf(loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerUploadSourceHashConfig"), testFile, string(hash)),732 Check: resource.ComposeTestCheckFunc(733 testAccContainerRunning("docker_container.foo", &c),734 grabFirstCheck,735 resource.TestCheckResourceAttr("docker_container.foo", "name", "tf-test"),736 resource.TestCheckResourceAttr("docker_container.foo", "upload.#", "1"),737 ),738 },739 {740 Config: fmt.Sprintf(loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerUploadSourceHashConfig"), testFile, string(hash)+"arbitrary"),741 Check: resource.ComposeTestCheckFunc(742 testAccContainerRunning("docker_container.foo", &c),743 testCheck,744 resource.TestCheckResourceAttr("docker_container.foo", "name", "tf-test"),745 resource.TestCheckResourceAttr("docker_container.foo", "upload.#", "1"),746 ),747 },748 },749 })750}751func TestAccDockerContainer_uploadAsBase64(t *testing.T) {752 var c types.ContainerJSON753 ctx := context.Background()754 testCheck := func(srcPath, wantedContent, filePerm string) func(*terraform.State) error {755 return func(*terraform.State) error {756 client := testAccProvider.Meta().(*ProviderConfig).DockerClient757 r, _, err := client.CopyFromContainer(ctx, c.ID, srcPath)758 if err != nil {759 return fmt.Errorf("Unable to download a file from container: %s", err)760 }761 tr := tar.NewReader(r)762 if header, err := tr.Next(); err != nil {763 return fmt.Errorf("Unable to read content of tar archive: %s", err)764 } else {765 mode := strconv.FormatInt(header.Mode, 8)766 if !strings.HasSuffix(mode, filePerm) {767 return fmt.Errorf("File permissions are incorrect: %s", mode)768 }769 }770 fbuf := new(bytes.Buffer)771 if _, err := fbuf.ReadFrom(tr); err != nil {772 return err773 }774 gotContent := fbuf.String()775 if wantedContent != gotContent {776 return fmt.Errorf("file content is invalid: want: %q, got: %q", wantedContent, gotContent)777 }778 return nil779 }780 }781 resource.Test(t, resource.TestCase{782 PreCheck: func() { testAccPreCheck(t) },783 ProviderFactories: providerFactories,784 Steps: []resource.TestStep{785 {786 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerUploadBase64Config"),787 Check: resource.ComposeTestCheckFunc(788 testAccContainerRunning("docker_container.foo", &c),789 // DevSkim: ignore DS173237790 testCheck("/terraform/test1.txt", "894fc3f56edf2d3a4c5fb5cb71df910f958a2ed8", "744"),791 testCheck("/terraform/test2.txt", "foobar", "100644"),792 resource.TestCheckResourceAttr("docker_container.foo", "name", "tf-test"),793 resource.TestCheckResourceAttr("docker_container.foo", "upload.#", "2"),794 resource.TestCheckResourceAttr("docker_container.foo", "upload.0.content", ""),795 resource.TestCheckResourceAttr("docker_container.foo", "upload.0.content_base64", "ODk0ZmMzZjU2ZWRmMmQzYTRjNWZiNWNiNzFkZjkxMGY5NThhMmVkOA=="),796 resource.TestCheckResourceAttr("docker_container.foo", "upload.0.executable", "true"),797 resource.TestCheckResourceAttr("docker_container.foo", "upload.0.file", "/terraform/test1.txt"),798 // TODO mavogel: should be content of the source be written to this attribute?799 // resource.TestCheckResourceAttr("docker_container.foo", "upload.1.content", "foo"),800 resource.TestCheckResourceAttr("docker_container.foo", "upload.1.content_base64", ""),801 resource.TestCheckResourceAttr("docker_container.foo", "upload.1.executable", "false"),802 resource.TestCheckResourceAttr("docker_container.foo", "upload.1.file", "/terraform/test2.txt"),803 ),804 },805 // We add a second on purpose to detect if there is a dirty plan806 // although the file content did not change807 {808 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerUploadBase64Config"),809 Check: resource.ComposeTestCheckFunc(810 testAccContainerRunning("docker_container.foo", &c),811 // DevSkim: ignore DS173237812 testCheck("/terraform/test1.txt", "894fc3f56edf2d3a4c5fb5cb71df910f958a2ed8", "744"),813 testCheck("/terraform/test2.txt", "foobar", "100644"),814 resource.TestCheckResourceAttr("docker_container.foo", "name", "tf-test"),815 resource.TestCheckResourceAttr("docker_container.foo", "upload.#", "2"),816 resource.TestCheckResourceAttr("docker_container.foo", "upload.0.content", ""),817 resource.TestCheckResourceAttr("docker_container.foo", "upload.0.content_base64", "ODk0ZmMzZjU2ZWRmMmQzYTRjNWZiNWNiNzFkZjkxMGY5NThhMmVkOA=="),818 resource.TestCheckResourceAttr("docker_container.foo", "upload.0.executable", "true"),819 resource.TestCheckResourceAttr("docker_container.foo", "upload.0.file", "/terraform/test1.txt"),820 // TODO mavogel: should be content of the source be written to this attribute?821 // resource.TestCheckResourceAttr("docker_container.foo", "upload.1.content", "foo"),822 resource.TestCheckResourceAttr("docker_container.foo", "upload.1.content_base64", ""),823 resource.TestCheckResourceAttr("docker_container.foo", "upload.1.executable", "false"),824 resource.TestCheckResourceAttr("docker_container.foo", "upload.1.file", "/terraform/test2.txt"),825 ),826 },827 },828 })829}830func TestAccDockerContainer_multipleUploadContentsConfig(t *testing.T) {831 resource.Test(t, resource.TestCase{832 PreCheck: func() { testAccPreCheck(t) },833 ProviderFactories: providerFactories,834 Steps: []resource.TestStep{835 {836 Config: `837 resource "docker_image" "foo" {838 name = "nginx:latest"839 keep_locally = true840 }841 842 resource "docker_container" "foo" {843 name = "tf-test"844 image = docker_image.foo.image_id845 must_run = "false"846 847 upload {848 content = "foobar"849 content_base64 = base64encode("barbaz")850 file = "/terraform/test1.txt"851 executable = true852 }853 }854 `,855 ExpectError: regexp.MustCompile(`.*only one of 'content', 'content_base64', or 'source' can be set.*`),856 },857 },858 })859}860func TestAccDockerContainer_noUploadContentsConfig(t *testing.T) {861 resource.Test(t, resource.TestCase{862 PreCheck: func() { testAccPreCheck(t) },863 ProviderFactories: providerFactories,864 Steps: []resource.TestStep{865 {866 Config: `867 resource "docker_image" "foo" {868 name = "nginx:latest"869 keep_locally = true870 }871 872 resource "docker_container" "foo" {873 name = "tf-test"874 image = docker_image.foo.image_id875 must_run = "false"876 877 upload {878 file = "/terraform/test1.txt"879 executable = true880 }881 }882 `,883 ExpectError: regexp.MustCompile(`.* one of 'content', 'content_base64', or 'source' must be set.*`),884 },885 },886 })887}888func TestAccDockerContainer_device(t *testing.T) {889 var c types.ContainerJSON890 ctx := context.Background()891 testCheck := func(*terraform.State) error {892 client := testAccProvider.Meta().(*ProviderConfig).DockerClient893 createExecOpts := types.ExecConfig{894 Cmd: []string{"dd", "if=/dev/zero_test", "of=/tmp/test.txt", "count=10", "bs=1"},895 }896 exec, err := client.ContainerExecCreate(ctx, c.ID, createExecOpts)897 if err != nil {898 return fmt.Errorf("Unable to create a exec instance on container: %s", err)899 }900 startExecOpts := types.ExecStartCheck{}901 if err := client.ContainerExecStart(ctx, exec.ID, startExecOpts); err != nil {902 return fmt.Errorf("Unable to run exec a instance on container: %s", err)903 }904 srcPath := "/tmp/test.txt"905 out, _, err := client.CopyFromContainer(ctx, c.ID, srcPath)906 if err != nil {907 return fmt.Errorf("Unable to download a file from container: %s", err)908 }909 tr := tar.NewReader(out)910 if _, err := tr.Next(); err != nil {911 return fmt.Errorf("Unable to read content of tar archive: %s", err)912 }913 fbuf := new(bytes.Buffer)914 if _, err := fbuf.ReadFrom(tr); err != nil {915 return err916 }917 content := fbuf.Bytes()918 if len(content) != 10 {919 return fmt.Errorf("Incorrect size of file: %d", len(content))920 }921 for _, value := range content {922 if value != 0 {923 return fmt.Errorf("Incorrect content in file: %v", content)924 }925 }926 return nil927 }928 resource.Test(t, resource.TestCase{929 PreCheck: func() { testAccPreCheck(t) },930 ProviderFactories: providerFactories,931 Steps: []resource.TestStep{932 {933 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerDeviceConfig"),934 Check: resource.ComposeTestCheckFunc(935 testAccContainerRunning("docker_container.foo", &c),936 testCheck,937 ),938 },939 },940 })941}942func TestAccDockerContainer_port_internal(t *testing.T) {943 var c types.ContainerJSON944 testCheck := func(*terraform.State) error {945 portMap := c.NetworkSettings.NetworkSettingsBase.Ports946 portBindings, ok := portMap["80/tcp"]947 if !ok || len(portMap["80/tcp"]) == 0 {948 return fmt.Errorf("Port 80 on tcp is not set")949 }950 portBindingsLength := len(portBindings)951 if portBindingsLength != 1 {952 return fmt.Errorf("Expected 1 binding on port 80, but was %d", portBindingsLength)953 }954 if len(portBindings[0].HostIP) == 0 {955 return fmt.Errorf("Expected host IP to be set, but was empty")956 }957 if len(portBindings[0].HostPort) == 0 {958 return fmt.Errorf("Expected host port to be set, but was empty")959 }960 return nil961 }962 resource.Test(t, resource.TestCase{963 PreCheck: func() { testAccPreCheck(t) },964 ProviderFactories: providerFactories,965 Steps: []resource.TestStep{966 {967 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerInternalPortConfig"),968 Check: resource.ComposeTestCheckFunc(969 testAccContainerRunning("docker_container.foo", &c),970 testCheck,971 resource.TestCheckResourceAttr("docker_container.foo", "name", "tf-test"),972 resource.TestCheckResourceAttr("docker_container.foo", "ports.#", "1"),973 resource.TestCheckResourceAttr("docker_container.foo", "ports.0.internal", "80"),974 resource.TestCheckResourceAttr("docker_container.foo", "ports.0.ip", "0.0.0.0"),975 resource.TestCheckResourceAttr("docker_container.foo", "ports.0.protocol", "tcp"),976 testValueHigherEqualThan("docker_container.foo", "ports.0.external", 32768),977 ),978 },979 },980 })981}982func TestAccDockerContainer_port_multiple_internal(t *testing.T) {983 var c types.ContainerJSON984 testCheck := func(*terraform.State) error {985 portMap := c.NetworkSettings.NetworkSettingsBase.Ports986 portBindings, ok := portMap["80/tcp"]987 if !ok || len(portMap["80/tcp"]) == 0 {988 return fmt.Errorf("Port 80 on tcp is not set")989 }990 portBindingsLength := len(portBindings)991 if portBindingsLength != 1 {992 return fmt.Errorf("Expected 1 binding on port 80, but was %d", portBindingsLength)993 }994 if len(portBindings[0].HostIP) == 0 {995 return fmt.Errorf("Expected host IP to be set, but was empty")996 }997 if len(portBindings[0].HostPort) == 0 {998 return fmt.Errorf("Expected host port to be set, but was empty")999 }1000 portBindings, ok = portMap["81/tcp"]1001 if !ok || len(portMap["81/tcp"]) == 0 {1002 return fmt.Errorf("Port 81 on tcp is not set")1003 }1004 portBindingsLength = len(portBindings)1005 if portBindingsLength != 1 {1006 return fmt.Errorf("Expected 1 binding on port 81, but was %d", portBindingsLength)1007 }1008 if len(portBindings[0].HostIP) == 0 {1009 return fmt.Errorf("Expected host IP to be set, but was empty")1010 }1011 if len(portBindings[0].HostPort) == 0 {1012 return fmt.Errorf("Expected host port to be set, but was empty")1013 }1014 return nil1015 }1016 resource.Test(t, resource.TestCase{1017 PreCheck: func() { testAccPreCheck(t) },1018 ProviderFactories: providerFactories,1019 Steps: []resource.TestStep{1020 {1021 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerMultipleInternalPortConfig"),1022 Check: resource.ComposeTestCheckFunc(1023 testAccContainerRunning("docker_container.foo", &c),1024 testCheck,1025 resource.TestCheckResourceAttr("docker_container.foo", "name", "tf-test"),1026 resource.TestCheckResourceAttr("docker_container.foo", "ports.#", "2"),1027 resource.TestCheckResourceAttr("docker_container.foo", "ports.0.internal", "80"),1028 resource.TestCheckResourceAttr("docker_container.foo", "ports.0.ip", "0.0.0.0"),1029 resource.TestCheckResourceAttr("docker_container.foo", "ports.0.protocol", "tcp"),1030 testValueHigherEqualThan("docker_container.foo", "ports.0.external", 32768),1031 resource.TestCheckResourceAttr("docker_container.foo", "ports.1.internal", "81"),1032 resource.TestCheckResourceAttr("docker_container.foo", "ports.1.ip", "0.0.0.0"),1033 resource.TestCheckResourceAttr("docker_container.foo", "ports.1.protocol", "tcp"),1034 testValueHigherEqualThan("docker_container.foo", "ports.1.external", 32768),1035 ),1036 },1037 },1038 })1039}1040func TestAccDockerContainer_port(t *testing.T) {1041 var c types.ContainerJSON1042 testCheck := func(*terraform.State) error {1043 portMap := c.NetworkSettings.NetworkSettingsBase.Ports1044 portBindings, ok := portMap["80/tcp"]1045 if !ok || len(portMap["80/tcp"]) == 0 {1046 return fmt.Errorf("Port 80 on tcp is not set")1047 }1048 portBindingsLength := len(portBindings)1049 if portBindingsLength != 1 {1050 return fmt.Errorf("Expected 1 binding on port 80, but was %d", portBindingsLength)1051 }1052 if len(portBindings[0].HostIP) == 0 {1053 return fmt.Errorf("Expected host IP to be set, but was empty")1054 }1055 if len(portBindings[0].HostPort) == 0 {1056 return fmt.Errorf("Expected host port to be set, but was empty")1057 }1058 return nil1059 }1060 resource.Test(t, resource.TestCase{1061 PreCheck: func() { testAccPreCheck(t) },1062 ProviderFactories: providerFactories,1063 Steps: []resource.TestStep{1064 {1065 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerPortConfig"),1066 Check: resource.ComposeTestCheckFunc(1067 testAccContainerRunning("docker_container.foo", &c),1068 testCheck,1069 resource.TestCheckResourceAttr("docker_container.foo", "name", "tf-test"),1070 resource.TestCheckResourceAttr("docker_container.foo", "ports.#", "1"),1071 resource.TestCheckResourceAttr("docker_container.foo", "ports.0.internal", "80"),1072 resource.TestCheckResourceAttr("docker_container.foo", "ports.0.ip", "0.0.0.0"),1073 resource.TestCheckResourceAttr("docker_container.foo", "ports.0.protocol", "tcp"),1074 resource.TestCheckResourceAttr("docker_container.foo", "ports.0.external", "32787"),1075 ),1076 },1077 {1078 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerConfig"),1079 Check: resource.ComposeTestCheckFunc(1080 testAccContainerRunning("docker_container.foo", &c),1081 resource.TestCheckResourceAttr("docker_container.foo", "name", "tf-test"),1082 resource.TestCheckResourceAttr("docker_container.foo", "ports.#", "0"),1083 ),1084 },1085 },1086 })1087}1088func TestAccDockerContainer_multiple_ports(t *testing.T) {1089 var c types.ContainerJSON1090 testCheck := func(*terraform.State) error {1091 portMap := c.NetworkSettings.NetworkSettingsBase.Ports1092 portBindings, ok := portMap["80/tcp"]1093 if !ok || len(portMap["80/tcp"]) == 0 {1094 return fmt.Errorf("Port 80 on tcp is not set")1095 }1096 portBindingsLength := len(portBindings)1097 if portBindingsLength != 1 {1098 return fmt.Errorf("Expected 1 binding on port 80, but was %d", portBindingsLength)1099 }1100 if len(portBindings[0].HostIP) == 0 {1101 return fmt.Errorf("Expected host IP to be set, but was empty")1102 }1103 if len(portBindings[0].HostPort) == 0 {1104 return fmt.Errorf("Expected host port to be set, but was empty")1105 }1106 portBindings, ok = portMap["81/tcp"]1107 if !ok || len(portMap["81/tcp"]) == 0 {1108 return fmt.Errorf("Port 81 on tcp is not set")1109 }1110 portBindingsLength = len(portBindings)1111 if portBindingsLength != 1 {1112 return fmt.Errorf("Expected 1 binding on port 81, but was %d", portBindingsLength)1113 }1114 if len(portBindings[0].HostIP) == 0 {1115 return fmt.Errorf("Expected host IP to be set, but was empty")1116 }1117 if len(portBindings[0].HostPort) == 0 {1118 return fmt.Errorf("Expected host port to be set, but was empty")1119 }1120 return nil1121 }1122 resource.Test(t, resource.TestCase{1123 PreCheck: func() { testAccPreCheck(t) },1124 ProviderFactories: providerFactories,1125 Steps: []resource.TestStep{1126 {1127 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerMultiplePortConfig"),1128 Check: resource.ComposeTestCheckFunc(1129 testAccContainerRunning("docker_container.foo", &c),1130 testCheck,1131 resource.TestCheckResourceAttr("docker_container.foo", "name", "tf-test"),1132 resource.TestCheckResourceAttr("docker_container.foo", "ports.#", "2"),1133 resource.TestCheckResourceAttr("docker_container.foo", "ports.0.internal", "80"),1134 resource.TestCheckResourceAttr("docker_container.foo", "ports.0.ip", "0.0.0.0"),1135 resource.TestCheckResourceAttr("docker_container.foo", "ports.0.protocol", "tcp"),1136 resource.TestCheckResourceAttr("docker_container.foo", "ports.0.external", "32787"),1137 resource.TestCheckResourceAttr("docker_container.foo", "ports.1.internal", "81"),1138 resource.TestCheckResourceAttr("docker_container.foo", "ports.1.ip", "0.0.0.0"),1139 resource.TestCheckResourceAttr("docker_container.foo", "ports.1.protocol", "tcp"),1140 resource.TestCheckResourceAttr("docker_container.foo", "ports.1.external", "32788"),1141 ),1142 },1143 },1144 })1145}1146func TestAccDockerContainer_rm(t *testing.T) {1147 var c types.ContainerJSON1148 ctx := context.Background()1149 testCheck := func(*terraform.State) error {1150 if !c.HostConfig.AutoRemove {1151 return fmt.Errorf("Container doesn't have a correct autoremove flag")1152 }1153 return nil1154 }1155 resource.Test(t, resource.TestCase{1156 PreCheck: func() { testAccPreCheck(t) },1157 ProviderFactories: providerFactories,1158 CheckDestroy: testAccContainerWaitConditionRemoved(ctx, "docker_container.foo", &c),1159 Steps: []resource.TestStep{1160 {1161 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerRmConfig"),1162 Check: resource.ComposeTestCheckFunc(1163 testAccContainerRunning("docker_container.foo", &c),1164 testCheck,1165 resource.TestCheckResourceAttr("docker_container.foo", "name", "tf-test"),1166 resource.TestCheckResourceAttr("docker_container.foo", "rm", "true"),1167 ),1168 },1169 },1170 })1171}1172func TestAccDockerContainer_readonly(t *testing.T) {1173 var c types.ContainerJSON1174 testCheck := func(*terraform.State) error {1175 if !c.HostConfig.ReadonlyRootfs {1176 return fmt.Errorf("Container isn't readonly")1177 }1178 return nil1179 }1180 resource.Test(t, resource.TestCase{1181 PreCheck: func() { testAccPreCheck(t) },1182 ProviderFactories: providerFactories,1183 Steps: []resource.TestStep{1184 {1185 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerReadOnlyConfig"),1186 Check: resource.ComposeTestCheckFunc(1187 testAccContainerRunning("docker_container.foo", &c),1188 testCheck,1189 resource.TestCheckResourceAttr("docker_container.foo", "name", "tf-test"),1190 resource.TestCheckResourceAttr("docker_container.foo", "read_only", "true"),1191 ),1192 },1193 },1194 })1195}1196func TestAccDockerContainer_healthcheck(t *testing.T) {1197 var c types.ContainerJSON1198 testCheck := func(*terraform.State) error {1199 if !reflect.DeepEqual(c.Config.Healthcheck.Test, []string{"CMD", "/bin/true"}) {1200 return fmt.Errorf("Container doesn't have a correct healthcheck test")1201 }1202 if c.Config.Healthcheck.Interval != 30000000000 {1203 return fmt.Errorf("Container doesn't have a correct healthcheck interval")1204 }1205 if c.Config.Healthcheck.Timeout != 5000000000 {1206 return fmt.Errorf("Container doesn't have a correct healthcheck timeout")1207 }1208 if c.Config.Healthcheck.StartPeriod != 15000000000 {1209 return fmt.Errorf("Container doesn't have a correct healthcheck retries")1210 }1211 if c.Config.Healthcheck.Retries != 10 {1212 return fmt.Errorf("Container doesn't have a correct healthcheck retries")1213 }1214 return nil1215 }1216 resource.Test(t, resource.TestCase{1217 PreCheck: func() { testAccPreCheck(t) },1218 ProviderFactories: providerFactories,1219 Steps: []resource.TestStep{1220 {1221 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerHealthcheckConfig"),1222 Check: resource.ComposeTestCheckFunc(1223 testAccContainerRunning("docker_container.foo", &c),1224 testCheck,1225 ),1226 },1227 },1228 })1229}1230func TestAccDockerContainer_nostart(t *testing.T) {1231 var c types.ContainerJSON1232 resource.Test(t, resource.TestCase{1233 PreCheck: func() { testAccPreCheck(t) },1234 ProviderFactories: providerFactories,1235 Steps: []resource.TestStep{1236 {1237 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerNoStartConfig"),1238 Check: resource.ComposeTestCheckFunc(1239 testAccContainerNotRunning("docker_container.foo", &c),1240 ),1241 },1242 },1243 })1244}1245func TestAccDockerContainer_attach(t *testing.T) {1246 var c types.ContainerJSON1247 resource.Test(t, resource.TestCase{1248 PreCheck: func() { testAccPreCheck(t) },1249 ProviderFactories: providerFactories,1250 Steps: []resource.TestStep{1251 {1252 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerAttachConfig"),1253 Check: resource.ComposeTestCheckFunc(1254 testAccContainerNotRunning("docker_container.foo", &c),1255 resource.TestCheckResourceAttr("docker_container.foo", "name", "tf-test"),1256 resource.TestCheckResourceAttr("docker_container.foo", "attach", "true"),1257 resource.TestCheckResourceAttr("docker_container.foo", "must_run", "false"),1258 ),1259 },1260 },1261 })1262}1263func TestAccDockerContainer_logs(t *testing.T) {1264 var c types.ContainerJSON1265 resource.Test(t, resource.TestCase{1266 PreCheck: func() { testAccPreCheck(t) },1267 ProviderFactories: providerFactories,1268 Steps: []resource.TestStep{1269 {1270 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerLogsConfig"),1271 Check: resource.ComposeTestCheckFunc(1272 testAccContainerNotRunning("docker_container.foo", &c),1273 resource.TestCheckResourceAttr("docker_container.foo", "name", "tf-test"),1274 resource.TestCheckResourceAttr("docker_container.foo", "attach", "true"),1275 resource.TestCheckResourceAttr("docker_container.foo", "logs", "true"),1276 resource.TestCheckResourceAttr("docker_container.foo", "must_run", "false"),1277 resource.TestCheckResourceAttr("docker_container.foo", "container_logs", "\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u00021\n\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u00022\n\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u00023\n\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u00024\n\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u00025\n\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u00026\n\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u00027\n\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u00028\n\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u00029\n\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u000310\n"),1278 ),1279 },1280 },1281 })1282}1283func TestAccDockerContainer_exitcode(t *testing.T) {1284 var c types.ContainerJSON1285 resource.Test(t, resource.TestCase{1286 PreCheck: func() { testAccPreCheck(t) },1287 ProviderFactories: providerFactories,1288 Steps: []resource.TestStep{1289 {1290 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerExitCodeConfig"),1291 Check: resource.ComposeTestCheckFunc(1292 testAccContainerWaitConditionNotRunning("docker_container.foo", &c),1293 resource.TestCheckResourceAttr("docker_container.foo", "name", "tf-test"),1294 resource.TestCheckResourceAttr("docker_container.foo", "exit_code", "123"),1295 ),1296 },1297 },1298 })1299}1300func TestAccDockerContainer_ipv4address(t *testing.T) {1301 var c types.ContainerJSON1302 testCheck := func(*terraform.State) error {1303 networks := c.NetworkSettings.Networks1304 if len(networks) != 1 {1305 return fmt.Errorf("Container doesn't have a correct network")1306 }1307 if _, ok := networks["tf-test"]; !ok {1308 return fmt.Errorf("Container doesn't have a correct network")1309 }1310 if c.NetworkSettings.Networks["tf-test"].IPAMConfig == nil {1311 return fmt.Errorf("Container doesn't have a correct IPAM config")1312 }1313 if c.NetworkSettings.Networks["tf-test"].IPAMConfig.IPv4Address != "10.0.1.123" {1314 return fmt.Errorf("Container doesn't have a correct IPv4 address")1315 }1316 return nil1317 }1318 resource.Test(t, resource.TestCase{1319 PreCheck: func() { testAccPreCheck(t) },1320 ProviderFactories: providerFactories,1321 Steps: []resource.TestStep{1322 {1323 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerNetworksIPv4AddressConfig"),1324 Check: resource.ComposeTestCheckFunc(1325 testAccContainerRunning("docker_container.foo", &c),1326 testCheck,1327 resource.TestCheckResourceAttr("docker_container.foo", "name", "tf-test"),1328 ),1329 },1330 },1331 })1332}1333func TestAccDockerContainer_ipv6address(t *testing.T) {1334 t.Skip("mavogel: need to fix ipv6 network state")1335 var c types.ContainerJSON1336 testCheck := func(*terraform.State) error {1337 networks := c.NetworkSettings.Networks1338 if len(networks) != 1 {1339 return fmt.Errorf("Container doesn't have a correct network")1340 }1341 if _, ok := networks["tf-test"]; !ok {1342 return fmt.Errorf("Container doesn't have a correct network")1343 }1344 if c.NetworkSettings.Networks["tf-test"].IPAMConfig == nil {1345 return fmt.Errorf("Container doesn't have a correct IPAM config")1346 }1347 if c.NetworkSettings.Networks["tf-test"].IPAMConfig.IPv6Address != "fd00:0:0:0::123" {1348 return fmt.Errorf("Container doesn't have a correct IPv6 address")1349 }1350 return nil1351 }1352 resource.Test(t, resource.TestCase{1353 PreCheck: func() { testAccPreCheck(t) },1354 ProviderFactories: providerFactories,1355 Steps: []resource.TestStep{1356 {1357 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerNetworksIPv6AddressConfig"),1358 Check: resource.ComposeTestCheckFunc(1359 testAccContainerRunning("docker_container.foo", &c),1360 testCheck,1361 resource.TestCheckResourceAttr("docker_container.foo", "name", "tf-test"),1362 resource.TestCheckResourceAttr("docker_container.foo", "network_data.0.global_ipv6_address", "fd00:0:0:0::123"),1363 resource.TestCheckResourceAttr("docker_container.foo", "network_data.0.global_ipv6_prefix_length", "64"),1364 resource.TestCheckResourceAttr("docker_container.foo", "network_data.0.ipv6_gateway", "fd00:0:0:0::f"),1365 ),1366 },1367 },1368 })1369}1370func TestAccDockerContainer_dualstackaddress(t *testing.T) {1371 var c types.ContainerJSON1372 testCheck := func(*terraform.State) error {1373 networks := c.NetworkSettings.Networks1374 if len(networks) != 1 {1375 return fmt.Errorf("Container doesn't have a correct network")1376 }1377 if _, ok := networks["tf-test"]; !ok {1378 return fmt.Errorf("Container doesn't have a correct network")1379 }1380 if c.NetworkSettings.Networks["tf-test"].IPAMConfig == nil {1381 return fmt.Errorf("Container doesn't have a correct IPAM config")1382 }1383 if c.NetworkSettings.Networks["tf-test"].IPAMConfig.IPv4Address != "10.0.1.123" {1384 return fmt.Errorf("Container doesn't have a correct IPv4 address")1385 }1386 if c.NetworkSettings.Networks["tf-test"].IPAMConfig.IPv6Address != "fd00:0:0:0::123" {1387 return fmt.Errorf("Container doesn't have a correct IPv6 address")1388 }1389 return nil1390 }1391 resource.Test(t, resource.TestCase{1392 PreCheck: func() { testAccPreCheck(t) },1393 ProviderFactories: providerFactories,1394 Steps: []resource.TestStep{1395 {1396 Config: loadTestConfiguration(t, RESOURCE, "docker_container", "testAccDockerContainerNetworksDualStackAddressConfig"),1397 Check: resource.ComposeTestCheckFunc(1398 testAccContainerRunning("docker_container.foo", &c),1399 testCheck,1400 resource.TestCheckResourceAttr("docker_container.foo", "name", "tf-test"),1401 ),1402 },1403 },1404 })1405}1406// /////////1407// HELPERS1408// /////////1409func testAccContainerRunning(resourceName string, container *types.ContainerJSON) resource.TestCheckFunc {1410 return func(s *terraform.State) error {1411 ctx := context.Background()1412 rs, ok := s.RootModule().Resources[resourceName]1413 if !ok {1414 return fmt.Errorf("Resource with name '%s' not found in state", resourceName)1415 }1416 if rs.Primary.ID == "" {1417 return fmt.Errorf("No ID is set")1418 }1419 client := testAccProvider.Meta().(*ProviderConfig).DockerClient1420 containers, err := client.ContainerList(ctx, types.ContainerListOptions{})1421 if err != nil {1422 return err1423 }1424 for _, c := range containers {1425 if c.ID == rs.Primary.ID {1426 inspected, err := client.ContainerInspect(ctx, c.ID)1427 if err != nil {1428 return fmt.Errorf("Container could not be inspected: %s", err)1429 }1430 *container = inspected1431 return nil1432 }1433 }1434 return fmt.Errorf("Container not found: %s", rs.Primary.ID)1435 }1436}1437func testAccContainerNotRunning(n string, container *types.ContainerJSON) resource.TestCheckFunc {1438 return func(s *terraform.State) error {1439 ctx := context.Background()1440 rs, ok := s.RootModule().Resources[n]1441 if !ok {1442 return fmt.Errorf("Not found: %s", n)1443 }1444 if rs.Primary.ID == "" {1445 return fmt.Errorf("No ID is set")1446 }1447 client := testAccProvider.Meta().(*ProviderConfig).DockerClient1448 containers, err := client.ContainerList(ctx, types.ContainerListOptions{1449 All: true,1450 })1451 if err != nil {1452 return err1453 }1454 for _, c := range containers {1455 if c.ID == rs.Primary.ID {1456 inspected, err := client.ContainerInspect(ctx, c.ID)1457 if err != nil {1458 return fmt.Errorf("Container could not be inspected: %s", err)1459 }1460 *container = inspected1461 if container.State.Running {1462 return fmt.Errorf("Container is running: %s", rs.Primary.ID)1463 }1464 }1465 }1466 return nil1467 }1468}1469func testAccContainerWaitConditionNotRunning(n string, ct *types.ContainerJSON) resource.TestCheckFunc {1470 return func(s *terraform.State) error {1471 ctx := context.Background()1472 rs, ok := s.RootModule().Resources[n]1473 if !ok {1474 return fmt.Errorf("Not found: %s", n)1475 }1476 if rs.Primary.ID == "" {1477 return fmt.Errorf("No ID is set")1478 }1479 client := testAccProvider.Meta().(*ProviderConfig).DockerClient1480 ctx, cancel := context.WithTimeout(ctx, 30*time.Second)1481 defer cancel()1482 statusC, errC := client.ContainerWait(ctx, rs.Primary.ID, container.WaitConditionNotRunning)1483 select {1484 case err := <-errC:1485 if err != nil {1486 return fmt.Errorf("Container is still running")1487 }1488 case <-statusC:1489 }1490 return nil1491 }1492}1493func testAccContainerWaitConditionRemoved(ctx context.Context, n string, ct *types.ContainerJSON) resource.TestCheckFunc {1494 return func(s *terraform.State) error {1495 rs, ok := s.RootModule().Resources[n]1496 if !ok {1497 return fmt.Errorf("Not found: %s", n)1498 }1499 if rs.Primary.ID == "" {1500 return fmt.Errorf("No ID is set")1501 }1502 client := testAccProvider.Meta().(*ProviderConfig).DockerClient1503 ctx, cancel := context.WithTimeout(ctx, 30*time.Second)1504 defer cancel()1505 statusC, errC := client.ContainerWait(ctx, rs.Primary.ID, container.WaitConditionRemoved)1506 select {1507 case err := <-errC:1508 if err != nil {1509 if !containsIgnorableErrorMessage(err.Error(), "No such container", "is already in progress") {1510 return fmt.Errorf("Container has not been removed: '%s'", err.Error())1511 }1512 }1513 case <-statusC:1514 }1515 return nil1516 }1517}1518func testValueHigherEqualThan(name, key string, value int) resource.TestCheckFunc {1519 return func(s *terraform.State) error {1520 ms := s.RootModule()1521 rs, ok := ms.Resources[name]1522 if !ok {1523 return fmt.Errorf("Not found: %s", name)1524 }1525 is := rs.Primary1526 if is == nil {1527 return fmt.Errorf("No primary instance: %s", name)1528 }1529 vRaw, ok := is.Attributes[key]1530 if !ok {1531 return fmt.Errorf("%s: Attribute '%s' not found", name, key)1532 }...

Full Screen

Full Screen

collector_api_test.go

Source:collector_api_test.go Github

copy

Full Screen

1package main2import (3 "fmt"4 "io/ioutil"5 "net"6 "net/http"7 "net/url"8 "os"9 "sync"10 "testing"11 "time"12 "github.com/DataDog/datadog-agent/pkg/process/checks"13 "github.com/DataDog/datadog-agent/pkg/process/util/api"14 "github.com/DataDog/agent-payload/process"15 "github.com/DataDog/datadog-agent/pkg/process/config"16 "github.com/stretchr/testify/assert"17 "github.com/stretchr/testify/require"18)19const testHostName = "test-host"20func TestSendConnectionsMessage(t *testing.T) {21 m := &process.CollectorConnections{22 HostName: testHostName,23 GroupId: 1,24 }25 check := &testCheck{26 name: checks.Connections.Name(),27 data: [][]process.MessageBody{{m}},28 }29 runCollectorTest(t, check, config.NewDefaultAgentConfig(false), &endpointConfig{}, func(cfg *config.AgentConfig, ep *mockEndpoint) {30 req := <-ep.Requests31 assert.Equal(t, "/api/v1/collector", req.uri)32 assert.Equal(t, cfg.HostName, req.headers.Get(api.HostHeader))33 assert.Equal(t, cfg.APIEndpoints[0].APIKey, req.headers.Get("DD-Api-Key"))34 reqBody, err := process.DecodeMessage(req.body)35 require.NoError(t, err)36 cc, ok := reqBody.Body.(*process.CollectorConnections)37 require.True(t, ok)38 assert.Equal(t, cfg.HostName, cc.HostName)39 assert.Equal(t, int32(1), cc.GroupId)40 })41}42func TestSendContainerMessage(t *testing.T) {43 m := &process.CollectorContainer{44 HostName: testHostName,45 GroupId: 1,46 Containers: []*process.Container{47 {Id: "1", Name: "foo"},48 },49 }50 check := &testCheck{51 name: checks.Container.Name(),52 data: [][]process.MessageBody{{m}},53 }54 runCollectorTest(t, check, config.NewDefaultAgentConfig(false), &endpointConfig{}, func(cfg *config.AgentConfig, ep *mockEndpoint) {55 req := <-ep.Requests56 assert.Equal(t, "/api/v1/container", req.uri)57 assert.Equal(t, cfg.HostName, req.headers.Get(api.HostHeader))58 assert.Equal(t, cfg.APIEndpoints[0].APIKey, req.headers.Get("DD-Api-Key"))59 assert.Equal(t, "1", req.headers.Get(api.ContainerCountHeader))60 reqBody, err := process.DecodeMessage(req.body)61 require.NoError(t, err)62 _, ok := reqBody.Body.(*process.CollectorContainer)63 require.True(t, ok)64 })65}66func TestSendProcMessage(t *testing.T) {67 m := &process.CollectorProc{68 HostName: testHostName,69 GroupId: 1,70 Containers: []*process.Container{71 {Id: "1", Name: "foo"},72 },73 }74 check := &testCheck{75 name: checks.Process.Name(),76 data: [][]process.MessageBody{{m}},77 }78 runCollectorTest(t, check, config.NewDefaultAgentConfig(false), &endpointConfig{}, func(cfg *config.AgentConfig, ep *mockEndpoint) {79 req := <-ep.Requests80 assert.Equal(t, "/api/v1/collector", req.uri)81 assert.Equal(t, cfg.HostName, req.headers.Get(api.HostHeader))82 assert.Equal(t, cfg.APIEndpoints[0].APIKey, req.headers.Get("DD-Api-Key"))83 assert.Equal(t, "1", req.headers.Get(api.ContainerCountHeader))84 assert.Equal(t, "1", req.headers.Get("X-DD-Agent-Attempts"))85 assert.NotEmpty(t, req.headers.Get(api.TimestampHeader))86 reqBody, err := process.DecodeMessage(req.body)87 require.NoError(t, err)88 _, ok := reqBody.Body.(*process.CollectorProc)89 require.True(t, ok)90 })91}92func TestSendProcMessageWithRetry(t *testing.T) {93 m := &process.CollectorProc{94 HostName: testHostName,95 GroupId: 1,96 Containers: []*process.Container{97 {Id: "1", Name: "foo"},98 },99 }100 check := &testCheck{101 name: checks.Process.Name(),102 data: [][]process.MessageBody{{m}},103 }104 runCollectorTest(t, check, config.NewDefaultAgentConfig(false), &endpointConfig{ErrorCount: 1}, func(cfg *config.AgentConfig, ep *mockEndpoint) {105 requests := []request{106 <-ep.Requests,107 <-ep.Requests,108 }109 timestamps := make(map[string]struct{})110 for _, req := range requests {111 assert.Equal(t, cfg.HostName, req.headers.Get(api.HostHeader))112 assert.Equal(t, cfg.APIEndpoints[0].APIKey, req.headers.Get("DD-Api-Key"))113 assert.Equal(t, "1", req.headers.Get(api.ContainerCountHeader))114 timestamps[req.headers.Get(api.TimestampHeader)] = struct{}{}115 reqBody, err := process.DecodeMessage(req.body)116 require.NoError(t, err)117 _, ok := reqBody.Body.(*process.CollectorProc)118 require.True(t, ok)119 }120 assert.Len(t, timestamps, 1)121 assert.Equal(t, "1", requests[0].headers.Get("X-DD-Agent-Attempts"))122 assert.Equal(t, "2", requests[1].headers.Get("X-DD-Agent-Attempts"))123 })124}125func TestRTProcMessageNotRetried(t *testing.T) {126 m := &process.CollectorRealTime{127 HostName: testHostName,128 GroupId: 1,129 }130 check := &testCheck{131 name: checks.RTProcess.Name(),132 data: [][]process.MessageBody{{m}},133 }134 runCollectorTest(t, check, config.NewDefaultAgentConfig(false), &endpointConfig{ErrorCount: 1}, func(cfg *config.AgentConfig, ep *mockEndpoint) {135 req := <-ep.Requests136 reqBody, err := process.DecodeMessage(req.body)137 require.NoError(t, err)138 _, ok := reqBody.Body.(*process.CollectorRealTime)139 require.True(t, ok)140 assert.Equal(t, "1", req.headers.Get("X-DD-Agent-Attempts"))141 select {142 case <-ep.Requests:143 t.Fatalf("should not have received another request")144 case <-time.After(2 * time.Second):145 }146 })147}148func TestSendPodMessage(t *testing.T) {149 clusterID := "d801b2b1-4811-11ea-8618-121d4d0938a3"150 orig := os.Getenv("DD_ORCHESTRATOR_CLUSTER_ID")151 _ = os.Setenv("DD_ORCHESTRATOR_CLUSTER_ID", clusterID)152 defer func() { _ = os.Setenv("DD_ORCHESTRATOR_CLUSTER_ID", orig) }()153 m := &process.CollectorPod{154 HostName: testHostName,155 GroupId: 1,156 }157 check := &testCheck{158 name: checks.Pod.Name(),159 data: [][]process.MessageBody{{m}},160 }161 runCollectorTest(t, check, config.NewDefaultAgentConfig(false), &endpointConfig{}, func(cfg *config.AgentConfig, ep *mockEndpoint) {162 req := <-ep.Requests163 assert.Equal(t, "/api/v1/orchestrator", req.uri)164 assert.Equal(t, cfg.HostName, req.headers.Get(api.HostHeader))165 assert.Equal(t, cfg.OrchestratorEndpoints[0].APIKey, req.headers.Get("DD-Api-Key"))166 assert.Equal(t, "0", req.headers.Get(api.ContainerCountHeader))167 assert.Equal(t, "1", req.headers.Get("X-DD-Agent-Attempts"))168 assert.NotEmpty(t, req.headers.Get(api.TimestampHeader))169 reqBody, err := process.DecodeMessage(req.body)170 require.NoError(t, err)171 cp, ok := reqBody.Body.(*process.CollectorPod)172 require.True(t, ok)173 assert.Equal(t, clusterID, req.headers.Get(api.ClusterIDHeader))174 assert.Equal(t, cfg.HostName, cp.HostName)175 })176}177func TestQueueSpaceNotAvailable(t *testing.T) {178 m := &process.CollectorRealTime{179 HostName: testHostName,180 GroupId: 1,181 }182 check := &testCheck{183 name: checks.RTProcess.Name(),184 data: [][]process.MessageBody{{m}},185 }186 cfg := config.NewDefaultAgentConfig(false)187 cfg.ProcessQueueBytes = 1188 runCollectorTest(t, check, cfg, &endpointConfig{ErrorCount: 1}, func(cfg *config.AgentConfig, ep *mockEndpoint) {189 select {190 case r := <-ep.Requests:191 t.Fatalf("should not have received a request: %+v", r)192 case <-time.After(2 * time.Second):193 }194 })195}196// TestQueueSpaceReleased tests that queue space is released after sending a payload197func TestQueueSpaceReleased(t *testing.T) {198 m1 := &process.CollectorRealTime{199 HostName: testHostName,200 GroupId: 1,201 }202 m2 := &process.CollectorRealTime{203 HostName: testHostName,204 GroupId: 2,205 }206 check := &testCheck{207 name: checks.RTProcess.Name(),208 data: [][]process.MessageBody{{m1}, {m2}},209 }210 cfg := config.NewDefaultAgentConfig(false)211 cfg.ProcessQueueBytes = 50 // This should be enough for one message, but not both if the space isn't released212 runCollectorTest(t, check, cfg, &endpointConfig{ErrorCount: 1}, func(cfg *config.AgentConfig, ep *mockEndpoint) {213 req := <-ep.Requests214 reqBody, err := process.DecodeMessage(req.body)215 require.NoError(t, err)216 body, ok := reqBody.Body.(*process.CollectorRealTime)217 require.True(t, ok)218 assert.Equal(t, int32(1), body.GroupId)219 req = <-ep.Requests220 reqBody, err = process.DecodeMessage(req.body)221 require.NoError(t, err)222 body, ok = reqBody.Body.(*process.CollectorRealTime)223 require.True(t, ok)224 assert.Equal(t, int32(2), body.GroupId)225 })226}227func runCollectorTest(t *testing.T, check checks.Check, cfg *config.AgentConfig, epConfig *endpointConfig, tc func(cfg *config.AgentConfig, ep *mockEndpoint)) {228 ep := newMockEndpoint(t, epConfig)229 collectorAddr, orchestratorAddr := ep.start()230 defer ep.stop()231 cfg.APIEndpoints = []api.Endpoint{{APIKey: "apiKey", Endpoint: collectorAddr}}232 cfg.OrchestratorEndpoints = []api.Endpoint{{APIKey: "orchestratorApiKey", Endpoint: orchestratorAddr}}233 cfg.HostName = testHostName234 cfg.CheckIntervals[check.Name()] = 500 * time.Millisecond235 exit := make(chan struct{})236 c := NewCollectorWithChecks(cfg, []checks.Check{check})237 var wg sync.WaitGroup238 wg.Add(1)239 go func() {240 defer wg.Done()241 err := c.run(exit)242 require.NoError(t, err)243 }()244 tc(cfg, ep)245 close(exit)246 wg.Wait()247}248type testCheck struct {249 name string250 data [][]process.MessageBody251}252func (t *testCheck) Init(_ *config.AgentConfig, _ *process.SystemInfo) {253}254func (t *testCheck) Name() string {255 return t.name256}257func (t *testCheck) RealTime() bool {258 return false259}260func (t *testCheck) Run(_ *config.AgentConfig, _ int32) ([]process.MessageBody, error) {261 if len(t.data) > 0 {262 result := t.data[0]263 t.data = t.data[1:]264 return result, nil265 }266 return nil, nil267}268var _ checks.Check = &testCheck{}269type request struct {270 headers http.Header271 uri string272 body []byte273}274type endpointConfig struct {275 ErrorCount int276}277type mockEndpoint struct {278 t *testing.T279 collectorServer *http.Server280 orchestratorServer *http.Server281 stopper sync.WaitGroup282 Requests chan request283 errorCount int284 errorsSent int285 closeOnce sync.Once286}287func newMockEndpoint(t *testing.T, config *endpointConfig) *mockEndpoint {288 m := &mockEndpoint{289 t: t,290 errorCount: config.ErrorCount,291 Requests: make(chan request, 1),292 }293 collectorMux := http.NewServeMux()294 collectorMux.HandleFunc("/api/v1/validate", m.handleValidate)295 collectorMux.HandleFunc("/api/v1/collector", m.handle)296 collectorMux.HandleFunc("/api/v1/container", m.handle)297 orchestratorMux := http.NewServeMux()298 orchestratorMux.HandleFunc("/api/v1/validate", m.handleValidate)299 orchestratorMux.HandleFunc("/api/v1/orchestrator", m.handle)300 m.collectorServer = &http.Server{Addr: ":", Handler: collectorMux}301 m.orchestratorServer = &http.Server{Addr: ":", Handler: orchestratorMux}302 return m303}304// start starts the http endpoints and returns (collector server url, orchestrator server url)305func (m *mockEndpoint) start() (*url.URL, *url.URL) {306 addrC := make(chan net.Addr, 1)307 m.stopper.Add(1)308 go func() {309 defer m.stopper.Done()310 listener, err := net.Listen("tcp", ":")311 require.NoError(m.t, err)312 addrC <- listener.Addr()313 _ = m.collectorServer.Serve(listener)314 }()315 collectorAddr := <-addrC316 m.stopper.Add(1)317 go func() {318 defer m.stopper.Done()319 listener, err := net.Listen("tcp", ":")320 require.NoError(m.t, err)321 addrC <- listener.Addr()322 _ = m.orchestratorServer.Serve(listener)323 }()324 orchestratorAddr := <-addrC325 close(addrC)326 collectorEndpoint, err := url.Parse(fmt.Sprintf("http://%s", collectorAddr.String()))327 require.NoError(m.t, err)328 orchestratorEndpoint, err := url.Parse(fmt.Sprintf("http://%s", orchestratorAddr.String()))329 require.NoError(m.t, err)330 return collectorEndpoint, orchestratorEndpoint331}332func (m *mockEndpoint) stop() {333 err := m.collectorServer.Close()334 require.NoError(m.t, err)335 err = m.orchestratorServer.Close()336 require.NoError(m.t, err)337 m.stopper.Wait()338 m.closeOnce.Do(func() {339 close(m.Requests)340 })341}342func (m *mockEndpoint) handleValidate(w http.ResponseWriter, _ *http.Request) {343 w.WriteHeader(http.StatusOK)344}345func (m *mockEndpoint) handle(w http.ResponseWriter, req *http.Request) {346 body, err := ioutil.ReadAll(req.Body)347 require.NoError(m.t, err)348 err = req.Body.Close()349 require.NoError(m.t, err)350 m.Requests <- request{headers: req.Header, body: body, uri: req.RequestURI}351 if m.errorCount != m.errorsSent {352 w.WriteHeader(http.StatusInternalServerError)353 m.errorsSent++354 return355 }356 out, err := process.EncodeMessage(process.Message{357 Header: process.MessageHeader{358 Version: process.MessageV3, // Intake normally returns v1 but the encoding in agent-payload only handles v3359 Encoding: process.MessageEncodingProtobuf,360 Type: process.MessageType(process.TypeResCollector),361 Timestamp: time.Now().Unix(),362 },363 Body: &process.ResCollector{364 Header: &process.ResCollector_Header{365 Type: process.TypeResCollector,366 },367 Message: "",368 Status: &process.CollectorStatus{369 ActiveClients: 0,370 Interval: 2,371 },372 },373 })374 require.NoError(m.t, err)375 w.WriteHeader(http.StatusAccepted)376 _, err = w.Write(out)377 require.NoError(m.t, err)378}...

Full Screen

Full Screen

TestCheck

Using AI Code Generation

copy

Full Screen

1import "fmt"2type Host struct {3}4func (h Host) TestCheck() {5 fmt.Println("Test Check")6}7func main() {8 h := Host{"

Full Screen

Full Screen

TestCheck

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 var h = host.Host{Host: "google.com"}4 if h.TestCheck() {5 fmt.Println("Site is up")6 } else {7 fmt.Println("Site is down")8 }9}

Full Screen

Full Screen

TestCheck

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 host1 := host.Host{4 }5 fmt.Println(host1.TestCheck())6}

Full Screen

Full Screen

TestCheck

Using AI Code Generation

copy

Full Screen

1import (2type Host struct {3}4func (h *Host) TestCheck() {5 fmt.Println("Test Check method of host")6}7func main() {8 h := Host{Host: "

Full Screen

Full Screen

TestCheck

Using AI Code Generation

copy

Full Screen

1import (2import (3import (4import (5import (6In the above code, the path and filepath packages are imported from the path package. The path package is imported from the path/filepath package. The path/filepath package is imported from the fmt package. The fmt package is imported from the main

Full Screen

Full Screen

TestCheck

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 host := NewHost("localhost", 80)4 host.SetBreaker(gobreaker.NewCircuitBreaker(gobreaker.Settings{5 ReadyToTrip: func(counts gobreaker.Counts) bool {6 },7 }))8 fmt.Println(host.TestCheck())9 fmt.Println(host.TestCheck())10 fmt.Println(host.TestCheck())11 fmt.Println(host.TestCheck())12}

Full Screen

Full Screen

TestCheck

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Enter a number")4 fmt.Scanln(&a)5 h := new(host)6 fmt.Println(h.TestCheck(a))7}8import (9func main() {10 fmt.Println("Enter a number")11 fmt.Scanln(&a)12 h := new(host)13 fmt.Println(h.TestCheck(a))14}15import (16func main() {17 fmt.Println("Enter a number")18 fmt.Scanln(&a)19 h := new(host)20 fmt.Println(h.TestCheck(a))21}22import (23func main() {24 fmt.Println("Enter a number")25 fmt.Scanln(&a)26 h := new(host)27 fmt.Println(h.TestCheck(a))28}29import (30func main() {31 fmt.Println("Enter a number")32 fmt.Scanln(&a)33 h := new(host)34 fmt.Println(h.TestCheck(a))35}36import (37func main() {38 fmt.Println("Enter a number")39 fmt.Scanln(&a)40 h := new(host)41 fmt.Println(h.TestCheck(a))42}43import (

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Syzkaller automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful