Best Testcontainers-go code snippet using testcontainers.State
containers_test.go
Source:containers_test.go
...18}19func GetContainers(t *testing.T) ContainersInterface {20 t.Helper()21 containersConfig := &Containers{22 DesiredState: ContainersState{23 testContainerName: &HostConfiguredContainer{24 Host: host.Host{25 DirectConfig: &direct.Config{},26 },27 Container: Container{28 Runtime: RuntimeConfig{29 Docker: &docker.Config{},30 },31 Config: types.ContainerConfig{32 Name: testConfigContainerName,33 Image: "busybox:latest",34 },35 },36 },37 },38 }39 c, err := containersConfig.New()40 if err != nil {41 t.Fatalf("Creating empty containers object should work, got: %v", err)42 }43 return c44}45// Containers() tests.46func TestContainersContainers(t *testing.T) {47 t.Parallel()48 testContainers := &containers{}49 if !reflect.DeepEqual(testContainers, testContainers.Containers()) {50 t.Fatalf("Containers() should return self")51 }52}53// CheckCurrentState() tests.54func TestContainersCheckCurrentStateNew(t *testing.T) {55 t.Parallel()56 c := GetContainers(t)57 if err := c.CheckCurrentState(); err != nil {58 t.Fatalf("Checking current state for new Containers should work, got: %v", err)59 }60}61// CurrentStateToYaml() tests.62func TestContainersCurrentStateToYAML(t *testing.T) {63 t.Parallel()64 c := GetContainers(t)65 if _, err := c.StateToYaml(); err != nil {66 t.Fatalf("Getting current state in YAML format should work, got: %v", err)67 }68}69// ToExported() tests.70func TestContainersToExported(t *testing.T) {71 t.Parallel()72 c := GetContainers(t)73 c.ToExported()74}75// FromYaml() tests.76func TestContainersFromYamlBad(t *testing.T) {77 t.Parallel()78 if _, err := FromYaml([]byte{}); err == nil {79 t.Fatalf("Creating containers from empty YAML should fail")80 }81}82func TestContainersFromYaml(t *testing.T) {83 t.Parallel()84 containersConfigRaw := `85desiredState:86 foo:87 host:88 direct: {}89 container:90 runtime:91 docker: {}92 config:93 name: foo94 image: busybox95`96 if _, err := FromYaml([]byte(containersConfigRaw)); err != nil {97 t.Fatalf("Creating containers from valid YAML should work, got: %v", err)98 }99}100// filesToUpdate() tests.101func TestFilesToUpdateEmpty(t *testing.T) {102 t.Parallel()103 expected := []string{testConfigPath}104 hcc := hostConfiguredContainer{105 configFiles: map[string]string{106 testConfigPath: testConfigContent,107 },108 }109 if v := filesToUpdate(hcc, nil); !reflect.DeepEqual(expected, v) {110 t.Fatalf("Expected %v, got %v", expected, hcc)111 }112}113// Validate() tests.114func TestValidateEmpty(t *testing.T) {115 t.Parallel()116 cc := &Containers{}117 if err := cc.Validate(); err == nil {118 t.Fatalf("Empty containers object shouldn't be valid")119 }120}121func TestValidateNil(t *testing.T) {122 t.Parallel()123 var cc Containers124 if err := cc.Validate(); err == nil {125 t.Fatalf("Nil containers object shouldn't be valid")126 }127}128func TestValidateNoContainers(t *testing.T) {129 t.Parallel()130 cc := &Containers{131 DesiredState: ContainersState{},132 PreviousState: ContainersState{},133 }134 if err := cc.Validate(); err == nil {135 t.Fatalf("Containers object without any containers shouldn't be valid")136 }137}138func TestValidateBadDesiredContainers(t *testing.T) {139 t.Parallel()140 containersConfig := &Containers{141 DesiredState: ContainersState{142 testContainerName: &HostConfiguredContainer{},143 },144 PreviousState: ContainersState{},145 }146 if err := containersConfig.Validate(); err == nil {147 t.Fatalf("Containers object with bad desired container shouldn't be valid")148 }149}150func TestValidateBadCurrentContainers(t *testing.T) {151 t.Parallel()152 containersConfig := &Containers{153 DesiredState: ContainersState{},154 PreviousState: ContainersState{155 testContainerName: &HostConfiguredContainer{},156 },157 }158 if err := containersConfig.Validate(); err == nil {159 t.Fatalf("Containers object with bad current container shouldn't be valid")160 }161}162// isUpdatable() tests.163func TestIsUpdatableWithoutCurrentState(t *testing.T) {164 t.Parallel()165 testContainers := &containers{166 desiredState: containersState{167 testContainerName: &hostConfiguredContainer{},168 },169 }170 if err := testContainers.isUpdatable(testContainerName); err == nil {171 t.Fatalf("Container without current state shouldn't be updatable.")172 }173}174func TestIsUpdatableToBeDeleted(t *testing.T) {175 t.Parallel()176 testContainers := &containers{177 currentState: containersState{178 testContainerName: &hostConfiguredContainer{},179 },180 }181 if err := testContainers.isUpdatable(testContainerName); err == nil {182 t.Fatalf("Container without desired state shouldn't be updatable.")183 }184}185func TestIsUpdatable(t *testing.T) {186 t.Parallel()187 testContainers := &containers{188 desiredState: containersState{189 testContainerName: &hostConfiguredContainer{},190 },191 currentState: containersState{192 testContainerName: &hostConfiguredContainer{},193 },194 }195 if err := testContainers.isUpdatable(testContainerName); err != nil {196 t.Fatalf("Container with current and desired state should be updatable, got: %v", err)197 }198}199// diffHost() tests.200func TestDiffHostNotUpdatable(t *testing.T) {201 t.Parallel()202 testContainers := &containers{203 currentState: containersState{204 testContainerName: &hostConfiguredContainer{},205 },206 }207 if _, err := testContainers.diffHost(testContainerName); err == nil {208 t.Fatalf("Not updatable container shouldn't return diff")209 }210}211func TestDiffHostNoDiff(t *testing.T) {212 t.Parallel()213 testContainers := &containers{214 desiredState: containersState{215 testContainerName: &hostConfiguredContainer{216 host: host.Host{},217 },218 },219 currentState: containersState{220 testContainerName: &hostConfiguredContainer{221 host: host.Host{},222 },223 },224 }225 diff, err := testContainers.diffHost(testContainerName)226 if err != nil {227 t.Fatalf("Updatable container should return diff, got: %v", err)228 }229 if diff != "" {230 t.Fatalf("Container without host updates shouldn't return diff, got: %s", diff)231 }232}233func TestDiffHost(t *testing.T) {234 t.Parallel()235 testContainers := &containers{236 desiredState: containersState{237 testContainerName: &hostConfiguredContainer{238 host: host.Host{239 DirectConfig: &direct.Config{},240 },241 },242 },243 currentState: containersState{244 testContainerName: &hostConfiguredContainer{245 host: host.Host{},246 },247 },248 }249 diff, err := testContainers.diffHost(testContainerName)250 if err != nil {251 t.Fatalf("Updatable container should return diff, got: %v", err)252 }253 if diff == "" {254 t.Fatalf("Container with host updates should return diff")255 }256}257// diffContainer() tests.258func TestDiffContainerNotUpdatable(t *testing.T) {259 t.Parallel()260 testContainers := &containers{261 currentState: containersState{262 testContainerName: &hostConfiguredContainer{},263 },264 }265 if _, err := testContainers.diffContainer(testContainerName); err == nil {266 t.Fatalf("Not updatable container shouldn't return diff")267 }268}269func TestDiffContainerNoDiff(t *testing.T) {270 t.Parallel()271 testContainers := &containers{272 desiredState: containersState{273 testContainerName: &hostConfiguredContainer{274 container: &container{275 base: base{276 config: types.ContainerConfig{},277 },278 },279 },280 },281 currentState: containersState{282 testContainerName: &hostConfiguredContainer{283 container: &container{284 base: base{285 config: types.ContainerConfig{},286 },287 },288 },289 },290 }291 diff, err := testContainers.diffContainer(testContainerName)292 if err != nil {293 t.Fatalf("Updatable container should return diff, got: %v", err)294 }295 if diff != "" {296 t.Fatalf("Container without host updates shouldn't return diff, got: %s", diff)297 }298}299func TestDiffContainer(t *testing.T) {300 t.Parallel()301 testContainers := &containers{302 desiredState: containersState{303 testContainerName: &hostConfiguredContainer{304 container: &container{305 base: base{306 config: types.ContainerConfig{},307 },308 },309 },310 },311 currentState: containersState{312 testContainerName: &hostConfiguredContainer{313 container: &container{314 base: base{315 config: types.ContainerConfig{316 Name: testConfigContainerName,317 },318 },319 },320 },321 },322 }323 diff, err := testContainers.diffContainer(testContainerName)324 if err != nil {325 t.Fatalf("Updatable container should return diff, got: %v", err)326 }327 if diff == "" {328 t.Fatalf("Container with config updates should return diff")329 }330}331func TestDiffContainerRuntimeConfig(t *testing.T) {332 t.Parallel()333 testContainers := &containers{334 desiredState: containersState{335 testContainerName: &hostConfiguredContainer{336 container: &container{337 base: base{338 config: types.ContainerConfig{},339 runtimeConfig: &docker.Config{},340 },341 },342 },343 },344 currentState: containersState{345 testContainerName: &hostConfiguredContainer{346 container: &container{347 base: base{348 config: types.ContainerConfig{},349 runtimeConfig: &docker.Config{350 Host: "foo",351 },352 },353 },354 },355 },356 }357 diff, err := testContainers.diffContainer(testContainerName)358 if err != nil {359 t.Fatalf("Updatable container should return diff, got: %v", err)360 }361 if diff == "" {362 t.Fatalf("Container with runtime config updates should return diff")363 }364}365// ensureRunning() tests.366func TestEnsureRunningNonExistent(t *testing.T) {367 t.Parallel()368 testContainers := &containers{369 currentState: containersState{},370 }371 if err := ensureRunning(testContainers.currentState[testAnotherContainerName]); err == nil {372 t.Fatalf("Ensuring that non existing container is running should fail")373 }374}375func TestEnsureRunning(t *testing.T) {376 t.Parallel()377 testContainers := &containers{378 currentState: containersState{379 testContainerName: &hostConfiguredContainer{380 container: &container{381 base: base{382 config: types.ContainerConfig{},383 status: types.ContainerStatus{384 ID: "existing",385 Status: "running",386 },387 },388 },389 },390 },391 }392 if err := ensureRunning(testContainers.currentState[testContainerName]); err != nil {393 t.Fatalf("Ensuring that running container is running should succeed, got: %v", err)394 }395}396// ensureExists() tests.397func TestEnsureExistsAlreadyExists(t *testing.T) {398 t.Parallel()399 testContainers := &containers{400 currentState: containersState{401 testContainerName: &hostConfiguredContainer{402 container: &container{403 base: base{404 config: types.ContainerConfig{},405 status: types.ContainerStatus{406 ID: "existing",407 },408 },409 },410 },411 },412 }413 if err := testContainers.ensureExists(testContainerName); err != nil {414 t.Fatalf("Ensuring that existing container exists should succeed, got: %v", err)415 }416}417func TestEnsureExistsFailCreate(t *testing.T) {418 t.Parallel()419 failingCreateRuntime := fakeRuntime()420 failingCreateRuntime.CreateF = func(config *types.ContainerConfig) (string, error) {421 return "", fmt.Errorf("create fail")422 }423 testContainers := &containers{424 currentState: containersState{},425 desiredState: containersState{426 testContainerName: &hostConfiguredContainer{427 host: host.Host{428 DirectConfig: &direct.Config{},429 },430 container: &container{431 base: base{432 config: types.ContainerConfig{},433 runtimeConfig: asRuntime(failingCreateRuntime),434 },435 },436 },437 },438 }439 if err := testContainers.ensureExists(testContainerName); err == nil {440 t.Fatalf("Ensuring that new container exists should propagate create error")441 }442 if len(testContainers.currentState) != 0 {443 t.Fatalf("If creation failed, current state should not be updated")444 }445}446func TestEnsureExistsFailStart(t *testing.T) {447 t.Parallel()448 testContainers := &containers{449 currentState: containersState{},450 desiredState: containersState{451 testContainerName: &hostConfiguredContainer{452 hooks: &Hooks{},453 host: host.Host{454 DirectConfig: &direct.Config{},455 },456 container: &container{457 base: base{458 config: types.ContainerConfig{},459 runtimeConfig: asRuntime(failingStartRuntime()),460 },461 },462 },463 },464 }465 if err := testContainers.ensureExists(testContainerName); err == nil {466 t.Fatalf("Ensuring that new container exists should fail")467 }468 if _, ok := testContainers.currentState[testContainerName]; !ok {469 t.Fatalf("EnsureExists should save state of created container even if starting failed")470 }471}472func TestEnsureExist(t *testing.T) {473 t.Parallel()474 testContainers := &containers{475 currentState: containersState{},476 desiredState: containersState{477 testContainerName: &hostConfiguredContainer{478 hooks: &Hooks{},479 host: host.Host{480 DirectConfig: &direct.Config{},481 },482 container: &container{483 base: base{484 config: types.ContainerConfig{},485 runtimeConfig: asRuntime(fakeRuntime()),486 },487 },488 },489 },490 }491 if err := testContainers.ensureExists(testContainerName); err != nil {492 t.Fatalf("Ensuring that new container exists should succeed, got: %v", err)493 }494 if _, ok := testContainers.currentState[testContainerName]; !ok {495 t.Fatalf("EnsureExists should save state of created container when creation succeeds")496 }497}498// ensureHost() tests.499func TestEnsureHostNoDiff(t *testing.T) {500 t.Parallel()501 testContainers := &containers{502 desiredState: containersState{503 testContainerName: &hostConfiguredContainer{504 host: host.Host{505 DirectConfig: &direct.Config{},506 },507 },508 },509 currentState: containersState{510 testContainerName: &hostConfiguredContainer{511 host: host.Host{512 DirectConfig: &direct.Config{},513 },514 },515 },516 }517 if err := testContainers.ensureHost(testContainerName); err != nil {518 t.Fatalf("Ensuring that container's host configuration is up to date should succeed, got: %v", err)519 }520}521func TestEnsureHostFailStart(t *testing.T) {522 t.Parallel()523 testContainers := &containers{524 currentState: containersState{525 testContainerName: &hostConfiguredContainer{526 host: host.Host{527 DirectConfig: &direct.Config{},528 },529 container: &container{530 base: base{531 status: types.ContainerStatus{532 ID: testContainerID,533 },534 runtimeConfig: asRuntime(fakeRuntime()),535 },536 },537 },538 },539 desiredState: containersState{540 testContainerName: &hostConfiguredContainer{541 hooks: &Hooks{},542 host: host.Host{543 DirectConfig: &direct.Config{544 Dummy: "foo",545 },546 },547 container: &container{548 base: base{549 runtimeConfig: asRuntime(failingStartRuntime()),550 },551 },552 },553 },554 }555 if err := testContainers.ensureHost(testContainerName); err == nil {556 t.Fatalf("Ensuring that container's host configuration is up to date should fail")557 }558 if gotID := testContainers.currentState[testContainerName].container.Status().ID; gotID != testAnotherContainerID {559 t.Logf("Expected container ID %q, got %q", testAnotherContainerID, gotID)560 t.Fatalf("Ensure host should persist state changes even if process fails")561 }562}563func TestEnsureHost(t *testing.T) {564 t.Parallel()565 testContainers := &containers{566 desiredState: containersState{567 testContainerName: &hostConfiguredContainer{568 hooks: &Hooks{},569 host: host.Host{570 DirectConfig: &direct.Config{571 Dummy: "foo",572 },573 },574 container: &container{575 base: base{576 runtimeConfig: asRuntime(fakeRuntime()),577 },578 },579 },580 },581 currentState: containersState{582 testContainerName: &hostConfiguredContainer{583 host: host.Host{584 DirectConfig: &direct.Config{},585 },586 container: &container{587 base: base{588 status: types.ContainerStatus{589 ID: testContainerID,590 },591 runtimeConfig: asRuntime(fakeRuntime()),592 },593 },594 },595 },596 }597 if err := testContainers.ensureHost(testContainerName); err != nil {598 t.Fatalf("Ensuring that container's host configuration is up to date should succeed, got: %v", err)599 }600 if testContainers.currentState[testContainerName].container.Status().ID != testAnotherContainerID {601 t.Fatalf("Ensure host should persist state changes even if process fails")602 }603}604// ensureContainer() tests.605func TestEnsureContainerNoDiff(t *testing.T) {606 t.Parallel()607 testContainers := &containers{608 desiredState: containersState{609 testContainerName: &hostConfiguredContainer{610 container: &container{611 base: base{612 config: types.ContainerConfig{},613 },614 },615 },616 },617 currentState: containersState{618 testContainerName: &hostConfiguredContainer{619 container: &container{620 base: base{621 config: types.ContainerConfig{},622 },623 },624 },625 },626 }627 if err := testContainers.ensureContainer(testContainerName); err != nil {628 t.Fatalf("Ensuring that container configuration is up to date should succeed, got: %v", err)629 }630}631func TestEnsureContainerFailStart(t *testing.T) {632 t.Parallel()633 testContainers := &containers{634 currentState: containersState{635 testContainerName: &hostConfiguredContainer{636 host: host.Host{637 DirectConfig: &direct.Config{},638 },639 container: &container{640 base: base{641 status: types.ContainerStatus{642 ID: testContainerID,643 },644 config: types.ContainerConfig{645 Image: testImage,646 },647 runtimeConfig: asRuntime(fakeRuntime()),648 },649 },650 },651 },652 desiredState: containersState{653 testContainerName: &hostConfiguredContainer{654 hooks: &Hooks{},655 host: host.Host{656 DirectConfig: &direct.Config{},657 },658 container: &container{659 base: base{660 config: types.ContainerConfig{661 Image: testImage,662 },663 runtimeConfig: asRuntime(failingStartRuntime()),664 },665 },666 },667 },668 }669 if err := testContainers.ensureContainer(testContainerName); err == nil {670 t.Fatalf("Ensuring that container configuration is up to date should fail")671 }672 if gotID := testContainers.currentState[testContainerName].container.Status().ID; gotID != testAnotherContainerID {673 t.Fatalf("Ensure container should persist state changes even if process fails")674 }675}676func TestEnsureContainer(t *testing.T) {677 t.Parallel()678 testContainers := &containers{679 desiredState: containersState{680 testContainerName: &hostConfiguredContainer{681 hooks: &Hooks{},682 host: host.Host{683 DirectConfig: &direct.Config{},684 },685 container: &container{686 base: base{687 config: types.ContainerConfig{688 Image: testImage,689 },690 runtimeConfig: asRuntime(fakeRuntime()),691 },692 },693 },694 },695 currentState: containersState{696 testContainerName: &hostConfiguredContainer{697 host: host.Host{698 DirectConfig: &direct.Config{},699 },700 container: &container{701 base: base{702 status: types.ContainerStatus{703 ID: testContainerID,704 },705 config: types.ContainerConfig{706 Image: testAnotherImage,707 },708 runtimeConfig: asRuntime(fakeRuntime()),709 },710 },711 },712 },713 }714 if err := testContainers.ensureContainer(testContainerName); err != nil {715 t.Fatalf("Ensuring that container configuration is up to date should succeed, got: %v", err)716 }717 if testContainers.currentState[testContainerName].container.Status().ID != testAnotherContainerID {718 t.Fatalf("Ensure container should persist state changes even if process fails")719 }720}721// recreate() tests.722func TestRecreateNonExistent(t *testing.T) {723 t.Parallel()724 testContainers := &containers{}725 if err := testContainers.recreate(testContainerName); err == nil {726 t.Fatalf("Recreating on empty containers should fail")727 }728}729// Deploy() tests.730func TestDeployNoCurrentState(t *testing.T) {731 t.Parallel()732 testContainers := &containers{}733 if err := testContainers.Deploy(); err == nil {734 t.Fatalf("Execute without current state should fail")735 }736}737// hasUpdates() tests.738func TestHasUpdatesHost(t *testing.T) {739 t.Parallel()740 testContainers := &containers{741 desiredState: containersState{742 testContainerName: &hostConfiguredContainer{743 container: &container{744 base: base{745 config: types.ContainerConfig{},746 },747 },748 host: host.Host{749 DirectConfig: &direct.Config{},750 },751 },752 },753 currentState: containersState{754 testContainerName: &hostConfiguredContainer{755 container: &container{756 base: base{757 config: types.ContainerConfig{},758 },759 },760 host: host.Host{},761 },762 },763 }764 u, err := testContainers.hasUpdates(testContainerName)765 if err != nil {766 t.Fatalf("Checking for updates should succeed, got: %v", err)767 }768 if !u {769 t.Fatalf("Container with host changes should indicate update")770 }771}772func TestHasUpdatesConfig(t *testing.T) {773 t.Parallel()774 testContainers := &containers{775 desiredState: containersState{776 testContainerName: &hostConfiguredContainer{777 container: &container{778 base: base{779 config: types.ContainerConfig{},780 },781 },782 configFiles: map[string]string{783 testConfigPath: testConfigContent,784 },785 },786 },787 currentState: containersState{788 testContainerName: &hostConfiguredContainer{789 container: &container{790 base: base{791 config: types.ContainerConfig{},792 },793 },794 },795 },796 }797 u, err := testContainers.hasUpdates(testContainerName)798 if err != nil {799 t.Fatalf("Checking for updates should succeed, got: %v", err)800 }801 if !u {802 t.Fatalf("Container with configuration files changes should indicate update")803 }804}805func TestHasUpdatesContainer(t *testing.T) {806 t.Parallel()807 testContainers := &containers{808 desiredState: containersState{809 testContainerName: &hostConfiguredContainer{810 container: &container{811 base: base{812 config: types.ContainerConfig{},813 },814 },815 },816 },817 currentState: containersState{818 testContainerName: &hostConfiguredContainer{819 container: &container{820 base: base{821 config: types.ContainerConfig{822 Name: testConfigContainerName,823 },824 },825 },826 },827 },828 }829 u, err := testContainers.hasUpdates(testContainerName)830 if err != nil {831 t.Fatalf("Checking for updates should succeed, got: %v", err)832 }833 if !u {834 t.Fatalf("Container with container configuration changes should indicate update")835 }836}837func TestHasUpdatesNoUpdates(t *testing.T) {838 t.Parallel()839 testContainers := &containers{840 desiredState: containersState{841 testContainerName: &hostConfiguredContainer{842 container: &container{843 base: base{844 config: types.ContainerConfig{},845 },846 },847 },848 },849 currentState: containersState{850 testContainerName: &hostConfiguredContainer{851 container: &container{852 base: base{853 config: types.ContainerConfig{},854 },855 },856 },857 },858 }859 u, err := testContainers.hasUpdates(testContainerName)860 if err != nil {861 t.Fatalf("Checking for updates should succeed, got: %v", err)862 }863 if u {864 t.Fatalf("Container with no changes should indicate no changes")865 }866}867// ensureConfigured() tests.868func TestEnsureConfiguredDisposable(t *testing.T) {869 t.Parallel()870 testContainers := &containers{871 desiredState: containersState{},872 currentState: containersState{873 testContainerName: &hostConfiguredContainer{874 configFiles: map[string]string{},875 },876 },877 }878 if err := testContainers.ensureConfigured(testContainerName); err != nil {879 t.Fatalf("Ensure configured should succeed when container is going to be removed, got: %v", err)880 }881}882func TestEnsureConfiguredNoUpdates(t *testing.T) {883 t.Parallel()884 testContainers := &containers{885 desiredState: containersState{886 testContainerName: &hostConfiguredContainer{887 configFiles: map[string]string{},888 },889 },890 currentState: containersState{891 testContainerName: &hostConfiguredContainer{892 configFiles: map[string]string{},893 },894 },895 }896 if err := testContainers.ensureConfigured(testContainerName); err != nil {897 t.Fatalf("Ensure configured should succeed, got: %v", err)898 }899}900const (901 testImage = "test-image"902 testAnotherImage = "test-another-image"903 testConfigContent = "test-config-content"904 testConfigPath = "/tmp/foo"905 testContainerID = "test-container-id"906 testAnotherContainerID = "test-another-container-id"907 testContainerName = "test-container-name"908 testConfigContainerName = "test-config-container-name"909 testAnotherContainerName = "test-another-container-name"910)911func TestEnsureConfigured(t *testing.T) {912 t.Parallel()913 called := false914 testConfigFiles := map[string]string{915 testConfigPath: testConfigContent,916 }917 testContainers := &containers{918 currentState: containersState{919 testContainerName: &hostConfiguredContainer{920 configFiles: map[string]string{},921 host: host.Host{922 DirectConfig: &direct.Config{},923 },924 container: &container{925 base: base{926 config: types.ContainerConfig{927 Image: testImage,928 },929 runtimeConfig: asRuntime(fakeRuntime()),930 },931 },932 },933 },934 desiredState: containersState{935 testContainerName: &hostConfiguredContainer{936 configFiles: testConfigFiles,937 host: host.Host{938 DirectConfig: &direct.Config{},939 },940 container: &container{941 base: base{942 config: types.ContainerConfig{943 Image: testImage,944 },945 runtimeConfig: asRuntime(testCopyingRuntime(t, &called, testContainerID, testConfigFiles)),946 },947 },948 },949 },950 }951 if err := testContainers.ensureConfigured(testContainerName); err != nil {952 t.Fatalf("Ensure configured should succeed, got: %v", err)953 }954 if !called {955 t.Fatalf("Should call Copy on container")956 }957}958func TestEnsureConfiguredFreshState(t *testing.T) {959 t.Parallel()960 called := false961 testConfigFiles := map[string]string{962 testConfigPath: testConfigContent,963 }964 testContainers := &containers{965 desiredState: containersState{966 testContainerName: &hostConfiguredContainer{967 configFiles: testConfigFiles,968 host: host.Host{969 DirectConfig: &direct.Config{},970 },971 container: &container{972 base: base{973 config: types.ContainerConfig{974 Image: testImage,975 },976 runtimeConfig: asRuntime(testCopyingRuntime(t, &called, testContainerID, testConfigFiles)),977 },978 },979 },980 },981 currentState: containersState{},982 }983 if err := testContainers.ensureConfigured(testContainerName); err != nil {984 t.Fatalf("Ensure configured should succeed, got: %v", err)985 }986 if !called {987 t.Fatalf("Should call Copy on container")988 }989}990func TestEnsureConfiguredNoStateUpdateOnFail(t *testing.T) {991 t.Parallel()992 testConfigFiles := map[string]string{993 testConfigPath: testConfigContent,994 }995 testContainers := &containers{996 desiredState: containersState{997 testContainerName: &hostConfiguredContainer{998 configFiles: testConfigFiles,999 host: host.Host{1000 DirectConfig: &direct.Config{},1001 },1002 container: &container{1003 base: base{1004 config: types.ContainerConfig{1005 Image: testImage,1006 },1007 runtimeConfig: &runtime.FakeConfig{1008 Runtime: &runtime.Fake{1009 CreateF: func(config *types.ContainerConfig) (string, error) {1010 return testContainerID, nil1011 },1012 StatusF: func(id string) (types.ContainerStatus, error) {1013 return types.ContainerStatus{}, nil1014 },1015 CopyF: func(id string, files []*types.File) error {1016 return fmt.Errorf("fail")1017 },1018 },1019 },1020 },1021 },1022 },1023 },1024 currentState: containersState{},1025 }1026 if err := testContainers.ensureConfigured(testContainerName); err == nil {1027 t.Fatalf("Ensure configured should fail")1028 }1029 if len(testContainers.currentState) != 0 {1030 t.Fatalf("If no files has been updated, current state should not be set")1031 }1032}1033// selectRuntime() tests.1034func TestSelectRuntime(t *testing.T) {1035 t.Parallel()1036 testContainer := &container{1037 base: base{1038 runtimeConfig: &docker.Config{},1039 },1040 }1041 if err := testContainer.selectRuntime(); err != nil {1042 t.Fatalf("Selecting runtime should succeed, got: %v", err)1043 }1044 if testContainer.base.runtime == nil {1045 t.Fatalf("SelectRuntime should set container runtime")1046 }1047}1048// DesiredState() tests.1049func TestContainersDesiredStateEmpty(t *testing.T) {1050 t.Parallel()1051 testContainers := &containers{}1052 e := ContainersState{}1053 if diff := cmp.Diff(e, testContainers.DesiredState()); diff != "" {1054 t.Fatalf("Unexpected diff: %s", diff)1055 }1056}1057func TestContainersDesiredStateOldID(t *testing.T) {1058 t.Parallel()1059 testContainers := &containers{1060 desiredState: containersState{1061 testContainerName: &hostConfiguredContainer{1062 container: &container{1063 base: base{1064 config: types.ContainerConfig{1065 Image: "a",1066 },1067 runtimeConfig: docker.DefaultConfig(),1068 },1069 },1070 },1071 },1072 previousState: containersState{1073 testContainerName: &hostConfiguredContainer{1074 container: &container{1075 base: base{1076 config: types.ContainerConfig{1077 Image: "b",1078 },1079 runtimeConfig: docker.DefaultConfig(),1080 status: types.ContainerStatus{1081 Status: "running",1082 ID: "foo",1083 },1084 },1085 },1086 },1087 },1088 }1089 expectedContainersState := ContainersState{1090 testContainerName: {1091 Container: Container{1092 Config: types.ContainerConfig{Image: "a"},1093 Status: &types.ContainerStatus{ID: "foo", Status: "running"},1094 Runtime: RuntimeConfig{1095 Docker: docker.DefaultConfig(),1096 },1097 },1098 ConfigFiles: map[string]string{},1099 },1100 }1101 if diff := cmp.Diff(testContainers.DesiredState(), expectedContainersState); diff != "" {1102 t.Fatalf("Unexpected diff: %s", diff)1103 }1104}1105func TestContainersDesiredStateStatusRunning(t *testing.T) {1106 t.Parallel()1107 testContainers := &containers{1108 desiredState: containersState{1109 testContainerName: &hostConfiguredContainer{1110 container: &container{1111 base: base{1112 config: types.ContainerConfig{1113 Image: "a",1114 },1115 runtimeConfig: docker.DefaultConfig(),1116 },1117 },1118 },1119 },1120 previousState: containersState{1121 testContainerName: &hostConfiguredContainer{1122 container: &container{1123 base: base{1124 config: types.ContainerConfig{1125 Image: "a",1126 },1127 runtimeConfig: docker.DefaultConfig(),1128 status: types.ContainerStatus{1129 Status: StatusMissing,1130 },1131 },1132 },1133 },1134 },1135 }1136 expectedContainersState := ContainersState{1137 testContainerName: {1138 Container: Container{1139 Config: types.ContainerConfig{Image: "a"},1140 Status: &types.ContainerStatus{Status: "running"},1141 Runtime: RuntimeConfig{1142 Docker: docker.DefaultConfig(),1143 },1144 },1145 ConfigFiles: map[string]string{},1146 },1147 }1148 if diff := cmp.Diff(testContainers.DesiredState(), expectedContainersState); diff != "" {1149 t.Fatalf("Unexpected diff: %s", diff)1150 }1151}1152// updateExistingContainers() tests.1153func TestUpdateExistingContainersRemoveAllOld(t *testing.T) {1154 t.Parallel()1155 fooRuntime := fakeRuntime()1156 fooRuntime.StatusF = func(id string) (types.ContainerStatus, error) {1157 return types.ContainerStatus{1158 Status: "running",1159 ID: "foo",1160 }, nil1161 }1162 barRuntime := fakeRuntime()1163 barRuntime.StatusF = func(id string) (types.ContainerStatus, error) {1164 return types.ContainerStatus{1165 Status: "running",1166 ID: "bar",1167 }, nil1168 }1169 testContainers := &containers{1170 desiredState: containersState{},1171 currentState: containersState{1172 testContainerName: &hostConfiguredContainer{1173 host: host.Host{1174 DirectConfig: &direct.Config{},1175 },1176 container: &container{1177 base: base{1178 status: types.ContainerStatus{1179 Status: "running",1180 ID: "foo",1181 },1182 runtimeConfig: asRuntime(fooRuntime),1183 },1184 },1185 },1186 testAnotherContainerName: &hostConfiguredContainer{1187 host: host.Host{1188 DirectConfig: &direct.Config{},1189 },1190 container: &container{1191 base: base{1192 status: types.ContainerStatus{1193 Status: "running",1194 ID: "bar",1195 },1196 runtimeConfig: asRuntime(barRuntime),1197 },1198 },1199 },1200 },1201 }1202 if err := testContainers.updateExistingContainers(); err != nil {1203 t.Fatalf("Updating existing containers should succeed, got: %v", err)1204 }1205 if len(testContainers.desiredState) != len(testContainers.currentState) {1206 t.Fatalf("All containers from current state should be removed")1207 }1208}1209// ensureCurrentContainer() tests.1210func TestEnsureCurrentContainer(t *testing.T) {1211 t.Parallel()1212 hcc := hostConfiguredContainer{1213 hooks: &Hooks{},1214 host: host.Host{1215 DirectConfig: &direct.Config{},1216 },1217 container: &container{1218 base: base{1219 status: types.ContainerStatus{1220 Status: "stopped",1221 ID: "foo",1222 },1223 runtimeConfig: &docker.Config{1224 Host: "unix:///nonexistent",1225 },1226 },1227 },1228 }1229 testContainers := &containers{1230 desiredState: containersState{1231 testContainerName: &hcc,1232 },1233 currentState: containersState{1234 testContainerName: &hcc,1235 },1236 }1237 _, err := testContainers.ensureCurrentContainer(testContainerName, hcc)1238 if err == nil {1239 t.Fatalf("Ensure stopped container should try to start the container and fail")1240 }1241 if !strings.Contains(err.Error(), "Is the docker daemon running?") {1242 t.Fatalf("Ensuring stopped container should fail to contact non existing runtime, got: %v", err)1243 }1244}1245func TestEnsureCurrentContainerNonExisting(t *testing.T) {1246 t.Parallel()1247 hcc := hostConfiguredContainer{1248 hooks: &Hooks{},1249 host: host.Host{1250 DirectConfig: &direct.Config{},1251 },1252 container: &container{1253 base: base{1254 status: types.ContainerStatus{1255 Status: "",1256 ID: "",1257 },1258 runtimeConfig: &docker.Config{1259 Host: "unix:///nonexistent",1260 },1261 },1262 },1263 }1264 testContainers := &containers{1265 desiredState: containersState{1266 testContainerName: &hcc,1267 },1268 currentState: containersState{1269 testContainerName: &hcc,1270 },1271 }1272 if _, err := testContainers.ensureCurrentContainer(testContainerName, hcc); err != nil {1273 t.Fatalf("Ensure stopped container should not fail on non-existing container, got: %v", err)1274 }1275 if len(testContainers.currentState) > 0 {1276 t.Fatalf("Ensuring removed container should remove it from current state to trigger creation")1277 }1278}1279func fakeRuntime() *runtime.Fake {1280 return &runtime.Fake{1281 CreateF: func(config *types.ContainerConfig) (string, error) {1282 return testContainerID, nil1283 },1284 StatusF: func(id string) (types.ContainerStatus, error) {1285 return types.ContainerStatus{1286 ID: testAnotherContainerID,1287 }, nil1288 },1289 DeleteF: func(id string) error {...
integration_test.go
Source:integration_test.go
...103 if !ok {104 continue105 }106 switch state.StringVal() {107 case metadata.LabelState.Active:108 present[state.StringVal()] = true109 case metadata.LabelState.Reading:110 present[state.StringVal()] = true111 case metadata.LabelState.Writing:112 present[state.StringVal()] = true113 case metadata.LabelState.Waiting:114 present[state.StringVal()] = true115 default:116 t.Error(fmt.Sprintf("connections with state %s not expected", state.StringVal()))117 }118 }119 // Ensure all 4 expected states were present120 require.Equal(t, 4, len(present))121 default:122 require.Nil(t, m.Name(), fmt.Sprintf("metric %s not expected", m.Name()))123 }124 }125}...
events_test.go
Source:events_test.go
...101 go func(i int) {102 defer wg.Done()103 amount := float64(rand.Intn(100))104 var e models.Event105 if i%5 == 0 { // StateWin106 e = genTestEvent(amount)107 } else { // StateLoss108 amount = amount * -1109 e = genTestEvent(amount)110 }111 err = eventsStorage.Create(ctx, e)112 if err != nil && errors.Cause(err) != errNegativeBalance {113 t.Error(err)114 return115 }116 if err == nil {117 tl.Lock()118 assumeTotal += e.Amount119 tl.Unlock()120 }121 }(i)122 t := time.Duration(rand.Int63n(5))123 time.Sleep(t * time.Millisecond)124 }125 wg.Wait()126 bal, err := getBalanceWithLock(ctx, db)127 a.NoError(err)128 t.Logf("Total balance: %f", bal)129 a.Equal(assumeTotal, bal)130 if bal < 0 {131 t.Error("Negative balance")132 }133}134func TestCancelLastOddEvents(t *testing.T) {135 a := assert.New(t)136 ctx := context.Background()137 postgresC, db, err := setupPostgresContainer(ctx)138 if postgresC != nil {139 defer postgresC.Terminate(ctx)140 }141 if err != nil {142 t.Error(err)143 return144 }145 eventsStorage := NewEvents(db)146 assumeBalance := 520.147 for i := 0; i < 40; i++ {148 e := genTestEvent(float64(i) + 1)149 err := eventsStorage.Create(ctx, e)150 a.NoError(err)151 }152 err = eventsStorage.CancelLastOddEvents(ctx, 10)153 a.NoError(err)154 bal, err := getBalanceWithLock(ctx, db)155 a.NoError(err)156 a.Equal(assumeBalance, bal)157}158func genTestEvent(amount float64) models.Event {159 u := uuid.New()160 var state models.EventState161 if amount > 0 {162 state = models.StateWin163 } else {164 state = models.StateLoss165 }166 return models.Event{167 State: state,168 Amount: amount,169 Status: models.StatusProcessed,170 TransactionID: u.String(),171 }172}...
State
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"6379/tcp"},6 WaitingFor: wait.ForListeningPort("6379/tcp"),7 }8 redis, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 defer redis.Terminate(ctx)14 ip, err := redis.Host(ctx)15 if err != nil {16 log.Fatal(err)17 }18 port, err := redis.MappedPort(ctx, "6379/tcp")19 if err != nil {20 log.Fatal(err)21 }22 fmt.Printf("Redis is available at %s:%s", ip, port.Port())23 state, err := redis.State(ctx)24 if err != nil {25 log.Fatal(err)26 }27 fmt.Println("Container state is", state)28}
State
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 panic(err)12 }13 defer postgresContainer.Terminate(ctx)14 ip, err := postgresContainer.Host(ctx)15 if err != nil {16 panic(err)17 }18 port, err := postgresContainer.MappedPort(ctx, "5432")19 if err != nil {20 panic(err)21 }22 fmt.Printf("postgres is available on %s:%s\n", ip, port.Port())23}24github.com/testcontainers/testcontainers-go.(*TestContainerRequest).Container(0xc0000c6b40, 0x7f1c2b2e2b00, 0xc0000c6b40, 0xc0000c6b40, 0x0)
State
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"6379/tcp"},6 WaitingFor: wait.ForListeningPort("6379/tcp"),7 }8 redis, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 defer redis.Terminate(ctx)14 redisID, err := redis.ContainerID(ctx)15 if err != nil {16 log.Fatal(err)17 }18 fmt.Println("Redis container ID is: ", redisID)19 mappedPort, err := redis.MappedPort(ctx, "6379/tcp")20 if err != nil {21 log.Fatal(err)22 }23 fmt.Println("Redis mapped port is: ", mappedPort)24 redisIP, err := redis.Host(ctx)25 if err != nil {26 log.Fatal(err)27 }28 fmt.Println("Redis container IP is: ", redisIP)29 redisState, err := redis.State(ctx)30 if err != nil {31 log.Fatal(err)32 }33 fmt.Println("Redis container state is: ", redisState)34 redisLogs, err := redis.Logs(ctx)35 if err != nil {36 log.Fatal(err)37 }38 fmt.Println("Redis container logs are: ", redisLogs)39 redisInfo, err := redis.Inspect(ctx)40 if err != nil {41 log.Fatal(err)42 }43 fmt.Println("Redis container info is: ", redisInfo)44 redisName, err := redis.Name(ctx)45 if err != nil {46 log.Fatal(err)47 }48 fmt.Println("Redis container name is: ", redisName)49 redisImage, err := redis.Image(ctx)50 if err != nil {51 log.Fatal(err)52 }53 fmt.Println("Redis container image is: ", redisImage)54 redisPlatform, err := redis.Platform(ctx)
State
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"6379/tcp"},6 WaitingFor: wait.ForLog("Ready to accept connections"),7 }8 redisContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 defer redisContainer.Terminate(ctx)14 redisContainerID, err := redisContainer.ContainerID(ctx)15 if err != nil {16 log.Fatal(err)17 }18 fmt.Println(redisContainerID)19 redisContainerState, err := redisContainer.State(ctx)20 if err != nil {21 log.Fatal(err)22 }23 fmt.Println(redisContainerState)24}
State
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 Cmd: []string{"sh", "-c", "while true; do echo hello world; sleep 1; done"},6 ExposedPorts: []string{"80/tcp"},7 WaitingFor: wait.ForLog("hello world"),8 }9 c, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{10 })11 if err != nil {12 log.Fatal(err)13 }14 defer c.Terminate(ctx)15 ip, err := c.Host(ctx)16 if err != nil {17 log.Fatal(err)18 }19 port, err := c.MappedPort(ctx, "80")20 if err != nil {21 log.Fatal(err)22 }23 fmt.Printf("Container is listening on %s:%s", ip, port.Port())24 time.Sleep(5 * time.Second)25 state, err := c.State(ctx)26 if err != nil {27 log.Fatal(err)28 }29 fmt.Printf("Container state: %s", state.String())30 err = c.Stop(ctx)31 if err != nil {32 log.Fatal(err)33 }34 state, err = c.State(ctx)35 if err != nil {36 log.Fatal(err)37 }38 fmt.Printf("Container state: %s", state.String())39 err = c.Terminate(ctx)40 if err != nil {41 log.Fatal(err)42 }43 state, err = c.State(ctx)44 if err != nil {45 log.Fatal(err)46 }47 fmt.Printf("Container state: %s", state.String())48}
State
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 Cmd: []string{"sleep", "3600"},6 WaitingFor: wait.ForLog("listening"),7 }8 c, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 panic(err)12 }13 defer c.Terminate(ctx)14 fmt.Println(c.State(ctx))15}16{true 0xc0000b4000}17import (18func main() {19 ctx := context.Background()20 req := testcontainers.ContainerRequest{21 Cmd: []string{"sleep", "3600"},22 WaitingFor: wait.ForLog("listening"),23 }24 c, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{25 })26 if err != nil {27 panic(err)28 }29 defer c.Terminate(ctx)30 fmt.Println(c.State(ctx))31 time.Sleep(5 * time.Second)32 c.Stop(ctx)33 fmt.Println(c.State(ctx))34}35{true 0xc0000b4000}36{false 0xc0000b4000}
State
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"4444/tcp"},6 WaitingFor: wait.ForListeningPort("4444/tcp"),7 Env: map[string]string{
State
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"80/tcp"},6 WaitingFor: wait.ForLog("listening on port 80"),7 }8 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 state, err := container.State(ctx)14 if err != nil {15 log.Fatal(err)16 }17 fmt.Println(state)18 defer container.Terminate(ctx)19}20import (21func main() {22 ctx := context.Background()23 req := testcontainers.ContainerRequest{24 ExposedPorts: []string{"80/tcp"},25 WaitingFor: wait.ForLog("listening on port 80"),26 }27 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{28 })29 if err != nil {30 log.Fatal(err)31 }32 state, err := container.State(ctx)33 if err != nil {34 log.Fatal(err)35 }36 fmt.Println(state)37 defer container.Terminate(ctx)38}
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!!