Home > Backend Development > Golang > How to Test Go Code that Reads from Stdin and Writes to Stdout?

How to Test Go Code that Reads from Stdin and Writes to Stdout?

Patricia Arquette
Release: 2024-10-27 05:20:03
Original
883 people have browsed it

How to Test Go Code that Reads from Stdin and Writes to Stdout?

Writing Go Tests for Code that Writes to Stdin

To write a Go test for code that reads from stdin and echoes it back to stdout, it's advisable to isolate the functionality into a separate function that takes an io.Reader and an io.Writer as parameters.

Instead of performing all operations in the main function using stdin and stdout directly, your code should define a function for this specific purpose. For instance:

<code class="go">func echo(r io.Reader, w io.Writer) {
    reader := bufio.NewReader(r)
    for {
        fmt.Print("> ", w)
        bytes, _, err := reader.ReadLine()
        if err == io.EOF {
            os.Exit(0)
        }
        fmt.Println(string(bytes), w)
    }
}</code>
Copy after login

Within your main function, you can then call the echo function:

<code class="go">func main() {
    echo(os.Stdin, os.Stdout)
}</code>
Copy after login

To test this function, you can create a test like this:

<code class="go">import (
    "bytes"
    "io"
    "testing"
)

func TestEcho(t *testing.T) {
    input := "abc\n"
    expected := "abc\n"

    r := bytes.NewBufferString(input)
    w := bytes.NewBufferString("")

    echo(r, w)

    if got := w.String(); got != expected {
        t.Errorf("Expected: %v, Got: %v", expected, got)
    }
}</code>
Copy after login

This test creates a buffered reader from the specified input string and a buffered writer to capture the output. It then calls the echo function, passing in the reader and writer. Finally, it compares the output with the expected result.

The above is the detailed content of How to Test Go Code that Reads from Stdin and Writes to Stdout?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template