Skip to content

Commit

Permalink
test: don't override os.Stdin
Browse files Browse the repository at this point in the history
  • Loading branch information
lgfa29 committed Sep 22, 2022
1 parent 42ce0a2 commit 6404a40
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 10 deletions.
2 changes: 2 additions & 0 deletions command/operator_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import (
"github.com/posener/complete"
)

// Stdin represents the system's standard input, but it's declared as a
// variable here to allow tests to override it with a regular file.
var Stdin = os.Stdin

type OperatorAPICommand struct {
Expand Down
19 changes: 9 additions & 10 deletions command/operator_api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package command

import (
"bytes"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
Expand Down Expand Up @@ -112,28 +111,28 @@ func TestOperatorAPICommand_Curl(t *testing.T) {
// TestOperatorAPICommand_ContentLength tests that requests have the proper
// ContentLength set.
//
// Don't run in parallel since it messes with os.Stdin.
// Don't run it in parallel as it modifies the package's Stdin variable.
func TestOperatorAPICommand_ContentLength(t *testing.T) {
contentLength := make(chan int, 1)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
contentLength <- int(r.ContentLength)
}))
defer ts.Close()

// Setup os.Stdin to a known value.
// The command stats stdin, so we can't mock it as another io.Reader.
// https://stackoverflow.com/a/46365584
// Setup a temp file to act as stdin.
input := []byte("test-input")
tmpfile, err := ioutil.TempFile("", "example")
fakeStdin, err := os.CreateTemp("", "fake-stdin")
require.NoError(t, err)
defer os.Remove(tmpfile.Name())
defer os.Remove(fakeStdin.Name())

_, err = tmpfile.Write(input)
_, err = fakeStdin.Write(input)
require.NoError(t, err)
_, err = tmpfile.Seek(0, 0)
_, err = fakeStdin.Seek(0, 0)
require.NoError(t, err)

Stdin = tmpfile
// Override the package's Stdin variable for testing.
Stdin = fakeStdin
defer func() { Stdin = os.Stdin }()

// Setup command.
buf := bytes.NewBuffer(nil)
Expand Down

0 comments on commit 6404a40

Please sign in to comment.