middleware_test.go 1.6 KB

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