middleware_test.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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/context"
  8. "github.com/docker/docker/errors"
  9. )
  10. func TestVersionMiddleware(t *testing.T) {
  11. handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  12. if ctx.Version() == "" {
  13. t.Fatalf("Expected version, got empty string")
  14. }
  15. return nil
  16. }
  17. h := versionMiddleware(handler)
  18. req, _ := http.NewRequest("GET", "/containers/json", nil)
  19. resp := httptest.NewRecorder()
  20. ctx := context.Background()
  21. if err := h(ctx, resp, req, map[string]string{}); err != nil {
  22. t.Fatal(err)
  23. }
  24. }
  25. func TestVersionMiddlewareWithErrors(t *testing.T) {
  26. handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  27. if ctx.Version() == "" {
  28. t.Fatalf("Expected version, got empty string")
  29. }
  30. return nil
  31. }
  32. h := versionMiddleware(handler)
  33. req, _ := http.NewRequest("GET", "/containers/json", nil)
  34. resp := httptest.NewRecorder()
  35. ctx := context.Background()
  36. vars := map[string]string{"version": "0.1"}
  37. err := h(ctx, resp, req, vars)
  38. if derr, ok := err.(errcode.Error); !ok || derr.ErrorCode() != errors.ErrorCodeOldClientVersion {
  39. t.Fatalf("Expected ErrorCodeOldClientVersion, got %v", err)
  40. }
  41. vars["version"] = "100000"
  42. err = h(ctx, resp, req, vars)
  43. if derr, ok := err.(errcode.Error); !ok || derr.ErrorCode() != errors.ErrorCodeNewerClientVersion {
  44. t.Fatalf("Expected ErrorCodeNewerClientVersion, got %v", err)
  45. }
  46. }
  47. func TestRequestIDMiddleware(t *testing.T) {
  48. handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  49. if ctx.RequestID() == "" {
  50. t.Fatalf("Expected request-id, got empty string")
  51. }
  52. return nil
  53. }
  54. h := requestIDMiddleware(handler)
  55. req, _ := http.NewRequest("GET", "/containers/json", nil)
  56. resp := httptest.NewRecorder()
  57. ctx := context.Background()
  58. if err := h(ctx, resp, req, map[string]string{}); err != nil {
  59. t.Fatal(err)
  60. }
  61. }