Skip to content

Commit

Permalink
test: add mock test for pouch package client
Browse files Browse the repository at this point in the history
Signed-off-by: Allen Sun <allensun.shl@alibaba-inc.com>
  • Loading branch information
allencloud committed Mar 25, 2018
1 parent b9f3816 commit 17912a9
Show file tree
Hide file tree
Showing 2 changed files with 93 additions and 0 deletions.
42 changes: 42 additions & 0 deletions client/client_mock_test.go
@@ -0,0 +1,42 @@
package client

import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"

"github.com/alibaba/pouch/apis/types"
)

type transportFunc func(*http.Request) (*http.Response, error)

func (transFunc transportFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return transFunc(req)
}

func newMockClient(handler func(*http.Request) (*http.Response, error)) *http.Client {
return &http.Client{
Transport: transportFunc(handler),
}
}

func errorMockResponse(statusCode int, message string) func(req *http.Request) (*http.Response, error) {
return func(req *http.Request) (*http.Response, error) {
header := http.Header{}
header.Set("Content-Type", "application/json")

body, err := json.Marshal(&types.Error{
Message: message,
})
if err != nil {
return nil, err
}

return &http.Response{
StatusCode: statusCode,
Body: ioutil.NopCloser(bytes.NewReader(body)),
Header: header,
}, nil
}
}
51 changes: 51 additions & 0 deletions client/container_start_test.go
@@ -0,0 +1,51 @@
package client

import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"testing"
)

func TestContainerStartError(t *testing.T) {
client := &APIClient{
HTTPCli: newMockClient(errorMockResponse(http.StatusInternalServerError, "Server error")),
}
err := client.ContainerStart(context.Background(), "nothing", "")
if err == nil || !strings.Contains(err.Error(), "Server error") {
t.Fatalf("expected a Server Error, got %v", err)
}
}

func TestContainerStart(t *testing.T) {
expectedURL := "/containers/container_id/start"

httpClient := newMockClient(func(req *http.Request) (*http.Response, error) {
if !strings.HasPrefix(req.URL.Path, expectedURL) {
return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL)
}
if req.Header.Get("Content-Type") == "application/json" {
var startConfig interface{}
if err := json.NewDecoder(req.Body).Decode(&startConfig); err != nil {
return nil, fmt.Errorf("failed to parse json: %v", err)
}
}

return &http.Response{
StatusCode: http.StatusOK,
Body: ioutil.NopCloser(bytes.NewReader([]byte(""))),
}, nil
})

client := &APIClient{
HTTPCli: httpClient,
}

if err := client.ContainerStart(context.Background(), "container_id", ""); err != nil {
t.Fatal(err)
}
}

0 comments on commit 17912a9

Please sign in to comment.