| 1 |
""" |
| 2 |
Tests for the struct module implemented at interp-level in pypy/module/struct. |
| 3 |
""" |
| 4 |
|
| 5 |
class AppTestFastPath(object): |
| 6 |
spaceconfig = dict(usemodules=['array', 'struct', '__pypy__']) |
| 7 |
|
| 8 |
def setup_class(cls): |
| 9 |
from rpython.rlib.rstruct import standardfmttable |
| 10 |
standardfmttable.ALLOW_SLOWPATH = False |
| 11 |
|
| 12 |
cls.w_struct = cls.space.appexec([], """(): |
| 13 |
import struct |
| 14 |
return struct |
| 15 |
""") |
| 16 |
cls.w_bytebuffer = cls.space.appexec([], """(): |
| 17 |
import __pypy__ |
| 18 |
return __pypy__.bytebuffer |
| 19 |
""") |
| 20 |
|
| 21 |
def teardown_class(cls): |
| 22 |
from rpython.rlib.rstruct import standardfmttable |
| 23 |
standardfmttable.ALLOW_SLOWPATH = True |
| 24 |
|
| 25 |
def test_unpack_simple(self): |
| 26 |
buf = self.struct.pack("iii", 0, 42, 43) |
| 27 |
assert self.struct.unpack("iii", buf) == (0, 42, 43) |
| 28 |
|
| 29 |
def test_unpack_from(self): |
| 30 |
buf = self.struct.pack("iii", 0, 42, 43) |
| 31 |
offset = self.struct.calcsize("i") |
| 32 |
assert self.struct.unpack_from("ii", buf, offset) == (42, 43) |
| 33 |
|
| 34 |
def test_unpack_bytearray(self): |
| 35 |
data = self.struct.pack("iii", 0, 42, 43) |
| 36 |
buf = bytearray(data) |
| 37 |
assert self.struct.unpack("iii", buf) == (0, 42, 43) |
| 38 |
|
| 39 |
def test_unpack_array(self): |
| 40 |
import array |
| 41 |
data = self.struct.pack("iii", 0, 42, 43) |
| 42 |
buf = array.array('B', data) |
| 43 |
assert self.struct.unpack("iii", buf) == (0, 42, 43) |
| 44 |
|
| 45 |
def test_pack_into_bytearray(self): |
| 46 |
expected = self.struct.pack("ii", 42, 43) |
| 47 |
buf = bytearray(len(expected)) |
| 48 |
self.struct.pack_into("ii", buf, 0, 42, 43) |
| 49 |
assert buf == expected |
| 50 |
|
| 51 |
def test_pack_into_bytearray_padding(self): |
| 52 |
expected = self.struct.pack("xxi", 42) |
| 53 |
buf = bytearray(len(expected)) |
| 54 |
self.struct.pack_into("xxi", buf, 0, 42) |
| 55 |
assert buf == expected |
| 56 |
|
| 57 |
def test_pack_into_bytearray_delete(self): |
| 58 |
expected = self.struct.pack("i", 42) |
| 59 |
|
| 60 |
buf = bytearray(64) |
| 61 |
del buf[:8] |
| 62 |
self.struct.pack_into("i", buf, 0, 42) |
| 63 |
buf = buf[:len(expected)] |
| 64 |
assert buf == expected |