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

Listing 1.8: Test for parseArgs() function

Оглавление

// chap1/flag-improvements/parse_args_test.go package main import ( "bufio" "bytes" "errors" "testing" ) func TestParseArgs(t *testing.T) { // TODO insert the test configs as per above tests := []struct { args []string config output string err error }{..} byteBuf := new(bytes.Buffer) for _, tc := range tests { c, err := parseArgs(byteBuf, tc.args) if tc.err == nil && err != nil { t.Fatalf("Expected nil error, got: %v\n", err) } if tc.err != nil && err.Error() != tc.err.Error() { t.Fatalf("Expected error to be: %v, got: %v\n", tc.err, err) } if c.numTimes != tc.numTimes { t.Errorf("Expected numTimes to be: %v, got: %v\n", tc.numTimes, c.numTimes) } gotMsg := byteBuf.String() if len(tc.output) != 0 && gotMsg != tc.output { t.Errorf("Expected stdout message to be: %#v, Got: %#v\n", tc.output, gotMsg) } byteBuf.Reset() } }

Save Listing 1.8 into a new file, parse_args_test.go, in the same directory that you used for Listing 1.7. The test for the validateArgs() function is the same as Listing 1.3, and you can find it in the validate_args_test.go file in the flag-improvements subdirectory of the book's code.

The unit test for the runCmd() function remains the same as that of Listing 1.4, except for a new test configuration where the name is specified by the user via a positional argument. The tests slice is defined as follows:

tests := []struct { c config input string output string err error }{ // Tests the behavior when an empty string is // entered interactively as input. { c: config{numTimes: 5}, input: "", output: strings.Repeat("Your name please? Press the Enter key when done.\n", 1), err: errors.New("You didn't enter your name"), }, // Tests the behavior when a positional argument // is not specified and the input is asked from the user { c: config{numTimes: 5}, input: "Bill Bryson", output: "Your name please? Press the Enter key when done.\n" + strings.Repeat("Nice to meet you Bill Bryson\n", 5), }, // Tests the new behavior where the user has entered their name // as a positional argument { c: config{numTimes: 5, name: "Bill Bryson"}, input: "", output: strings.Repeat("Nice to meet you Bill Bryson\n", 5), }, }

The complete test is shown in Listing 1.9.

Practical Go

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