rune_trie_test.go 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package trie
  2. import (
  3. "errors"
  4. "math/rand"
  5. "testing"
  6. "time"
  7. "go-common/app/service/main/antispam/util"
  8. )
  9. func TestRuneTrieAdd(t *testing.T) {
  10. tr := NewRuneTrie()
  11. tr.Put("jimmy", 1)
  12. tr.Put("anny", 87)
  13. tr.Put("xxxx", 23)
  14. tr.Put("jim", 2)
  15. if v := tr.Get("jimxx"); v != nil {
  16. t.Errorf("expected nil, got %v", v)
  17. }
  18. if v := tr.Get("jimmy"); v.(int) != 1 {
  19. t.Errorf("expected val, got %v", v)
  20. }
  21. if v := tr.Get("anny"); v.(int) != 87 {
  22. t.Errorf("expected val, got %v", v)
  23. }
  24. if v := tr.Get("xxxx"); v.(int) != 23 {
  25. t.Errorf("expected val, got %v", v)
  26. }
  27. if v := tr.Get("jim"); v.(int) != 2 {
  28. t.Errorf("expected val, got %v", v)
  29. }
  30. }
  31. func BenchmarkRuneTriePut(b *testing.B) {
  32. rand.Seed(time.Now().UnixNano())
  33. tr := NewRuneTrie()
  34. for i := 0; i < b.N; i++ {
  35. tr.Put(util.RandStr(10), 845)
  36. }
  37. }
  38. func TestRuneTrieFind(t *testing.T) {
  39. tr := NewRuneTrie()
  40. tr.Put("我才是大佬", 2)
  41. tr.Put("我才是大佬", 88)
  42. tr.Put("mm", 1)
  43. tr.Put("mmp", 2)
  44. tr.Put("my name is jimmymmp", 2)
  45. tr.Put("xxx", 88)
  46. tr.Put("jimmy xxx, hhjhmmp", 2)
  47. cases := []struct {
  48. content string
  49. expectKey string
  50. expectValue int
  51. }{
  52. {
  53. content: "mm",
  54. expectKey: "mm",
  55. expectValue: 1,
  56. },
  57. {
  58. content: "m都xx发生地方范德萨发爱迪生刚发的否多少发生的否阿萨德否收到符文大师否xxxmy name is jimy, hhjhmp",
  59. expectKey: "xxx",
  60. expectValue: 88,
  61. },
  62. {
  63. content: "m都mxx发生地方范德萨发爱迪生刚发的否多少发生的否阿萨德否收到符文大师否xxxmy name is jimy, hhjhmp",
  64. expectKey: "xxx",
  65. expectValue: 88,
  66. },
  67. {
  68. content: "我才是大佬",
  69. expectKey: "我才是大佬",
  70. expectValue: 88,
  71. },
  72. }
  73. for _, c := range cases {
  74. t.Run("", func(t *testing.T) {
  75. k, v := tr.Find(c.content, "")
  76. if v == nil {
  77. t.Fatal(errors.New("val is nil"))
  78. }
  79. if k != c.expectKey || v.(int) != c.expectValue {
  80. t.Errorf("want key: %s, val:%v, got key:%s, val:%v", c.expectKey, c.expectValue, k, v)
  81. }
  82. })
  83. }
  84. }
  85. //BenchmarkTrieListFind-4 50000 25347 ns/op
  86. func BenchmarkRuneTrieFind(b *testing.B) {
  87. rand.Seed(time.Now().UnixNano())
  88. tr := NewRuneTrie()
  89. for i := 0; i < b.N; i++ {
  90. tr.Put(util.RandStr(10), i)
  91. }
  92. tr.Put("地方考虑saDFFDSALK", 8888)
  93. tr.Put("都说了开发贷款", 7512)
  94. for i := 0; i < b.N; i++ {
  95. tr.Find("dfa啥都发生地方的施工费按发的噶是打发士大夫撒旦噶尔尕热狗怕的是结果来看;砥节奉公;来人速度感而过;sfdsfas fsadf asd fsad f asd都说了sdfs gfdgd jimmy开发速度来发噶都说了开发贷款时间范德萨了空间发的是 jimmy按时到路口发生撒地方考虑saDFFDSALKFDFASDFASDFSDFSADFRGEWTRETGERG", "")
  96. }
  97. }