Skip to content
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

proposal: testing: add assertion methods #52555

Closed
bkielbasa opened this issue Apr 25, 2022 · 4 comments
Closed

proposal: testing: add assertion methods #52555

bkielbasa opened this issue Apr 25, 2022 · 4 comments

Comments

@bkielbasa
Copy link

bkielbasa commented Apr 25, 2022

It's very common to use packages like testify or is as a set of helper methods that make testing code more readable. The reason behind using packages like that is to avoid writing repetitive code like the following.

func TestAddition(t *testing.T) {
  given := 2+4
  expected := 4

  if given != expected {
    t.Errorf("expected %d but %d given", expected, given)
  }
}

The if statement with the error message can be repeated even a hundred times. That's why we use external libraries to avoid that.

As we have generics in the language, we can make use of it and provide a new method in testing.T and testing.B:

func (t T) Equal[T comparable](expected, given T) {
  // comparing
  t.Fail()
}

func (t T) Equalf[T comparable](expected, given T, format string, args ...string) {
  // comparing
  t.Fail()
}

The first snipped would be simplified into:

func TestAddition(t *testing.T) {
  given := 2+4
  expected := 4

  t.Equal(expected, given)
}

func TestAddition2(t *testing.T) {
  given := 2+4
  expected := 4

  t.Equalf(expected, given, "math should always work")
}

Using generics has a big benefit over using any - we have a compile-time type check.

I know that saving those 2 lines of code doesn't seem to be a big win but please remember that the code may be repeated many times in a single test file.

@gopherbot gopherbot added this to the Proposal milestone Apr 25, 2022
@seankhliao
Copy link
Member

seankhliao commented Apr 25, 2022

Note we recommend against assertion libraries in TestComments https://github.com/golang/go/wiki/TestComments#assert-libraries

@ianlancetaylor
Copy link
Contributor

ianlancetaylor commented Apr 25, 2022

See also https://go.dev/doc/faq#assertions. This is an intentional choice.

@ianlancetaylor ianlancetaylor added this to Incoming in Proposals (old) Apr 25, 2022
@icholy

This comment has been hidden.

@rsc rsc moved this from Incoming to Declined in Proposals (old) May 4, 2022
@rsc
Copy link
Contributor

rsc commented May 4, 2022

This proposal has been declined as retracted.
— rsc for the proposal review group

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

No branches or pull requests

6 participants