github.com/ocurr/cryorio@v0.0.0-20220116160810-2fb94073801b/roborio/test_docker_rio_test.go (about) 1 package roborio 2 3 import ( 4 "context" 5 "io" 6 "os" 7 "testing" 8 9 "github.com/docker/docker/api/types" 10 "github.com/docker/docker/api/types/container" 11 "github.com/docker/docker/client" 12 "github.com/docker/go-connections/nat" 13 ) 14 15 type dockerRio struct { 16 ctx context.Context 17 cli *client.Client 18 t *testing.T 19 id string 20 } 21 22 func newDockerRio(t *testing.T) *dockerRio { 23 ctx := context.Background() 24 cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation()) 25 if err != nil { 26 t.Fatal(err) 27 } 28 29 reader, err := cli.ImagePull(ctx, "docker.io/ocurr/ssh-server", types.ImagePullOptions{}) 30 if err != nil { 31 t.Fatal(err) 32 } 33 defer reader.Close() 34 io.Copy(os.Stdout, reader) 35 36 hostConfig := &container.HostConfig{ 37 PortBindings: nat.PortMap{ 38 "8080/tcp": []nat.PortBinding{ 39 { 40 HostIP: "0.0.0.0", 41 HostPort: "8080", 42 }, 43 }, 44 }, 45 } 46 47 resp, err := cli.ContainerCreate(ctx, &container.Config{ 48 Image: "ocurr/ssh-server", 49 ExposedPorts: nat.PortSet{ 50 "22/tcp": struct{}{}, 51 }, 52 }, hostConfig, nil, nil, "") 53 if err != nil { 54 t.Fatal(err) 55 } 56 57 if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil { 58 t.Fatal(err) 59 } 60 61 return &dockerRio{ 62 ctx, 63 cli, 64 t, 65 resp.ID, 66 } 67 } 68 69 func (d *dockerRio) shutdown() { 70 err := d.cli.ContainerStop(d.ctx, d.id, nil) 71 if err != nil { 72 d.t.Fatal(err) 73 } 74 }