replacer_fuzz_test.go 876 B

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