github.com/Redstoneguy129/cli@v0.0.0-20230211220159-15dca4e91917/internal/testing/apitest/helper.go (about) 1 package apitest 2 3 import ( 4 "bytes" 5 "fmt" 6 "github.com/Redstoneguy129/cli/internal/utils" 7 "net/http" 8 9 "github.com/docker/docker/api" 10 "github.com/docker/docker/api/types" 11 "github.com/docker/docker/api/types/container" 12 "github.com/docker/docker/client" 13 "github.com/docker/docker/pkg/stdcopy" 14 "gopkg.in/h2non/gock.v1" 15 ) 16 17 var mockHost = "http://" + utils.Config.Hostname + "" 18 19 func MockDocker(docker *client.Client) error { 20 // Skip setup if docker is already mocked 21 if docker.DaemonHost() == mockHost { 22 return nil 23 } 24 if err := client.WithVersion(api.DefaultVersion)(docker); err != nil { 25 return err 26 } 27 if err := client.WithHost(mockHost)(docker); err != nil { 28 return err 29 } 30 return client.WithHTTPClient(http.DefaultClient)(docker) 31 } 32 33 // Ref: internal/utils/docker.go::DockerStart 34 func MockDockerStart(docker *client.Client, image, containerID string) { 35 gock.New(docker.DaemonHost()). 36 Get("/v" + docker.ClientVersion() + "/images/" + image + "/json"). 37 Reply(http.StatusOK). 38 JSON(types.ImageInspect{}) 39 gock.New(docker.DaemonHost()). 40 Post("/v" + docker.ClientVersion() + "/networks/create"). 41 Reply(http.StatusCreated). 42 JSON(types.NetworkCreateResponse{}) 43 gock.New(docker.DaemonHost()). 44 Post("/v" + docker.ClientVersion() + "/containers/create"). 45 Reply(http.StatusOK). 46 JSON(container.ContainerCreateCreatedBody{ID: containerID}) 47 gock.New(docker.DaemonHost()). 48 Post("/v" + docker.ClientVersion() + "/containers/" + containerID + "/start"). 49 Reply(http.StatusAccepted) 50 } 51 52 // Ref: internal/utils/docker.go::DockerRunOnce 53 func MockDockerLogs(docker *client.Client, containerID, stdout string) error { 54 var body bytes.Buffer 55 writer := stdcopy.NewStdWriter(&body, stdcopy.Stdout) 56 _, err := writer.Write([]byte(stdout)) 57 gock.New(docker.DaemonHost()). 58 Get("/v"+docker.ClientVersion()+"/containers/"+containerID+"/logs"). 59 Reply(http.StatusOK). 60 SetHeader("Content-Type", "application/vnd.docker.raw-stream"). 61 Body(&body) 62 gock.New(docker.DaemonHost()). 63 Get("/v" + docker.ClientVersion() + "/containers/" + containerID + "/json"). 64 Reply(http.StatusOK). 65 JSON(types.ContainerJSONBase{State: &types.ContainerState{ExitCode: 0}}) 66 gock.New(docker.DaemonHost()). 67 Delete("/v" + docker.ClientVersion() + "/containers/" + containerID). 68 Reply(http.StatusOK) 69 return err 70 } 71 72 func ListUnmatchedRequests() []string { 73 result := make([]string, len(gock.GetUnmatchedRequests())) 74 for i, r := range gock.GetUnmatchedRequests() { 75 result[i] = fmt.Sprintln(r.Method, r.URL.Path) 76 } 77 return result 78 }