| 1 | |
| 2 | from rpython.rtyper.test.tool import BaseRtypingTest |
| 3 | from rpython.rtyper.lltypesystem.rbytearray import hlbytearray |
| 4 | from rpython.rtyper.annlowlevel import llstr, hlstr |
| 5 | |
| 6 | class TestByteArray(BaseRtypingTest): |
| 7 | def test_bytearray_creation(self): |
| 8 | def f(x): |
| 9 | if x: |
| 10 | b = bytearray(str(x)) |
| 11 | else: |
| 12 | b = bytearray("def") |
| 13 | return b |
| 14 | ll_res = self.interpret(f, [0]) |
| 15 | assert hlbytearray(ll_res) == "def" |
| 16 | ll_res = self.interpret(f, [1]) |
| 17 | assert hlbytearray(ll_res) == "1" |
| 18 | |
| 19 | def test_addition(self): |
| 20 | def f(x): |
| 21 | return bytearray("a") + hlstr(x) |
| 22 | |
| 23 | ll_res = self.interpret(f, [llstr("def")]) |
| 24 | assert hlbytearray(ll_res) == "adef" |
| 25 | |
| 26 | def f2(x): |
| 27 | return hlstr(x) + bytearray("a") |
| 28 | |
| 29 | ll_res = self.interpret(f2, [llstr("def")]) |
| 30 | assert hlbytearray(ll_res) == "defa" |
| 31 | |
| 32 | def f3(x): |
| 33 | return bytearray(hlstr(x)) + bytearray("a") |
| 34 | |
| 35 | ll_res = self.interpret(f3, [llstr("def")]) |
| 36 | assert hlbytearray(ll_res) == "defa" |
| 37 | |
| 38 | def test_getitem_setitem(self): |
| 39 | def f(s, i, c): |
| 40 | b = bytearray(hlstr(s)) |
| 41 | b[i] = c |
| 42 | return b[i] + b[i + 1] * 255 |
| 43 | |
| 44 | ll_res = self.interpret(f, [llstr("abc"), 1, ord('d')]) |
| 45 | assert ll_res == ord('d') + ord('c') * 255 |
| 46 | |
| 47 | def test_str_of_bytearray(self): |
| 48 | def f(x): |
| 49 | return str(bytearray(str(x))) |
| 50 | |
| 51 | ll_res = self.interpret(f, [123]) |
| 52 | assert hlstr(ll_res) == "123" |
| 53 | |
| 54 | def test_getslice(self): |
| 55 | def f(x): |
| 56 | b = bytearray(str(x)) |
| 57 | b = b[1:3] |
| 58 | b[0] += 5 |
| 59 | return str(b) |
| 60 | |
| 61 | ll_res = self.interpret(f, [12345]) |
| 62 | assert hlstr(ll_res) == f(12345) == "73" |
| 63 | |
| 64 | def test_bytearray_not_constant(self): |
| 65 | for constant in ['f', 'foo']: |
| 66 | def f(x): |
| 67 | i = 0 |
| 68 | total = 0 |
| 69 | while i < x: |
| 70 | b = bytearray(constant) |
| 71 | b[0] = b[0] + 1 |
| 72 | total += b[0] |
| 73 | i += 1 |
| 74 | return total |
| 75 | ll_res = self.interpret(f, [5]) |
| 76 | assert ll_res == f(5) |