github.com/ncdc/docker@v0.10.1-0.20160129113957-6c6729ef5b74/api/server/middleware_test.go (about)

     1  package server
     2  
     3  import (
     4  	"net/http"
     5  	"net/http/httptest"
     6  	"testing"
     7  
     8  	"github.com/docker/distribution/registry/api/errcode"
     9  	"github.com/docker/docker/api/server/httputils"
    10  	"github.com/docker/docker/errors"
    11  	"golang.org/x/net/context"
    12  )
    13  
    14  func TestVersionMiddleware(t *testing.T) {
    15  	handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
    16  		if httputils.VersionFromContext(ctx) == "" {
    17  			t.Fatalf("Expected version, got empty string")
    18  		}
    19  		return nil
    20  	}
    21  
    22  	h := versionMiddleware(handler)
    23  
    24  	req, _ := http.NewRequest("GET", "/containers/json", nil)
    25  	resp := httptest.NewRecorder()
    26  	ctx := context.Background()
    27  	if err := h(ctx, resp, req, map[string]string{}); err != nil {
    28  		t.Fatal(err)
    29  	}
    30  }
    31  
    32  func TestVersionMiddlewareWithErrors(t *testing.T) {
    33  	handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
    34  		if httputils.VersionFromContext(ctx) == "" {
    35  			t.Fatalf("Expected version, got empty string")
    36  		}
    37  		return nil
    38  	}
    39  
    40  	h := versionMiddleware(handler)
    41  
    42  	req, _ := http.NewRequest("GET", "/containers/json", nil)
    43  	resp := httptest.NewRecorder()
    44  	ctx := context.Background()
    45  
    46  	vars := map[string]string{"version": "0.1"}
    47  	err := h(ctx, resp, req, vars)
    48  	if derr, ok := err.(errcode.Error); !ok || derr.ErrorCode() != errors.ErrorCodeOldClientVersion {
    49  		t.Fatalf("Expected ErrorCodeOldClientVersion, got %v", err)
    50  	}
    51  
    52  	vars["version"] = "100000"
    53  	err = h(ctx, resp, req, vars)
    54  	if derr, ok := err.(errcode.Error); !ok || derr.ErrorCode() != errors.ErrorCodeNewerClientVersion {
    55  		t.Fatalf("Expected ErrorCodeNewerClientVersion, got %v", err)
    56  	}
    57  }