replacer_fuzz_test.go 857 B

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