S SmartDocs
Série: Go go 58 lignes · Mis à jour 2026-04-18

strings_test.go

Go/part1-language/examples/11_testing/strings_test.go

package strs

import (
	"fmt"
	"testing"
)

func TestReverse(t *testing.T) {
	cases := []struct {
		name, in, want string
	}{
		{"empty", "", ""},
		{"single", "a", "a"},
		{"ascii", "abc", "cba"},
		{"unicode", "héllo", "olléh"},
		{"palindrome", "level", "level"},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			if got := Reverse(tc.in); got != tc.want {
				t.Errorf("Reverse(%q) = %q, want %q", tc.in, got, tc.want)
			}
		})
	}
}

func TestIsPalindrome(t *testing.T) {
	if !IsPalindrome("level") {
		t.Error("expected palindrome")
	}
	if IsPalindrome("hello") {
		t.Error("expected not palindrome")
	}
}

func ExampleReverse() {
	fmt.Println(Reverse("abc"))
	// Output: cba
}

func BenchmarkReverse(b *testing.B) {
	s := "the quick brown fox jumps over the lazy dog"
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		_ = Reverse(s)
	}
}

func FuzzReverse(f *testing.F) {
	f.Add("hello")
	f.Add("héllo")
	f.Fuzz(func(t *testing.T, s string) {
		twice := Reverse(Reverse(s))
		if twice != s {
			t.Errorf("Reverse(Reverse(%q)) = %q", s, twice)
		}
	})
}

Articles liés