Читать книгу Practical Go - Amit Saha - Страница 36

Listing 1.4: Test for the runCmd() function

Оглавление

// chap1/manual-parse/run_cmd_test.go package main import ( "bytes" "errors" "strings" "testing" ) func TestRunCmd(t *testing.T) { // TODO Insert definition tests[] array as earlier byteBuf := new(bytes.Buffer) for _, tc := range tests { rd := strings.NewReader(tc.input) err := runCmd(rd, byteBuf, tc.c) if err != nil && tc.err == nil { t.Fatalf("Expected nil error, got: %v\n", err) } if tc.err != nil && err.Error() != tc.err.Error() { t.Fatalf("Expected error: %v, Got error: %v\n", tc.err.Error(), err.Error()) } gotMsg := byteBuf.String() if gotMsg != tc.output { t.Errorf("Expected stdout message to be: %v, Got: %v\n", tc.output, gotMsg) } byteBuf.Reset() } }

We call the byteBuf.Reset() method so that the buffer is emptied before executing the next test case. Save Listing 1.4 into the same directory as Listings 1.1, 1.2, and 1.3. Name the file run_cmd_test.go and run all of the tests:

$ go test -v === RUN TestParseArgs --- PASS: TestParseArgs (0.00s) === RUN TestRunCmd --- PASS: TestRunCmd (0.00s) PASS ok github.com/practicalgo/code/chap1/manual-parse 0.529s

You may be curious to find out what the test coverage looks like and visually see which parts of your code are not tested. To do so, run the following command first to create a coverage profile:

$ go test -coverprofile cover.out PASS coverage: 71.7% of statements ok github.com/practicalgo/code/chap1/manual-parse 0.084s

The above output tells us that our tests cover 71.7 percent of the code in main.go. To see which parts of the code are covered, run the following:

$ go tool cover -html=cover.out

This will open your default browser application and show the coverage of your code in an HTML file. Notably, you will see that the main() function is reported as uncovered since we didn't write a test for it. This leads nicely to Exercise 1.1.

EXERCISE 1.1: TESTING THE MAIN() FUNCTION In this exercise, you will write a test for the main() function. However, unlike with other functions, you will need to test the exit status for different input arguments. To do so, your test should do the following:

1 Build the application. You will find using the special TestMain() function useful here.

2 Execute the application with different command-line arguments using the os.Exec() function. This will allow you to verify both the standard output and the exit code.

Congratulations! You have written your first command-line application. You parsed the os.Args slice to allow the user to provide input to the application. You learned how to make use of the io . Reader and io . Writer interfaces to write code that is unit testable.

Next, we will see how the standard library's flag package automatically takes care of the command-line argument parsing, validation of the type of data, and more.

Practical Go

Подняться наверх