Fix ctypes tests to avoid implicit bytes-unicode conversion

This commit is contained in:
Victor Stinner 2010-07-27 23:36:41 +00:00
parent 455f7bdc05
commit 42746df17b
20 changed files with 57 additions and 61 deletions

View file

@ -42,7 +42,7 @@ class ArrayTestCase(unittest.TestCase):
CharArray = ARRAY(c_char, 3) CharArray = ARRAY(c_char, 3)
ca = CharArray("a", "b", "c") ca = CharArray(b"a", b"b", b"c")
# Should this work? It doesn't: # Should this work? It doesn't:
# CharArray("abc") # CharArray("abc")
@ -89,7 +89,7 @@ class ArrayTestCase(unittest.TestCase):
def test_from_address(self): def test_from_address(self):
# Failed with 0.9.8, reported by JUrner # Failed with 0.9.8, reported by JUrner
p = create_string_buffer("foo") p = create_string_buffer(b"foo")
sz = (c_char * 3).from_address(addressof(p)) sz = (c_char * 3).from_address(addressof(p))
self.assertEqual(sz[:], b"foo") self.assertEqual(sz[:], b"foo")
self.assertEqual(sz[::], b"foo") self.assertEqual(sz[::], b"foo")

View file

@ -37,14 +37,14 @@ class C_Test(unittest.TestCase):
for name in "ABCDEFGHI": for name in "ABCDEFGHI":
b = BITS() b = BITS()
setattr(b, name, i) setattr(b, name, i)
self.assertEqual((name, i, getattr(b, name)), (name, i, func(byref(b), name))) self.assertEqual(getattr(b, name), func(byref(b), name.encode('ascii')))
def test_shorts(self): def test_shorts(self):
for i in range(256): for i in range(256):
for name in "MNOPQRS": for name in "MNOPQRS":
b = BITS() b = BITS()
setattr(b, name, i) setattr(b, name, i)
self.assertEqual((name, i, getattr(b, name)), (name, i, func(byref(b), name))) self.assertEqual(getattr(b, name), func(byref(b), name.encode('ascii')))
signed_int_types = (c_byte, c_short, c_int, c_long, c_longlong) signed_int_types = (c_byte, c_short, c_int, c_long, c_longlong)
unsigned_int_types = (c_ubyte, c_ushort, c_uint, c_ulong, c_ulonglong) unsigned_int_types = (c_ubyte, c_ushort, c_uint, c_ulong, c_ulonglong)

View file

@ -9,7 +9,7 @@ class StringBufferTestCase(unittest.TestCase):
self.assertEqual(sizeof(b), 32 * sizeof(c_char)) self.assertEqual(sizeof(b), 32 * sizeof(c_char))
self.assertTrue(type(b[0]) is bytes) self.assertTrue(type(b[0]) is bytes)
b = create_string_buffer("abc") b = create_string_buffer(b"abc")
self.assertEqual(len(b), 4) # trailing nul char self.assertEqual(len(b), 4) # trailing nul char
self.assertEqual(sizeof(b), 4 * sizeof(c_char)) self.assertEqual(sizeof(b), 4 * sizeof(c_char))
self.assertTrue(type(b[0]) is bytes) self.assertTrue(type(b[0]) is bytes)

View file

@ -11,10 +11,10 @@ class BytesTest(unittest.TestCase):
(c_char * 3)(b"a", b"b", b"c") (c_char * 3)(b"a", b"b", b"c")
def test_c_wchar(self): def test_c_wchar(self):
x = c_wchar(b"x") x = c_wchar("x")
x.value = b"y" x.value = "y"
c_wchar.from_param(b"x") c_wchar.from_param("x")
(c_wchar * 3)(b"a", b"b", b"c") (c_wchar * 3)("a", "b", "c")
def test_c_char_p(self): def test_c_char_p(self):
c_char_p("foo bar") c_char_p("foo bar")
@ -37,8 +37,8 @@ class BytesTest(unittest.TestCase):
class X(Structure): class X(Structure):
_fields_ = [("a", c_wchar * 3)] _fields_ = [("a", c_wchar * 3)]
X("abc") X(b"abc")
x = X(b"abc") x = X("abc")
self.assertEqual(x.a, "abc") self.assertEqual(x.a, "abc")
self.assertEqual(type(x.a), str) self.assertEqual(type(x.a), str)

View file

@ -33,17 +33,17 @@ class Test(unittest.TestCase):
def test_p2a_objects(self): def test_p2a_objects(self):
array = (c_char_p * 5)() array = (c_char_p * 5)()
self.assertEqual(array._objects, None) self.assertEqual(array._objects, None)
array[0] = "foo bar" array[0] = b"foo bar"
self.assertEqual(array._objects, {'0': b"foo bar"}) self.assertEqual(array._objects, {'0': b"foo bar"})
p = cast(array, POINTER(c_char_p)) p = cast(array, POINTER(c_char_p))
# array and p share a common _objects attribute # array and p share a common _objects attribute
self.assertTrue(p._objects is array._objects) self.assertTrue(p._objects is array._objects)
self.assertEqual(array._objects, {'0': b"foo bar", id(array): array}) self.assertEqual(array._objects, {'0': b"foo bar", id(array): array})
p[0] = "spam spam" p[0] = b"spam spam"
self.assertEqual(p._objects, {'0': b"spam spam", id(array): array}) self.assertEqual(p._objects, {'0': b"spam spam", id(array): array})
self.assertTrue(array._objects is p._objects) self.assertTrue(array._objects is p._objects)
p[1] = "foo bar" p[1] = b"foo bar"
self.assertEqual(p._objects, {'1': b'foo bar', '0': b"spam spam", id(array): array}) self.assertEqual(p._objects, {'1': b'foo bar', '0': b"spam spam", id(array): array})
self.assertTrue(array._objects is p._objects) self.assertTrue(array._objects is p._objects)
@ -71,7 +71,7 @@ class Test(unittest.TestCase):
def test_char_p(self): def test_char_p(self):
# This didn't work: bad argument to internal function # This didn't work: bad argument to internal function
s = c_char_p("hiho") s = c_char_p(b"hiho")
self.assertEqual(cast(cast(s, c_void_p), c_char_p).value, self.assertEqual(cast(cast(s, c_void_p), c_char_p).value,
b"hiho") b"hiho")

View file

@ -107,7 +107,7 @@ class CFunctions(unittest.TestCase):
def test_ulong_plus(self): def test_ulong_plus(self):
self._dll.tf_bL.restype = c_ulong self._dll.tf_bL.restype = c_ulong
self._dll.tf_bL.argtypes = (c_char, c_ulong) self._dll.tf_bL.argtypes = (c_char, c_ulong)
self.assertEqual(self._dll.tf_bL(' ', 4294967295), 1431655765) self.assertEqual(self._dll.tf_bL(b' ', 4294967295), 1431655765)
self.assertEqual(self.U(), 4294967295) self.assertEqual(self.U(), 4294967295)
def test_longlong(self): def test_longlong(self):

View file

@ -19,7 +19,7 @@ class Test(unittest.TestCase):
libc_open.argtypes = c_char_p, c_int libc_open.argtypes = c_char_p, c_int
self.assertEqual(libc_open("", 0), -1) self.assertEqual(libc_open(b"", 0), -1)
self.assertEqual(get_errno(), errno.ENOENT) self.assertEqual(get_errno(), errno.ENOENT)
self.assertEqual(set_errno(32), errno.ENOENT) self.assertEqual(set_errno(32), errno.ENOENT)
@ -35,7 +35,7 @@ class Test(unittest.TestCase):
else: else:
libc_open = libc.open libc_open = libc.open
libc_open.argtypes = c_char_p, c_int libc_open.argtypes = c_char_p, c_int
self.assertEqual(libc_open("", 0), -1) self.assertEqual(libc_open(b"", 0), -1)
self.assertEqual(get_errno(), 0) self.assertEqual(get_errno(), 0)
t = threading.Thread(target=_worker) t = threading.Thread(target=_worker)

View file

@ -70,19 +70,17 @@ class ObjectsTestCase(unittest.TestCase):
class Y(Structure): class Y(Structure):
_fields_ = [("x", X), ("y", X)] _fields_ = [("x", X), ("y", X)]
s1 = "Hello, World" s1 = b"Hello, World"
s2 = "Hallo, Welt" s2 = b"Hallo, Welt"
x = X() x = X()
x.a = s1 x.a = s1
x.b = s2 x.b = s2
self.assertEqual(x._objects, {"0": bytes(s1, "ascii"), self.assertEqual(x._objects, {"0": s1, "1": s2})
"1": bytes(s2, "ascii")})
y = Y() y = Y()
y.x = x y.x = x
self.assertEqual(y._objects, {"0": {"0": bytes(s1, "ascii"), self.assertEqual(y._objects, {"0": {"0": s1, "1": s2}})
"1": bytes(s2, "ascii")}})
## x = y.x ## x = y.x
## del y ## del y
## print x._b_base_._objects ## print x._b_base_._objects

View file

@ -13,9 +13,9 @@ class SimpleTestCase(unittest.TestCase):
def test_ccharp(self): def test_ccharp(self):
x = c_char_p() x = c_char_p()
self.assertEquals(x._objects, None) self.assertEquals(x._objects, None)
x.value = "abc" x.value = b"abc"
self.assertEquals(x._objects, b"abc") self.assertEquals(x._objects, b"abc")
x = c_char_p("spam") x = c_char_p(b"spam")
self.assertEquals(x._objects, b"spam") self.assertEquals(x._objects, b"spam")
class StructureTestCase(unittest.TestCase): class StructureTestCase(unittest.TestCase):
@ -37,8 +37,8 @@ class StructureTestCase(unittest.TestCase):
x = X() x = X()
self.assertEquals(x._objects, None) self.assertEquals(x._objects, None)
x.a = "spam" x.a = b"spam"
x.b = "foo" x.b = b"foo"
self.assertEquals(x._objects, {"0": b"spam", "1": b"foo"}) self.assertEquals(x._objects, {"0": b"spam", "1": b"foo"})
def test_struct_struct(self): def test_struct_struct(self):

View file

@ -25,7 +25,7 @@ class LibTest(unittest.TestCase):
def sort(a, b): def sort(a, b):
return three_way_cmp(a[0], b[0]) return three_way_cmp(a[0], b[0])
chars = create_string_buffer("spam, spam, and spam") chars = create_string_buffer(b"spam, spam, and spam")
lib.my_qsort(chars, len(chars)-1, sizeof(c_char), comparefunc(sort)) lib.my_qsort(chars, len(chars)-1, sizeof(c_char), comparefunc(sort))
self.assertEqual(chars.raw, b" ,,aaaadmmmnpppsss\x00") self.assertEqual(chars.raw, b" ,,aaaadmmmnpppsss\x00")

View file

@ -20,7 +20,7 @@ None
The memory block stores pointers to strings, and the strings itself The memory block stores pointers to strings, and the strings itself
assigned from Python must be kept. assigned from Python must be kept.
>>> array[4] = 'foo bar' >>> array[4] = b'foo bar'
>>> array._objects >>> array._objects
{'4': b'foo bar'} {'4': b'foo bar'}
>>> array[4] >>> array[4]
@ -45,7 +45,7 @@ of 'x' ('_b_base_' is either None, or the root object owning the memory block):
<ctypes.test.test_objects.X object at 0x...> <ctypes.test.test_objects.X object at 0x...>
>>> >>>
>>> x.array[0] = 'spam spam spam' >>> x.array[0] = b'spam spam spam'
>>> x._objects >>> x._objects
{'0:2': b'spam spam spam'} {'0:2': b'spam spam spam'}
>>> x.array._b_base_._objects >>> x.array._b_base_._objects

View file

@ -19,7 +19,6 @@ class SimpleTypesTestCase(unittest.TestCase):
else: else:
set_conversion_mode(*self.prev_conv_mode) set_conversion_mode(*self.prev_conv_mode)
def test_subclasses(self): def test_subclasses(self):
from ctypes import c_void_p, c_char_p from ctypes import c_void_p, c_char_p
# ctypes 0.9.5 and before did overwrite from_param in SimpleType_new # ctypes 0.9.5 and before did overwrite from_param in SimpleType_new
@ -60,12 +59,11 @@ class SimpleTypesTestCase(unittest.TestCase):
# new in 0.9.1: convert (encode) unicode to ascii # new in 0.9.1: convert (encode) unicode to ascii
self.assertEqual(c_char_p.from_param("123")._obj, b"123") self.assertEqual(c_char_p.from_param("123")._obj, b"123")
self.assertRaises(UnicodeEncodeError, c_char_p.from_param, "123\377") self.assertRaises(UnicodeEncodeError, c_char_p.from_param, "123\377")
self.assertRaises(TypeError, c_char_p.from_param, 42) self.assertRaises(TypeError, c_char_p.from_param, 42)
# calling c_char_p.from_param with a c_char_p instance # calling c_char_p.from_param with a c_char_p instance
# returns the argument itself: # returns the argument itself:
a = c_char_p("123") a = c_char_p(b"123")
self.assertTrue(c_char_p.from_param(a) is a) self.assertTrue(c_char_p.from_param(a) is a)
def test_cw_strings(self): def test_cw_strings(self):

View file

@ -127,7 +127,7 @@ class CharPointersTestCase(unittest.TestCase):
self.assertEqual(None, func(c_char_p(None))) self.assertEqual(None, func(c_char_p(None)))
self.assertEqual(b"123", func(c_buffer(b"123"))) self.assertEqual(b"123", func(c_buffer(b"123")))
ca = c_char("a") ca = c_char(b"a")
self.assertEqual(ord(b"a"), func(pointer(ca))[0]) self.assertEqual(ord(b"a"), func(pointer(ca))[0])
self.assertEqual(ord(b"a"), func(byref(ca))[0]) self.assertEqual(ord(b"a"), func(byref(ca))[0])

View file

@ -72,10 +72,10 @@ class PythonAPITestCase(unittest.TestCase):
PyOS_snprintf.argtypes = POINTER(c_char), c_size_t, c_char_p PyOS_snprintf.argtypes = POINTER(c_char), c_size_t, c_char_p
buf = c_buffer(256) buf = c_buffer(256)
PyOS_snprintf(buf, sizeof(buf), "Hello from %s", b"ctypes") PyOS_snprintf(buf, sizeof(buf), b"Hello from %s", b"ctypes")
self.assertEqual(buf.value, b"Hello from ctypes") self.assertEqual(buf.value, b"Hello from ctypes")
PyOS_snprintf(buf, sizeof(buf), "Hello from %s (%d, %d, %d)", b"ctypes", 1, 2, 3) PyOS_snprintf(buf, sizeof(buf), b"Hello from %s (%d, %d, %d)", b"ctypes", 1, 2, 3)
self.assertEqual(buf.value, b"Hello from ctypes (1, 2, 3)") self.assertEqual(buf.value, b"Hello from ctypes (1, 2, 3)")
# not enough arguments # not enough arguments

View file

@ -66,7 +66,7 @@ class CallbackTracbackTestCase(unittest.TestCase):
def test_TypeErrorDivisionError(self): def test_TypeErrorDivisionError(self):
cb = CFUNCTYPE(c_int, c_char_p)(callback_func) cb = CFUNCTYPE(c_int, c_char_p)(callback_func)
out = self.capture_stderr(cb, "spam") out = self.capture_stderr(cb, b"spam")
self.assertEqual(out.splitlines()[-1], self.assertEqual(out.splitlines()[-1],
"TypeError: " "TypeError: "
"unsupported operand type(s) for /: 'int' and 'bytes'") "unsupported operand type(s) for /: 'int' and 'bytes'")

View file

@ -22,8 +22,8 @@ class ReprTest(unittest.TestCase):
self.assertEqual("<X object at", repr(typ(42))[:12]) self.assertEqual("<X object at", repr(typ(42))[:12])
def test_char(self): def test_char(self):
self.assertEqual("c_char(b'x')", repr(c_char('x'))) self.assertEqual("c_char(b'x')", repr(c_char(b'x')))
self.assertEqual("<X object at", repr(X('x'))[:12]) self.assertEqual("<X object at", repr(X(b'x'))[:12])
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()

View file

@ -28,10 +28,10 @@ class ReturnFuncPtrTestCase(unittest.TestCase):
# _CFuncPtr instances are now callable with an integer argument # _CFuncPtr instances are now callable with an integer argument
# which denotes a function address: # which denotes a function address:
strchr = CFUNCTYPE(c_char_p, c_char_p, c_char)(addr) strchr = CFUNCTYPE(c_char_p, c_char_p, c_char)(addr)
self.assertTrue(strchr("abcdef", "b"), "bcdef") self.assertTrue(strchr(b"abcdef", b"b"), "bcdef")
self.assertEqual(strchr("abcdef", "x"), None) self.assertEqual(strchr(b"abcdef", b"x"), None)
self.assertRaises(ArgumentError, strchr, "abcdef", 3.0) self.assertRaises(ArgumentError, strchr, b"abcdef", 3.0)
self.assertRaises(TypeError, strchr, "abcdef") self.assertRaises(TypeError, strchr, b"abcdef")
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()

View file

@ -14,7 +14,7 @@ class StringPtrTestCase(unittest.TestCase):
# NULL pointer access # NULL pointer access
self.assertRaises(ValueError, getattr, x.str, "contents") self.assertRaises(ValueError, getattr, x.str, "contents")
b = c_buffer("Hello, World") b = c_buffer(b"Hello, World")
from sys import getrefcount as grc from sys import getrefcount as grc
self.assertEqual(grc(b), 2) self.assertEqual(grc(b), 2)
x.str = b x.str = b
@ -63,8 +63,8 @@ class StringPtrTestCase(unittest.TestCase):
# So we must keep a reference to buf separately # So we must keep a reference to buf separately
strchr.restype = POINTER(c_char) strchr.restype = POINTER(c_char)
buf = c_buffer("abcdef") buf = c_buffer(b"abcdef")
r = strchr(buf, "c") r = strchr(buf, b"c")
x = r[0], r[1], r[2], r[3], r[4] x = r[0], r[1], r[2], r[3], r[4]
self.assertEqual(x, (b"c", b"d", b"e", b"f", b"\000")) self.assertEqual(x, (b"c", b"d", b"e", b"f", b"\000"))
del buf del buf

View file

@ -5,23 +5,23 @@ class StringArrayTestCase(unittest.TestCase):
def test(self): def test(self):
BUF = c_char * 4 BUF = c_char * 4
buf = BUF("a", "b", "c") buf = BUF(b"a", b"b", b"c")
self.assertEqual(buf.value, b"abc") self.assertEqual(buf.value, b"abc")
self.assertEqual(buf.raw, b"abc\000") self.assertEqual(buf.raw, b"abc\000")
buf.value = "ABCD" buf.value = b"ABCD"
self.assertEqual(buf.value, b"ABCD") self.assertEqual(buf.value, b"ABCD")
self.assertEqual(buf.raw, b"ABCD") self.assertEqual(buf.raw, b"ABCD")
buf.value = "x" buf.value = b"x"
self.assertEqual(buf.value, b"x") self.assertEqual(buf.value, b"x")
self.assertEqual(buf.raw, b"x\000CD") self.assertEqual(buf.raw, b"x\000CD")
buf[1] = "Z" buf[1] = b"Z"
self.assertEqual(buf.value, b"xZCD") self.assertEqual(buf.value, b"xZCD")
self.assertEqual(buf.raw, b"xZCD") self.assertEqual(buf.raw, b"xZCD")
self.assertRaises(ValueError, setattr, buf, "value", "aaaaaaaa") self.assertRaises(ValueError, setattr, buf, "value", b"aaaaaaaa")
self.assertRaises(TypeError, setattr, buf, "value", 42) self.assertRaises(TypeError, setattr, buf, "value", 42)
def test_c_buffer_value(self): def test_c_buffer_value(self):

View file

@ -205,15 +205,15 @@ class StructureTestCase(unittest.TestCase):
("age", c_int)] ("age", c_int)]
self.assertRaises(TypeError, Person, 42) self.assertRaises(TypeError, Person, 42)
self.assertRaises(ValueError, Person, "asldkjaslkdjaslkdj") self.assertRaises(ValueError, Person, b"asldkjaslkdjaslkdj")
self.assertRaises(TypeError, Person, "Name", "HI") self.assertRaises(TypeError, Person, "Name", "HI")
# short enough # short enough
self.assertEqual(Person("12345", 5).name, b"12345") self.assertEqual(Person(b"12345", 5).name, b"12345")
# exact fit # exact fit
self.assertEqual(Person("123456", 5).name, b"123456") self.assertEqual(Person(b"123456", 5).name, b"123456")
# too long # too long
self.assertRaises(ValueError, Person, "1234567", 5) self.assertRaises(ValueError, Person, b"1234567", 5)
def test_conflicting_initializers(self): def test_conflicting_initializers(self):
class POINT(Structure): class POINT(Structure):
@ -267,7 +267,7 @@ class StructureTestCase(unittest.TestCase):
("phone", Phone), ("phone", Phone),
("age", c_int)] ("age", c_int)]
p = Person("Someone", ("1234", "5678"), 5) p = Person(b"Someone", (b"1234", b"5678"), 5)
self.assertEqual(p.name, b"Someone") self.assertEqual(p.name, b"Someone")
self.assertEqual(p.phone.areacode, b"1234") self.assertEqual(p.phone.areacode, b"1234")
@ -284,8 +284,8 @@ class StructureTestCase(unittest.TestCase):
_fields_ = [("name", c_wchar * 12), _fields_ = [("name", c_wchar * 12),
("age", c_int)] ("age", c_int)]
p = PersonW("Someone") p = PersonW("Someone \xe9")
self.assertEqual(p.name, "Someone") self.assertEqual(p.name, "Someone \xe9")
self.assertEqual(PersonW("1234567890").name, "1234567890") self.assertEqual(PersonW("1234567890").name, "1234567890")
self.assertEqual(PersonW("12345678901").name, "12345678901") self.assertEqual(PersonW("12345678901").name, "12345678901")
@ -304,13 +304,13 @@ class StructureTestCase(unittest.TestCase):
("phone", Phone), ("phone", Phone),
("age", c_int)] ("age", c_int)]
cls, msg = self.get_except(Person, "Someone", (1, 2)) cls, msg = self.get_except(Person, b"Someone", (1, 2))
self.assertEqual(cls, RuntimeError) self.assertEqual(cls, RuntimeError)
self.assertEqual(msg, self.assertEqual(msg,
"(Phone) <class 'TypeError'>: " "(Phone) <class 'TypeError'>: "
"expected string, int found") "expected string, int found")
cls, msg = self.get_except(Person, "Someone", ("a", "b", "c")) cls, msg = self.get_except(Person, b"Someone", (b"a", b"b", b"c"))
self.assertEqual(cls, RuntimeError) self.assertEqual(cls, RuntimeError)
if issubclass(Exception, object): if issubclass(Exception, object):
self.assertEqual(msg, self.assertEqual(msg,