6
6
"fmt"
7
7
"os/exec"
8
8
"regexp"
9
+ "strings"
9
10
"testing"
10
11
"time"
11
12
@@ -14,35 +15,68 @@ import (
14
15
)
15
16
16
17
type RunContainer struct {
18
+ name string
19
+ ctx context.Context
17
20
}
18
21
19
- func NewRunContainer (ctx context.Context , image , name string ) * RunContainer {
20
- //exec.CommandContext(ctx, "docker", "start")
21
- // TODO: startup docker container
22
- return & RunContainer {}
22
+ func NewRunContainer (ctx context.Context , image , name string ) (* RunContainer , error ) {
23
+ cmd := exec .CommandContext (ctx ,
24
+ "docker" , "run" ,
25
+ "--name" , name ,
26
+ "-it" , "-d" ,
27
+ image ,
28
+ )
29
+
30
+ out , err := cmd .CombinedOutput ()
31
+ if err != nil {
32
+ return nil , xerrors .Errorf (
33
+ "failed to start testing container %q, (%s): %w" ,
34
+ name , string (out ), err )
35
+ }
36
+
37
+ return & RunContainer {
38
+ name : name ,
39
+ ctx : ctx ,
40
+ }, nil
23
41
}
24
42
25
- func (r RunContainer ) Teardown () error {
26
- // TODO: teardown run environment
43
+ func (r * RunContainer ) Close () error {
44
+ cmd := exec .CommandContext (r .ctx ,
45
+ "sh" , "-c" , strings .Join ([]string {
46
+ "docker" , "kill" , r .name , "&&" ,
47
+ "docker" , "rm" , r .name ,
48
+ }, " " ))
49
+
50
+ out , err := cmd .CombinedOutput ()
51
+ if err != nil {
52
+ return xerrors .Errorf (
53
+ "failed to stop testing container %q, (%s): %w" ,
54
+ r .name , string (out ), err )
55
+ }
27
56
return nil
28
57
}
29
58
30
59
type Assertable struct {
31
- cmd string
32
- ctx context.Context
60
+ cmd string
61
+ ctx context.Context
62
+ container * RunContainer
33
63
}
34
64
35
- func (* RunContainer ) Run (ctx context.Context , cmd string ) * Assertable {
65
+ func (r * RunContainer ) Run (ctx context.Context , cmd string ) * Assertable {
36
66
return & Assertable {
37
- cmd : cmd ,
38
- ctx : ctx ,
67
+ cmd : cmd ,
68
+ ctx : ctx ,
69
+ container : r ,
39
70
}
40
71
}
41
72
42
73
func (a Assertable ) Assert (t * testing.T , option ... Assertion ) {
43
74
var cmdResult CommandResult
44
75
45
- cmd := exec .CommandContext (a .ctx , "sh" , "-c" , a .cmd )
76
+ cmd := exec .CommandContext (a .ctx ,
77
+ "docker" , "exec" , a .container .name ,
78
+ "sh" , "-c" , a .cmd ,
79
+ )
46
80
var (
47
81
stdout bytes.Buffer
48
82
stderr bytes.Buffer
0 commit comments