$ go test -v
=== RUN TestReverse
--- PASS: TestReverse (0.00s)
=== RUN: ExampleReverse
--- PASS: ExampleReverse (0.00s)
PASS
ok github.com/golang/example/stringutil 0.009s
Last active
April 8, 2018 18:53
-
-
Save OlegGorj/98abfff702c54ea2ce57abc68899c084 to your computer and use it in GitHub Desktop.
GOlang examples and snippets
// Package stringutil contains utility functions for working with strings.
package stringutil
// Reverse returns its argument string reversed rune-wise left to right.
func Reverse(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package stringutil | |
import "testing" | |
func TestReverse(t *testing.T) { | |
for _, c := range []struct { | |
in, want string | |
}{ | |
{"Hello, world", "dlrow ,olleH"}, | |
{"Hello, 世界", "界世 ,olleH"}, | |
{"", ""}, | |
} { | |
got := Reverse(c.in) | |
if got != c.want { | |
t.Errorf("Reverse(%q) == %q, want %q", c.in, got, c.want) | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package stringutil_test | |
import ( | |
"fmt" | |
"github.com/golang/example/stringutil" | |
) | |
func ExampleReverse() { | |
fmt.Println(stringutil.Reverse("hello")) | |
// Output: olleh | |
} |
What does it mean that the ExampleReverse function "passes"?
As it executes the example, the testing framework captures data written to standard output and then compares the output against the example's "Output:" comment. The test passes if the test's output matches its output comment.
To see a failing example we can change the output comment text to something obviously incorrect
func ExampleReverse() {
fmt.Println(stringutil.Reverse("hello"))
// Output: golly
}
and run the tests again:
$ go test
--- FAIL: ExampleReverse (0.00s)
got:
olleh
want:
golly
FAIL
If we remove the output comment entirely
func ExampleReverse() {
fmt.Println(stringutil.Reverse("hello"))
}
then the example function is compiled but not executed:
$ go test -v
=== RUN TestReverse
--- PASS: TestReverse (0.00s)
PASS
ok github.com/golang/example/stringutil 0.009s
Examples without output comments are useful for demonstrating code that cannot run as unit tests, such as that which accesses the network, while guaranteeing the example at least compiles.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment