Files
tasks/common/testing/testhooks/noop_impl.go
Tim Deeb-SwihartandGitHub 68f8d14534 testhooks: add context-wrapping functionality (#7923)
## 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
2025-06-16 13:39:54 -07:00

54 lines
1.4 KiB
Go

//go:build !test_dep
package testhooks
import (
"context"
"go.uber.org/fx"
)
var Module = fx.Options(
fx.Provide(func() (_ TestHooks) { return }),
)
type (
// TestHooks (in production mode) is an empty struct just so the build works.
// See TestHooks in test_impl.go.
//
// TestHooks are an inherently unclean way of writing tests. They require mixing test-only
// concerns into production code. In general you should prefer other ways of writing tests
// wherever possible, and only use TestHooks sparingly, as a last resort.
TestHooks struct{}
)
// Get gets the value of a test hook. In production mode it always returns the zero value and
// false, which hopefully the compiler will inline and remove the hook as dead code.
//
// TestHooks should be used very sparingly, see comment on TestHooks.
func Get[T any](_ TestHooks, key Key) (T, bool) {
var zero T
return zero, false
}
// GetCtx gets the value of a test hook from the registry embedded in the
// context chain.
//
// TestHooks should be used sparingly, see comment on TestHooks.
func GetCtx[T any](ctx context.Context, key Key) (T, bool) {
var zero T
return zero, false
}
// Call calls a func() hook if present.
//
// TestHooks should be used very sparingly, see comment on TestHooks.
func Call(_ TestHooks, key Key) {
}
// CallCtx calls a func(context.Context) hook if present.
//
// TestHooks should be used very sparingly, see comment on TestHooks.
func CallCtx(_ context.Context, key Key) {
}