Repository navigation
Description
Proposal Details
helpers for named table driven tests
API additions
package testing
// Corpus holds a set of test data for use in tests, benchmarks, or fuzz tests.
type Corpus[D any] struct{
// unexported fields
}
// Add a test case to the corpus.
func (c *Corpus[D]) Add(name string, data D) {}
// Test runs the given test function against all entries in the corpus
func (c *Corpus[D]) Test(t *T, f func(t *T, data D))
// Benchmark runs the given benchmark function against all entries in the corpus
func (c *Corpus[D]) Benchmark(b *B, f func(b *B, data D))
// Seed adds all the entries in the corpus as named seeds to the given fuzz test
func (c *Corupus[D]) Seed(f *F)output format
=== RUN TestFoo
=== ATTR TestFoo CorpusEntry my_test.go:1234
--- FAIL: TestFoo (0.00s)
why
This is an alternative to #52751 and #70070
The accepted proposal for #52751 is quite verbose,
requiring a Pos field in every test case struct,
and a Mark entry in every definition.
The variations in the comments are fairly similar,
mostly centering around making name hold more data.
I think we should instead work around that by wrapping the entire table definition instead.
Corpus would be equivalent to the ad-hoc slices defined today to hold test cases,
and by running the test function from the corpus,
one level of indenting can be eliminated in the common case of using a loop and a subtest.
Since Corpus would hold named test entries,
I think it can be reused for seeding the fuzz tests with names.
For the output, I would rather not have the double my_test.go:1234 my_test.go:4321 ... format which becomes unwieldy especially with long file names or full paths.
I think an attribute logged once at the start of the test is the right way to represent this.
Example: baseline
This is a baseline test function
func TestTrimFoo_orig(t *testing.T) {
entries := []struct {
name string
in string
want string
}{{
name: "empty",
in: "",
want: "",
}, {
name: "foo",
in: "foo",
want: "",
}, {
name: "bar",
in: "bar",
want: "bar",
}}
for _, c := range cases {
t.Run(e.name, func(t *testing.T) {
got := strings.TrimPrefix(e.in, "foo")
if got != e.want {
t.Error("f(%q) = %q, want = %q", e.in, got, e.want)
}
})
}
}Example: inline table in test function
This is the test function above, translated to the new api.
It is denser than the original (name and a brace are combine on one line),
but it does involve creating a named type to hold the test case.
The actual test function is also one level less indented.
func TestTrimFoo_inline(t *testing.T) {
type entry struct {
in string
want string
}
var corpus testing.Corpus[entry]
corpus.Add("empty", entry{
in: "",
want: "",
})
corpus.Add("foo", entry{
in: "foo",
want: "",
})
corpus.Add("bar", entry{
in: "bar",
want: "bar",
})
corpus.Test(t, func(t *testing.T, e entry) {
got := strings.TrimPrefix(e.in, "foo")
if got != e.want {
t.Error("f(%q) = %q, want = %q", e.in, got, e.want)
}
})
}Example: shared corpus for different tests
This is shows the same corpus definition being reused for different tests/fuzz tests.
type trimFooEntry struct {
in string
want string
}
var trimFooCorpus = func() *testing.Corpus[trimFooEntry] {
var corpus testing.Corpus[trimFooEntry]
corpus.Add("empty", trimFooEntry{
in: "",
want: "",
})
corpus.Add("foo", trimFooEntry{
in: "foo",
want: "",
})
corpus.Add("bar", trimFooEntry{
in: "bar",
want: "bar",
})
return corpus
}
func TestTrimFoo_shared(t *testing.T) {
corpus.Test(t, func(t *testing.T, e entry) {
got := strings.TrimPrefix(e.in, "foo")
if got != e.want {
t.Error("f(%q) = %q, want = %q", e.in, got, e.want)
}
})
}
func FuzzTrimFoo_shared(f *testing.F) {
corpus.Seed(f)
f.Fuzz(func(e entry){
got := strings.TrimPrefix(e.in, "foo")
if got != e.want {
t.Error("f(%q) = %q, want = %q", e.in, got, e.want)
}
})
}
Activity
gabyhelp commentedon Dec 28, 2025
Related Issues
(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)
jimmyfrasche commentedon Dec 28, 2025
That is still too verbose.
Some observations:
go testuses code generationMaybe we could have something like
then the source code of the tests looks for all calls to
Table, grabs the info out of the second parameter, writes it to a generated go file, and then rewrites the above call toTableso that firstnilis whatever variable name was generated by the previous step. A bit hand wavy but that's the gist.jimmyfrasche commentedon Dec 28, 2025
For even more magic the information could be recorded in a map keyed by file:line and
Tablecould get that at runtime to look up the appropriate entry. That might be preferable as you could avoid storing the info in a generated .go and just pass it in as an embedded json file or the like.mateusz834 commentedon Dec 28, 2025
Dcan by any type, butf.Adddoes not accept arbitrary types. It will panic in such case, right? Also struct fields would have to be inlined inf.Addparameters.seankhliao commentedon Dec 28, 2025
I think compile time magic for tests isn't great, e.g. you can't define a regular package that exports test data.
In adding the
embedpackage, we chose not have magic functions to do the embedding, I don't see this as special enough to add magic for.I think panic for invalid Seed / Add is appropriate as it does now.
Perhaps, Seed / Fuzz isn't a great point to integrate now, I thought it supported structs of the allowed data types but I guess not yet?
jimmyfrasche commentedon Dec 28, 2025
There's nothing inherent about in the design.
Say the pos/name info is stored in a generated .go file in a big map keyed by a string derived from the runtime call info. The table's data structure is just
struct { key string; vals []T }where key is the call site info and vals are the entries. The factory just creates the key and stores the values as is. The various test/bench/fuzz methods can grab the pos/name information when called so it's safe to use the factory outside of the testing package. If the data is from an external package and the factory is not, it's still possible to record the info for the external value, the routine recording that info just needs to look up where the variable is defined.It is a little magic but
go testis rife with magic and it would be very convenient to continue to write the test table as a single literal and just have it work.neild commentedon Dec 29, 2025
I do like this better than #52721, which is verbose and easy to misuse.
Is the
Corpustype necessary? Consider this helper function instead, which is essentiallyT.Runwith an additional parameter passed to the test function:This lets us write the example above as:
That's about the same level of verbosity, and requires less mechanism. The test case location is logged rather than output as an attribute, though:
A corpus can be reused across multiple tests by inverting the flow of control:
seankhliao commentedon Dec 29, 2025
I think the
RunCaseyou've shown is simpler, but more of a mental hurdle to get across, since it feels like manually unrolling a for loop.I also think it's also a bit harder to write since there's no assistance in setting up both the data type and the test function, whereas with Corpus, once you initialize the type, the rest can be autocompleted / prefilled with templates.
perhaps:
it would look even nicer with something like #12854 to eliminate the named type.
AndrewHarrisSPU commentedon Dec 29, 2025
I buy that the shape of
Corpus.Add(name string, data D)seems more intuitive thanPos/Mark/SetPosfrom #52751. If I care about file/line position of a case, I probably care enough to name the case. This seems really nice, I'd prefer it in most cases. By most cases, I mean: table-driven tests are great and the right organizing principle, often for unit tests or similarly easily sequenced test logic.But occasionally table-driven tests are not the right approach, so I'm intrigued that there could a hidden structure definition behind a
Corpus, maybe that could be exported?Corpus[D].Addis still useful here, but could users be trusted to adhere to annotated-by-construction when they're off ofCorpus?Also,
Pos/Mark/SetPosseem strictly more precise in the rare cases where I'd want something analogous to a named breakpoint. But, maybe there's a way to recover the named breakpoint notion from atype Marker Entry[struct{}].Merovius commentedon Dec 30, 2025
I disagree with this. I frequently use
for i, tc := range tcs { t.Run(fmt.Sprintf("%.3d", i), …) }in table-driven tests, but would still very much like to be able to easily find the failing case. To me, being forced to provide a name would mostly have the effect of discouraging me from adding lots of test cases.On the other hand, that's a problem I'd have with #52751 as well.
seankhliao commentedon Dec 30, 2025
I think it'd be fine to pass it an empty string as the name and have it choose a name for you, as it already does for t.Run
earthboundkid commentedon Dec 31, 2025
What about having a function
TestAll[D any](*T, map[string]D, func(*T, D))?The example gets a little less verbose and closer to the []struct version:
The map entries could be sorted by TestAll to provide a stable testing order. There could also be
BenchmarkAllandFuzzAllfor those.seankhliao commentedon Dec 31, 2025
That doesn't help with wanting to get a quick link / line number to where the case was defined.
mateusz834 commentedon Dec 31, 2025
That comment made me wonder how useful that actually is, this proposal requires a name to be provided,
Add(name, data). I think name is sufficient to grep/locate in a specific file, thus i don't see a need for a position if we have a name already. I think the only benefit of positions is when you don't want to/don't have test case names.This comment does not take into account empty strings and auto generated names, mentioned #77022 (comment).
This raises the question of whether Add should accept a name. It could be useful, especially to avoid grepping through files for a specific test case, but the benefit seems smaller than it is for unnamed test cases.
seankhliao commentedon Dec 31, 2025
I think a lot of the places that don't have names now don't use
T.Runto run each case, instead just using a plain for loop.But that's somewhat awkward for when you want to display additional per case information, since there's no right scope to attach that information to.
A lot of the non-trivial table driven tests will have a name field.
Or sometimes I've seen people just add a comment instead of a name.
Even simple tests will often have groupings that describe different scenarios.
I think having a clear place to name the test case is good. We could probably make it clear that it doesn't need to be unique.
AndrewHarrisSPU commentedon Jan 2, 2026
That's an entirely reasonable and fair point, and it's been stuck in the back of my mind.
I think what @jimmyfrasche suggests is a workable idea - build a map from table-constructor-positions -> slices-of-entry-positions, from the AST. It's just the question about having an expectation that
go testembeds source text, or some data structure derived from source text like this - does it pass everyone's smell test? Would it be easier to include asxpackage? I can't really answer that, although I also think it'd be fine as far as I would use it.firelizzard18 commentedon Jun 21, 2026
This would make static detection of table driven tests (see golang/vscode-go#2445) significantly cleaner. The current plan is basically a fancy syntactic pattern matcher. If we could instead say, "Update your table-driven tests to use
testing.Corpus", static detection would reduce down to "Find calls to Corpus.Test, find calls to Corpus.Add, extract the name" (there are a lot of details of course, but I'm confident it would be significantly cleaner than "detect looping over a map/slice/array and calling t.Run on the range arg(s)"). CC @h9jiang