forked from WojciechMula/pyahocorasick
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunittests.py
1596 lines (1087 loc) · 41.8 KB
/
unittests.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
This is part of pyahocorasick Python module.
Unit tests for the C-based ahocorasick module.
Author : Wojciech Muła, [email protected]
WWW : http://0x80.pl/proj/pyahocorasick/
License : public domain
"""
import sys
import os
import unittest
import ahocorasick
try:
import _pickle
except ImportError:
_pickle = None
if ahocorasick.unicode:
conv = lambda x: x
else:
if sys.version_info.major >= 3:
conv = lambda x: bytes(x, 'ascii')
else:
conv = lambda x: x
class TestCase(unittest.TestCase):
def __init__(self, *args):
super(TestCase, self).__init__(*args)
if not hasattr(self, 'assertRaisesRegex'):
# fixup for Py2
self.assertRaisesRegex = self.assertRaisesRegexp
def assertEmpty(self, collection):
self.assertEqual(0, len(collection))
def assertNotEmpty(self, collection):
self.assertGreater(len(collection), 0)
class TestConstructor(TestCase):
def test_constructor_wrong_store(self):
with self.assertRaisesRegex(ValueError, "store value must be one of.*"):
ahocorasick.Automaton(-42)
def test_constructor_wrong_key_type(self):
with self.assertRaisesRegex(ValueError, "key_type must have value.*"):
ahocorasick.Automaton(ahocorasick.STORE_ANY, -42)
class TestTrieStorePyObjectsBase(TestCase):
def setUp(self):
self.A = ahocorasick.Automaton();
self.words = "word python aho corasick \x00\x00\x00".split()
self.inexisting = "test foo bar dword".split()
class TestTrieMethods(TestTrieStorePyObjectsBase):
"Test basic methods related to trie structure"
def test_empty(self):
A = self.A
self.assertTrue(A.kind == ahocorasick.EMPTY)
self.assertTrue(len(A) == 0)
def test_add_word(self):
A = self.A
self.assertTrue(A.kind == ahocorasick.EMPTY)
n = 0
for word in self.words:
n += 1
A.add_word(conv(word), None)
self.assertEqual(A.kind, ahocorasick.TRIE)
self.assertEqual(len(A), n)
# dupliacted entry
A.add_word(conv(self.words[0]), None)
self.assertTrue(A.kind == ahocorasick.TRIE)
self.assertTrue(len(A) == n)
def test_add_empty_word(self):
if ahocorasick.unicode:
self.assertFalse(self.A.add_word("", None))
else:
self.assertFalse(self.A.add_word(b"", None))
self.assertEqual(len(self.A), 0)
self.assertEqual(self.A.kind, ahocorasick.EMPTY)
def test_clear(self):
A = self.A
self.assertTrue(A.kind == ahocorasick.EMPTY)
for w in self.words:
A.add_word(conv(w), w)
self.assertEqual(len(A), len(self.words))
A.clear()
self.assertEqual(A.kind, ahocorasick.EMPTY)
self.assertEqual(len(A), 0)
def test_exists(self):
A = self.A
for w in self.words:
A.add_word(conv(w), w)
for w in self.words:
self.assertTrue(A.exists(conv(w)))
for w in self.inexisting:
self.assertFalse(A.exists(conv(w)))
def test_contains(self):
A = self.A
for w in self.words:
A.add_word(conv(w), w)
for w in self.words:
self.assertTrue(conv(w) in A)
for w in self.inexisting:
self.assertTrue(conv(w) not in A)
def test_match(self):
A = self.A
for word in self.words:
A.add_word(conv(word), word)
prefixes = "w wo wor word p py pyt pyth pytho python \x00 \x00\x00 \x00\x00\x00".split()
for word in prefixes:
self.assertTrue(A.match(conv(word)))
inexisting = "wa apple pyTon \x00\x00\x00\x00".split()
for word in inexisting:
self.assertFalse(A.match(conv(word)))
def test_get1(self):
A = self.A
for i, w in enumerate(self.words):
A.add_word(conv(w), i + 1)
for i, w in enumerate(self.words):
self.assertEqual(A.get(conv(w)), i + 1)
def test_get2(self):
A = self.A
for i, w in enumerate(self.words):
A.add_word(conv(w), i + 1)
for w in self.inexisting:
self.assertEqual(A.get(conv(w), None), None)
def test_get3(self):
A = self.A
for i, w in enumerate(self.words):
A.add_word(conv(w), i + 1)
for w in self.inexisting:
with self.assertRaises(KeyError):
A.get(conv(w))
def test_get_from_an_empty_automaton(self):
A = ahocorasick.Automaton()
r = A.get('foo', None)
self.assertEqual(r, None)
def test_longest_prefix(self):
A = self.A
for i, w in enumerate(self.words):
A.add_word(conv(w), i + 1)
# there is "word"
self.assertEqual(A.longest_prefix(conv("wo")), 2)
self.assertEqual(A.longest_prefix(conv("working")), 3)
self.assertEqual(A.longest_prefix(conv("word")), 4)
self.assertEqual(A.longest_prefix(conv("wordbook")), 4)
self.assertEqual(A.longest_prefix(conv("void")), 0)
self.assertEqual(A.longest_prefix(conv("")), 0)
def test_stats_have_valid_structure(self):
A = self.A
for i, w in enumerate(self.words):
A.add_word(conv(w), i + 1)
platform_dependent = None
reference = {
'longest_word': 8,
'total_size': platform_dependent,
'sizeof_node': platform_dependent,
'nodes_count': 25,
'words_count': 5,
'links_count': 24
}
s = A.get_stats()
self.assertEqual(len(s), len(reference))
for key in reference:
self.assertIn(key, s)
for key in (key for key in reference if reference[key] != platform_dependent):
self.assertEqual(reference[key], s[key])
def test_stats_for_empty_tire_are_empty(self):
s = self.A.get_stats()
self.assertTrue(len(s) > 0)
for key in s:
if key != "sizeof_node":
self.assertEqual(s[key], 0)
class TestTrieRemoveWord(TestTrieStorePyObjectsBase):
def test_remove_word_from_empty_trie(self):
self.assertFalse(self.A.remove_word("test"))
def test_remove_existing_word(self):
A = self.A
words = ["he", "her", "hi", "him", "his"]
for w in words:
A.add_word(conv(w), w)
expected_len = len(A)
for w in words:
self.assertTrue(self.A.remove_word(w))
self.assertFalse(self.A.exists(w))
expected_len -= 1
self.assertEqual(expected_len, len(A))
def test_remove_inexisting_word(self):
A = self.A
words = ["he", "her", "hi", "him", "his"]
for w in words:
A.add_word(conv(w), w)
expected_len = len(A)
for w in ["cat", "dog", "tree"]:
self.assertFalse(self.A.exists(w))
self.assertFalse(self.A.remove_word(w))
self.assertEqual(expected_len, len(A))
def test_remove__case1(self):
words = ["k", "ki", "kit", "kitt", "kitte", "kitten"
, "kitc", "kitch", "kitche", "kitchen"]
A = self.A
for w in words:
A.add_word(conv(w), w)
expected_set = set(words)
for w in words:
self.assertTrue(self.A.remove_word(w))
expected_set.discard(w)
current_set = set(A.keys())
self.assertEqual(expected_set, current_set)
self.assertEqual(len(expected_set), len(A))
def test_remove__case2(self):
words = ["k", "ki", "kit", "kitt", "kitte", "kitten"
, "kitc", "kitch", "kitche", "kitchen"]
A = self.A
for w in words:
A.add_word(conv(w), w)
expected_set = set(words)
for w in reversed(words):
self.assertTrue(self.A.remove_word(w))
expected_set.discard(w)
current_set = set(A.keys())
self.assertEqual(expected_set, current_set)
self.assertEqual(len(expected_set), len(A))
def test_remove_word_changes_type_of_automaton(self):
A = self.A
words = ["he", "her", "hi", "him", "his"]
for w in words:
A.add_word(conv(w), w)
A.make_automaton()
self.assertEqual(ahocorasick.AHOCORASICK, A.kind)
self.assertFalse(A.remove_word("inexisting"))
self.assertEqual(ahocorasick.AHOCORASICK, A.kind)
self.assertTrue(A.remove_word("hi"))
self.assertEqual(ahocorasick.TRIE, A.kind)
class TestTriePop(TestTrieStorePyObjectsBase):
def test_pop_from_empty_trie(self):
with self.assertRaises(KeyError):
self.A.pop("test")
def test_pop_existing_word(self):
A = self.A
words = ["he", "her", "hi", "him", "his"]
for w in words:
A.add_word(conv(w), w)
expected_len = len(A)
for w in words:
self.assertEqual(w, self.A.pop(w))
self.assertFalse(self.A.exists(w))
expected_len -= 1
self.assertEqual(expected_len, len(A))
def test_pop_inexisting_word(self):
A = self.A
words = ["he", "her", "hi", "him", "his"]
for w in words:
A.add_word(conv(w), w)
expected_len = len(A)
for w in ["cat", "dog", "tree"]:
with self.assertRaises(KeyError):
self.A.pop(w)
self.assertEqual(expected_len, len(A))
def test_pop__case1(self):
words = ["k", "ki", "kit", "kitt", "kitte", "kitten"
, "kitc", "kitch", "kitche", "kitchen"]
A = self.A
for w in words:
A.add_word(conv(w), w)
expected_set = set(words)
for w in words:
self.assertEqual(w, self.A.pop(w))
expected_set.discard(w)
current_set = set(A.keys())
self.assertEqual(expected_set, current_set)
self.assertEqual(len(expected_set), len(A))
def test_pop__case2(self):
words = ["k", "ki", "kit", "kitt", "kitte", "kitten"
, "kitc", "kitch", "kitche", "kitchen"]
A = self.A
for w in words:
A.add_word(conv(w), w)
expected_set = set(words)
for w in reversed(words):
self.assertEqual(w, self.A.pop(w))
expected_set.discard(w)
current_set = set(A.keys())
self.assertEqual(expected_set, current_set)
self.assertEqual(len(expected_set), len(A))
def test_pop_changes_type_of_automaton(self):
A = self.A
words = ["he", "her", "hi", "him", "his"]
for w in words:
A.add_word(conv(w), w)
A.make_automaton()
self.assertEqual(ahocorasick.AHOCORASICK, A.kind)
with self.assertRaises(KeyError):
A.pop("inexisting")
self.assertEqual(ahocorasick.AHOCORASICK, A.kind)
self.assertEqual("hi", A.pop("hi"))
self.assertEqual(ahocorasick.TRIE, A.kind)
class TestTrieIterators(TestTrieStorePyObjectsBase):
"Test iterators walking over trie"
def test_iter(self):
A = self.A
for i, w in enumerate(self.words):
A.add_word(conv(w), i + 1)
L = [word for word in A]
K = list(map(conv, self.words))
self.assertEqual(len(L), len(K))
self.assertEqual(set(L), set(K))
def test_keys(self):
A = self.A
for i, w in enumerate(self.words):
A.add_word(conv(w), i + 1)
L = [word for word in A.keys()]
K = [conv(word) for word in self.words]
self.assertEqual(len(L), len(K))
self.assertEqual(set(L), set(K))
def test_values(self):
A = self.A
for i, w in enumerate(self.words):
A.add_word(conv(w), i + 1)
L = [x for x in A.values()]
V = list(range(1, len(self.words) + 1))
self.assertEqual(len(L), len(V))
self.assertEqual(set(L), set(V))
def test_items(self):
A = self.A
I = []
for i, w in enumerate(self.words):
A.add_word(conv(w), i + 1)
I.append((conv(w), i + 1))
L = [x for x in A.items()]
self.assertEqual(len(L), len(I))
self.assertEqual(set(L), set(I))
def test_items_with_prefix_valid(self):
A = self.A
words = "he she her hers star ham".split()
for word in words:
A.add_word(conv(word), word)
I = list(map(conv, "he her hers".split()))
L = [x for x in A.keys(conv("he"))]
self.assertEqual(len(L), len(I))
self.assertEqual(set(L), set(I))
def test_items_with_prefix_invalid(self):
A = self.A
words = "he she her hers star ham".split()
for word in words:
A.add_word(conv(word), word)
I = []
L = [x for x in A.keys(conv("cat"))]
self.assertEqual(len(L), len(I))
self.assertEqual(set(L), set(I))
def test_items_with_valid_pattern(self):
A = self.A
words = "abcde aXcd aZcdef aYc Xbcdefgh".split()
for word in words:
A.add_word(conv(word), word)
I = ["aXcd"]
L = [x for x in A.keys(conv("a?cd"), conv("?"))]
self.assertEqual(set(I), set(L))
def test_items_with_valid_pattern2(self):
A = self.A
words = "abcde aXcde aZcdef aYc Xbcdefgh".split()
for word in words:
A.add_word(conv(word), word)
L = [x for x in A.keys(conv("a?c??"), conv("?"), ahocorasick.MATCH_EXACT_LENGTH)]
I = ["abcde", "aXcde"]
self.assertEqual(set(I), set(L))
L = [x for x in A.keys(conv("a?c??"), conv("?"), ahocorasick.MATCH_AT_MOST_PREFIX)]
I = ["aYc", "abcde", "aXcde"]
self.assertEqual(set(I), set(L))
L = [x for x in A.keys(conv("a?c??"), conv("?"), ahocorasick.MATCH_AT_LEAST_PREFIX)]
I = ["abcde", "aXcde", "aZcdef"]
self.assertEqual(set(I), set(L))
def test_items_wrong_wildcrard(self):
with self.assertRaisesRegex(ValueError, "Wildcard must be a single character.*"):
self.A.keys(conv("anything"), conv("??"))
def test_items_wrong_match_enum(self):
with self.assertRaisesRegex(ValueError, "The optional how third argument must be one of"):
self.A.keys(conv("anything"), conv("?"), -42)
class TestTrieIteratorsInvalidate(TestTrieStorePyObjectsBase):
"Test invalidating iterator when trie is changed"
def helper(self, method):
A = self.A
for i, w in enumerate(self.words):
A.add_word(conv(w), i + 1)
it = method()
w = next(it)
# word already exists, just change associated value
# iterator is still valid
A.add_word(conv(self.words[0]), 2)
w = next(it)
# new word, iterator is invalidated
A.add_word(conv("should fail"), 1)
with self.assertRaises(ValueError):
w = next(it)
def test_keys(self):
self.helper(self.A.keys)
def test_values(self):
self.helper(self.A.values)
def test_items(self):
self.helper(self.A.items)
class TestAutomatonBase(TestCase):
def setUp(self):
self.A = ahocorasick.Automaton();
self.words = "he her hers she".split()
self.string = "_sherhershe_"
self.correct_positons = [
(3, "she"),
(3, "he"),
(4, "her"),
(6, "he"),
(7, "her"),
(8, "hers"),
(10, "she"),
(10, "he")
]
def add_words(self):
for word in self.words:
self.A.add_word(conv(word), word)
return self.A
def add_words_and_make_automaton(self):
self.add_words()
self.A.make_automaton()
return self.A
class TestAutomatonConstruction(TestAutomatonBase):
"Test converting trie to Aho-Corasick automaton"
def test_make_automaton1(self):
A = self.A
self.assertEqual(A.kind, ahocorasick.EMPTY)
A.make_automaton()
# empty trie is never converted to automaton
self.assertEqual(A.kind, ahocorasick.EMPTY)
def test_make_automaton2(self):
A = self.A
self.assertEqual(A.kind, ahocorasick.EMPTY)
self.add_words()
self.assertEqual(A.kind, ahocorasick.TRIE)
A.make_automaton()
self.assertEqual(A.kind, ahocorasick.AHOCORASICK)
def test_make_automaton3(self):
A = self.A
self.assertEqual(A.kind, ahocorasick.EMPTY)
self.add_words()
self.assertEqual(A.kind, ahocorasick.TRIE)
A.make_automaton()
self.assertEqual(A.kind, ahocorasick.AHOCORASICK)
A.add_word(conv("rollback?"), True)
self.assertEqual(A.kind, ahocorasick.TRIE)
class TestAutomatonSearch(TestAutomatonBase):
"Test searching using constructed automaton (method find_all)"
def test_find_all1(self):
"no action is performed until automaton is constructed"
A = self.A
self.assertEqual(A.kind, ahocorasick.EMPTY)
self.assertEqual(A.find_all(self.string, conv("any arg")), None)
A.add_word(conv("word"), None)
self.assertEqual(A.kind, ahocorasick.TRIE)
self.assertEqual(A.find_all(self.string, conv("any arg")), None)
def test_find_all2(self):
A = self.add_words_and_make_automaton()
L = []
def callback(index, word):
L.append((index, word))
A.find_all(conv(self.string), callback)
C = self.correct_positons
self.assertEqual(L, C)
def test_find_all3(self):
A = self.add_words_and_make_automaton()
L = []
def callback(index, word):
L.append((index, word))
start = 4
end = 9
L = []
A.find_all(conv(self.string[start:end]), callback)
C = [(pos + start, word) for pos, word in L]
L = []
A.find_all(conv(self.string), callback, start, end)
self.assertEqual(L, C)
def test_find_all__not_a_callable_object(self):
A = self.add_words_and_make_automaton()
with self.assertRaisesRegex(TypeError, "The callback argument must be a callable such as a function."):
A.find_all(conv(self.string), None)
def test_find_all__wrong_range__case_1(self):
A = self.add_words_and_make_automaton()
L = []
def callback(index, word):
L.append((index, word))
with self.assertRaisesRegex(IndexError, "end index not in range 0..12"):
A.find_all(conv(self.string), callback, 0, len(self.string) + 5)
def test_find_all__wrong_range__case_2(self):
A = self.add_words_and_make_automaton()
L = []
def callback(index, word):
L.append((index, word))
with self.assertRaisesRegex(IndexError, "start index not in range 0..12"):
A.find_all(conv(self.string), callback, -len(self.string) - 1, 3)
def test_find_all__end_index_not_given(self):
A = self.add_words_and_make_automaton()
L = []
def callback(index, word):
L.append((index, word))
A.find_all(conv(self.string), callback, 0)
def test_find_all__start_is_negative(self):
A = self.add_words_and_make_automaton()
L = []
def callback(index, word):
L.append((index, word))
A.find_all(conv(self.string), callback, -3, 4)
def test_find_all__end_is_negative(self):
A = self.add_words_and_make_automaton()
L = []
def callback(index, word):
L.append((index, word))
A.find_all(conv(self.string), callback, 0, -1)
class TestAutomatonIterSearch(TestAutomatonBase):
"Test searching using constructed automaton (iterator)"
def test_iter1(self):
A = self.A
self.assertEqual(A.kind, ahocorasick.EMPTY)
with self.assertRaises(AttributeError):
A.iter(conv(self.string))
A.add_word(conv("word"), None)
self.assertEqual(A.kind, ahocorasick.TRIE)
with self.assertRaises(AttributeError):
A.iter(conv(self.string))
def test_iter2(self):
A = self.add_words_and_make_automaton()
L = []
for index, word in A.iter(conv(self.string)):
L.append((index, word))
C = self.correct_positons
self.assertEqual(L, C)
def test_iter3(self):
A = self.add_words_and_make_automaton()
start = 4
end = 9
C = []
for index, word in A.iter(conv(self.string[start:end])):
C.append((index + start, word))
L = []
for index, word in A.iter(conv(self.string), start, end):
L.append((index, word))
self.assertEqual(L, C)
def test_iter_set(self):
A = self.add_words_and_make_automaton()
parts = "_sh erhe rshe _".split()
expected = {
'_sh' : [],
'erhe' : [(3, 'she'),
(3, 'he'),
(4, 'her'),
(6, 'he')],
'rshe' : [(7, 'her'),
(8, 'hers'),
(10, 'she'),
(10, 'he')],
'_' : []
}
it = A.iter(conv(""))
result = {}
for part in parts:
it.set(conv(part))
result[part] = []
for item in it:
result[part].append(item)
self.assertEqual(expected, result)
def test_iter_set__with_reset(self):
A = self.add_words_and_make_automaton()
expected = {
'he' : [(1, 'he')],
'she' : [(2, 'she'), (2, 'he')],
}
it = A.iter(conv(""))
result = {}
for part in ["he", "she"]:
it.set(conv(part), True)
result[part] = []
for item in it:
result[part].append(item)
self.assertEqual(expected, result)
def test_iter_compare_with_find_all(self):
A = self.add_words_and_make_automaton()
# results from find_all
L = []
def callback(index, word):
L.append((index, word))
A.find_all(conv(self.string), callback)
# results from iterator
C = []
for index, word in A.iter(conv(self.string)):
C.append((index, word))
self.assertEqual(L, C)
def test_iter_wrong_argument_type(self):
A = self.add_words_and_make_automaton()
with self.assertRaisesRegex(TypeError, "string required"):
A.iter(None)
class TestAutomatonIterSearchWithIgnoreWhiteSpace(TestAutomatonBase):
"Test searching using constructed automaton (iterator)"
def setUp(self):
self.A = ahocorasick.Automaton()
self.words = "he her hers she".split()
self.string = "_sh e rher she_"
self.correct_positons = [
(4, "she"),
(4, "he"),
(6, "her"),
(8, "he"),
(9, "her"),
(11, "hers"),
(13, "she"),
(13, "he")
]
self.correct_positons_start_12 = [
(13, "he")
]
def test_iter1(self):
self.add_words_and_make_automaton()
A = self.A
self.assertEqual(A.kind, ahocorasick.AHOCORASICK)
L = []
for index, word in A.iter(conv(self.string), ignore_white_space=True):
L.append((index, word))
self.assertEqual(L, self.correct_positons)
def test_iter2(self):
self.add_words_and_make_automaton()
A = self.A
self.assertEqual(A.kind, ahocorasick.AHOCORASICK)
L = []
for index, word in A.iter(conv(self.string), ignore_white_space=True, start=12):
L.append((index, word))
self.assertEqual(L, self.correct_positons_start_12)
def test_wrong_keyword(self):
self.add_words_and_make_automaton()
A = self.A
self.assertEqual(A.kind, ahocorasick.AHOCORASICK)
with self.assertRaises(TypeError):
A.iter(conv(self.string), ignore_white_space2=True)
class TestAutomatonIterInvalidate(TestAutomatonBase):
"Test if searching iterator is invalidated when trie/automaton change"
def test_iter1(self):
A = self.add_words_and_make_automaton()
it = A.iter(conv(self.string))
w = next(it)
A.add_word(conv("should fail"), 1)
with self.assertRaises(ValueError):
w = next(it)
def test_iter2(self):
A = self.add_words_and_make_automaton()
it = A.iter(conv(self.string))
w = next(it)
A.clear()
with self.assertRaises(ValueError):
w = next(it)
print_dumps = False
class TestPickle(TestAutomatonBase):
"Test pickling/unpickling"
def test_pickle(self):
import pickle
A = self.add_words_and_make_automaton();
reduced = A.__reduce__()
self.assertEqual(len(reduced), 2)
if print_dumps:
print(pickle.dumps(A))
def test_unpickle(self):
import pickle
A = self.add_words_and_make_automaton();
dump = pickle.dumps(A)
B = pickle.loads(dump)
self.compare_automatons(A, B)
def test_unicode(self):
# sample Russian words from issue #8
import pickle
test_sentences_rus = ["!ASM Print",
"!ASM Print, tyre компания er",
"!ASM Print, рекламно-производственная компания rr",
"!Action Pact!",
"!T.O.O.H.!",
"!YES, лингвистический центр",
"!ts, магазин",
"!ФЕСТ",
'"100-th" department store',
'"1000 мелочей"',
'"1001 мелочь"',
'"19 отряд Федеральной противопожарной службы по Ленинградской области"',
'"У Друзей"',
'"ШТОРЫ и не только..."']
A = ahocorasick.Automaton()
for sentences in test_sentences_rus[-7:]:
for index, word in enumerate(sentences.split(' ')):
A.add_word(word, (index, word))
dump = pickle.dumps(A)
B = pickle.loads(dump)
self.compare_automatons(A, B)
def test_empty(self):
import pickle
A = ahocorasick.Automaton()
dump = pickle.dumps(A)
B = pickle.loads(dump)
self.compare_automatons(A, B)
def compare_automatons(self, A, B):
if print_dumps:
print([x for x in B.items()])
print([x for x in A.items()])
self.assertEqual(len(A), len(B))
for item in zip(A.items(), B.items()):
(AK, AV), (BK, BV) = item
self.assertEqual(AK, BK)
self.assertEqual(AV, BV)