mirror of
https://github.com/hanzoai/tasks.git
synced 2026-10-04 02:04:03 +00:00
## What changed? I've added context-based methods to our testhooks package. This includes: - `NewInjectedTestHooksImpl` - returns a context and the registry injected into its chain - `SetCtx` - set a testhooks key on the first TestHooks implementor found in the context chain - `GetCtx` - get a testhooks value from the first TestHooks implementor found in the context chain - `CallCtx` - call a testhooks callback value in the first TestHooks implementor found in the context chain ## Why? This simplifies TestHook usage for modules that have an externally-controllable context. Rather than attach a TestHooks implementation to your production structs, you can instead inject it into the context provided by your tests. This does not work for temporal's end-to-end or functional tests at the moment, though a gRPC interceptor that injects a registry would not be difficult to write. ## How did you test it? - [x] built - [x] run locally and tested manually - [ ] covered by existing tests - [x] added new unit test(s) - [ ] added new functional test(s) ## Potential risks None
53 lines
1.4 KiB
Go
53 lines
1.4 KiB
Go
//go:build test_dep
|
|
|
|
package testhooks
|
|
|
|
import "testing"
|
|
|
|
// Ensure that testhook functionality that operates on contexts functions as
|
|
// expected.
|
|
func TestTestHooks_Context(t *testing.T) {
|
|
t.Run("Values can be set and get on the context directly", func(t *testing.T) {
|
|
ctx, _ := NewInjectedTestHooksImpl(t.Context())
|
|
cleanup := SetCtx(ctx, UpdateWithStartInBetweenLockAndStart, 33)
|
|
defer cleanup()
|
|
|
|
v, ok := GetCtx[int](ctx, UpdateWithStartInBetweenLockAndStart)
|
|
if !ok {
|
|
t.Fatal("Expected TestHooksImpl to contain value")
|
|
}
|
|
if v != 33 {
|
|
t.Fatal("Expected value to be 33")
|
|
}
|
|
})
|
|
|
|
t.Run("Values set directly on the registry are visible through the context", func(t *testing.T) {
|
|
ctx, reg := NewInjectedTestHooksImpl(t.Context())
|
|
cleanup := Set(reg, UpdateWithStartInBetweenLockAndStart, 44)
|
|
defer cleanup()
|
|
|
|
v, ok := GetCtx[int](ctx, UpdateWithStartInBetweenLockAndStart)
|
|
if !ok {
|
|
t.Fatal("Expected TestHooksImpl to contain value")
|
|
}
|
|
if v != 44 {
|
|
t.Fatal("Expected value to be 44")
|
|
}
|
|
})
|
|
|
|
t.Run("CallCtx uses the registry injected into the context", func(t *testing.T) {
|
|
ctx, reg := NewInjectedTestHooksImpl(t.Context())
|
|
var value int
|
|
callback := func() {
|
|
value = 55
|
|
}
|
|
cleanup := Set(reg, UpdateWithStartInBetweenLockAndStart, callback)
|
|
defer cleanup()
|
|
|
|
CallCtx(ctx, UpdateWithStartInBetweenLockAndStart)
|
|
if value != 55 {
|
|
t.Fatal("Expected value to be 55")
|
|
}
|
|
})
|
|
}
|