content_moderation_keyword_matcher_test.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package service
  2. import (
  3. "math/rand"
  4. "strings"
  5. "testing"
  6. "github.com/stretchr/testify/require"
  7. )
  8. func TestContentModerationKeywordMatcherMatchesLegacyBehavior(t *testing.T) {
  9. tests := []struct {
  10. name string
  11. text string
  12. keywords []string
  13. }{
  14. {name: "miss", text: "clean prompt", keywords: []string{"blocked", "secret"}},
  15. {name: "case insensitive", text: "contains SECRET value", keywords: []string{"secret"}},
  16. {name: "configured order wins", text: "early appears before later", keywords: []string{"later", "early"}},
  17. {name: "overlap uses configured order", text: "abc", keywords: []string{"bc", "abc"}},
  18. {name: "unicode", text: "这里包含敏感词和世界", keywords: []string{"世界", "敏感词"}},
  19. {name: "duplicates", text: "duplicate", keywords: []string{"duplicate", "DUPLICATE"}},
  20. {name: "empty entries", text: "blocked", keywords: []string{"", "blocked"}},
  21. }
  22. for _, tt := range tests {
  23. t.Run(tt.name, func(t *testing.T) {
  24. wantKeyword, wantHit := matchBlockedKeyword(tt.text, tt.keywords)
  25. gotKeyword, gotHit := newContentModerationKeywordMatcher(tt.keywords).Match(tt.text)
  26. require.Equal(t, wantHit, gotHit)
  27. require.Equal(t, wantKeyword, gotKeyword)
  28. })
  29. }
  30. }
  31. func TestContentModerationKeywordMatcherRandomizedParity(t *testing.T) {
  32. rng := rand.New(rand.NewSource(20260714))
  33. const alphabet = "abcXYZ"
  34. for iteration := 0; iteration < 1000; iteration++ {
  35. keywords := make([]string, 1+rng.Intn(30))
  36. for index := range keywords {
  37. length := 1 + rng.Intn(8)
  38. var value strings.Builder
  39. for range length {
  40. _ = value.WriteByte(alphabet[rng.Intn(len(alphabet))])
  41. }
  42. keywords[index] = value.String()
  43. }
  44. var text strings.Builder
  45. for range 20 + rng.Intn(100) {
  46. _ = text.WriteByte(alphabet[rng.Intn(len(alphabet))])
  47. }
  48. wantKeyword, wantHit := matchBlockedKeyword(text.String(), keywords)
  49. gotKeyword, gotHit := newContentModerationKeywordMatcher(keywords).Match(text.String())
  50. require.Equal(t, wantHit, gotHit, "iteration %d", iteration)
  51. require.Equal(t, wantKeyword, gotKeyword, "iteration %d", iteration)
  52. }
  53. }