BASICS · IN THE APP NOW
Package with tests
One function, one test file and a table of cases, including a multi-byte string that a byte-wise reverse would break.
Offline: standard library only
What it is
Reverse converts the string to runes before swapping, so "héllo" becomes "olléh" rather than invalid UTF-8. The test names each case and runs it as a subtest, so a failure says exactly which input broke.
Every template's Go program was compiled for GOOS=wasip1 GOARCH=wasm with Go 1.27, then run, vetted and tested before it was added to the app.
Files
text
tested-package/
├── go.mod
├── main.go
├── reverse.go
└── reverse_test.goThe code
reverse.go
go
package main
// Reverse returns s with its runes in the opposite order. It works on
// runes rather than bytes so multi-byte characters survive.
func Reverse(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}reverse_test.go
go
package main
import "testing"
func TestReverse(t *testing.T) {
cases := []struct {
name string
in string
want string
}{
{name: "ascii", in: "gopher", want: "rehpog"},
{name: "empty", in: "", want: ""},
{name: "multibyte", in: "héllo", want: "olléh"},
}
for _, testCase := range cases {
t.Run(testCase.name, func(t *testing.T) {
if got := Reverse(testCase.in); got != testCase.want {
t.Errorf("Reverse(%q) = %q, want %q", testCase.in, got, testCase.want)
}
})
}
}What you learn
- Put tests in a _test.go file next to the code they check.
- Write a table of named cases and run each with t.Run.
- Report mismatches with t.Errorf and %q so empty strings stay visible.
- Work on runes, not bytes, when text may contain multi-byte characters.
Run it on a server
The same commands work on any machine with Go installed.
bash
go test ./...
go test -run TestReverse/multibyte -v .Related: Tests are a file, not a framework · Packages, modules and tooling