{"id":576,"date":"2022-04-27T13:15:00","date_gmt":"2022-04-27T13:15:00","guid":{"rendered":"https:\/\/andrejacobs.org\/?p=576"},"modified":"2022-05-27T15:52:03","modified_gmt":"2022-05-27T15:52:03","slug":"learning-go-day-7","status":"publish","type":"post","link":"https:\/\/andrejacobs.org\/study-notes\/learning-go-day-7\/","title":{"rendered":"Learning Go – Day 7"},"content":{"rendered":"\n
Featured image by Egon Elbre<\/a><\/p>\n\n\n\n Generally all .go files in the same directory has to belong to the same Go package except for unit-tests that are allowed to belong to a different package. This helps ensure that your package only exports the types and functions\/methods as you intended and thus the unit-test can only import what you exported.<\/p>\n Convention is to name unit-test files with the Example: main.go will be unit-tested with main_test.go and that has a <\/p>\n <\/p>\n Featured image by Egon Elbre […]<\/p>\n\n
stdin<\/code>.\n
\n
import (\n\t"bufio"\n\t"io"\n\t"os"\n)\n\nfunc count(r io.Reader, countLines bool) int {\n\tscanner := bufio.NewScanner(r)\n\n\tif !countLines {\n\t\tscanner.Split(bufio.ScanWords)\n\t}\n\n\twc := 0\n\n\tfor scanner.Scan() {\n\t\twc++\n\t}\n\n\treturn wc\n}\n\n\/\/ Count words\ncount(os.Stdin, false)\n\/\/ Count lines (\\n) [except the trailing one]\ncount(os.Stdin, true)\n<\/code><\/pre>\n
\n
stderr<\/code> (and not
stdout<\/code>) and return non zero exit codes.<\/li>\n<\/ul>\n
if err := someOperation(); err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(42)\n}\n<\/code><\/pre>\n
\n
os.Args<\/code> (which is declared as
var Args []string<\/code> in the os package). Remember item 0 is the path of the application and thus you can use
Args[1:]<\/code> to return the slice of only the passed arguments.<\/li>\n
runtime<\/code> package. For example
runtime.GOOS == "windows"<\/code>.<\/li>\n<\/ul>\n
Unit-testing<\/h3>\n
_test.go<\/code> suffix and also for the package name.<\/p>\n
package main_test<\/code> as the first line.<\/p>\n
\n
$ go test -v\n=== RUN TestOne\n--- PASS: TestOne (0.00s)\n=== RUN TestSomething\n--- PASS: TestSomething (0.00s)\n=== RUN TestTwo\n--- PASS: TestTwo (0.00s)\nPASS\nok todo 0.097s\n\n$ go test -v\n=== RUN TestOne\n--- FAIL: TestOne (0.00s)\n...\n<\/code><\/pre>\n
\n
\n
$ go test -timeout 30s -coverprofile=\/path\/to\/codecoverage packagename\n<\/code><\/pre>\n
\n
$ go test -timeout 30s -run ^TestAdd$ todo\n<\/code><\/pre>\n
\n
(t *testing.T)<\/code>.<\/li>\n<\/ul>\n
package todo_test\n\nimport (\n\t"testing"\n\t"todo"\n)\n\nfunc TestAdd(t *testing.T) {\n\t\/\/ Do something you want to test\n\t...\n\n\tif result != expected {\n\t\tt.Errorf("Expected %q, got %q\\n", expected, result)\n\t}\n}\n<\/code><\/pre>\n
\n
testdata<\/code>. The Go tooling will ignore these files.<\/li>\n<\/ul>\n<\/div>\n","protected":false},"excerpt":{"rendered":"