Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
138238: testutils: add HookGlobal test util r=msbutler a=kev-cao

This commit adds HookGlobal, a test utility that provides a way to temporarily set package-global variables for testing.

Epic: none

Release note: None

Co-authored-by: Kevin Cao <[email protected]>
  • Loading branch information
craig[bot] and kev-cao committed Jan 3, 2025
2 parents 393c4f9 + 6cc88d8 commit 6c39c80
Showing 1 changed file with 9 additions and 0 deletions.
9 changes: 9 additions & 0 deletions pkg/testutils/hook.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,12 @@ func TestingHook(ptr, val interface{}) func() {
global.Set(reflect.ValueOf(val))
return func() { global.Set(orig) }
}

// HookGlobal provides a way to temporarily set a package-global variable to a
// new value for the duration of a test. It returns a closure that restores the
// original value.
func HookGlobal[T any](ptr *T, val T) func() {
orig := *ptr
*ptr = val
return func() { *ptr = orig }
}

0 comments on commit 6c39c80

Please sign in to comment.