/
confort_test.go
1870 lines (1691 loc) · 42.8 KB
/
confort_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
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package confort_test
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"log"
"net"
"net/http"
"net/http/httputil"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/daichitakahashi/confort"
"github.com/daichitakahashi/confort/internal/beacon"
"github.com/daichitakahashi/confort/internal/beacon/server"
"github.com/daichitakahashi/confort/unique"
"github.com/daichitakahashi/confort/wait"
"github.com/daichitakahashi/testingc"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/client"
"github.com/docker/go-connections/nat"
"github.com/google/uuid"
"golang.org/x/sync/errgroup"
"google.golang.org/grpc"
)
const (
imageCommunicator = "github.com/daichitakahashi/confort/testdata/communicator:test"
imageEcho = "github.com/daichitakahashi/confort/testdata/echo:test"
imageLs = "github.com/daichitakahashi/confort/testdata/ls:"
)
var (
// generate unique namespace and name for container
uniqueName, _ = unique.String(context.Background(), 16)
)
func TestMain(m *testing.M) {
ctx := context.Background()
err := os.Setenv(beacon.LogLevelEnv, "0")
if err != nil {
log.Panic(err)
}
cft, err := confort.New(ctx,
confort.WithNamespace("for-build", false),
)
if err != nil {
log.Panic(err)
}
defer func() {
_ = cft.Close()
}()
cli := cft.APIClient()
defer func() {
_, err := cli.ImagesPrune(ctx, filters.NewArgs(
filters.Arg("dangling", "true"),
))
if err != nil {
log.Printf("prune dangling images failed: %s", err)
}
}()
log.Printf("building image: %s", imageCommunicator)
err = cft.Build(ctx, &confort.BuildParams{
Image: imageCommunicator,
Dockerfile: "testdata/communicator/Dockerfile",
ContextDir: "testdata/communicator",
}, confort.WithBuildOutput(io.Discard), confort.WithForceBuild())
if err != nil {
log.Panic(err)
}
defer func() {
log.Printf("remove image: %s", imageCommunicator)
_, err := cli.ImageRemove(ctx, imageCommunicator, types.ImageRemoveOptions{})
if err != nil {
log.Printf("failed to remove image %q: %s", imageCommunicator, err)
}
}()
log.Printf("building image: %s", imageEcho)
err = cft.Build(ctx, &confort.BuildParams{
Image: imageEcho,
Dockerfile: "testdata/echo/Dockerfile",
ContextDir: "testdata/echo/",
}, confort.WithBuildOutput(io.Discard), confort.WithForceBuild())
if err != nil {
log.Println(err)
}
defer func() {
log.Printf("remove image: %s", imageEcho)
_, err := cli.ImageRemove(ctx, imageEcho, types.ImageRemoveOptions{})
if err != nil {
log.Printf("failed to remove image %q: %s", imageEcho, err)
}
}()
m.Run()
}
// test network creation and communication between host and container,
// and between containers.
func TestConfort_Run_Communication(t *testing.T) {
t.Parallel()
ctx := context.Background()
cft, err := confort.New(ctx,
confort.WithNamespace(t.Name(), false),
)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_ = cft.Close()
})
comOne, err := cft.Run(ctx, &confort.ContainerParams{
Name: "one",
Image: imageCommunicator,
Env: map[string]string{
"CM_TARGET": "two",
},
ExposedPorts: []string{"80/tcp"},
Waiter: wait.LogContains("communicator is ready", 1),
})
if err != nil {
t.Fatal(err)
}
portsOne, releaseOne, err := comOne.UseExclusive(ctx)
if err != nil {
t.Fatal(err)
}
t.Cleanup(releaseOne)
hostOne := portsOne.HostPort("80/tcp")
if hostOne == "" {
t.Logf("%#v", portsOne)
t.Fatal("one: bound port not found")
}
comTwo, err := cft.Run(ctx, &confort.ContainerParams{
Name: "two",
Image: imageCommunicator,
Env: map[string]string{
"CM_TARGET": "one",
},
ExposedPorts: []string{"80/tcp"},
Waiter: wait.LogContains("communicator is ready", 1),
})
if err != nil {
t.Fatal(err)
}
portsTwo, releaseTwo, err := comTwo.UseExclusive(ctx)
if err != nil {
t.Fatal(err)
}
t.Cleanup(releaseTwo)
hostTwo := portsTwo.HostPort("80/tcp")
if hostTwo == "" {
t.Fatal("two: bound port not found")
}
// set one's status
communicate(t, hostOne, "set", "at home")
// set two's status
communicate(t, hostTwo, "set", "at office")
// exchange status between one and two using docker network
communicate(t, hostOne, "exchange", "")
// check exchanged one's status
if s := communicate(t, hostOne, "get", ""); s != "at office" {
t.Fatalf("one: expected status is %q, but actual %q", "at office", s)
}
// check exchanged
if s := communicate(t, hostTwo, "get", ""); s != "at home" {
t.Fatalf("two: expected status is %q, but actual %q", "at home", s)
}
}
// test container identification with namespace
func TestConfort_Run_ContainerIdentification(t *testing.T) {
t.Parallel()
var (
namespace = uniqueName.Must(t)
containerName = uniqueName.Must(t)
port = "80/tcp"
)
createContainer := func(t *testing.T, namespace string) string {
t.Helper()
ctx := context.Background()
cft, err := confort.New(ctx, confort.WithNamespace(namespace, true))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_ = cft.Close()
})
echo, err := cft.Run(ctx, &confort.ContainerParams{
Name: containerName,
Image: imageEcho,
ExposedPorts: []string{port},
Waiter: wait.CommandSucceeds([]string{"wget", "-q", "--spider", "http://localhost"}),
})
if err != nil {
t.Fatal(err)
}
ports, release, err := echo.UseShared(ctx)
if err != nil {
t.Fatal(err)
}
t.Cleanup(release)
endpoint := ports.HostPort(nat.Port(port))
if endpoint == "" {
t.Fatalf("cannot get endpoint of %q: %v", port, ports)
}
return endpoint
}
expectedEndpoint := createContainer(t, namespace)
t.Run(fmt.Sprintf("try to create container %q in same namespace", containerName), func(t *testing.T) {
t.Parallel()
actualEndpoint := createContainer(t, namespace)
if expectedEndpoint != actualEndpoint {
t.Fatalf("unexpected endpoint: want %q, got: %q", expectedEndpoint, actualEndpoint)
}
})
t.Run(fmt.Sprintf("try to create container %q in different namespace", containerName), func(t *testing.T) {
t.Parallel()
namespace := uniqueName.Must(t)
actualEndpoint := createContainer(t, namespace)
if expectedEndpoint == actualEndpoint {
t.Fatalf("each endpoint must differ because they are in different namespaces: %q, %q",
expectedEndpoint, actualEndpoint)
}
})
}
// check test fails if container name conflicts between different images
func TestConfort_Run_SameNameButAnotherImage(t *testing.T) {
t.Parallel()
var (
ctx = context.Background()
namespace = uniqueName.Must(t)
containerName = uniqueName.Must(t)
)
cft1, err := confort.New(ctx,
confort.WithNamespace(namespace, true),
)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_ = cft1.Close()
})
echo, err := cft1.Run(ctx, &confort.ContainerParams{
Name: containerName,
Image: imageEcho,
ExposedPorts: []string{"80/tcp"},
Waiter: wait.Healthy(),
})
if err != nil {
t.Fatal(err)
}
fullName := echo.Name()
cft2, err := confort.New(ctx,
confort.WithNamespace(namespace, true),
)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_ = cft2.Close()
})
_, err = cft2.Run(ctx, &confort.ContainerParams{ // same name, but different image
Name: containerName,
Image: imageCommunicator,
})
if err == nil {
t.Fatal("error expected on run containers that has same name and different image")
}
if !strings.Contains(err.Error(), fullName) {
t.Fatalf("unexpected error: %s", err)
}
}
// test if container can join different networks simultaneously
func TestConfort_Run_AttachAliasToAnotherNetwork(t *testing.T) {
t.Parallel()
var (
ctx = context.Background()
namespaceA = "namespace"
namespaceB = "namespace-foo"
)
// Network1 ┳ Container "namespace-foo-A"
// ┗ Container "namespace-foo-B" ┳ Network2
// Container "namespace-foo-C" ┛
cft1, err := confort.New(ctx,
confort.WithNamespace(namespaceA, true),
)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_ = cft1.Close()
})
com1, err := cft1.Run(ctx, &confort.ContainerParams{
Name: "foo-A",
Image: imageCommunicator,
Env: map[string]string{
"CM_TARGET": "foo-B",
},
ExposedPorts: []string{"80/tcp"},
Waiter: wait.Healthy(),
})
if err != nil {
t.Fatal(err)
}
e, release1, err := com1.UseShared(ctx)
if err != nil {
t.Fatal(err)
}
t.Cleanup(release1)
hostA := e.HostPort("80/tcp")
if hostA == "" {
t.Fatal("failed to get host/port")
}
com2, err := cft1.Run(ctx, &confort.ContainerParams{
Name: "foo-B",
Image: imageCommunicator,
Env: map[string]string{
"CM_TARGET": "C",
},
// Using ephemeral port makes test flaky, why?
// Without specifying host port, container loses the port binding occasionally.
ExposedPorts: []string{"8080:80/tcp"},
Waiter: wait.Healthy(),
})
if err != nil {
t.Fatal(err)
}
e, release2, err := com2.UseShared(ctx)
if err != nil {
t.Fatal(err)
}
t.Cleanup(release2)
hostB := e.HostPort("80/tcp")
if hostB == "" {
t.Fatal("failed to get host/port")
}
cft2, err := confort.New(ctx,
confort.WithNamespace(namespaceB, true),
)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_ = cft2.Close()
})
com3, err := cft2.Run(ctx, &confort.ContainerParams{ // same name container
Name: "B",
Image: imageCommunicator,
Env: map[string]string{
"CM_TARGET": "C",
},
ExposedPorts: []string{"8080:80/tcp"},
Waiter: wait.Healthy(),
})
if err != nil {
t.Fatal(err)
}
e, release3, err := com3.UseShared(ctx)
if err != nil {
t.Fatal(err)
}
t.Cleanup(release3)
hostB2 := e.HostPort("80/tcp")
if hostB2 == "" {
t.Fatal("failed to get host/port")
}
if hostB != hostB2 {
t.Fatalf("expected same host: want %q, got %q", hostB, hostB2)
}
com4, err := cft2.Run(ctx, &confort.ContainerParams{
Name: "C",
Image: imageCommunicator,
Env: map[string]string{
"CM_TARGET": com3.Alias(), // "B" CHECK THIS WORKS
},
ExposedPorts: []string{"80/tcp"},
Waiter: wait.Healthy(),
})
if err != nil {
t.Fatal(err)
}
e, release4, err := com4.UseShared(ctx)
if err != nil {
t.Fatal(err)
}
t.Cleanup(release4)
hostC := e.HostPort("80/tcp")
if hostC == "" {
t.Fatal("failed to get host/port")
}
// set initial values
// Container "namespace-foo-A" => 1
// Container "namespace-foo-B" => 2
// Container "namespace-foo-C" => 3
communicate(t, hostA, "set", "1")
communicate(t, hostB, "set", "2")
communicate(t, hostC, "set", "3")
// exchange values
// Container "namespace-foo-A" => 1 ┓ 1.exchange
// Container "namespace-foo-B" => 2 ┛ ┓
// Container "namespace-foo-C" => 3 ┛ 2.exchange
communicate(t, hostA, "exchange", "")
communicate(t, hostC, "exchange", "")
// check all values
a := communicate(t, hostA, "get", "")
b := communicate(t, hostB, "get", "")
c := communicate(t, hostC, "get", "")
if !(a == "2" && b == "3" && c == "1") {
t.Fatalf("unexpected result: a=%q, b=%q, c=%q", a, b, c)
}
}
func communicate(t *testing.T, host, method, status string) string {
t.Helper()
resp, err := http.Post(
fmt.Sprintf("http://%s/%s", host, method),
"text/plain",
strings.NewReader(status),
)
if err != nil {
t.Fatal(err)
}
defer func() {
_ = resp.Body.Close()
}()
stat, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != http.StatusOK {
t.Fatalf("got error response: %d: %s", resp.StatusCode, stat)
}
return string(stat)
}
func TestWithClientOptions(t *testing.T) {
t.Parallel()
ctx := context.Background()
c, err := client.NewClientWithOpts(client.FromEnv)
if err != nil {
t.Fatal(err)
}
c.NegotiateAPIVersion(ctx)
// wrap transport
logOut := bytes.NewBuffer(nil)
httpCli := c.HTTPClient()
transport := httpCli.Transport
httpCli.Transport = transportFunc(func(r *http.Request) (*http.Response, error) {
resp, err := transport.RoundTrip(r)
if err != nil {
return nil, err
}
dump, err := httputil.DumpResponse(resp, true)
if err != nil {
return nil, err
}
logOut.Write(dump)
logOut.WriteByte('\n')
return resp, err
})
cft, err := confort.New(ctx,
confort.WithClientOptions(client.FromEnv, client.WithHTTPClient(httpCli)),
confort.WithNamespace(uuid.NewString(), true),
)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_ = cft.Close()
})
if logOut.Len() == 0 {
t.Fatal("no log output")
}
}
type transportFunc func(*http.Request) (*http.Response, error)
func (f transportFunc) RoundTrip(r *http.Request) (*http.Response, error) {
return f(r)
}
func TestWithNamespace(t *testing.T) {
ctx := context.Background()
testCases := []struct {
desc string
envNamespace string
optNamespace string
force bool
expectedNamespace string
}{
{
desc: "without env or enforcement",
envNamespace: "",
optNamespace: "opt-namespace",
expectedNamespace: "opt-namespace-",
}, {
desc: "with env and no enforcement",
envNamespace: "env-namespace",
optNamespace: "opt-namespace",
expectedNamespace: "env-namespace-",
}, {
desc: "without env and with enforcement",
envNamespace: "",
optNamespace: "opt-namespace",
force: true,
expectedNamespace: "opt-namespace-",
}, {
desc: "with env and enforcement",
envNamespace: "env-namespace",
optNamespace: "opt-namespace",
force: true,
expectedNamespace: "opt-namespace-",
},
}
for _, tc := range testCases {
t.Run(tc.desc, func(t *testing.T) {
if tc.envNamespace != "" {
t.Setenv(beacon.NamespaceEnv, tc.envNamespace)
}
cft, err := confort.New(ctx, confort.WithNamespace(tc.optNamespace, tc.force))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_ = cft.Close()
})
actual := cft.Namespace()
if tc.expectedNamespace != actual {
t.Fatalf("expected namespace %q, got %q", tc.expectedNamespace, actual)
}
})
}
}
func TestWithNamespace_empty(t *testing.T) {
t.Parallel()
cft, err := confort.New(context.Background(),
confort.WithNamespace("", true),
)
if err == nil {
_ = cft.Close()
t.Fatal("expected to fail, but succeeded")
}
}
func TestWithDefaultTimeout(t *testing.T) {
t.Parallel()
// test timeout for Docker API request
httpClient := func(fn func(deadline time.Time, ok bool)) *http.Client {
cli, err := client.NewClientWithOpts(client.FromEnv)
if err != nil {
t.Fatal(err)
}
httpCli := cli.HTTPClient()
transport := httpCli.Transport
var tested bool
httpCli.Transport = transportFunc(func(r *http.Request) (*http.Response, error) {
ctx := r.Context()
// test once
if !tested {
deadline, ok := ctx.Deadline()
fn(deadline, ok)
tested = true
}
return transport.RoundTrip(r)
})
return httpCli
}
testCases := []struct {
desc string
timeout time.Duration
newCtx func() (context.Context, context.CancelFunc)
test func(t *testing.T, deadline time.Time, ok bool)
}{
{
desc: "default default timeout(1 min.)",
timeout: -1, // without confort.WithDefaultTimeout
test: func(t *testing.T, deadline time.Time, ok bool) {
if !ok {
t.Fatal("deadline expected")
}
d := time.Until(deadline)
if d < time.Second*59 || time.Minute < d {
t.Fatalf("expected timeout is more than 59 sec. and less than 1 min., actual %s", d)
}
},
}, {
desc: "no timeout",
timeout: 0, // confort.WithDefaultTimeout(0)
test: func(t *testing.T, deadline time.Time, ok bool) {
if ok {
t.Fatal("no deadline expected")
}
},
}, {
desc: "with default timeout(5 sec.)",
timeout: time.Second * 5, // confort.WithDefaultTimeout(time.Second*5)
test: func(t *testing.T, deadline time.Time, ok bool) {
if !ok {
t.Fatal("deadline expected")
}
d := time.Until(deadline)
if d < time.Second*4 || time.Second*5 < d {
t.Fatalf("expected timeout is more than 4 min., and less than 5 min., actual %s", d)
}
},
}, {
desc: "with default timeout(5 sec.) and timeout for confort.New(3 sec.)",
timeout: time.Second * 5, // confort.WithDefaultTimeout(time.Second*5)
newCtx: func() (context.Context, context.CancelFunc) {
return context.WithTimeout(context.Background(), time.Second*3)
},
test: func(t *testing.T, deadline time.Time, ok bool) {
if !ok {
t.Fatal("deadline expected")
}
d := time.Until(deadline)
if d < time.Second*2 || time.Second*3 < d {
t.Fatalf("expected timeout is more than 2 sec., and less than 3 sec., actual %s", d)
}
},
}, {
desc: "with default timeout(5 sec.) and timeout for confort.New(7 sec.)",
timeout: time.Second * 5, // confort.WithDefaultTimeout(time.Second*5)
newCtx: func() (context.Context, context.CancelFunc) {
return context.WithTimeout(context.Background(), time.Second*7)
},
test: func(t *testing.T, deadline time.Time, ok bool) {
if !ok {
t.Fatal("deadline expected")
}
d := time.Until(deadline)
if d < time.Second*6 || time.Second*7 < d {
t.Fatalf("expected timeout is more than 6 sec., and less than 7 sec., actual %s", d)
}
},
},
}
for _, tc := range testCases {
t.Run(tc.desc, func(t *testing.T) {
httpCli := httpClient(func(deadline time.Time, ok bool) {
tc.test(t, deadline, ok)
})
opts := []confort.NewOption{
confort.WithNamespace(uuid.NewString(), true),
confort.WithClientOptions(client.FromEnv, client.WithHTTPClient(httpCli)),
}
if tc.timeout >= 0 {
opts = append(opts, confort.WithDefaultTimeout(tc.timeout))
}
ctx := context.Background()
if tc.newCtx != nil {
var cancel context.CancelFunc
ctx, cancel = tc.newCtx()
t.Cleanup(cancel)
}
cft, err := confort.New(ctx, opts...)
if err != nil {
t.Fatal(err)
}
_ = cft.Close()
})
}
}
func TestWithResourcePolicy(t *testing.T) {
t.Parallel()
ctx := context.Background()
cli, err := client.NewClientWithOpts(client.FromEnv)
if err != nil {
t.Fatal(err)
}
cli.NegotiateAPIVersion(ctx)
// define assertions
// container or network is reused
assertReused := func(t *testing.T, precedingID, id string, result *testingc.TestResult) {
t.Helper()
if result.Failed() {
t.Fatalf("unexpected error: %s", result.Logs())
}
if precedingID != id {
t.Fatalf("ids are not match: %q and %q", precedingID, id)
}
}
// create network or container is failed because network/container having same name already exists
assertFailed := func(t *testing.T, _, _ string, result *testingc.TestResult) {
t.Helper()
if !result.Failed() {
t.Fatal("expected failure, but succeeds")
}
}
// after termination, check the network is still alive or not
assertNetwork := func(removed bool) func(t *testing.T, networkID string) {
return func(t *testing.T, networkID string) {
t.Helper()
_, err := cli.NetworkInspect(ctx, networkID, types.NetworkInspectOptions{})
found := err == nil
if found && removed {
t.Fatalf("expected to be removed but exists: %q", networkID)
} else if !found && !removed {
t.Fatalf("network not found: %q", networkID)
}
}
}
// after termination, check the container is still alive or not
assertContainer := func(removed bool) func(t *testing.T, containerID string) {
return func(t *testing.T, containerID string) {
t.Helper()
_, err := cli.ContainerInspect(ctx, containerID)
found := err == nil
if found && removed {
t.Fatalf("expected to be removed but exists: %q", containerID)
} else if !found && !removed {
t.Fatalf("container not found: %q", containerID)
}
}
}
testCases := []struct {
policy confort.ResourcePolicy
afterNamespaceCreated func(t *testing.T, foundNetworkID, gotNetworkID string, result *testingc.TestResult)
afterNamespaceTerminated func(t *testing.T, networkID string)
afterContainerCreated func(t *testing.T, foundContainerID, gotContainerID string, result *testingc.TestResult)
afterContainerTerminated func(t *testing.T, containerID string)
}{
{
policy: confort.ResourcePolicyReuse,
afterNamespaceCreated: assertReused,
afterNamespaceTerminated: assertNetwork(false),
afterContainerCreated: assertReused,
afterContainerTerminated: assertContainer(false),
},
{
policy: confort.ResourcePolicyReusable,
afterNamespaceCreated: assertReused,
afterNamespaceTerminated: assertNetwork(false),
afterContainerCreated: assertReused,
afterContainerTerminated: assertContainer(false),
},
{
policy: confort.ResourcePolicyTakeOver,
afterNamespaceCreated: assertReused,
afterNamespaceTerminated: assertNetwork(true),
afterContainerCreated: assertReused,
afterContainerTerminated: assertContainer(true),
},
{
policy: confort.ResourcePolicyError,
afterNamespaceCreated: assertFailed,
afterNamespaceTerminated: assertNetwork(false),
afterContainerCreated: assertFailed,
afterContainerTerminated: assertContainer(false),
},
}
for _, tc := range testCases {
tc := tc
t.Run(string(tc.policy), func(t *testing.T) {
t.Parallel()
t.Run("duplicated namespace(network)", func(t *testing.T) {
t.Parallel()
// create preceding network
networkName := uniqueName.Must(t)
precedes, err := confort.New(ctx, confort.WithNamespace(networkName, true))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_ = precedes.Close()
})
// try to re-create
var cft *confort.Confort
var terminated bool
var networkID string
result := testingc.Test(func(t *testingc.T) {
cft, err = confort.New(ctx,
confort.WithNamespace(networkName, true),
confort.WithResourcePolicy(tc.policy),
)
if err != nil {
t.Fatal(err)
}
if cft != nil && cft.Network() != nil {
networkID = cft.Network().ID
}
})
t.Cleanup(func() {
if !terminated && cft != nil {
_ = cft.Close()
}
})
tc.afterNamespaceCreated(t, precedes.Network().ID, networkID, result)
if cft != nil {
_ = cft.Close()
terminated = true
}
tc.afterNamespaceTerminated(t, precedes.Network().ID)
})
t.Run("duplicated container name", func(t *testing.T) {
t.Parallel()
// create preceding network and container
namespacePrefix := uniqueName.Must(t)
middleName := uniqueName.Must(t)
containerNameSuffix := uniqueName.Must(t)
precedes, err := confort.New(ctx,
confort.WithNamespace(fmt.Sprintf("%s-%s", namespacePrefix, middleName), true),
)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_ = precedes.Close()
})
echo, err := precedes.Run(ctx, &confort.ContainerParams{
Name: containerNameSuffix,
Image: imageEcho,
})
if err != nil {
t.Fatal(err)
}
precedingContainerID := echo.ID()
// try to re-create
var cft *confort.Confort
var terminated bool
var containerID string
result := testingc.Test(func(t *testingc.T) {
cft, err = confort.New(ctx,
confort.WithNamespace(namespacePrefix, true),
confort.WithResourcePolicy(tc.policy),
)
if err != nil {
t.Fatal(err)
}
echo, err := cft.Run(ctx, &confort.ContainerParams{
Name: fmt.Sprintf("%s-%s", middleName, containerNameSuffix),
Image: imageEcho,
})
if err != nil {
t.Fatal(err)
}
containerID = echo.ID()
})
t.Cleanup(func() {
if !terminated {
_ = cft.Close()
}
})
tc.afterContainerCreated(t, precedingContainerID, containerID, result)
_ = cft.Close()
terminated = true
tc.afterContainerTerminated(t, precedingContainerID)
// remove network if it exists
_ = cli.NetworkRemove(ctx, cft.Network().ID)
})
})
}
}
func TestWithResourcePolicy_reusable(t *testing.T) {
t.Parallel()
ctx := context.Background()
cft, err := confort.New(ctx,
confort.WithNamespace(t.Name(), true),
confort.WithResourcePolicy(confort.ResourcePolicyReusable),
)
if err != nil {
t.Fatal(err)
}
cli := cft.APIClient()
networkID := cft.Network().ID
echo, err := cft.Run(ctx, &confort.ContainerParams{
Name: "echo",
Image: imageEcho,
})
if err != nil {
t.Fatal(err)
}
containerID := echo.ID()
_ = cft.Close()
t.Cleanup(func() {
err = cli.ContainerRemove(ctx, containerID, types.ContainerRemoveOptions{
Force: true,
})
if err != nil {
t.Log(err)
}
err := cli.NetworkRemove(ctx, networkID)
if err != nil {
t.Log(err)
}
})
// check created resources are alive
_, err = cli.NetworkInspect(ctx, networkID, types.NetworkInspectOptions{})
if err != nil {
t.Errorf("network %s not found: %s", networkID, err)
}
_, err = cli.ContainerInspect(ctx, containerID)
if err != nil {
t.Errorf("container %s not found: %s", containerID, err)
}
}
func TestWithResourcePolicy_invalid(t *testing.T) {
t.Run("invalid policy from env", func(t *testing.T) {
t.Setenv(beacon.ResourcePolicyEnv, "invalid")
cft, err := confort.New(context.Background(),
confort.WithNamespace(uuid.NewString(), true),
)
if err == nil {
_ = cft.Close()
t.Fatal("expected to fail, but succeeded")
}
})
t.Run("invalid policy from WithResourcePolicy", func(t *testing.T) {
cft, err := confort.New(context.Background(),
confort.WithNamespace(uuid.NewString(), true),