replacer_fuzz_test.go 893 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. //go:build go1.18
  2. // +build go1.18
  3. package stringx
  4. import (
  5. "fmt"
  6. "math/rand"
  7. "strings"
  8. "testing"
  9. )
  10. func FuzzReplacerReplace(f *testing.F) {
  11. keywords := make(map[string]string)
  12. for i := 0; i < 20; i++ {
  13. keywords[Randn(rand.Intn(10)+5)] = Randn(rand.Intn(5) + 1)
  14. }
  15. rep := NewReplacer(keywords)
  16. printableKeywords := func() string {
  17. var buf strings.Builder
  18. for k, v := range keywords {
  19. fmt.Fprintf(&buf, "%q: %q,\n", k, v)
  20. }
  21. return buf.String()
  22. }
  23. f.Add(50)
  24. f.Fuzz(func(t *testing.T, n int) {
  25. text := Randn(rand.Intn(n%50+50) + 1)
  26. defer func() {
  27. if r := recover(); r != nil {
  28. t.Errorf("mapping: %s\ntext: %s", printableKeywords(), text)
  29. }
  30. }()
  31. val := rep.Replace(text)
  32. keys := rep.(*replacer).node.find([]rune(val))
  33. if len(keys) > 0 {
  34. t.Errorf("mapping: %s\ntext: %s\nresult: %s\nmatch: %v",
  35. printableKeywords(), text, val, keys)
  36. }
  37. })
  38. }