msgpack-python/test/test_pack.py

87 lines
2.2 KiB
Python
Raw Normal View History

2009-06-29 09:31:43 +09:00
#!/usr/bin/env python
# coding: utf-8
from nose import main
from nose.tools import *
from nose.plugins.skip import SkipTest
2009-06-29 09:31:43 +09:00
2012-06-19 13:55:14 +09:00
from msgpack import packs, unpacks, Unpacker, Packer
2009-06-29 09:31:43 +09:00
2012-06-19 13:55:14 +09:00
from io import BytesIO
2009-06-29 09:31:43 +09:00
def check(data):
re = unpacks(packs(data))
assert_equal(re, data)
def testPack():
test_data = [
0, 1, 127, 128, 255, 256, 65535, 65536,
-1, -32, -33, -128, -129, -32768, -32769,
1.0,
2012-06-19 13:55:14 +09:00
b"", b"a", b"a"*31, b"a"*32,
2009-06-29 09:31:43 +09:00
None, True, False,
(), ((),), ((), None,),
{None: 0},
(1<<23),
2009-06-29 09:31:43 +09:00
]
for td in test_data:
check(td)
def testPackUnicode():
test_data = [
2012-06-19 13:55:14 +09:00
"", "abcd", ("defgh",), "Русский текст",
]
for td in test_data:
re = unpacks(packs(td, encoding='utf-8'), encoding='utf-8')
assert_equal(re, td)
packer = Packer(encoding='utf-8')
data = packer.pack(td)
2012-06-19 13:55:14 +09:00
re = Unpacker(BytesIO(data), encoding='utf-8').unpack()
assert_equal(re, td)
def testPackUTF32():
try:
test_data = [
2012-06-19 13:55:14 +09:00
"", "abcd", ("defgh",), "Русский текст",
]
for td in test_data:
re = unpacks(packs(td, encoding='utf-32'), encoding='utf-32')
assert_equal(re, td)
except LookupError:
raise SkipTest
def testPackBytes():
test_data = [
2012-06-19 13:55:14 +09:00
b"", b"abcd", (b"defgh",),
]
for td in test_data:
check(td)
def testIgnoreUnicodeErrors():
2012-06-19 13:55:14 +09:00
re = unpacks(packs(b'abc\xeddef'),
encoding='utf-8', unicode_errors='ignore')
assert_equal(re, "abcdef")
@raises(UnicodeDecodeError)
def testStrictUnicodeUnpack():
2012-06-19 13:55:14 +09:00
unpacks(packs(b'abc\xeddef'), encoding='utf-8')
@raises(UnicodeEncodeError)
def testStrictUnicodePack():
2012-06-19 13:55:14 +09:00
packs("abc\xeddef", encoding='ascii', unicode_errors='strict')
def testIgnoreErrorsPack():
2012-06-19 13:55:14 +09:00
re = unpacks(packs("abcФФФdef", encoding='ascii', unicode_errors='ignore'), encoding='utf-8')
assert_equal(re, "abcdef")
@raises(TypeError)
def testNoEncoding():
2012-06-19 13:55:14 +09:00
packs("abc", encoding=None)
def testDecodeBinary():
2012-06-19 13:55:14 +09:00
re = unpacks(packs("abc"), encoding=None)
assert_equal(re, b"abc")
2009-06-29 09:31:43 +09:00
if __name__ == '__main__':
main()