Powerful Command-Line Applications in Go: Your First Command-Line Program in Go, flag, byte counter, test
Powerful Command-Line Applications in Go(Ricardo Gerardi(著)、Pragmatic Bookshelf)のChapter 1(Your First Command-Line Program in Go)、Exercisesの解答を求めてみる。
コード
main_test.go
package main
import (
"bytes"
"testing"
)
func TestCountWords(t *testing.T) {
b := bytes.NewBufferString("word1 word2 word3 word4\n")
got := count(b, false, false)
exp := 4
if got != exp {
t.Errorf("Expected %d, got %d instead.\n", exp, got)
}
}
func TestCountLines(t *testing.T) {
b := bytes.NewBufferString("word1 word2 word3\nline2\nline3 word1")
got := count(b, true, false)
exp := 3
if got != exp {
t.Errorf("Expected %d, got %d, instead.\n", exp, got)
}
}
func TestCountBytes(t *testing.T) {
b := bytes.NewBufferString("word1 日本語")
got := count(b, false, true)
exp := 15
if got != exp {
t.Errorf("Expected %d, got %d, instead.\n", exp, got)
}
}
main.go
package main
import (
"bufio"
"flag"
"fmt"
"io"
"os"
)
func count(r io.Reader, countLines bool, countBytes bool) int {
scanner := bufio.NewScanner(r)
if !countLines {
scanner.Split(bufio.ScanWords)
}
if countBytes {
scanner.Split(bufio.ScanBytes)
}
wc := 0
for scanner.Scan() {
wc++
}
return wc
}
func main() {
lines := flag.Bool("l", false, "Count lines")
bytes := flag.Bool("b", false, "Count Bytes")
flag.Parse()
fmt.Println(count(os.Stdin, *lines, *bytes))
}
入出力結果(Terminal, Zsh)
% go test
PASS
ok pragprog.com/rggo/firstProgram/wc 0.632s
% go test
# pragprog.com/rggo/firstProgram/wc [pragprog.com/rggo/firstProgram/wc.test]
./main_test.go:28:14: too many arguments in call to count
have (*bytes.Buffer, bool, bool)
want (io.Reader, bool)
FAIL pragprog.com/rggo/firstProgram/wc [build failed]
% go test
# pragprog.com/rggo/firstProgram/wc [pragprog.com/rggo/firstProgram/wc.test]
./main_test.go:10:14: not enough arguments in call to count
have (*bytes.Buffer, bool)
want (io.Reader, bool, bool)
./main_test.go:19:14: not enough arguments in call to count
have (*bytes.Buffer, bool)
want (io.Reader, bool, bool)
FAIL pragprog.com/rggo/firstProgram/wc [build failed]
% go test
--- FAIL: TestCountBytes (0.00s)
main_test.go:31: Expected 15, got 2, instead.
FAIL
exit status 1
FAIL pragprog.com/rggo/firstProgram/wc 0.952s
% go test
--- FAIL: TestCountLines (0.00s)
main_test.go:22: Expected 3, got 35, instead.
--- FAIL: TestCountBytes (0.00s)
main_test.go:31: Expected 15, got 2, instead.
FAIL
exit status 1
FAIL pragprog.com/rggo/firstProgram/wc 1.123s
% go test
PASS
ok pragprog.com/rggo/firstProgram/wc 0.426s
%