code.gitea.io/gitea@v1.22.3/modules/web/routemock.go (about)

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