forked from testcontainers/testcontainers-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lifecycle_test.go
918 lines (803 loc) · 28.1 KB
/
lifecycle_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
package testcontainers
import (
"bufio"
"context"
"fmt"
"strings"
"testing"
"time"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/mount"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/api/types/strslice"
"github.com/docker/go-connections/nat"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/testcontainers/testcontainers-go/wait"
)
func TestPreCreateModifierHook(t *testing.T) {
ctx := context.Background()
provider, err := NewDockerProvider()
require.NoError(t, err)
defer provider.Close()
t.Run("No exposed ports", func(t *testing.T) {
// reqWithModifiers {
req := ContainerRequest{
Image: nginxAlpineImage, // alpine image does expose port 80
ConfigModifier: func(config *container.Config) {
config.Env = []string{"a=b"}
},
Mounts: ContainerMounts{
{
Source: DockerVolumeMountSource{
Name: "appdata",
VolumeOptions: &mount.VolumeOptions{
Labels: GenericLabels(),
},
},
Target: "/data",
},
},
HostConfigModifier: func(hostConfig *container.HostConfig) {
hostConfig.PortBindings = nat.PortMap{
"80/tcp": []nat.PortBinding{
{
HostIP: "1",
HostPort: "2",
},
},
}
},
EnpointSettingsModifier: func(endpointSettings map[string]*network.EndpointSettings) {
endpointSettings["a"] = &network.EndpointSettings{
Aliases: []string{"b"},
Links: []string{"link1", "link2"},
}
},
}
// }
// define empty inputs to be overwritten by the pre create hook
inputConfig := &container.Config{
Image: req.Image,
}
inputHostConfig := &container.HostConfig{}
inputNetworkingConfig := &network.NetworkingConfig{}
err = provider.preCreateContainerHook(ctx, req, inputConfig, inputHostConfig, inputNetworkingConfig)
require.NoError(t, err)
// assertions
assert.Equal(
t,
[]string{"a=b"},
inputConfig.Env,
"Docker config's env should be overwritten by the modifier",
)
assert.Equal(t,
nat.PortSet(nat.PortSet{"80/tcp": struct{}{}}),
inputConfig.ExposedPorts,
"Docker config's exposed ports should be overwritten by the modifier",
)
assert.Equal(
t,
[]mount.Mount{
{
Type: mount.TypeVolume,
Source: "appdata",
Target: "/data",
VolumeOptions: &mount.VolumeOptions{
Labels: GenericLabels(),
},
},
},
inputHostConfig.Mounts,
"Host config's mounts should be mapped to Docker types",
)
assert.Equal(t, nat.PortMap{
"80/tcp": []nat.PortBinding{
{
HostIP: "",
HostPort: "",
},
},
}, inputHostConfig.PortBindings,
"Host config's port bindings should be overwritten by the modifier",
)
assert.Equal(
t,
[]string{"b"},
inputNetworkingConfig.EndpointsConfig["a"].Aliases,
"Networking config's aliases should be overwritten by the modifier",
)
assert.Equal(
t,
[]string{"link1", "link2"},
inputNetworkingConfig.EndpointsConfig["a"].Links,
"Networking config's links should be overwritten by the modifier",
)
})
t.Run("No exposed ports and network mode IsContainer", func(t *testing.T) {
req := ContainerRequest{
Image: nginxAlpineImage, // alpine image does expose port 80
HostConfigModifier: func(hostConfig *container.HostConfig) {
hostConfig.PortBindings = nat.PortMap{
"80/tcp": []nat.PortBinding{
{
HostIP: "1",
HostPort: "2",
},
},
}
hostConfig.NetworkMode = "container:foo"
},
}
// define empty inputs to be overwritten by the pre create hook
inputConfig := &container.Config{
Image: req.Image,
}
inputHostConfig := &container.HostConfig{}
inputNetworkingConfig := &network.NetworkingConfig{}
err = provider.preCreateContainerHook(ctx, req, inputConfig, inputHostConfig, inputNetworkingConfig)
require.NoError(t, err)
// assertions
assert.Equal(
t,
nat.PortSet(nat.PortSet{}),
inputConfig.ExposedPorts,
"Docker config's exposed ports should be empty",
)
assert.Equal(t,
nat.PortMap{},
inputHostConfig.PortBindings,
"Host config's portBinding should be empty",
)
})
t.Run("Nil hostConfigModifier should apply default host config modifier", func(t *testing.T) {
req := ContainerRequest{
Image: nginxAlpineImage, // alpine image does expose port 80
AutoRemove: true,
CapAdd: []string{"addFoo", "addBar"},
CapDrop: []string{"dropFoo", "dropBar"},
Binds: []string{"bindFoo", "bindBar"},
ExtraHosts: []string{"hostFoo", "hostBar"},
NetworkMode: "networkModeFoo",
Resources: container.Resources{
Memory: 2048,
NanoCPUs: 8,
},
HostConfigModifier: nil,
}
// define empty inputs to be overwritten by the pre create hook
inputConfig := &container.Config{
Image: req.Image,
}
inputHostConfig := &container.HostConfig{}
inputNetworkingConfig := &network.NetworkingConfig{}
err = provider.preCreateContainerHook(ctx, req, inputConfig, inputHostConfig, inputNetworkingConfig)
require.NoError(t, err)
// assertions
assert.Equal(t, req.AutoRemove, inputHostConfig.AutoRemove, "Deprecated AutoRemove should come from the container request")
assert.Equal(t, strslice.StrSlice(req.CapAdd), inputHostConfig.CapAdd, "Deprecated CapAdd should come from the container request")
assert.Equal(t, strslice.StrSlice(req.CapDrop), inputHostConfig.CapDrop, "Deprecated CapDrop should come from the container request")
assert.Equal(t, req.Binds, inputHostConfig.Binds, "Deprecated Binds should come from the container request")
assert.Equal(t, req.ExtraHosts, inputHostConfig.ExtraHosts, "Deprecated ExtraHosts should come from the container request")
assert.Equal(t, req.Resources, inputHostConfig.Resources, "Deprecated Resources should come from the container request")
})
t.Run("Request contains more than one network including aliases", func(t *testing.T) {
networkName := "foo"
net, err := provider.CreateNetwork(ctx, NetworkRequest{
Name: networkName,
})
require.NoError(t, err)
defer func() {
err := net.Remove(ctx)
if err != nil {
t.Logf("failed to remove network %s: %s\n", networkName, err)
}
}()
dockerNetwork, err := provider.GetNetwork(ctx, NetworkRequest{
Name: networkName,
})
require.NoError(t, err)
req := ContainerRequest{
Image: nginxAlpineImage, // alpine image does expose port 80
Networks: []string{networkName, "bar"},
NetworkAliases: map[string][]string{
"foo": {"foo1"}, // network aliases are needed at the moment there is a network
},
}
// define empty inputs to be overwritten by the pre create hook
inputConfig := &container.Config{
Image: req.Image,
}
inputHostConfig := &container.HostConfig{}
inputNetworkingConfig := &network.NetworkingConfig{}
err = provider.preCreateContainerHook(ctx, req, inputConfig, inputHostConfig, inputNetworkingConfig)
require.NoError(t, err)
// assertions
assert.Equal(
t,
req.NetworkAliases[networkName],
inputNetworkingConfig.EndpointsConfig[networkName].Aliases,
"Networking config's aliases should come from the container request",
)
assert.Equal(
t,
dockerNetwork.ID,
inputNetworkingConfig.EndpointsConfig[networkName].NetworkID,
"Networking config's network ID should be retrieved from Docker",
)
})
t.Run("Request contains more than one network without aliases", func(t *testing.T) {
networkName := "foo"
net, err := provider.CreateNetwork(ctx, NetworkRequest{
Name: networkName,
})
require.NoError(t, err)
defer func() {
err := net.Remove(ctx)
if err != nil {
t.Logf("failed to remove network %s: %s\n", networkName, err)
}
}()
dockerNetwork, err := provider.GetNetwork(ctx, NetworkRequest{
Name: networkName,
})
require.NoError(t, err)
req := ContainerRequest{
Image: nginxAlpineImage, // alpine image does expose port 80
Networks: []string{networkName, "bar"},
}
// define empty inputs to be overwritten by the pre create hook
inputConfig := &container.Config{
Image: req.Image,
}
inputHostConfig := &container.HostConfig{}
inputNetworkingConfig := &network.NetworkingConfig{}
err = provider.preCreateContainerHook(ctx, req, inputConfig, inputHostConfig, inputNetworkingConfig)
require.NoError(t, err)
// assertions
assert.Empty(
t,
inputNetworkingConfig.EndpointsConfig[networkName].Aliases,
"Networking config's aliases should be empty",
)
assert.Equal(
t,
dockerNetwork.ID,
inputNetworkingConfig.EndpointsConfig[networkName].NetworkID,
"Networking config's network ID should be retrieved from Docker",
)
})
t.Run("Request contains exposed port modifiers without protocol", func(t *testing.T) {
req := ContainerRequest{
Image: nginxAlpineImage, // alpine image does expose port 80
HostConfigModifier: func(hostConfig *container.HostConfig) {
hostConfig.PortBindings = nat.PortMap{
"80/tcp": []nat.PortBinding{
{
HostIP: "localhost",
HostPort: "8080",
},
},
}
},
ExposedPorts: []string{"80"},
}
// define empty inputs to be overwritten by the pre create hook
inputConfig := &container.Config{
Image: req.Image,
}
inputHostConfig := &container.HostConfig{}
inputNetworkingConfig := &network.NetworkingConfig{}
err = provider.preCreateContainerHook(ctx, req, inputConfig, inputHostConfig, inputNetworkingConfig)
require.NoError(t, err)
// assertions
assert.Equal(t, "localhost", inputHostConfig.PortBindings["80/tcp"][0].HostIP)
assert.Equal(t, "8080", inputHostConfig.PortBindings["80/tcp"][0].HostPort)
})
t.Run("Request contains exposed port modifiers with protocol", func(t *testing.T) {
req := ContainerRequest{
Image: nginxAlpineImage, // alpine image does expose port 80
HostConfigModifier: func(hostConfig *container.HostConfig) {
hostConfig.PortBindings = nat.PortMap{
"80/tcp": []nat.PortBinding{
{
HostIP: "localhost",
HostPort: "8080",
},
},
}
},
ExposedPorts: []string{"80/tcp"},
}
// define empty inputs to be overwritten by the pre create hook
inputConfig := &container.Config{
Image: req.Image,
}
inputHostConfig := &container.HostConfig{}
inputNetworkingConfig := &network.NetworkingConfig{}
err = provider.preCreateContainerHook(ctx, req, inputConfig, inputHostConfig, inputNetworkingConfig)
require.NoError(t, err)
// assertions
assert.Equal(t, "localhost", inputHostConfig.PortBindings["80/tcp"][0].HostIP)
assert.Equal(t, "8080", inputHostConfig.PortBindings["80/tcp"][0].HostPort)
})
}
func TestMergePortBindings(t *testing.T) {
type arg struct {
configPortMap nat.PortMap
parsedPortMap nat.PortMap
exposedPorts []string
}
cases := []struct {
name string
arg arg
expected nat.PortMap
}{
{
name: "empty ports",
arg: arg{
configPortMap: nil,
parsedPortMap: nil,
exposedPorts: nil,
},
expected: map[nat.Port][]nat.PortBinding{},
},
{
name: "config port map but not exposed",
arg: arg{
configPortMap: map[nat.Port][]nat.PortBinding{
"80/tcp": {{HostIP: "1", HostPort: "2"}},
},
parsedPortMap: nil,
exposedPorts: nil,
},
expected: map[nat.Port][]nat.PortBinding{},
},
{
name: "parsed port map without config",
arg: arg{
configPortMap: nil,
parsedPortMap: map[nat.Port][]nat.PortBinding{
"80/tcp": {{HostIP: "", HostPort: ""}},
},
exposedPorts: nil,
},
expected: map[nat.Port][]nat.PortBinding{
"80/tcp": {{HostIP: "", HostPort: ""}},
},
},
{
name: "parsed and configured but not exposed",
arg: arg{
configPortMap: map[nat.Port][]nat.PortBinding{
"80/tcp": {{HostIP: "1", HostPort: "2"}},
},
parsedPortMap: map[nat.Port][]nat.PortBinding{
"80/tcp": {{HostIP: "", HostPort: ""}},
},
exposedPorts: nil,
},
expected: map[nat.Port][]nat.PortBinding{
"80/tcp": {{HostIP: "", HostPort: ""}},
},
},
{
name: "merge both parsed and config",
arg: arg{
configPortMap: map[nat.Port][]nat.PortBinding{
"60/tcp": {{HostIP: "1", HostPort: "2"}},
"70/tcp": {{HostIP: "1", HostPort: "2"}},
"80/tcp": {{HostIP: "1", HostPort: "2"}},
},
parsedPortMap: map[nat.Port][]nat.PortBinding{
"80/tcp": {{HostIP: "", HostPort: ""}},
"90/tcp": {{HostIP: "", HostPort: ""}},
},
exposedPorts: []string{"70", "80/tcp"},
},
expected: map[nat.Port][]nat.PortBinding{
"70/tcp": {{HostIP: "1", HostPort: "2"}},
"80/tcp": {{HostIP: "1", HostPort: "2"}},
"90/tcp": {{HostIP: "", HostPort: ""}},
},
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
res := mergePortBindings(c.arg.configPortMap, c.arg.parsedPortMap, c.arg.exposedPorts)
assert.Equal(t, c.expected, res)
})
}
}
func TestLifecycleHooks(t *testing.T) {
tests := []struct {
name string
reuse bool
}{
{
name: "GenericContainer",
reuse: false,
},
{
name: "ReuseContainer",
reuse: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
prints := []string{}
ctx := context.Background()
// reqWithLifecycleHooks {
req := ContainerRequest{
Image: nginxAlpineImage,
LifecycleHooks: []ContainerLifecycleHooks{
{
PreCreates: []ContainerRequestHook{
func(ctx context.Context, req ContainerRequest) error {
prints = append(prints, fmt.Sprintf("pre-create hook 1: %#v", req))
return nil
},
func(ctx context.Context, req ContainerRequest) error {
prints = append(prints, fmt.Sprintf("pre-create hook 2: %#v", req))
return nil
},
},
PostCreates: []ContainerHook{
func(ctx context.Context, c Container) error {
prints = append(prints, fmt.Sprintf("post-create hook 1: %#v", c))
return nil
},
func(ctx context.Context, c Container) error {
prints = append(prints, fmt.Sprintf("post-create hook 2: %#v", c))
return nil
},
},
PreStarts: []ContainerHook{
func(ctx context.Context, c Container) error {
prints = append(prints, fmt.Sprintf("pre-start hook 1: %#v", c))
return nil
},
func(ctx context.Context, c Container) error {
prints = append(prints, fmt.Sprintf("pre-start hook 2: %#v", c))
return nil
},
},
PostStarts: []ContainerHook{
func(ctx context.Context, c Container) error {
prints = append(prints, fmt.Sprintf("post-start hook 1: %#v", c))
return nil
},
func(ctx context.Context, c Container) error {
prints = append(prints, fmt.Sprintf("post-start hook 2: %#v", c))
return nil
},
},
PostReadies: []ContainerHook{
func(ctx context.Context, c Container) error {
prints = append(prints, fmt.Sprintf("post-ready hook 1: %#v", c))
return nil
},
func(ctx context.Context, c Container) error {
prints = append(prints, fmt.Sprintf("post-ready hook 2: %#v", c))
return nil
},
},
PreStops: []ContainerHook{
func(ctx context.Context, c Container) error {
prints = append(prints, fmt.Sprintf("pre-stop hook 1: %#v", c))
return nil
},
func(ctx context.Context, c Container) error {
prints = append(prints, fmt.Sprintf("pre-stop hook 2: %#v", c))
return nil
},
},
PostStops: []ContainerHook{
func(ctx context.Context, c Container) error {
prints = append(prints, fmt.Sprintf("post-stop hook 1: %#v", c))
return nil
},
func(ctx context.Context, c Container) error {
prints = append(prints, fmt.Sprintf("post-stop hook 2: %#v", c))
return nil
},
},
PreTerminates: []ContainerHook{
func(ctx context.Context, c Container) error {
prints = append(prints, fmt.Sprintf("pre-terminate hook 1: %#v", c))
return nil
},
func(ctx context.Context, c Container) error {
prints = append(prints, fmt.Sprintf("pre-terminate hook 2: %#v", c))
return nil
},
},
PostTerminates: []ContainerHook{
func(ctx context.Context, c Container) error {
prints = append(prints, fmt.Sprintf("post-terminate hook 1: %#v", c))
return nil
},
func(ctx context.Context, c Container) error {
prints = append(prints, fmt.Sprintf("post-terminate hook 2: %#v", c))
return nil
},
},
},
},
}
// }
if tt.reuse {
req.Name = "reuse-container"
}
c, err := GenericContainer(ctx, GenericContainerRequest{
ContainerRequest: req,
Reuse: tt.reuse,
Started: true,
})
require.NoError(t, err)
require.NotNil(t, c)
duration := 1 * time.Second
err = c.Stop(ctx, &duration)
require.NoError(t, err)
err = c.Start(ctx)
require.NoError(t, err)
err = c.Terminate(ctx)
require.NoError(t, err)
lifecycleHooksIsHonouredFn(t, ctx, prints)
})
}
}
// customLoggerImplementation {
type inMemoryLogger struct {
data []string
}
func (l *inMemoryLogger) Printf(format string, args ...interface{}) {
l.data = append(l.data, fmt.Sprintf(format, args...))
}
// }
func TestLifecycleHooks_WithDefaultLogger(t *testing.T) {
ctx := context.Background()
// reqWithDefaultLogginHook {
dl := inMemoryLogger{}
req := ContainerRequest{
Image: nginxAlpineImage,
LifecycleHooks: []ContainerLifecycleHooks{
DefaultLoggingHook(&dl),
},
}
// }
c, err := GenericContainer(ctx, GenericContainerRequest{
ContainerRequest: req,
Started: true,
})
require.NoError(t, err)
require.NotNil(t, c)
duration := 1 * time.Second
err = c.Stop(ctx, &duration)
require.NoError(t, err)
err = c.Start(ctx)
require.NoError(t, err)
err = c.Terminate(ctx)
require.NoError(t, err)
require.Len(t, dl.data, 12)
}
func TestCombineLifecycleHooks(t *testing.T) {
prints := []string{}
preCreateFunc := func(prefix string, hook string, lifecycleID int, hookID int) func(ctx context.Context, req ContainerRequest) error {
return func(ctx context.Context, _ ContainerRequest) error {
prints = append(prints, fmt.Sprintf("[%s] pre-%s hook %d.%d", prefix, hook, lifecycleID, hookID))
return nil
}
}
hookFunc := func(prefix string, hookType string, hook string, lifecycleID int, hookID int) func(ctx context.Context, c Container) error {
return func(ctx context.Context, _ Container) error {
prints = append(prints, fmt.Sprintf("[%s] %s-%s hook %d.%d", prefix, hookType, hook, lifecycleID, hookID))
return nil
}
}
preFunc := func(prefix string, hook string, lifecycleID int, hookID int) func(ctx context.Context, c Container) error {
return hookFunc(prefix, "pre", hook, lifecycleID, hookID)
}
postFunc := func(prefix string, hook string, lifecycleID int, hookID int) func(ctx context.Context, c Container) error {
return hookFunc(prefix, "post", hook, lifecycleID, hookID)
}
lifecycleHookFunc := func(prefix string, lifecycleID int) ContainerLifecycleHooks {
return ContainerLifecycleHooks{
PreCreates: []ContainerRequestHook{preCreateFunc(prefix, "create", lifecycleID, 1), preCreateFunc(prefix, "create", lifecycleID, 2)},
PostCreates: []ContainerHook{postFunc(prefix, "create", lifecycleID, 1), postFunc(prefix, "create", lifecycleID, 2)},
PreStarts: []ContainerHook{preFunc(prefix, "start", lifecycleID, 1), preFunc(prefix, "start", lifecycleID, 2)},
PostStarts: []ContainerHook{postFunc(prefix, "start", lifecycleID, 1), postFunc(prefix, "start", lifecycleID, 2)},
PostReadies: []ContainerHook{postFunc(prefix, "ready", lifecycleID, 1), postFunc(prefix, "ready", lifecycleID, 2)},
PreStops: []ContainerHook{preFunc(prefix, "stop", lifecycleID, 1), preFunc(prefix, "stop", lifecycleID, 2)},
PostStops: []ContainerHook{postFunc(prefix, "stop", lifecycleID, 1), postFunc(prefix, "stop", lifecycleID, 2)},
PreTerminates: []ContainerHook{preFunc(prefix, "terminate", lifecycleID, 1), preFunc(prefix, "terminate", lifecycleID, 2)},
PostTerminates: []ContainerHook{postFunc(prefix, "terminate", lifecycleID, 1), postFunc(prefix, "terminate", lifecycleID, 2)},
}
}
defaultHooks := []ContainerLifecycleHooks{lifecycleHookFunc("default", 1), lifecycleHookFunc("default", 2)}
userDefinedHooks := []ContainerLifecycleHooks{lifecycleHookFunc("user-defined", 1), lifecycleHookFunc("user-defined", 2), lifecycleHookFunc("user-defined", 3)}
hooks := combineContainerHooks(defaultHooks, userDefinedHooks)
// call all the hooks in the right order, honouring the lifecycle
req := ContainerRequest{}
err := hooks.Creating(context.Background())(req)
require.NoError(t, err)
c := &DockerContainer{}
err = hooks.Created(context.Background())(c)
require.NoError(t, err)
err = hooks.Starting(context.Background())(c)
require.NoError(t, err)
err = hooks.Started(context.Background())(c)
require.NoError(t, err)
err = hooks.Readied(context.Background())(c)
require.NoError(t, err)
err = hooks.Stopping(context.Background())(c)
require.NoError(t, err)
err = hooks.Stopped(context.Background())(c)
require.NoError(t, err)
err = hooks.Terminating(context.Background())(c)
require.NoError(t, err)
err = hooks.Terminated(context.Background())(c)
require.NoError(t, err)
// assertions
// There are 2 default container lifecycle hooks and 3 user-defined container lifecycle hooks.
// Each lifecycle hook has 2 pre-create hooks and 2 post-create hooks.
// That results in 16 hooks per lifecycle (8 defaults + 12 user-defined = 20)
// There are 5 lifecycles (create, start, ready, stop, terminate),
// but ready has only half of the hooks (it only has post), so we have 90 hooks in total.
assert.Len(t, prints, 90)
// The order of the hooks is:
// - pre-X hooks: first default (2*2), then user-defined (3*2)
// - post-X hooks: first user-defined (3*2), then default (2*2)
for i := 0; i < 5; i++ {
var hookType string
// this is the particular order of execution for the hooks
switch i {
case 0:
hookType = "create"
case 1:
hookType = "start"
case 2:
hookType = "ready"
case 3:
hookType = "stop"
case 4:
hookType = "terminate"
}
initialIndex := i * 20
if i >= 2 {
initialIndex -= 10
}
if hookType != "ready" {
// default pre-hooks: 4 hooks
assert.Equal(t, fmt.Sprintf("[default] pre-%s hook 1.1", hookType), prints[initialIndex])
assert.Equal(t, fmt.Sprintf("[default] pre-%s hook 1.2", hookType), prints[initialIndex+1])
assert.Equal(t, fmt.Sprintf("[default] pre-%s hook 2.1", hookType), prints[initialIndex+2])
assert.Equal(t, fmt.Sprintf("[default] pre-%s hook 2.2", hookType), prints[initialIndex+3])
// user-defined pre-hooks: 6 hooks
assert.Equal(t, fmt.Sprintf("[user-defined] pre-%s hook 1.1", hookType), prints[initialIndex+4])
assert.Equal(t, fmt.Sprintf("[user-defined] pre-%s hook 1.2", hookType), prints[initialIndex+5])
assert.Equal(t, fmt.Sprintf("[user-defined] pre-%s hook 2.1", hookType), prints[initialIndex+6])
assert.Equal(t, fmt.Sprintf("[user-defined] pre-%s hook 2.2", hookType), prints[initialIndex+7])
assert.Equal(t, fmt.Sprintf("[user-defined] pre-%s hook 3.1", hookType), prints[initialIndex+8])
assert.Equal(t, fmt.Sprintf("[user-defined] pre-%s hook 3.2", hookType), prints[initialIndex+9])
}
// user-defined post-hooks: 6 hooks
assert.Equal(t, fmt.Sprintf("[user-defined] post-%s hook 1.1", hookType), prints[initialIndex+10])
assert.Equal(t, fmt.Sprintf("[user-defined] post-%s hook 1.2", hookType), prints[initialIndex+11])
assert.Equal(t, fmt.Sprintf("[user-defined] post-%s hook 2.1", hookType), prints[initialIndex+12])
assert.Equal(t, fmt.Sprintf("[user-defined] post-%s hook 2.2", hookType), prints[initialIndex+13])
assert.Equal(t, fmt.Sprintf("[user-defined] post-%s hook 3.1", hookType), prints[initialIndex+14])
assert.Equal(t, fmt.Sprintf("[user-defined] post-%s hook 3.2", hookType), prints[initialIndex+15])
// default post-hooks: 4 hooks
assert.Equal(t, fmt.Sprintf("[default] post-%s hook 1.1", hookType), prints[initialIndex+16])
assert.Equal(t, fmt.Sprintf("[default] post-%s hook 1.2", hookType), prints[initialIndex+17])
assert.Equal(t, fmt.Sprintf("[default] post-%s hook 2.1", hookType), prints[initialIndex+18])
assert.Equal(t, fmt.Sprintf("[default] post-%s hook 2.2", hookType), prints[initialIndex+19])
}
}
func TestLifecycleHooks_WithMultipleHooks(t *testing.T) {
ctx := context.Background()
dl := inMemoryLogger{}
req := ContainerRequest{
Image: nginxAlpineImage,
LifecycleHooks: []ContainerLifecycleHooks{
DefaultLoggingHook(&dl),
DefaultLoggingHook(&dl),
},
}
c, err := GenericContainer(ctx, GenericContainerRequest{
ContainerRequest: req,
Started: true,
})
require.NoError(t, err)
require.NotNil(t, c)
duration := 1 * time.Second
err = c.Stop(ctx, &duration)
require.NoError(t, err)
err = c.Start(ctx)
require.NoError(t, err)
err = c.Terminate(ctx)
require.NoError(t, err)
require.Len(t, dl.data, 24)
}
type linesTestLogger struct {
data []string
}
func (l *linesTestLogger) Printf(format string, args ...interface{}) {
l.data = append(l.data, fmt.Sprintf(format, args...))
}
func TestPrintContainerLogsOnError(t *testing.T) {
ctx := context.Background()
req := ContainerRequest{
Image: "docker.io/alpine",
Cmd: []string{"echo", "-n", "I am expecting this"},
WaitingFor: wait.ForLog("I was expecting that").WithStartupTimeout(5 * time.Second),
}
arrayOfLinesLogger := linesTestLogger{
data: []string{},
}
container, err := GenericContainer(ctx, GenericContainerRequest{
ProviderType: providerType,
ContainerRequest: req,
Logger: &arrayOfLinesLogger,
Started: true,
})
// it should fail because the waiting for condition is not met
if err == nil {
t.Fatal(err)
}
terminateContainerOnEnd(t, ctx, container)
containerLogs, err := container.Logs(ctx)
if err != nil {
t.Fatal(err)
}
defer containerLogs.Close()
// read container logs line by line, checking that each line is present in the stdout
rd := bufio.NewReader(containerLogs)
for {
line, err := rd.ReadString('\n')
if err != nil {
if err.Error() == "EOF" {
break
}
t.Fatal("Read Error:", err)
}
// the last line of the array should contain the line of interest,
// but we are checking all the lines to make sure that is present
found := false
for _, l := range arrayOfLinesLogger.data {
if strings.Contains(l, line) {
found = true
break
}
}
assert.True(t, found, "container log line not found in the output of the logger: %s", line)
}
}
func lifecycleHooksIsHonouredFn(t *testing.T, ctx context.Context, prints []string) {
require.Len(t, prints, 24)
assert.True(t, strings.HasPrefix(prints[0], "pre-create hook 1: "))
assert.True(t, strings.HasPrefix(prints[1], "pre-create hook 2: "))
assert.True(t, strings.HasPrefix(prints[2], "post-create hook 1: "))
assert.True(t, strings.HasPrefix(prints[3], "post-create hook 2: "))
assert.True(t, strings.HasPrefix(prints[4], "pre-start hook 1: "))
assert.True(t, strings.HasPrefix(prints[5], "pre-start hook 2: "))
assert.True(t, strings.HasPrefix(prints[6], "post-start hook 1: "))
assert.True(t, strings.HasPrefix(prints[7], "post-start hook 2: "))
assert.True(t, strings.HasPrefix(prints[8], "post-ready hook 1: "))
assert.True(t, strings.HasPrefix(prints[9], "post-ready hook 2: "))
assert.True(t, strings.HasPrefix(prints[10], "pre-stop hook 1: "))
assert.True(t, strings.HasPrefix(prints[11], "pre-stop hook 2: "))
assert.True(t, strings.HasPrefix(prints[12], "post-stop hook 1: "))
assert.True(t, strings.HasPrefix(prints[13], "post-stop hook 2: "))
assert.True(t, strings.HasPrefix(prints[14], "pre-start hook 1: "))
assert.True(t, strings.HasPrefix(prints[15], "pre-start hook 2: "))
assert.True(t, strings.HasPrefix(prints[16], "post-start hook 1: "))
assert.True(t, strings.HasPrefix(prints[17], "post-start hook 2: "))
assert.True(t, strings.HasPrefix(prints[18], "post-ready hook 1: "))
assert.True(t, strings.HasPrefix(prints[19], "post-ready hook 2: "))
assert.True(t, strings.HasPrefix(prints[20], "pre-terminate hook 1: "))
assert.True(t, strings.HasPrefix(prints[21], "pre-terminate hook 2: "))
assert.True(t, strings.HasPrefix(prints[22], "post-terminate hook 1: "))
assert.True(t, strings.HasPrefix(prints[23], "post-terminate hook 2: "))
}