Skip to content

Instantly share code, notes, and snippets.

@kimh
Last active November 24, 2016 14:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kimh/ef56d7e7b4daae96abf8c22d9512ae92 to your computer and use it in GitHub Desktop.
Save kimh/ef56d7e7b4daae96abf8c22d9512ae92 to your computer and use it in GitHub Desktop.
package mytest
import (
"errors"
"fmt"
"net/http"
"io"
"io/ioutil"
"testing"
"context"
"net/http/httptest"
"github.com/docker/docker/client"
"github.com/docker/docker/api/types"
)
func mockResponse(target string) (string, error) {
supportedEndpoints := []string{
"/containers/json",
}
// Is endpoint supported?
supported := false
for _, endpoint := range supportedEndpoints {
if endpoint == target {
supported = true
}
}
if !supported {
return "", errors.New("Not supported endpoint")
}
var mockData string
switch target {
case "/containers/json":
dat, err := ioutil.ReadFile("/tmp/list_containers")
if err != nil {
return "", err
}
mockData = string(dat)
}
return mockData, nil
}
func NewMockDockerClient(mockServerURL string) (*client.Client, error) {
httpClient := &http.Client{
Transport: new(http.Transport),
}
cli, err := client.NewClient(mockServerURL, "v1.24", httpClient, nil)
if err != nil {
return nil, err
}
return cli, nil
}
func NewMockDockerServer(responseFunc func(w http.ResponseWriter, r *http.Request), endpoint string) (*httptest.Server, error) {
ts := httptest.NewServer(http.HandlerFunc(
responseFunc,
))
return ts, nil
}
func TestContainersList(t *testing.T) {
responseBody, err := mockResponse("/containers/json")
if err != nil {
t.Error(err)
}
ts, err := NewMockDockerServer(
func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-Type", "application/json")
io.WriteString(w, responseBody)
return
}, "/containers/json")
defer ts.Close()
if err != nil {
t.Errorf("Fail to create Docker mock server")
}
cli, err := NewMockDockerClient(ts.URL)
if err != nil {
t.Error(err)
}
res, err := cli.ContainerList(context.Background(), types.ContainerListOptions{})
if err != nil {
t.Error(err)
}
fmt.Println(res)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment