mirror of
https://codeberg.org/forgejo/forgejo.git
synced 2024-12-14 11:48:09 -05:00
884b3c0f4b
It is fine to use MockVariableValue to change a setting such as: defer test.MockVariableValue(&setting.Mirror.Enabled, true)() But when testing for errors and mocking a function, multiple variants of the functions will be used, not just one. MockProtect a function will make sure that when the test fails it always restores a sane version of the function. For instance: defer test.MockProtect(&mirror_service.AddPushMirrorRemote)() mirror_service.AddPushMirrorRemote = mockOne do some tests that may fail mirror_service.AddPushMirrorRemote = mockTwo do more tests that may fail
48 lines
1 KiB
Go
48 lines
1 KiB
Go
// Copyright 2017 The Gitea Authors. All rights reserved.
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
package test
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
|
|
"code.gitea.io/gitea/modules/json"
|
|
)
|
|
|
|
// RedirectURL returns the redirect URL of a http response.
|
|
// It also works for JSONRedirect: `{"redirect": "..."}`
|
|
func RedirectURL(resp http.ResponseWriter) string {
|
|
loc := resp.Header().Get("Location")
|
|
if loc != "" {
|
|
return loc
|
|
}
|
|
if r, ok := resp.(*httptest.ResponseRecorder); ok {
|
|
m := map[string]any{}
|
|
err := json.Unmarshal(r.Body.Bytes(), &m)
|
|
if err == nil {
|
|
if loc, ok := m["redirect"].(string); ok {
|
|
return loc
|
|
}
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func IsNormalPageCompleted(s string) bool {
|
|
return strings.Contains(s, `<footer class="page-footer"`) && strings.Contains(s, `</html>`)
|
|
}
|
|
|
|
// use for global variables only
|
|
func MockVariableValue[T any](p *T, v T) (reset func()) {
|
|
old := *p
|
|
*p = v
|
|
return func() { *p = old }
|
|
}
|
|
|
|
// use for global variables only
|
|
func MockProtect[T any](p *T) (reset func()) {
|
|
old := *p
|
|
return func() { *p = old }
|
|
}
|