github.com/afxcn/moby@v1.13.1/client/container_wait_test.go (about)

     1  package client
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"fmt"
     7  	"io/ioutil"
     8  	"log"
     9  	"net/http"
    10  	"strings"
    11  	"testing"
    12  	"time"
    13  
    14  	"github.com/docker/docker/api/types/container"
    15  
    16  	"golang.org/x/net/context"
    17  )
    18  
    19  func TestContainerWaitError(t *testing.T) {
    20  	client := &Client{
    21  		client: newMockClient(errorMock(http.StatusInternalServerError, "Server error")),
    22  	}
    23  	code, err := client.ContainerWait(context.Background(), "nothing")
    24  	if err == nil || err.Error() != "Error response from daemon: Server error" {
    25  		t.Fatalf("expected a Server Error, got %v", err)
    26  	}
    27  	if code != -1 {
    28  		t.Fatalf("expected a status code equal to '-1', got %d", code)
    29  	}
    30  }
    31  
    32  func TestContainerWait(t *testing.T) {
    33  	expectedURL := "/containers/container_id/wait"
    34  	client := &Client{
    35  		client: newMockClient(func(req *http.Request) (*http.Response, error) {
    36  			if !strings.HasPrefix(req.URL.Path, expectedURL) {
    37  				return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL)
    38  			}
    39  			b, err := json.Marshal(container.ContainerWaitOKBody{
    40  				StatusCode: 15,
    41  			})
    42  			if err != nil {
    43  				return nil, err
    44  			}
    45  			return &http.Response{
    46  				StatusCode: http.StatusOK,
    47  				Body:       ioutil.NopCloser(bytes.NewReader(b)),
    48  			}, nil
    49  		}),
    50  	}
    51  
    52  	code, err := client.ContainerWait(context.Background(), "container_id")
    53  	if err != nil {
    54  		t.Fatal(err)
    55  	}
    56  	if code != 15 {
    57  		t.Fatalf("expected a status code equal to '15', got %d", code)
    58  	}
    59  }
    60  
    61  func ExampleClient_ContainerWait_withTimeout() {
    62  	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    63  	defer cancel()
    64  
    65  	client, _ := NewEnvClient()
    66  	_, err := client.ContainerWait(ctx, "container_id")
    67  	if err != nil {
    68  		log.Fatal(err)
    69  	}
    70  }