Debian Codegraph @

rpython/rlib/test/test_rope.py

raw symbols SCIP
1 import py
2 import random, sys
3 from rpython.rlib.rope import *
4
5 def make_random_string(operations=10, slicing=True, print_seed=True,
6 unicode=False):
7 seed = random.randrange(10000)
8 if print_seed:
9 print seed
10 random.seed(seed)
11 st = "abc"
12 curr = LiteralStringNode(st)
13 if slicing:
14 choice = [0, 1, 2]
15 else:
16 choice = [0, 1]
17 for i in range(operations):
18 if not unicode:
19 a = (chr(random.randrange(ord('a'), ord('z') + 1)) *
20 random.randrange(500))
21 node = LiteralStringNode(a)
22 else:
23 a = (unichr(random.randrange(sys.maxunicode)) *
24 random.randrange(500))
25 node = LiteralUnicodeNode(a)
26 c = random.choice(choice)
27 if c == 0:
28 curr = curr + node
29 st = st + a
30 elif c == 1:
31 curr = node + curr
32 st = a + st
33 else:
34 if len(st) < 10:
35 continue
36 start = random.randrange(len(st) // 3)
37 stop = random.randrange(len(st) // 3 * 2, len(st))
38 curr = getslice_one(curr, start, stop)
39 st = st[start: stop]
40 return curr, st
41
42
43 def test_add():
44 s = (LiteralStringNode("a" * 32) + LiteralStringNode("bc" * 32) +
45 LiteralStringNode("d" * 32) + LiteralStringNode("ef" * 32) +
46 LiteralStringNode(""))
47 assert s.depth() == 3
48 assert s.flatten_string() == "".join([c * 32 for c in "a", "bc", "d", "ef"])
49 s = s.rebalance()
50 assert s.flatten_string() == "".join([c * 32 for c in "a", "bc", "d", "ef"])
51
52 def test_dont_rebalance_again():
53 s = (LiteralStringNode("a" * 32) + LiteralStringNode("b" * 32) +
54 LiteralStringNode("d" * 32) + LiteralStringNode("e" * 32) +
55 LiteralStringNode(""))
56 assert s.depth() == 3
57 assert s.flatten_string() == "".join([c * 32 for c in "abde"])
58 s = s.rebalance()
59 assert s.check_balanced()
60 assert s.balanced
61 assert s.flatten_string() == "".join([c * 32 for c in "abde"])
62
63 def test_random_addition_test():
64 seed = random.randrange(10000)
65 print seed # 4443
66 st = "abc"
67 curr = LiteralStringNode(st)
68 for i in range(1000):
69 a = (chr(random.randrange(ord('a'), ord('z') + 1)) *
70 random.randrange(100))
71 if random.choice([0, 1]):
72 curr = curr + LiteralStringNode(a)
73 st = st + a
74 else:
75 curr = LiteralStringNode(a) + curr
76 st = a + st
77 assert curr.flatten_string() == st
78 curr = curr.rebalance()
79 assert curr.flatten_string() == st
80
81 def test_getitem():
82 result = "".join([c * 32 for c in "a", "bc", "d", "ef"])
83 s1 = (LiteralStringNode("a" * 32) + LiteralStringNode("bc" * 32) +
84 LiteralStringNode("d" * 32) + LiteralStringNode("ef" * 32) +
85 LiteralStringNode(""))
86 s2 = s1.rebalance()
87 for i in range(len(result)):
88 for s in [s1, s2]:
89 assert s.getchar(i) == result[i]
90 assert s.getint(i) == ord(result[i])
91
92 def test_getitem_unicode():
93 s1, result = make_random_string(200, unicode=True)
94 s2 = s1.rebalance()
95 for i in range(len(result)):
96 for s in [s1, s2]:
97 assert s.getunichar(i) == result[i]
98 assert s.getint(i) == ord(result[i])
99
100 def test_getslice():
101 result = "".join([c * 32 for c in "a", "bc", "d", "ef"])
102 s1 = (LiteralStringNode("a" * 32) + LiteralStringNode("bc" * 32) +
103 LiteralStringNode("d" * 32) + LiteralStringNode("ef" * 32) +
104 LiteralStringNode(""))
105 s2 = s1.rebalance()
106 for s in [s1, s2]:
107 for start in range(0, len(result)):
108 for stop in range(start, len(result)):
109 assert getslice_one(s, start, stop).flatten_string() == result[start:stop]
110
111 def test_getslice_bug():
112 s1 = LiteralStringNode("/home/arigo/svn/pypy/branch/rope-branch/pypy/bin")
113 s2 = LiteralStringNode("/pypy")
114 s = s1 + s2
115 r = getslice_one(s, 1, 5)
116 assert r.flatten_string() == "home"
117
118
119 def test_getslice_step():
120 s1 = (LiteralStringNode("abcde") + LiteralStringNode("fghijklm") +
121 LiteralStringNode("nopqrstu") + LiteralStringNode("vwxyz") +
122 LiteralStringNode("zyxwvut") + LiteralStringNode("srqpomnlk"))
123 s2 = s1.rebalance()
124 result = s1.flatten_string()
125 assert s2.flatten_string() == result
126 for s in [s1, s2]:
127 for start in range(0, len(result)):
128 for stop in range(start, len(result)):
129 for step in range(1, stop - start):
130 assert getslice(s, start, stop, step).flatten_string() == result[start:stop:step]
131
132 def test_getslice_step_unicode():
133 s1 = (LiteralUnicodeNode(u"\uaaaa") +
134 LiteralUnicodeNode(u"\ubbbb" * 5) +
135 LiteralUnicodeNode(u"\uaaaa\ubbbb\u1000\u2000") +
136 LiteralUnicodeNode(u"vwxyz") +
137 LiteralUnicodeNode(u"zyxwvu\u1234" * 2) +
138 LiteralUnicodeNode(u"12355"))
139 s2 = s1.rebalance()
140 result = s1.flatten_unicode()
141 assert s2.flatten_unicode() == result
142 for s in [s1, s2]:
143 for start in range(0, len(result)):
144 for stop in range(start, len(result)):
145 for step in range(1, stop - start):
146 assert getslice(s, start, stop, step).flatten_unicode() == result[start:stop:step]
147
148 def test_random_addition_and_slicing():
149 seed = random.randrange(10000)
150 print seed
151 random.seed(seed)
152 st = "abc"
153 curr = LiteralStringNode(st)
154 last = None
155 all = []
156 for i in range(1000):
157 a = (chr(random.randrange(ord('a'), ord('z') + 1)) *
158 random.randrange(500))
159 last = curr
160 all.append(curr)
161 c = random.choice([0, 1, 2])
162 if c == 0:
163 curr = curr + LiteralStringNode(a)
164 st = st + a
165 elif c == 1:
166 curr = LiteralStringNode(a) + curr
167 st = a + st
168 else:
169 if len(st) < 10:
170 continue
171 # get a significant portion of the string
172 #import pdb; pdb.set_trace()
173 start = random.randrange(len(st) // 3)
174 stop = random.randrange(len(st) // 3 * 2, len(st))
175 curr = getslice_one(curr, start, stop)
176 st = st[start: stop]
177 assert curr.flatten_string() == st
178 curr = curr.rebalance()
179 assert curr.flatten_string() == st
180
181 def test_iteration():
182 rope, real_st = make_random_string(200)
183 iter = ItemIterator(rope)
184 for c in real_st:
185 c2 = iter.nextchar()
186 assert c2 == c
187 py.test.raises(StopIteration, iter.nextchar)
188 iter = ItemIterator(rope)
189 for c in real_st:
190 c2 = iter.nextunichar()
191 assert c2 == c
192 py.test.raises(StopIteration, iter.nextchar)
193 iter = ItemIterator(rope)
194 for c in real_st:
195 c2 = iter.nextint()
196 assert c2 == ord(c)
197 py.test.raises(StopIteration, iter.nextchar)
198
199 def test_iteration_startpos():
200 rope, real_st = make_random_string(200)
201 for i in range(0, len(real_st), len(real_st) // 20):
202 iter = ItemIterator(rope, i)
203 x = i
204 for c in real_st[i:]:
205 x += 1
206 c2 = iter.nextchar()
207 assert c2 == c
208 py.test.raises(StopIteration, iter.nextchar)
209
210 def test_iteration_unicode():
211 rope, real_st = make_random_string(200, unicode=True)
212 iter = ItemIterator(rope)
213 for c in real_st:
214 c2 = iter.nextunichar()
215 assert c2 == c
216 py.test.raises(StopIteration, iter.nextchar)
217 iter = ItemIterator(rope)
218 for c in real_st:
219 c2 = iter.nextint()
220 assert c2 == ord(c)
221 py.test.raises(StopIteration, iter.nextchar)
222
223 def test_reverse_iteration():
224 rope, real_st = make_random_string(200)
225 iter = ReverseItemIterator(rope)
226 for c in reversed(real_st):
227 c2 = iter.nextchar()
228 assert c2 == c
229 py.test.raises(StopIteration, iter.nextchar)
230 iter = ReverseItemIterator(rope)
231 for c in py.builtin.reversed(real_st):
232 c2 = iter.nextint()
233 assert c2 == ord(c)
234 py.test.raises(StopIteration, iter.nextchar)
235
236 def test_reverse_iteration_unicode():
237 rope, real_st = make_random_string(200, unicode=True)
238 iter = ReverseItemIterator(rope)
239 for c in reversed(real_st):
240 c2 = iter.nextunichar()
241 assert c2 == c
242 py.test.raises(StopIteration, iter.nextchar)
243 iter = ReverseItemIterator(rope)
244 for c in reversed(real_st):
245 c2 = iter.nextint()
246 assert c2 == ord(c)
247 py.test.raises(StopIteration, iter.nextchar)
248
249 def test_multiply():
250 strs = [(LiteralStringNode("a"), "a"), (LiteralStringNode("abc"), "abc"),
251 make_random_string(500)]
252 times = range(100)
253 for i in range(9, 30):
254 times.append(i ** 2 - 1)
255 times.append(i ** 2)
256 times.append(i ** 2 + 1)
257 times.append(i ** 2 + 2)
258 for r, st in strs:
259 for i in times:
260 r2 = multiply(r, i)
261 assert r2.flatten_string() == st * i
262
263 def test_multiply_unicode():
264 strs = [(LiteralUnicodeNode(u"\uaaaa"), u"\uaaaa"),
265 (LiteralUnicodeNode(u"\uaaaa\ubbbb\ucccc"), u"\uaaaa\ubbbb\ucccc"),
266 make_random_string(500)]
267 times = range(100)
268 for i in range(9, 30):
269 times.append(i ** 2 - 1)
270 times.append(i ** 2)
271 times.append(i ** 2 + 1)
272 times.append(i ** 2 + 2)
273 for r, st in strs:
274 for i in times:
275 r2 = multiply(r, i)
276 assert r2.flatten_unicode() == st * i
277
278 def test_join():
279 seps = [(LiteralStringNode("a"), "a"), (LiteralStringNode("abc"), "abc"),
280 (LiteralStringNode("d"), "d"), (LiteralStringNode(""), "")]
281 l, strs = zip(*[(LiteralStringNode("x"), "x"),
282 (LiteralStringNode("xyz"), "xyz"),
283 (LiteralStringNode("w"), "w")])
284 l = list(l)
285 for s, st in seps:
286 node = join(s, l)
287 result1 = node.flatten_string()
288 result2 = st.join(strs)
289 for i in range(node.length()):
290 assert result1[i] == result2[i]
291
292 strings = ['', '<',
293 '/home/arigo/svn/pypy/branch/rope-branch/py/code/source.py',
294 ':', '213', '>']
295 l = [LiteralStringNode(s) for s in strings]
296 node = join(LiteralStringNode(""), l)
297 assert node.flatten_string() == ''.join(strings)
298
299 def test_join_random():
300 l, strs = zip(*[make_random_string(10 * i) for i in range(1, 5)])
301 l = list(l)
302 seps = [(LiteralStringNode("a"), "a"), (LiteralStringNode("abc"), "abc"),
303 make_random_string(500)]
304 for s, st in seps:
305 node = join(s, l)
306 result1 = node.flatten_string()
307 result2 = st.join(strs)
308 for i in range(node.length()):
309 assert result1[i] == result2[i]
310
311 def test_join_random_unicode():
312 l, strs = zip(*[make_random_string(10 * i, unicode=True) for i in range(1, 5)])
313 l = list(l)
314 seps = [(LiteralStringNode("a"), "a"), (LiteralStringNode("abc"), "abc"),
315 make_random_string(500)]
316 for s, st in seps:
317 node = join(s, l)
318 result1 = node.flatten_unicode()
319 result2 = st.join(strs)
320 for i in range(node.length()):
321 assert result1[i] == result2[i]
322
323 def test_seekbackward():
324 rope = BinaryConcatNode(BinaryConcatNode(LiteralStringNode("abc"),
325 LiteralStringNode("def")),
326 LiteralStringNode("ghi"))
327 iter = SeekableItemIterator(rope)
328 for c in "abcdefgh":
329 c2 = iter.nextchar()
330 assert c2 == c
331 for i in range(7):
332 iter.seekback(i)
333 for c in "abcdefghi"[-1-i:-1]:
334 c2 = iter.nextchar()
335 assert c2 == c
336 c2 = iter.nextchar()
337 assert c2 == "i"
338 py.test.raises(StopIteration, iter.nextchar)
339
340 def test_fringe_iterator():
341 ABC = LiteralStringNode("abc")
342 DEF = LiteralStringNode("def")
343 GHI = LiteralStringNode("ghi")
344 rope = BinaryConcatNode(BinaryConcatNode(ABC, DEF), GHI)
345 iter = FringeIterator(rope)
346 n = iter.next()
347 assert n is ABC
348 n = iter.next()
349 assert n is DEF
350 n = iter.next()
351 assert n is GHI
352 py.test.raises(StopIteration, iter.next)
353 iter = FringeIterator(rope)
354
355 def test_fringe_iterator_seekforward():
356 ABC = LiteralStringNode("abc")
357 DEF = LiteralStringNode("def")
358 GHI = LiteralStringNode("ghi")
359 rope = BinaryConcatNode(BinaryConcatNode(ABC, DEF), GHI)
360 iter = FringeIterator(rope)
361 n = iter.next()
362 assert n is ABC
363 i = iter._seekforward(5)
364 assert i == 2
365 n = iter.next()
366 assert n is GHI
367 py.test.raises(StopIteration, iter.next)
368 iter = FringeIterator(rope)
369 i = iter._seekforward(7)
370 assert i == 1
371 n = iter.next()
372 assert n is GHI
373
374
375 def test_seekforward():
376 rope = BinaryConcatNode(BinaryConcatNode(LiteralStringNode("abc"),
377 LiteralStringNode("def")),
378 LiteralStringNode("ghi"))
379 rope = rope + rope
380 result = rope.flatten_string()
381 for j in range(len(result) - 1):
382 for i in range(len(result) - 1 - j):
383 iter = SeekableItemIterator(rope)
384 for c in result[:j]:
385 c2 = iter.nextchar()
386 assert c2 == c
387 iter.seekforward(i)
388 for c in result[i + j:]:
389 c2 = iter.nextchar()
390 assert c2 == c
391 py.test.raises(StopIteration, iter.nextchar)
392
393 def test_iterbackward():
394 rope = BinaryConcatNode(BinaryConcatNode(LiteralStringNode("abc"),
395 LiteralStringNode("def")),
396 LiteralStringNode("ghi"))
397 iter = SeekableItemIterator(rope)
398 iter.seekforward(8)
399 for c in "abcdefghi"[::-1]:
400 c2 = iter.lastchar()
401 assert c2 == c
402 py.test.raises(StopIteration, iter.lastchar)
403
404 def test_find_int():
405 rope, st = make_random_string()
406 rope = getslice_one(rope, 10, 100)
407 st = st[10:100]
408 for i in range(len(st)):
409 for j in range(i + 1, len(st)):
410 c = st[i:j][(j - i) // 2]
411 pos = find_int(rope, ord(c), i, j)
412 assert pos == st.find(c, i, j)
413
414 def test_find_int_bugs():
415 r = find_int(LiteralStringNode("ascii"), ord(" "), 0, 5)
416 assert r == -1
417 r = find_int(LiteralStringNode("a"), ord("a"))
418 assert r == 0
419
420
421 def test_restart_positions():
422 restart = construct_restart_positions_node(
423 BinaryConcatNode(LiteralStringNode("aba"), LiteralStringNode("bcabab")))
424 assert restart == [0, 0, 1, 2, 0, 1, 2, 3, 4]
425 restart = construct_restart_positions_node(
426 BinaryConcatNode(LiteralStringNode("aba"), LiteralStringNode("bcababb")))
427 assert restart == [0, 0, 1, 2, 0, 1, 2, 3, 4, 0]
428 restart = construct_restart_positions_node(LiteralStringNode("ababb"))
429 assert restart == [0, 0, 1, 2, 0]
430
431
432 def test_find():
433 node = BinaryConcatNode(LiteralStringNode("aba"),
434 LiteralStringNode("bcabab"))
435 pos = find(node, LiteralStringNode("abc"), 0, node.length())
436 assert pos == 2
437 node = BinaryConcatNode(LiteralStringNode("btffp"),
438 LiteralStringNode("bacbb"))
439 pos = find(node, LiteralStringNode("a"), 0, node.length())
440 assert pos == 6
441 pos = find(node, LiteralStringNode("aaa"), 0, 2)
442 assert pos == -1
443 pos = find(node, LiteralStringNode("btf"), 0, 3)
444 assert pos == 0
445
446 def test_find_random():
447 py.test.skip("fix me!")
448 rope, st = make_random_string(unicode=True)
449 rope = getslice_one(rope, 10, 10000)
450 st = st[10:10000]
451 for i in range(1000):
452 searchlength = random.randrange(2, min(len(st) - 1, 1001))
453 start = random.randrange(len(st) - searchlength)
454 searchstart = random.randrange(len(st))
455 searchstop = random.randrange(searchstart, len(st))
456 p = st[start:start+searchlength]
457 rp = getslice_one(rope, start, start + searchlength)
458 pos = find(rope, rp, searchstart, searchstop)
459 assert pos == st.find(p, searchstart, searchstop)
460
461 def test_find_unicode():
462 node = BinaryConcatNode(LiteralUnicodeNode(u"\uaaaa\ubbbb\uaaaa"),
463 LiteralUnicodeNode(u"\ubbbb\ucccc\uaaaa\ubbbb\uaaaa\ubbbb"))
464 pos = find(node, LiteralUnicodeNode(u"\uaaaa\ubbbb\ucccc"), 0, node.length())
465 assert pos == 2
466 node = BinaryConcatNode(LiteralUnicodeNode(u"btffp"),
467 LiteralUnicodeNode(u"b\uaaaacbb"))
468 pos = find(node, LiteralUnicodeNode(u"\uaaaa"), 0, node.length())
469 assert pos == 6
470
471 def test_fromcharlist():
472 for i in range(0, 100, 10):
473 chars = ["a"] * 50 + ["b"] * i
474 node = rope_from_charlist(chars)
475 assert node.flatten_string() == "a" * 50 + "b" * i
476 assert rope_from_charlist([]).flatten_string() == ""
477
478 def test_find_iterator():
479 for searchstring in ["abc", "a", "", "x", "xyz", "abababcabcabb"]:
480 node = join(LiteralStringNode(searchstring),
481 [LiteralStringNode("cde" * i) for i in range(1, 10)])
482 #node.view()
483 iter = FindIterator(node, LiteralStringNode(searchstring))
484 s = node.flatten_string()
485 assert s == searchstring.join(["cde" * i for i in range(1, 10)])
486 start = 0
487 while 1:
488 r2 = s.find(searchstring, start)
489 try:
490 r1 = iter.next()
491 except StopIteration:
492 assert r2 == -1
493 break
494 assert r1 == r2
495 start = r2 + max(len(searchstring), 1)
496
497
498 def test_find_iterator_unicode():
499 if sys.version_info < (2, 5):
500 py.test.skip("bug in unicode.find that was fixed in 2.5")
501 for searchstring in [
502 u"\uAAAA\uBBBB\uCCCC", u"\uAAAA", u"", u"\u6666",
503 u"\u6666\u7777\u8888",
504 u"\uAAAA\uBBBB\uAAAA\uBBBB\uAAAA\uBBBB\uCCCC\uAAAA\uBBBB\uCCCC\uAAAA\uBBBB\uBBBB"]:
505 node = join(LiteralUnicodeNode(searchstring),
506 [LiteralUnicodeNode(u"\ucccc\udddd" * i)
507 for i in range(1, 10)])
508 iter = FindIterator(node, LiteralUnicodeNode(searchstring))
509 s = node.flatten_unicode()
510 assert s == searchstring.join([u"\ucccc\udddd" * i for i in range(1, 10)])
511 start = 0
512 while 1:
513 r2 = s.find(searchstring, start)
514 try:
515 r1 = iter.next()
516 except StopIteration:
517 assert r2 == -1
518 break
519 assert r1 == r2
520 start = r2 + max(len(searchstring), 1)
521
522 def test_hash():
523 from rpython.rlib.rarithmetic import intmask
524 for i in range(10):
525 rope, _ = make_random_string()
526 if rope.length() == 0:
527 assert hash_rope(rope) == -1
528 continue
529 h = hash_rope(rope)
530 x = LiteralStringNode(rope.flatten_string()).hash_part()
531 assert x == rope.hash_part()
532 x <<= 1
533 x ^= rope.getint(0)
534 x ^= rope.length()
535 assert intmask(x) == h
536 # hash again to check for cache effects
537 h1 = hash_rope(rope)
538 assert h1 == h
539
540 def test_hash_collisions_identifiers():
541 hashes1 = {}
542 hashes2 = {}
543 cs = [""] + [chr(i) for i in range(256)]
544 cs = "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
545 for i in range(50000):
546 s = "".join([random.choice(cs)
547 for i in range(random.randrange(1, 15))])
548 rope = LiteralStringNode(s)
549 h1 = hash_rope(rope)
550 hashes1[h1] = hashes1.get(h1, -1) + 1
551 h2 = hash(s)
552 hashes2[h2] = hashes2.get(h2, -1) + 1
553 # hope that there are only ten percent more collisions
554 # than with CPython's hash:
555 assert sum(hashes1.values()) < sum(hashes2.values()) * 1.10
556
557 def test_hash_distribution_tiny_strings():
558 hashes = [0 for i in range(256)]
559 cs = [""] + [chr(i) for i in range(256)]
560 for c1 in cs:
561 for c2 in cs:
562 rope = LiteralStringNode(c1 + c2)
563 h = hash_rope(rope)
564 hashes[h & 0xff] += 1
565 hashes[(h & 0xff00) >> 8] += 1
566 hashes[(h & 0xff0000) >> 16] += 1
567 for h in hashes:
568 assert h > 300
569
570 def test_hash_distribution_small_strings():
571 random.seed(42) # prevent randomly failing test
572 hashes = [0 for i in range(256)]
573 for i in range(20000):
574 s = "".join([chr(random.randrange(256))
575 for i in range(random.randrange(1, 15))])
576 rope = LiteralStringNode(s)
577 h = hash_rope(rope)
578 hashes[h & 0xff] += 1
579 hashes[(h & 0xff00) >> 8] += 1
580 hashes[(h & 0xff0000) >> 16] += 1
581 for h in hashes:
582 assert h > 180
583 print hashes
584
585 def test_hash_distribution_big_strings():
586 random.seed(42) # prevent randomly failing test
587 hashes = [0 for i in range(256)]
588 for i in range(4000):
589 s = "".join([chr(random.randrange(256))
590 for i in range(random.randrange(20, 500))])
591 rope = LiteralStringNode(s)
592 h = hash_rope(rope)
593 hashes[h & 0xff] += 1
594 hashes[(h & 0xff00) >> 8] += 1
595 hashes[(h & 0xff0000) >> 16] += 1
596 for h in hashes:
597 assert h > 29
598
599 def test_hash_distribution_identifiers():
600 random.seed(42) # prevent randomly failing test
601 hashes = [0 for i in range(256)]
602 cs = "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
603 for i in range(50000):
604 s = "".join([random.choice(cs)
605 for i in range(random.randrange(1, 15))])
606 rope = LiteralStringNode(s)
607 h = hash_rope(rope)
608 hashes[h & 0xff] += 1
609 hashes[(h & 0xff00) >> 8] += 1
610 hashes[(h & 0xff0000) >> 16] += 1
611 for h in hashes:
612 assert h > 450
613 print hashes
614
615
616 def test_hash_part():
617 a = "".join([chr(random.randrange(256)) * random.randrange(500)])
618 h = None
619 for split in range(1, len(a) - 1):
620 s1 = LiteralStringNode(a[:split])
621 s2 = LiteralStringNode(a[split:])
622 s = BinaryConcatNode(s1, s2)
623 if h is None:
624 h = s.hash_part()
625 else:
626 # try twice due to caching reasons
627 assert s.hash_part() == h
628 assert s.hash_part() == h
629
630 def test_hash_part_unicode():
631 a, st = make_random_string(5, unicode=True)
632 h = a.hash_part()
633 for split in range(1, len(st) - 1):
634 s1 = LiteralUnicodeNode(st[:split])
635 s2 = LiteralUnicodeNode(st[split:])
636 s = BinaryConcatNode(s1, s2)
637 if h is None:
638 h = s.hash_part()
639 else:
640 # try twice due to caching reasons
641 assert s.hash_part() == h
642 assert s.hash_part() == h
643
644 def test_hash_part_more():
645 for i in range(100):
646 rope, st = make_random_string()
647 h = rope.hash_part()
648 assert LiteralStringNode(st).hash_part() == h
649
650 def test_equality():
651 l = [make_random_string() for i in range(3)]
652 l.append((LiteralStringNode(""), ""))
653 for rope1, st1 in l:
654 for rope2, st2 in l:
655 assert eq(rope1, rope2) == (st1 == st2)
656
657 def test_equality_unicode():
658 l = [make_random_string() for i in range(3)]
659 l.append((LiteralStringNode(""), ""))
660 for rope1, st1 in l:
661 for rope2, st2 in l:
662 assert eq(rope1, rope2) == (st1 == st2)
663
664 def test_compare_random():
665 l = [make_random_string() for i in range(3)]
666 l.append((LiteralStringNode(""), ""))
667 for rope1, st1 in l:
668 for rope2, st2 in l:
669 c = compare(rope1, rope2)
670 if c:
671 c = c // abs(c)
672 assert c == cmp(st1, st2)
673
674 def test_compare_random_unicode():
675 l = [make_random_string() for i in range(3)]
676 l.append((LiteralStringNode(""), ""))
677 for rope1, st1 in l:
678 for rope2, st2 in l:
679 c = compare(rope1, rope2)
680 if c:
681 c = c // abs(c)
682 assert c == cmp(st1, st2)
683
684
685 def test_power():
686 for i in range(0, 60, 13):
687 print i
688 for j in range(1, 10000, 7):
689 assert intmask(i * (1000003**j)) == masked_mul_by_1000003_pow(i, j)
690
691
692 def test_seekable_bug():
693 node = BinaryConcatNode(LiteralStringNode("abc"), LiteralStringNode("def"))
694 iter = SeekableItemIterator(node)
695 c = iter.nextchar(); assert c == "a"
696 c = iter.nextchar(); assert c == "b"
697 c = iter.nextchar(); assert c == "c"
698 iter.seekback(1)
699 c = iter.nextchar(); assert c == "c"
700 c = iter.nextchar(); assert c == "d"
701 c = iter.nextchar(); assert c == "e"
702 c = iter.nextchar(); assert c == "f"
703 py.test.raises(StopIteration, iter.nextchar)
704 node = LiteralStringNode("abcdef")
705 iter = SeekableItemIterator(node)
706 c = iter.nextchar(); assert c == "a"
707 c = iter.nextchar(); assert c == "b"
708 c = iter.nextchar(); assert c == "c"
709 iter.seekback(3)
710 c = iter.nextchar(); assert c == "a"
711 c = iter.nextchar(); assert c == "b"
712 c = iter.nextchar(); assert c == "c"
713
714 def test_strip():
715 node = BinaryConcatNode(LiteralStringNode(" \t\n abc "),
716 LiteralStringNode("def "))
717 r = strip(node)
718 assert r.flatten_string() == "abc def"
719 r = strip(node, left=False)
720 assert r.flatten_string() == " \t\n abc def"
721 r = strip(node, right=False)
722 assert r.flatten_string() == "abc def "
723
724 node = BinaryConcatNode(LiteralStringNode("aaaYYYYa"),
725 LiteralStringNode("abab"))
726 predicate = lambda i: chr(i) in "ab"
727 r = strip(node, predicate=predicate)
728 assert r.flatten_string() == "YYYY"
729 r = strip(node, left=False, predicate=predicate)
730 assert r.flatten_string() == "aaaYYYY"
731 r = strip(node, right=False, predicate=predicate)
732 assert r.flatten_string() == "YYYYaabab"
733
734 def test_getrope():
735 s1, result = make_random_string(200, unicode=True)
736 s2 = s1.rebalance()
737 for i in range(len(result)):
738 for s in [s1, s2]:
739 r = s.getrope(i)
740 assert r.length() == 1
741 assert r.getint(0) == s.getint(i)
742 assert isinstance(r, LiteralNode)
743 assert r.getint(0) >= 128 or isinstance(r, LiteralStringNode)
744 assert r.getrope(0) is r
745
746 def test_split():
747 seps = [(LiteralStringNode("a"), "a"), (LiteralStringNode("abc"), "abc"),
748 (LiteralStringNode("d"), "d"), (LiteralStringNode(""), "")]
749 l, strs = zip(*[(LiteralStringNode("x"), "x"),
750 (LiteralStringNode("xyz"), "xyz"),
751 (LiteralStringNode("w"), "w")])
752 l = list(l)
753 for s, st in seps:
754 node = join(s, l)
755 l2 = split(node, s)
756 for n1, n2 in zip(l, l2):
757 assert n1.flatten_string() == n2.flatten_string()
758 for i in range(4):
759 l1 = split(LiteralStringNode("ababababa"), LiteralStringNode("b"), i)
760 l2 = "ababababa".split("b", i)
761 assert len(l1) == len(l2)
762 for n, s in zip(l1, l2):
763 assert n.flatten_string() == s
764
765 def test_splitlines():
766 seps = [(LiteralStringNode("\n"), "\n"), (LiteralStringNode("\r"), "\r"),
767 (LiteralStringNode("\r\n"), "\r\n")]
768 l, strs = zip(*[(LiteralStringNode("xafnarsp"), "xafnarsp"),
769 (LiteralStringNode("xyzaaaa"), "xyzaaaa"),
770 (LiteralStringNode("wxxxx"), "wxxxx")])
771 l = list(l)
772 for s, st in seps:
773 node = join(s, l)
774 l2 = splitlines(node)
775 for n1, n2 in zip(l, l2):
776 assert n1.flatten_string() == n2.flatten_string()
777 for keepends in [True, False]:
778 l1 = splitlines(LiteralStringNode("ab\nab\n\raba\rba"), keepends)
779 l2 = "ab\nab\n\raba\rba".splitlines(keepends)
780 assert len(l1) == len(l2)
781 for n, s in zip(l1, l2):
782 assert n.flatten_string() == s
783
784 def test_rope_from_unicode():
785 node = rope_from_unicode(u"aaabbbbbcccdddeeefffggggnnn")
786 assert node.is_bytestring()
787 assert node.is_ascii()
788 node = rope_from_unicode(u"a" * 30 + u"\ufffd" * 30 + "x" * 30)
789 assert node.length() == 90
790 assert not node.is_ascii()
791 assert not node.is_bytestring()
792
793 def test_encode():
794 node = LiteralStringNode("abc")
795 assert unicode_encode_ascii(node) is node
796 assert unicode_encode_latin1(node) is node
797 assert unicode_encode_utf8(node) is node
798 node = LiteralStringNode("abc\xff")
799 assert unicode_encode_ascii(node) is None
800 assert unicode_encode_latin1(node) is node
801 assert unicode_encode_utf8(node).s == 'abc\xc3\xbf'
802 node = LiteralUnicodeNode(u"\uffffab")
803 assert unicode_encode_ascii(node) is None
804 assert unicode_encode_latin1(node) is None
805 assert unicode_encode_utf8(node).s == '\xef\xbf\xbfab'
806 node = BinaryConcatNode(LiteralStringNode("abc"),
807 LiteralUnicodeNode(u"\uffffab"))
808 assert unicode_encode_ascii(node) is None
809 assert unicode_encode_latin1(node) is None
810 res = unicode_encode_utf8(node)
811 assert res.left is node.left
812 assert res.right.s == '\xef\xbf\xbfab'
813
814 def test_decode():
815 node = LiteralStringNode("abc")
816 assert str_decode_ascii(node) is node
817 assert str_decode_latin1(node) is node
818 assert str_decode_utf8(node) is node
819 node = LiteralStringNode("abc\xff")
820 assert str_decode_ascii(node) is None
821 assert str_decode_latin1(node) is node
822
823 def test_decode_utf8():
824 # bad data
825 node = LiteralStringNode("\xd7\x50")
826 assert str_decode_utf8(node) is None
827 node = LiteralStringNode("\xf0\x90\x91")
828 assert str_decode_utf8(node) is None
829
830 # correct data in one node
831 node = LiteralStringNode('\xef\xbf\xbfab')
832 assert str_decode_utf8(node).u == u"\uffffab"
833
834 # binary node, left node can be decoded
835 node = BinaryConcatNode(LiteralStringNode('\xef\xbf\xbfab'),
836 LiteralStringNode('\xef\xbf\xbfab'))
837 res = str_decode_utf8(node)
838 assert res.left.u == u"\uffffab"
839 assert res.right.u == u"\uffffab"
840
841 # binary node, left node alone cannot be decoded
842 node = BinaryConcatNode(LiteralStringNode('\xef'),
843 LiteralStringNode('\xbf\xbfab'))
844 res = str_decode_utf8(node)
845 assert res.u == u"\uffffab"
846
847 # binary node, left node cannot be decoded, bad data
848 node = BinaryConcatNode(LiteralStringNode("\xf0\x90"),
849 LiteralStringNode("\x91"))
850 assert str_decode_utf8(node) is None
851
852 # binary node, incomplete data
853 node = BinaryConcatNode(LiteralStringNode('ab\xef'),
854 LiteralStringNode('\xbf'))
855
856 res = str_decode_utf8(node)
857 assert res is None
858
859 def test_multiply_result_needs_no_rebalancing():
860 r1 = multiply(LiteralStringNode("s"), 2**31 - 2)
861 assert r1.rebalance() is r1