You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

routemock.go 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright 2023 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package web
  4. import (
  5. "net/http"
  6. "code.gitea.io/gitea/modules/setting"
  7. )
  8. // MockAfterMiddlewares is a general mock point, it's between middlewares and the handler
  9. const MockAfterMiddlewares = "MockAfterMiddlewares"
  10. var routeMockPoints = map[string]func(next http.Handler) http.Handler{}
  11. // RouteMockPoint registers a mock point as a middleware for testing, example:
  12. //
  13. // r.Use(web.RouteMockPoint("my-mock-point-1"))
  14. // r.Get("/foo", middleware2, web.RouteMockPoint("my-mock-point-2"), middleware2, handler)
  15. //
  16. // Then use web.RouteMock to mock the route execution.
  17. // It only takes effect in testing mode (setting.IsInTesting == true).
  18. func RouteMockPoint(pointName string) func(next http.Handler) http.Handler {
  19. if !setting.IsInTesting {
  20. return nil
  21. }
  22. routeMockPoints[pointName] = nil
  23. return func(next http.Handler) http.Handler {
  24. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  25. if h := routeMockPoints[pointName]; h != nil {
  26. h(next).ServeHTTP(w, r)
  27. } else {
  28. next.ServeHTTP(w, r)
  29. }
  30. })
  31. }
  32. }
  33. // RouteMock uses the registered mock point to mock the route execution, example:
  34. //
  35. // defer web.RouteMockReset()
  36. // web.RouteMock(web.MockAfterMiddlewares, func(ctx *context.Context) {
  37. // ctx.WriteResponse(...)
  38. // }
  39. //
  40. // Then the mock function will be executed as a middleware at the mock point.
  41. // It only takes effect in testing mode (setting.IsInTesting == true).
  42. func RouteMock(pointName string, h any) {
  43. if _, ok := routeMockPoints[pointName]; !ok {
  44. panic("route mock point not found: " + pointName)
  45. }
  46. routeMockPoints[pointName] = toHandlerProvider(h)
  47. }
  48. // RouteMockReset resets all mock points (no mock anymore)
  49. func RouteMockReset() {
  50. for k := range routeMockPoints {
  51. routeMockPoints[k] = nil // keep the keys because RouteMock will check the keys to make sure no misspelling
  52. }
  53. }