Skip to content

testing: expose common struct as interface #56516

Description

@Olshansk

I recently found myself doing the following in one of our test suites

func Foo[T testing.T | testing.B | testing.F](t *T) *Bar {
   // test prep stuff

	var cleanupFn func(func())
	switch any(t).(type) {
	case *testing.T:
		cleanupFn = any(t).(*testing.T).Cleanup
	case *testing.B:
		cleanupFn = any(t).(*testing.B).Cleanup
	case *testing.F:
		cleanupFn = any(t).(*testing.F).Cleanup
	default:
		log.Fatalf("Error: unsupported type %T", t)
	}
	
	cleanupFn(func(){
      // test cleanup stuff
    })

The cleanup function is common to all of these and is part of the common struct, which is embedded in each of testingT, testing.B, and testing.F.

Screen Shot 2022-10-31 at 11 13 18 AM

I was wondering if common could potentially be exposed as an interface?

I'm happy to take a first stab at the PR if this is something the library mainteras would be open to, unless there's a technical reason this shouldn't be the case. Please lmk!

Activity

  1. seankhliao commented on Nov 1, 2022

    @seankhliao
    Member

    https://pkg.go.dev/testing#TB

    Unlike many projects, the Go project does not use GitHub Issues for general discussion or asking questions. GitHub Issues are used for tracking bugs and proposals only.

    For questions please refer to https://github.com/golang/go/wiki/Questions

  2. Olshansk commented on Nov 2, 2022

    @Olshansk
    Author

    @seankhliao This is a proposal though. I'm proposing to make an interface for the common struct under testing. I didn't want to put the effort into implementation before getting a 👍 so I don't waste time implementing.

  3. cespare commented on Nov 2, 2022

    @cespare
    Contributor

    @Olshansk @seankhliao's message includes a link to the already-existing interface: https://pkg.go.dev/testing#TB.

  4. Olshansk commented on Nov 3, 2022

    @Olshansk
    Author

    That's exactly what I needed. Sorry for not RTFM the first time @seankhliao!

  5. locked and limited conversation to collaborators on Nov 3, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions