Skip to content

proposal: testing: add WithValue and Value methods to testing.T (and others) #73288

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
mitar opened this issue Apr 9, 2025 · 0 comments
Open
Labels
Milestone

Comments

@mitar
Copy link
Contributor

mitar commented Apr 9, 2025

Proposal Details

I propose to add the following methods to testing.T (and others):

func (*testing.T) WithValue(key, val any) *testing.T

func (*testing.T) Value(key any) any

Its use would be similar to context.Context, but the idea is that it allows one to pass additional configuration parameters to testing helpers which might be called somewhere deep. Because generally testing.T is passed to all helpers (so that they can call t.Helper() it is reasonable to use t also to pass some additional optional values.

Example: github.com/stretchr/testify package prints diffs when assertions fail. The issue is that there are different ways to print those diffs. For example, should one respect String methods on structs printed (might hide important information) or not (might make structs unreadable because it uses default state representation). To configure this github.com/stretchr/testify could have global settings, but that is fragile. Better would be that caller could call something like t = t.WithValue(testify.UseStringify, true) and then pass this t to its assert.Equal. Why is this better than just having assert.Equal accepting a parameter because assert.Equal might be called deep inside some other testing helper and caller wants to control that. So I propose that such setting could be passed through t itself.

Ugly workaround is to misuse environment variables and use t.Setenv but that disables parallelism and is simply ugly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants