Skip to content

proposal: testing: helpers for named table driven tests #77022

Open

Description

@seankhliao

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

  1. added this to the Proposal milestone on Dec 28, 2025
  2. added
    LibraryProposalIssues describing a requested change to the Go standard library or x/ libraries, but not to a tool
    on Dec 28, 2025
  3. jimmyfrasche commented on Dec 28, 2025

    @jimmyfrasche
    Member

    That is still too verbose.

    Some observations:

    1. all the attempts to solve this focus on runtime solutions
    2. go test uses code generation
    3. all of the information is already in the AST

    Maybe we could have something like

    var table = testing.Table(nil, []struct{ ... }{ ... })

    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 to Table so that first nil is whatever variable name was generated by the previous step. A bit hand wavy but that's the gist.

  4. jimmyfrasche commented on Dec 28, 2025

    @jimmyfrasche
    Member

    For even more magic the information could be recorded in a map keyed by file:line and Table could 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.

  5. mateusz834 commented on Dec 28, 2025

    @mateusz834
    Member
    // Seed adds all the entries in the corpus as named seeds to the given fuzz test
    func (c *Corupus[D]) Seed(f *F)

    D can by any type, but f.Add does not accept arbitrary types. It will panic in such case, right? Also struct fields would have to be inlined in f.Add parameters.

  6. seankhliao commented on Dec 28, 2025

    @seankhliao
    MemberAuthor

    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 embed package, 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?

  7. jimmyfrasche commented on Dec 28, 2025

    @jimmyfrasche
    Member

    e.g. you can't define a regular package that exports test data.

    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 test is 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.

  8. neild commented on Dec 29, 2025

    @neild
    Contributor

    I do like this better than #52721, which is verbose and easy to misuse.

    Is the Corpus type necessary? Consider this helper function instead, which is essentially T.Run with an additional parameter passed to the test function:

    func RunCase[T any](t *testing.T, f func(*testing.T, T), name string, test T) {
            t.Helper()
            t.Run(name, func(t *testing.T) {
                    t.Helper()
                    t.Log("test case defined here")
                    f(t, test)
            })
    }

    This lets us write the example above as:

    func Test(t *testing.T) {
            type entry struct {
                    in   string
                    want string
            }
            run := func(t *testing.T, e entry) {
                    got := strings.TrimPrefix(e.in, "foo")
                    if got != e.want {
                            t.Errorf("f(%q) = %q, want = %q", e.in, got, e.want)
                    }
            }
            RunCase(t, run, "empty", entry{
                    in:   "",
                    want: "",
            })
            RunCase(t, run, "foo", entry{
                    in:   "foo",
                    want: "",
            })
            RunCase(t, run, "bar", entry{
                    in:   "bar",
                    want: "bar",
            })
    }

    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:

    === RUN   Test
    === RUN   Test/empty
        main_test.go:33: test case defined here
    === RUN   Test/foo
        main_test.go:37: test case defined here
    === RUN   Test/bar
        main_test.go:41: test case defined here
    --- PASS: Test (0.00s)
        --- PASS: Test/empty (0.00s)
        --- PASS: Test/foo (0.00s)
        --- PASS: Test/bar (0.00s)
    

    A corpus can be reused across multiple tests by inverting the flow of control:

    func testCorpus(t *testing.T, f func(t *testing.T, e entry)) {
            RunCase(t, f, "empty", entry{
                    in:   "",
                    want: "",
            })
    }
  9. seankhliao commented on Dec 29, 2025

    @seankhliao
    MemberAuthor

    I think the RunCase you'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:

    func CaseRunner[D any](t *testing.T, f func(t *testing.T, data D)) func(string, D) {
    	return func(s string, d D) {
    		t.Helper()
    		t.Run(s, func(t *testing.T) {
    			t.Helper()
    			t.Log("case", "defined here")
    			f(t, d)
    		})
    	}
    }
    
    func Test(t *testing.T) {
    	type entry struct {
    		in   string
    		want string
    	}
    	test := CaseRunner(t, func(t *testing.T, e entry) {
    		got := strings.TrimPrefix(e.in, "foo")
    		if got != e.want {
    			t.Errorf("f(%q) = %q, want = %q", e.in, got, e.want)
    		}
    	})
    
    	test("empty", entry{
    		in:   "",
    		want: "",
    	})
    }

    it would look even nicer with something like #12854 to eliminate the named type.

  10. AndrewHarrisSPU commented on Dec 29, 2025

    @AndrewHarrisSPU

    I buy that the shape of Corpus.Add(name string, data D) seems more intuitive than Pos/Mark/SetPos from #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?

    Entry[D any] struct {
        Name, Pos string
        D
    }
    
    func NewEntry[D] (name string, data D) Entry[D] { ... }
    

    Corpus[D].Add is still useful here, but could users be trusted to adhere to annotated-by-construction when they're off of Corpus?

    Also, Pos/Mark/SetPos seem 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 a type Marker Entry[struct{}].

  11. Merovius commented on Dec 30, 2025

    @Merovius
    Contributor

    If I care about file/line position of a case, I probably care enough to name the case.

    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.

  12. seankhliao commented on Dec 30, 2025

    @seankhliao
    MemberAuthor

    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

  13. earthboundkid commented on Dec 31, 2025

    @earthboundkid
    Contributor

    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:

    func TestTrimFoo_inline(t *testing.T) {
    	type entry struct {
    		in   string
    		want string
    	}
    	testing.TestAll(t, map[string]entry{
    		"empty": entry{
    			in:   "",
    			want: "",
    		},
    		"foo": entry{
    			in:   "foo",
    			want: "",
    		},
    		"bar": entry{
    			in:   "bar",
    			want: "bar",
    		},
    	},
    		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)
    			}
    		})
    }

    The map entries could be sorted by TestAll to provide a stable testing order. There could also be BenchmarkAll and FuzzAll for those.

  14. seankhliao commented on Dec 31, 2025

    @seankhliao
    MemberAuthor

    That doesn't help with wanting to get a quick link / line number to where the case was defined.

  15. mateusz834 commented on Dec 31, 2025

    @mateusz834
    Member

    That doesn't help with wanting to get a quick link / line number to where the case was defined.

    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.

  16. seankhliao commented on Dec 31, 2025

    @seankhliao
    MemberAuthor

    I think a lot of the places that don't have names now don't use T.Run to 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.

  17. AndrewHarrisSPU commented on Jan 2, 2026

    @AndrewHarrisSPU

    If I care about file/line position of a case, I probably care enough to name the case.

    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.

    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 test embeds 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 as x package? I can't really answer that, although I also think it'd be fine as far as I would use it.

  18. firelizzard18 commented on Jun 21, 2026

    @firelizzard18
    Contributor

    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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    LibraryProposalIssues describing a requested change to the Go standard library or x/ libraries, but not to a toolProposal

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions