If you are stubbing this test by creating a fake file that os.Stdin
is referencing, your tests will become tremendously OS specific when you try to handle ReadPassword()
. This is because under the hood Go is compiling separate syscalls depending on the OS. ReadPassword()
is implemented here, but the syscalls based on architecture and OS are in this directory. As you can see there are many. I cannot think of a good way to stub this test in the way you are specifying.
With the limited understanding of your problem the solution I would propose would be to inject a simple interface along the lines of:
type PasswordReader interface {
ReadPassword(fd int) ([]byte, error)
}
func (pr PasswordReader) ReadPassword(fd int) ([]byte, error) {
return terminal.ReadPassword(fd)
}
This way you can pass in a fake object to your tests, and stub the response to ReadPassword
. I know this feels like writing your code for your tests, but you can reframe this thought as terminal
is an outside dependency (I/O) that should be injected! So now your tests are not only ensuring your code works, but actually helping you make good design decisions.