test(util): MockProtect when mocking multiple times

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
This commit is contained in:
Earl Warren 2024-05-29 19:47:15 +02:00
parent c7f01c9bbd
commit 884b3c0f4b
No known key found for this signature in database
GPG key ID: 0579CB2928A78A00
2 changed files with 25 additions and 0 deletions

View file

@ -0,0 +1,18 @@
// Copyright 2024 The Forgejo Authors
// SPDX-License-Identifier: MIT
package test
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestMockProtect(t *testing.T) {
mockable := "original"
restore := MockProtect(&mockable)
mockable = "tainted"
restore()
assert.Equal(t, "original", mockable)
}