Skip to content

proposal: testing: add TB.SetStdout #68810

Description

@sivchari

Proposal Details

I propose to add SetStdout to testing package.

If we want to test about Stdout, we must write like below.

func TestStdout(t *testing.T) {
	r, w, err := os.Pipe()
	if err != nil {
		t.Fatal(err)
	}

	defer r.Close()
	defer w.Close()

	oldStdout := os.Stdout

	t.Cleanup(func() {
		os.Stdout = oldStdout
	})

	os.Stdout = w

        // test
}

The reason I propose this API is similar with this.

Stdout is used globally and if we forget to restore the Stdout, many tests would be effected by this. So I think it's better approach to prevent it by to provide TB.SetStdout(). And there are a few codes that use this case in Go core. So I think it's common approach when we want to check stdout by go test.
As another idea, it might be good to check by static analysis.
Thanks.

Activity

  1. added this to the Proposal milestone on Aug 9, 2024
  2. gabyhelp commented on Aug 9, 2024

    @gabyhelp

    Related Issues and Documentation

    (Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)

  3. seankhliao commented on Aug 9, 2024

    @seankhliao
    Member

    see also #59928 testing.TB.Output()

  4. moved this to Incoming in Proposalson Aug 9, 2024
  5. seankhliao commented on May 11, 2025

    @seankhliao
    Member

    Output() was accepted. I think in general it's best to avoid modifying stdout, and instead prefer to use explicit writers where necessary.

  6. locked and limited conversation to collaborators on May 11, 2026
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

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions