Commit 04349c60 authored by Zachary Ware's avatar Zachary Ware

Issue #19493: Backport 6f63fff5c120

parent 925c6ad8
...@@ -2,7 +2,15 @@ import os, sys, unittest, getopt, time ...@@ -2,7 +2,15 @@ import os, sys, unittest, getopt, time
use_resources = [] use_resources = []
class ResourceDenied(Exception): import ctypes
ctypes_symbols = dir(ctypes)
def need_symbol(name):
return unittest.skipUnless(name in ctypes_symbols,
'{!r} is required'.format(name))
class ResourceDenied(unittest.SkipTest):
"""Test skipped because it requested a disallowed resource. """Test skipped because it requested a disallowed resource.
This is raised when a test calls requires() for a resource that This is raised when a test calls requires() for a resource that
......
import unittest import unittest
from ctypes import * from ctypes import *
from ctypes.test import need_symbol
formats = "bBhHiIlLqQfd" formats = "bBhHiIlLqQfd"
formats = c_byte, c_ubyte, c_short, c_ushort, c_int, c_uint, \ formats = c_byte, c_ubyte, c_short, c_ushort, c_int, c_uint, \
...@@ -101,11 +103,7 @@ class ArrayTestCase(unittest.TestCase): ...@@ -101,11 +103,7 @@ class ArrayTestCase(unittest.TestCase):
self.assertEqual(sz[1:4:2], "o") self.assertEqual(sz[1:4:2], "o")
self.assertEqual(sz.value, "foo") self.assertEqual(sz.value, "foo")
try: @need_symbol('create_unicode_buffer')
create_unicode_buffer
except NameError:
pass
else:
def test_from_addressW(self): def test_from_addressW(self):
p = create_unicode_buffer("foo") p = create_unicode_buffer("foo")
sz = (c_wchar * 3).from_address(addressof(p)) sz = (c_wchar * 3).from_address(addressof(p))
......
import unittest import unittest
from ctypes import * from ctypes import *
from ctypes.test import need_symbol
import _ctypes_test import _ctypes_test
dll = CDLL(_ctypes_test.__file__) dll = CDLL(_ctypes_test.__file__)
...@@ -17,11 +18,8 @@ class BasicWrapTestCase(unittest.TestCase): ...@@ -17,11 +18,8 @@ class BasicWrapTestCase(unittest.TestCase):
def wrap(self, param): def wrap(self, param):
return param return param
@need_symbol('c_wchar')
def test_wchar_parm(self): def test_wchar_parm(self):
try:
c_wchar
except NameError:
return
f = dll._testfunc_i_bhilfd f = dll._testfunc_i_bhilfd
f.argtypes = [c_byte, c_wchar, c_int, c_long, c_float, c_double] f.argtypes = [c_byte, c_wchar, c_int, c_long, c_float, c_double]
result = f(self.wrap(1), self.wrap(u"x"), self.wrap(3), self.wrap(4), self.wrap(5.0), self.wrap(6.0)) result = f(self.wrap(1), self.wrap(u"x"), self.wrap(3), self.wrap(4), self.wrap(5.0), self.wrap(6.0))
......
from ctypes import * from ctypes import *
from ctypes.test import need_symbol
import unittest import unittest
import os import os
...@@ -127,20 +128,18 @@ class BitFieldTest(unittest.TestCase): ...@@ -127,20 +128,18 @@ class BitFieldTest(unittest.TestCase):
result = self.fail_fields(("a", c_char, 1)) result = self.fail_fields(("a", c_char, 1))
self.assertEqual(result, (TypeError, 'bit fields not allowed for type c_char')) self.assertEqual(result, (TypeError, 'bit fields not allowed for type c_char'))
try:
c_wchar
except NameError:
pass
else:
result = self.fail_fields(("a", c_wchar, 1))
self.assertEqual(result, (TypeError, 'bit fields not allowed for type c_wchar'))
class Dummy(Structure): class Dummy(Structure):
_fields_ = [] _fields_ = []
result = self.fail_fields(("a", Dummy, 1)) result = self.fail_fields(("a", Dummy, 1))
self.assertEqual(result, (TypeError, 'bit fields not allowed for type Dummy')) self.assertEqual(result, (TypeError, 'bit fields not allowed for type Dummy'))
@need_symbol('c_wchar')
def test_c_wchar(self):
result = self.fail_fields(("a", c_wchar, 1))
self.assertEqual(result,
(TypeError, 'bit fields not allowed for type c_wchar'))
def test_single_bitfield_size(self): def test_single_bitfield_size(self):
for c_typ in int_types: for c_typ in int_types:
result = self.fail_fields(("a", c_typ, -1)) result = self.fail_fields(("a", c_typ, -1))
...@@ -240,7 +239,7 @@ class BitFieldTest(unittest.TestCase): ...@@ -240,7 +239,7 @@ class BitFieldTest(unittest.TestCase):
_anonymous_ = ["_"] _anonymous_ = ["_"]
_fields_ = [("_", X)] _fields_ = [("_", X)]
@unittest.skipUnless(hasattr(ctypes, "c_uint32"), "c_int32 is required") @need_symbol('c_uint32')
def test_uint32(self): def test_uint32(self):
class X(Structure): class X(Structure):
_fields_ = [("a", c_uint32, 32)] _fields_ = [("a", c_uint32, 32)]
...@@ -250,7 +249,7 @@ class BitFieldTest(unittest.TestCase): ...@@ -250,7 +249,7 @@ class BitFieldTest(unittest.TestCase):
x.a = 0xFDCBA987 x.a = 0xFDCBA987
self.assertEqual(x.a, 0xFDCBA987) self.assertEqual(x.a, 0xFDCBA987)
@unittest.skipUnless(hasattr(ctypes, "c_uint64"), "c_int64 is required") @need_symbol('c_uint64')
def test_uint64(self): def test_uint64(self):
class X(Structure): class X(Structure):
_fields_ = [("a", c_uint64, 64)] _fields_ = [("a", c_uint64, 64)]
......
from ctypes import * from ctypes import *
from ctypes.test import need_symbol
import unittest import unittest
class StringBufferTestCase(unittest.TestCase): class StringBufferTestCase(unittest.TestCase):
...@@ -36,11 +37,7 @@ class StringBufferTestCase(unittest.TestCase): ...@@ -36,11 +37,7 @@ class StringBufferTestCase(unittest.TestCase):
self.assertEqual(b[::2], "ac") self.assertEqual(b[::2], "ac")
self.assertEqual(b[::5], "a") self.assertEqual(b[::5], "a")
try: @need_symbol('c_wchar')
c_wchar
except NameError:
pass
else:
def test_unicode_buffer(self): def test_unicode_buffer(self):
b = create_unicode_buffer(32) b = create_unicode_buffer(32)
self.assertEqual(len(b), 32) self.assertEqual(len(b), 32)
...@@ -58,6 +55,7 @@ class StringBufferTestCase(unittest.TestCase): ...@@ -58,6 +55,7 @@ class StringBufferTestCase(unittest.TestCase):
self.assertEqual(b[::2], "ac") self.assertEqual(b[::2], "ac")
self.assertEqual(b[::5], "a") self.assertEqual(b[::5], "a")
@need_symbol('c_wchar')
def test_unicode_conversion(self): def test_unicode_conversion(self):
b = create_unicode_buffer("abc") b = create_unicode_buffer("abc")
self.assertEqual(len(b), 4) # trailing nul char self.assertEqual(len(b), 4) # trailing nul char
......
...@@ -14,7 +14,8 @@ def bin(s): ...@@ -14,7 +14,8 @@ def bin(s):
# For Structures and Unions, these types are created on demand. # For Structures and Unions, these types are created on demand.
class Test(unittest.TestCase): class Test(unittest.TestCase):
def X_test(self): @unittest.skip('test disabled')
def test_X(self):
print >> sys.stderr, sys.byteorder print >> sys.stderr, sys.byteorder
for i in range(32): for i in range(32):
bits = BITS() bits = BITS()
......
import unittest import unittest
from ctypes import * from ctypes import *
from ctypes.test import need_symbol
import _ctypes_test import _ctypes_test
class Callbacks(unittest.TestCase): class Callbacks(unittest.TestCase):
...@@ -94,9 +95,10 @@ class Callbacks(unittest.TestCase): ...@@ -94,9 +95,10 @@ class Callbacks(unittest.TestCase):
# disabled: would now (correctly) raise a RuntimeWarning about # disabled: would now (correctly) raise a RuntimeWarning about
# a memory leak. A callback function cannot return a non-integral # a memory leak. A callback function cannot return a non-integral
# C type without causing a memory leak. # C type without causing a memory leak.
## def test_char_p(self): @unittest.skip('test disabled')
## self.check_type(c_char_p, "abc") def test_char_p(self):
## self.check_type(c_char_p, "def") self.check_type(c_char_p, "abc")
self.check_type(c_char_p, "def")
def test_pyobject(self): def test_pyobject(self):
o = () o = ()
...@@ -148,13 +150,12 @@ class Callbacks(unittest.TestCase): ...@@ -148,13 +150,12 @@ class Callbacks(unittest.TestCase):
CFUNCTYPE(None)(lambda x=Nasty(): None) CFUNCTYPE(None)(lambda x=Nasty(): None)
try: @need_symbol('WINFUNCTYPE')
WINFUNCTYPE class StdcallCallbacks(Callbacks):
except NameError: try:
pass
else:
class StdcallCallbacks(Callbacks):
functype = WINFUNCTYPE functype = WINFUNCTYPE
except NameError:
pass
################################################################ ################################################################
...@@ -184,7 +185,7 @@ class SampleCallbacksTestCase(unittest.TestCase): ...@@ -184,7 +185,7 @@ class SampleCallbacksTestCase(unittest.TestCase):
from ctypes.util import find_library from ctypes.util import find_library
libc_path = find_library("c") libc_path = find_library("c")
if not libc_path: if not libc_path:
return # cannot test self.skipTest('could not find libc')
libc = CDLL(libc_path) libc = CDLL(libc_path)
@CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int)) @CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
...@@ -196,11 +197,7 @@ class SampleCallbacksTestCase(unittest.TestCase): ...@@ -196,11 +197,7 @@ class SampleCallbacksTestCase(unittest.TestCase):
libc.qsort(array, len(array), sizeof(c_int), cmp_func) libc.qsort(array, len(array), sizeof(c_int), cmp_func)
self.assertEqual(array[:], [1, 5, 7, 33, 99]) self.assertEqual(array[:], [1, 5, 7, 33, 99])
try: @need_symbol('WINFUNCTYPE')
WINFUNCTYPE
except NameError:
pass
else:
def test_issue_8959_b(self): def test_issue_8959_b(self):
from ctypes.wintypes import BOOL, HWND, LPARAM from ctypes.wintypes import BOOL, HWND, LPARAM
global windowCount global windowCount
......
from ctypes import * from ctypes import *
from ctypes.test import need_symbol
import unittest import unittest
import sys import sys
...@@ -75,11 +76,7 @@ class Test(unittest.TestCase): ...@@ -75,11 +76,7 @@ class Test(unittest.TestCase):
self.assertEqual(cast(cast(s, c_void_p), c_char_p).value, self.assertEqual(cast(cast(s, c_void_p), c_char_p).value,
"hiho") "hiho")
try: @need_symbol('c_wchar_p')
c_wchar_p
except NameError:
pass
else:
def test_wchar_p(self): def test_wchar_p(self):
s = c_wchar_p("hiho") s = c_wchar_p("hiho")
self.assertEqual(cast(cast(s, c_void_p), c_wchar_p).value, self.assertEqual(cast(cast(s, c_void_p), c_wchar_p).value,
......
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
import unittest import unittest
from ctypes import * from ctypes import *
from ctypes.test import need_symbol
import _ctypes_test import _ctypes_test
...@@ -193,7 +194,7 @@ class CFunctions(unittest.TestCase): ...@@ -193,7 +194,7 @@ class CFunctions(unittest.TestCase):
try: try:
WinDLL WinDLL
except NameError: except NameError:
pass def stdcall_dll(*_): pass
else: else:
class stdcall_dll(WinDLL): class stdcall_dll(WinDLL):
def __getattr__(self, name): def __getattr__(self, name):
...@@ -203,9 +204,9 @@ else: ...@@ -203,9 +204,9 @@ else:
setattr(self, name, func) setattr(self, name, func)
return func return func
class stdcallCFunctions(CFunctions): @need_symbol('WinDLL')
class stdcallCFunctions(CFunctions):
_dll = stdcall_dll(_ctypes_test.__file__) _dll = stdcall_dll(_ctypes_test.__file__)
pass
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()
import unittest import unittest
from ctypes import * from ctypes import *
from ctypes.test import need_symbol
class CHECKED(c_int): class CHECKED(c_int):
def _check_retval_(value): def _check_retval_(value):
...@@ -25,11 +26,7 @@ class Test(unittest.TestCase): ...@@ -25,11 +26,7 @@ class Test(unittest.TestCase):
del dll._testfunc_p_p.restype del dll._testfunc_p_p.restype
self.assertEqual(42, dll._testfunc_p_p(42)) self.assertEqual(42, dll._testfunc_p_p(42))
try: @need_symbol('oledll')
oledll
except NameError:
pass
else:
def test_oledll(self): def test_oledll(self):
self.assertRaises(WindowsError, self.assertRaises(WindowsError,
oledll.oleaut32.CreateTypeLib2, oledll.oleaut32.CreateTypeLib2,
......
import sys
from ctypes import *
##class HMODULE(Structure):
## _fields_ = [("value", c_void_p)]
## def __repr__(self):
## return "<HMODULE %s>" % self.value
##windll.kernel32.GetModuleHandleA.restype = HMODULE
##print windll.kernel32.GetModuleHandleA("python23.dll")
##print hex(sys.dllhandle)
##def nonzero(handle):
## return (GetLastError(), handle)
##windll.kernel32.GetModuleHandleA.errcheck = nonzero
##print windll.kernel32.GetModuleHandleA("spam")
import unittest import unittest
import os
import sys import sys
from ctypes import * from ctypes import *
from ctypes.util import find_library from ctypes.util import find_library
...@@ -40,43 +41,43 @@ class Test_OpenGL_libs(unittest.TestCase): ...@@ -40,43 +41,43 @@ class Test_OpenGL_libs(unittest.TestCase):
except OSError: except OSError:
pass pass
if lib_gl: @unittest.skipUnless(lib_gl, 'lib_gl not available')
def test_gl(self): def test_gl(self):
if self.gl: if self.gl:
self.gl.glClearIndex self.gl.glClearIndex
if lib_glu: @unittest.skipUnless(lib_glu, 'lib_glu not available')
def test_glu(self): def test_glu(self):
if self.glu: if self.glu:
self.glu.gluBeginCurve self.glu.gluBeginCurve
if lib_gle: @unittest.skipUnless(lib_gle, 'lib_gle not available')
def test_gle(self): def test_gle(self):
if self.gle: if self.gle:
self.gle.gleGetJoinStyle self.gle.gleGetJoinStyle
##if os.name == "posix" and sys.platform != "darwin": # On platforms where the default shared library suffix is '.so',
# at least some libraries can be loaded as attributes of the cdll
## # On platforms where the default shared library suffix is '.so', # object, since ctypes now tries loading the lib again
## # at least some libraries can be loaded as attributes of the cdll # with '.so' appended of the first try fails.
## # object, since ctypes now tries loading the lib again #
## # with '.so' appended of the first try fails. # Won't work for libc, unfortunately. OTOH, it isn't
## # # needed for libc since this is already mapped into the current
## # Won't work for libc, unfortunately. OTOH, it isn't # process (?)
## # needed for libc since this is already mapped into the current #
## # process (?) # On MAC OSX, it won't work either, because dlopen() needs a full path,
## # # and the default suffix is either none or '.dylib'.
## # On MAC OSX, it won't work either, because dlopen() needs a full path, @unittest.skip('test disabled')
## # and the default suffix is either none or '.dylib'. @unittest.skipUnless(os.name=="posix" and sys.platform != "darwin",
'test not suitable for this platform')
## class LoadLibs(unittest.TestCase): class LoadLibs(unittest.TestCase):
## def test_libm(self): def test_libm(self):
## import math import math
## libm = cdll.libm libm = cdll.libm
## sqrt = libm.sqrt sqrt = libm.sqrt
## sqrt.argtypes = (c_double,) sqrt.argtypes = (c_double,)
## sqrt.restype = c_double sqrt.restype = c_double
## self.assertEqual(sqrt(2), math.sqrt(2)) self.assertEqual(sqrt(2), math.sqrt(2))
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
...@@ -6,6 +6,7 @@ Later... ...@@ -6,6 +6,7 @@ Later...
""" """
from ctypes import * from ctypes import *
from ctypes.test import need_symbol
import sys, unittest import sys, unittest
try: try:
...@@ -63,22 +64,16 @@ class FunctionTestCase(unittest.TestCase): ...@@ -63,22 +64,16 @@ class FunctionTestCase(unittest.TestCase):
pass pass
@need_symbol('c_wchar')
def test_wchar_parm(self): def test_wchar_parm(self):
try:
c_wchar
except NameError:
return
f = dll._testfunc_i_bhilfd f = dll._testfunc_i_bhilfd
f.argtypes = [c_byte, c_wchar, c_int, c_long, c_float, c_double] f.argtypes = [c_byte, c_wchar, c_int, c_long, c_float, c_double]
result = f(1, u"x", 3, 4, 5.0, 6.0) result = f(1, u"x", 3, 4, 5.0, 6.0)
self.assertEqual(result, 139) self.assertEqual(result, 139)
self.assertEqual(type(result), int) self.assertEqual(type(result), int)
@need_symbol('c_wchar')
def test_wchar_result(self): def test_wchar_result(self):
try:
c_wchar
except NameError:
return
f = dll._testfunc_i_bhilfd f = dll._testfunc_i_bhilfd
f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_double] f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_double]
f.restype = c_wchar f.restype = c_wchar
...@@ -155,11 +150,8 @@ class FunctionTestCase(unittest.TestCase): ...@@ -155,11 +150,8 @@ class FunctionTestCase(unittest.TestCase):
self.assertEqual(result, -21) self.assertEqual(result, -21)
self.assertEqual(type(result), float) self.assertEqual(type(result), float)
@need_symbol('c_longlong')
def test_longlongresult(self): def test_longlongresult(self):
try:
c_longlong
except NameError:
return
f = dll._testfunc_q_bhilfd f = dll._testfunc_q_bhilfd
f.restype = c_longlong f.restype = c_longlong
f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_double] f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_double]
...@@ -296,6 +288,7 @@ class FunctionTestCase(unittest.TestCase): ...@@ -296,6 +288,7 @@ class FunctionTestCase(unittest.TestCase):
result = f(-10, cb) result = f(-10, cb)
self.assertEqual(result, -18) self.assertEqual(result, -18)
@need_symbol('c_longlong')
def test_longlong_callbacks(self): def test_longlong_callbacks(self):
f = dll._testfunc_callback_q_qf f = dll._testfunc_callback_q_qf
...@@ -348,7 +341,7 @@ class FunctionTestCase(unittest.TestCase): ...@@ -348,7 +341,7 @@ class FunctionTestCase(unittest.TestCase):
s2h = dll.ret_2h_func(inp) s2h = dll.ret_2h_func(inp)
self.assertEqual((s2h.x, s2h.y), (99*2, 88*3)) self.assertEqual((s2h.x, s2h.y), (99*2, 88*3))
if sys.platform == "win32": @unittest.skipUnless(sys.platform == "win32", 'Windows-specific test')
def test_struct_return_2H_stdcall(self): def test_struct_return_2H_stdcall(self):
class S2H(Structure): class S2H(Structure):
_fields_ = [("x", c_short), _fields_ = [("x", c_short),
...@@ -376,7 +369,7 @@ class FunctionTestCase(unittest.TestCase): ...@@ -376,7 +369,7 @@ class FunctionTestCase(unittest.TestCase):
self.assertEqual((s8i.a, s8i.b, s8i.c, s8i.d, s8i.e, s8i.f, s8i.g, s8i.h), self.assertEqual((s8i.a, s8i.b, s8i.c, s8i.d, s8i.e, s8i.f, s8i.g, s8i.h),
(9*2, 8*3, 7*4, 6*5, 5*6, 4*7, 3*8, 2*9)) (9*2, 8*3, 7*4, 6*5, 5*6, 4*7, 3*8, 2*9))
if sys.platform == "win32": @unittest.skipUnless(sys.platform == "win32", 'Windows-specific test')
def test_struct_return_8H_stdcall(self): def test_struct_return_8H_stdcall(self):
class S8I(Structure): class S8I(Structure):
_fields_ = [("a", c_int), _fields_ = [("a", c_int),
...@@ -391,7 +384,8 @@ class FunctionTestCase(unittest.TestCase): ...@@ -391,7 +384,8 @@ class FunctionTestCase(unittest.TestCase):
windll.s_ret_8i_func.argtypes = [S8I] windll.s_ret_8i_func.argtypes = [S8I]
inp = S8I(9, 8, 7, 6, 5, 4, 3, 2) inp = S8I(9, 8, 7, 6, 5, 4, 3, 2)
s8i = windll.s_ret_8i_func(inp) s8i = windll.s_ret_8i_func(inp)
self.assertEqual((s8i.a, s8i.b, s8i.c, s8i.d, s8i.e, s8i.f, s8i.g, s8i.h), self.assertEqual(
(s8i.a, s8i.b, s8i.c, s8i.d, s8i.e, s8i.f, s8i.g, s8i.h),
(9*2, 8*3, 7*4, 6*5, 5*6, 4*7, 3*8, 2*9)) (9*2, 8*3, 7*4, 6*5, 5*6, 4*7, 3*8, 2*9))
def test_sf1651235(self): def test_sf1651235(self):
......
# superseded by test_numbers.py
import unittest
if __name__ == '__main__':
unittest.main()
...@@ -94,7 +94,8 @@ class PointerTestCase(unittest.TestCase): ...@@ -94,7 +94,8 @@ class PointerTestCase(unittest.TestCase):
self.assertEqual(x._objects, {'1': i}) self.assertEqual(x._objects, {'1': i})
class DeletePointerTestCase(unittest.TestCase): class DeletePointerTestCase(unittest.TestCase):
def X_test(self): @unittest.skip('test disabled')
def test_X(self):
class X(Structure): class X(Structure):
_fields_ = [("p", POINTER(c_char_p))] _fields_ = [("p", POINTER(c_char_p))]
x = X() x = X()
......
...@@ -21,13 +21,16 @@ class LoaderTest(unittest.TestCase): ...@@ -21,13 +21,16 @@ class LoaderTest(unittest.TestCase):
unknowndll = "xxrandomnamexx" unknowndll = "xxrandomnamexx"
if libc_name is not None: @unittest.skipUnless(libc_name is not None, 'could not find libc')
def test_load(self): def test_load(self):
CDLL(libc_name) CDLL(libc_name)
CDLL(os.path.basename(libc_name)) CDLL(os.path.basename(libc_name))
self.assertRaises(OSError, CDLL, self.unknowndll) self.assertRaises(OSError, CDLL, self.unknowndll)
if libc_name is not None and os.path.basename(libc_name) == "libc.so.6": @unittest.skipUnless(libc_name is not None, 'could not find libc')
@unittest.skipUnless(libc_name is not None and
os.path.basename(libc_name) == "libc.so.6",
'wrong libc path for test')
def test_load_version(self): def test_load_version(self):
cdll.LoadLibrary("libc.so.6") cdll.LoadLibrary("libc.so.6")
# linux uses version, libc 9 should not exist # linux uses version, libc 9 should not exist
...@@ -41,7 +44,8 @@ class LoaderTest(unittest.TestCase): ...@@ -41,7 +44,8 @@ class LoaderTest(unittest.TestCase):
cdll.LoadLibrary(lib) cdll.LoadLibrary(lib)
CDLL(lib) CDLL(lib)
if os.name in ("nt", "ce"): @unittest.skipUnless(os.name in ("nt", "ce"),
'test specific to Windows (NT/CE)')
def test_load_library(self): def test_load_library(self):
self.assertIsNotNone(libc_name) self.assertIsNotNone(libc_name)
if is_resource_enabled("printing"): if is_resource_enabled("printing"):
...@@ -59,6 +63,8 @@ class LoaderTest(unittest.TestCase): ...@@ -59,6 +63,8 @@ class LoaderTest(unittest.TestCase):
windll.LoadLibrary("coredll").GetModuleHandleW windll.LoadLibrary("coredll").GetModuleHandleW
WinDLL("coredll").GetModuleHandleW WinDLL("coredll").GetModuleHandleW
@unittest.skipUnless(os.name in ("nt", "ce"),
'test specific to Windows (NT/CE)')
def test_load_ordinal_functions(self): def test_load_ordinal_functions(self):
import _ctypes_test import _ctypes_test
dll = WinDLL(_ctypes_test.__file__) dll = WinDLL(_ctypes_test.__file__)
...@@ -74,7 +80,7 @@ class LoaderTest(unittest.TestCase): ...@@ -74,7 +80,7 @@ class LoaderTest(unittest.TestCase):
self.assertRaises(AttributeError, dll.__getitem__, 1234) self.assertRaises(AttributeError, dll.__getitem__, 1234)
if os.name == "nt": @unittest.skipUnless(os.name == "nt", 'Windows-specific test')
def test_1703286_A(self): def test_1703286_A(self):
from _ctypes import LoadLibrary, FreeLibrary from _ctypes import LoadLibrary, FreeLibrary
# On winXP 64-bit, advapi32 loads at an address that does # On winXP 64-bit, advapi32 loads at an address that does
...@@ -85,6 +91,7 @@ class LoaderTest(unittest.TestCase): ...@@ -85,6 +91,7 @@ class LoaderTest(unittest.TestCase):
handle = LoadLibrary("advapi32") handle = LoadLibrary("advapi32")
FreeLibrary(handle) FreeLibrary(handle)
@unittest.skipUnless(os.name == "nt", 'Windows-specific test')
def test_1703286_B(self): def test_1703286_B(self):
# Since on winXP 64-bit advapi32 loads like described # Since on winXP 64-bit advapi32 loads like described
# above, the (arbitrarily selected) CloseEventLog function # above, the (arbitrarily selected) CloseEventLog function
...@@ -97,7 +104,8 @@ class LoaderTest(unittest.TestCase): ...@@ -97,7 +104,8 @@ class LoaderTest(unittest.TestCase):
self.assertEqual(0, advapi32.CloseEventLog(None)) self.assertEqual(0, advapi32.CloseEventLog(None))
windll.kernel32.GetProcAddress.argtypes = c_void_p, c_char_p windll.kernel32.GetProcAddress.argtypes = c_void_p, c_char_p
windll.kernel32.GetProcAddress.restype = c_void_p windll.kernel32.GetProcAddress.restype = c_void_p
proc = windll.kernel32.GetProcAddress(advapi32._handle, "CloseEventLog") proc = windll.kernel32.GetProcAddress(advapi32._handle,
"CloseEventLog")
self.assertTrue(proc) self.assertTrue(proc)
# This is the real test: call the function via 'call_function' # This is the real test: call the function via 'call_function'
self.assertEqual(0, call_function(proc, (None,))) self.assertEqual(0, call_function(proc, (None,)))
......
...@@ -45,7 +45,7 @@ def find_lib(name): ...@@ -45,7 +45,7 @@ def find_lib(name):
raise ValueError("%s not found" % (name,)) raise ValueError("%s not found" % (name,))
class MachOTest(unittest.TestCase): class MachOTest(unittest.TestCase):
if sys.platform == "darwin": @unittest.skipUnless(sys.platform == "darwin", 'OSX-specific test')
def test_find(self): def test_find(self):
self.assertEqual(find_lib('pthread'), self.assertEqual(find_lib('pthread'),
......
import sys import sys
import unittest import unittest
from ctypes import * from ctypes import *
from ctypes.test import need_symbol
class MemFunctionsTest(unittest.TestCase): class MemFunctionsTest(unittest.TestCase):
## def test_overflow(self): @unittest.skip('test disabled')
## # string_at and wstring_at must use the Python calling def test_overflow(self):
## # convention (which acquires the GIL and checks the Python # string_at and wstring_at must use the Python calling
## # error flag). Provoke an error and catch it; see also issue # convention (which acquires the GIL and checks the Python
## # #3554: <http://bugs.python.org/issue3554> # error flag). Provoke an error and catch it; see also issue
## self.assertRaises((OverflowError, MemoryError, SystemError), # #3554: <http://bugs.python.org/issue3554>
## lambda: wstring_at(u"foo", sys.maxint - 1)) self.assertRaises((OverflowError, MemoryError, SystemError),
## self.assertRaises((OverflowError, MemoryError, SystemError), lambda: wstring_at(u"foo", sys.maxint - 1))
## lambda: string_at("foo", sys.maxint - 1)) self.assertRaises((OverflowError, MemoryError, SystemError),
lambda: string_at("foo", sys.maxint - 1))
def test_memmove(self): def test_memmove(self):
# large buffers apparently increase the chance that the memory # large buffers apparently increase the chance that the memory
...@@ -59,11 +61,7 @@ class MemFunctionsTest(unittest.TestCase): ...@@ -59,11 +61,7 @@ class MemFunctionsTest(unittest.TestCase):
self.assertEqual(string_at("foo bar", 8), "foo bar\0") self.assertEqual(string_at("foo bar", 8), "foo bar\0")
self.assertEqual(string_at("foo bar", 3), "foo") self.assertEqual(string_at("foo bar", 3), "foo")
try: @need_symbol('create_unicode_buffer')
create_unicode_buffer
except NameError:
pass
else:
def test_wstring_at(self): def test_wstring_at(self):
p = create_unicode_buffer("Hello, World") p = create_unicode_buffer("Hello, World")
a = create_unicode_buffer(1000000) a = create_unicode_buffer(1000000)
......
...@@ -82,12 +82,13 @@ class NumberTestCase(unittest.TestCase): ...@@ -82,12 +82,13 @@ class NumberTestCase(unittest.TestCase):
self.assertRaises(TypeError, t, "") self.assertRaises(TypeError, t, "")
self.assertRaises(TypeError, t, None) self.assertRaises(TypeError, t, None)
## def test_valid_ranges(self): @unittest.skip('test disabled')
## # invalid values of the correct type def test_valid_ranges(self):
## # raise ValueError (not OverflowError) # invalid values of the correct type
## for t, (l, h) in zip(unsigned_types, unsigned_ranges): # raise ValueError (not OverflowError)
## self.assertRaises(ValueError, t, l-1) for t, (l, h) in zip(unsigned_types, unsigned_ranges):
## self.assertRaises(ValueError, t, h+1) self.assertRaises(ValueError, t, l-1)
self.assertRaises(ValueError, t, h+1)
def test_from_param(self): def test_from_param(self):
# the from_param class method attribute always # the from_param class method attribute always
...@@ -199,16 +200,17 @@ class NumberTestCase(unittest.TestCase): ...@@ -199,16 +200,17 @@ class NumberTestCase(unittest.TestCase):
self.assertEqual(v.value, a[0]) self.assertEqual(v.value, a[0])
# array does not support c_bool / 't' # array does not support c_bool / 't'
# def test_bool_from_address(self): @unittest.skip('test disabled')
# from ctypes import c_bool def test_bool_from_address(self):
# from array import array from ctypes import c_bool
# a = array(c_bool._type_, [True]) from array import array
# v = t.from_address(a.buffer_info()[0]) a = array(c_bool._type_, [True])
# self.assertEqual(v.value, a[0]) v = t.from_address(a.buffer_info()[0])
# self.assertEqual(type(v) is t) self.assertEqual(v.value, a[0])
# a[0] = False self.assertEqual(type(v) is t)
# self.assertEqual(v.value, a[0]) a[0] = False
# self.assertEqual(type(v) is t) self.assertEqual(v.value, a[0])
self.assertEqual(type(v) is t)
def test_init(self): def test_init(self):
# c_int() can be initialized from Python's int, and c_int. # c_int() can be initialized from Python's int, and c_int.
...@@ -226,8 +228,9 @@ class NumberTestCase(unittest.TestCase): ...@@ -226,8 +228,9 @@ class NumberTestCase(unittest.TestCase):
if (hasattr(t, "__ctype_le__")): if (hasattr(t, "__ctype_le__")):
self.assertRaises(OverflowError, t.__ctype_le__, big_int) self.assertRaises(OverflowError, t.__ctype_le__, big_int)
## def test_perf(self): @unittest.skip('test disabled')
## check_perf() def test_perf(self):
check_perf()
from ctypes import _SimpleCData from ctypes import _SimpleCData
class c_int_S(_SimpleCData): class c_int_S(_SimpleCData):
......
...@@ -59,12 +59,9 @@ import unittest, doctest, sys ...@@ -59,12 +59,9 @@ import unittest, doctest, sys
import ctypes.test.test_objects import ctypes.test.test_objects
class TestCase(unittest.TestCase): class TestCase(unittest.TestCase):
if sys.hexversion > 0x02040000:
# Python 2.3 has no ELLIPSIS flag, so we don't test with this
# version:
def test(self): def test(self):
doctest.testmod(ctypes.test.test_objects) failures, tests = doctest.testmod(ctypes.test.test_objects)
self.assertFalse(failures, 'doctests failed, see output above')
if __name__ == '__main__': if __name__ == '__main__':
if sys.hexversion > 0x02040000:
doctest.testmod(ctypes.test.test_objects) doctest.testmod(ctypes.test.test_objects)
import unittest, sys import unittest, sys
from ctypes.test import need_symbol
class SimpleTypesTestCase(unittest.TestCase): class SimpleTypesTestCase(unittest.TestCase):
...@@ -36,10 +37,9 @@ class SimpleTypesTestCase(unittest.TestCase): ...@@ -36,10 +37,9 @@ class SimpleTypesTestCase(unittest.TestCase):
self.assertEqual(CVOIDP.from_param("abc"), "abcabc") self.assertEqual(CVOIDP.from_param("abc"), "abcabc")
self.assertEqual(CCHARP.from_param("abc"), "abcabcabcabc") self.assertEqual(CCHARP.from_param("abc"), "abcabcabcabc")
try: @need_symbol('c_wchar_p')
def test_subclasses_c_wchar_p(self):
from ctypes import c_wchar_p from ctypes import c_wchar_p
except ImportError:
return
class CWCHARP(c_wchar_p): class CWCHARP(c_wchar_p):
def from_param(cls, value): def from_param(cls, value):
...@@ -68,13 +68,9 @@ class SimpleTypesTestCase(unittest.TestCase): ...@@ -68,13 +68,9 @@ class SimpleTypesTestCase(unittest.TestCase):
a = c_char_p("123") a = c_char_p("123")
self.assertIs(c_char_p.from_param(a), a) self.assertIs(c_char_p.from_param(a), a)
@need_symbol('c_wchar_p')
def test_cw_strings(self): def test_cw_strings(self):
from ctypes import byref from ctypes import byref, c_wchar_p
try:
from ctypes import c_wchar_p
except ImportError:
## print "(No c_wchar_p)"
return
s = u"123" s = u"123"
if sys.platform == "win32": if sys.platform == "win32":
self.assertTrue(c_wchar_p.from_param(s)._obj is s) self.assertTrue(c_wchar_p.from_param(s)._obj is s)
...@@ -144,9 +140,6 @@ class SimpleTypesTestCase(unittest.TestCase): ...@@ -144,9 +140,6 @@ class SimpleTypesTestCase(unittest.TestCase):
self.assertRaises(TypeError, LPINT.from_param, c_long*3) self.assertRaises(TypeError, LPINT.from_param, c_long*3)
self.assertRaises(TypeError, LPINT.from_param, c_uint*3) self.assertRaises(TypeError, LPINT.from_param, c_uint*3)
## def test_performance(self):
## check_perf()
def test_noctypes_argtype(self): def test_noctypes_argtype(self):
import _ctypes_test import _ctypes_test
from ctypes import CDLL, c_void_p, ArgumentError from ctypes import CDLL, c_void_p, ArgumentError
......
from ctypes import * from ctypes import *
from ctypes.test import need_symbol
import unittest import unittest
# IMPORTANT INFO: # IMPORTANT INFO:
...@@ -135,11 +136,12 @@ class CharPointersTestCase(unittest.TestCase): ...@@ -135,11 +136,12 @@ class CharPointersTestCase(unittest.TestCase):
func(pointer(c_int())) func(pointer(c_int()))
func((c_int * 3)()) func((c_int * 3)())
try: @need_symbol('c_wchar_p')
def test_c_void_p_arg_with_c_wchar_p(self):
func = testdll._testfunc_p_p
func.restype = c_wchar_p func.restype = c_wchar_p
except NameError: func.argtypes = c_void_p,
pass
else:
self.assertEqual(None, func(c_wchar_p(None))) self.assertEqual(None, func(c_wchar_p(None)))
self.assertEqual(u"123", func(c_wchar_p(u"123"))) self.assertEqual(u"123", func(c_wchar_p(u"123")))
...@@ -156,12 +158,8 @@ class CharPointersTestCase(unittest.TestCase): ...@@ -156,12 +158,8 @@ class CharPointersTestCase(unittest.TestCase):
func.argtypes = None func.argtypes = None
self.assertEqual(None, func(X())) self.assertEqual(None, func(X()))
try: @need_symbol('c_wchar')
c_wchar class WCharPointersTestCase(unittest.TestCase):
except NameError:
pass
else:
class WCharPointersTestCase(unittest.TestCase):
def setUp(self): def setUp(self):
func = testdll._testfunc_p_p func = testdll._testfunc_p_p
......
from ctypes import * from ctypes import *
import unittest, sys import unittest, sys
from ctypes.test import is_resource_enabled from ctypes.test import requires
################################################################ ################################################################
# This section should be moved into ctypes\__init__.py, when it's ready. # This section should be moved into ctypes\__init__.py, when it's ready.
...@@ -37,10 +37,10 @@ class PythonAPITestCase(unittest.TestCase): ...@@ -37,10 +37,10 @@ class PythonAPITestCase(unittest.TestCase):
del pyob del pyob
self.assertEqual(grc(s), refcnt) self.assertEqual(grc(s), refcnt)
if is_resource_enabled("refcount"):
# This test is unreliable, because it is possible that code in # This test is unreliable, because it is possible that code in
# unittest changes the refcount of the '42' integer. So, it # unittest changes the refcount of the '42' integer. So, it
# is disabled by default. # is disabled by default.
@requires("refcount")
def test_PyInt_Long(self): def test_PyInt_Long(self):
ref42 = grc(42) ref42 = grc(42)
pythonapi.PyInt_FromLong.restype = py_object pythonapi.PyInt_FromLong.restype = py_object
......
...@@ -5,9 +5,8 @@ def callback_func(arg): ...@@ -5,9 +5,8 @@ def callback_func(arg):
42 // arg 42 // arg
raise ValueError(arg) raise ValueError(arg)
if sys.platform == "win32": @unittest.skipUnless(sys.platform == "win32", 'Windows-specific test')
class call_function_TestCase(unittest.TestCase):
class call_function_TestCase(unittest.TestCase):
# _ctypes.call_function is deprecated and private, but used by # _ctypes.call_function is deprecated and private, but used by
# Gary Bishp's readline module. If we have it, we must test it as well. # Gary Bishp's readline module. If we have it, we must test it as well.
......
import unittest import unittest
from ctypes import * from ctypes import *
from ctypes.test import need_symbol
import _ctypes_test import _ctypes_test
...@@ -131,11 +132,7 @@ class SlicesTestCase(unittest.TestCase): ...@@ -131,11 +132,7 @@ class SlicesTestCase(unittest.TestCase):
self.assertEqual(p[2:5:-3], s[2:5:-3]) self.assertEqual(p[2:5:-3], s[2:5:-3])
try: @need_symbol('c_wchar')
c_wchar
except NameError:
pass
else:
def test_wchar_ptr(self): def test_wchar_ptr(self):
s = u"abcdefghijklmnopqrstuvwxyz\0" s = u"abcdefghijklmnopqrstuvwxyz\0"
...@@ -163,7 +160,7 @@ class SlicesTestCase(unittest.TestCase): ...@@ -163,7 +160,7 @@ class SlicesTestCase(unittest.TestCase):
elif sizeof(c_wchar) == sizeof(c_long): elif sizeof(c_wchar) == sizeof(c_long):
dll.my_wcsdup.restype = POINTER(c_long) dll.my_wcsdup.restype = POINTER(c_long)
else: else:
return self.skipTest('Pointers to c_wchar are not supported')
res = dll.my_wcsdup(s) res = dll.my_wcsdup(s)
tmpl = range(ord("a"), ord("z")+1) tmpl = range(ord("a"), ord("z")+1)
self.assertEqual(res[:len(s)-1], tmpl) self.assertEqual(res[:len(s)-1], tmpl)
......
import unittest import unittest
from ctypes import * from ctypes import *
from ctypes.test import need_symbol
from test import test_support from test import test_support
class StringArrayTestCase(unittest.TestCase): class StringArrayTestCase(unittest.TestCase):
...@@ -60,12 +61,8 @@ class StringArrayTestCase(unittest.TestCase): ...@@ -60,12 +61,8 @@ class StringArrayTestCase(unittest.TestCase):
## print BUF.from_param(c_char_p("python")) ## print BUF.from_param(c_char_p("python"))
## print BUF.from_param(BUF(*"pyth")) ## print BUF.from_param(BUF(*"pyth"))
try: @need_symbol('c_wchar')
c_wchar class WStringArrayTestCase(unittest.TestCase):
except NameError:
pass
else:
class WStringArrayTestCase(unittest.TestCase):
def test(self): def test(self):
BUF = c_wchar * 4 BUF = c_wchar * 4
...@@ -82,7 +79,8 @@ else: ...@@ -82,7 +79,8 @@ else:
self.assertEqual(buf.value, u"xZCD") self.assertEqual(buf.value, u"xZCD")
class StringTestCase(unittest.TestCase): class StringTestCase(unittest.TestCase):
def XX_test_basic_strings(self): @unittest.skip('test disabled')
def test_basic_strings(self):
cs = c_string("abcdef") cs = c_string("abcdef")
# Cannot call len on a c_string any longer # Cannot call len on a c_string any longer
...@@ -108,7 +106,8 @@ class StringTestCase(unittest.TestCase): ...@@ -108,7 +106,8 @@ class StringTestCase(unittest.TestCase):
self.assertRaises(TypeError, c_string, u"123") self.assertRaises(TypeError, c_string, u"123")
def XX_test_sized_strings(self): @unittest.skip('test disabled')
def test_sized_strings(self):
# New in releases later than 0.4.0: # New in releases later than 0.4.0:
self.assertRaises(TypeError, c_string, None) self.assertRaises(TypeError, c_string, None)
...@@ -125,7 +124,8 @@ class StringTestCase(unittest.TestCase): ...@@ -125,7 +124,8 @@ class StringTestCase(unittest.TestCase):
self.assertEqual(c_string(2).raw[-1], "\000") self.assertEqual(c_string(2).raw[-1], "\000")
self.assertEqual(len(c_string(2).raw), 2) self.assertEqual(len(c_string(2).raw), 2)
def XX_test_initialized_strings(self): @unittest.skip('test disabled')
def test_initialized_strings(self):
self.assertEqual(c_string("ab", 4).raw[:2], "ab") self.assertEqual(c_string("ab", 4).raw[:2], "ab")
self.assertEqual(c_string("ab", 4).raw[:2:], "ab") self.assertEqual(c_string("ab", 4).raw[:2:], "ab")
...@@ -134,7 +134,8 @@ class StringTestCase(unittest.TestCase): ...@@ -134,7 +134,8 @@ class StringTestCase(unittest.TestCase):
self.assertEqual(c_string("ab", 4).raw[-1], "\000") self.assertEqual(c_string("ab", 4).raw[-1], "\000")
self.assertEqual(c_string("ab", 2).raw, "a\000") self.assertEqual(c_string("ab", 2).raw, "a\000")
def XX_test_toolong(self): @unittest.skip('test disabled')
def test_toolong(self):
cs = c_string("abcdef") cs = c_string("abcdef")
# Much too long string: # Much too long string:
self.assertRaises(ValueError, setattr, cs, "value", "123456789012345") self.assertRaises(ValueError, setattr, cs, "value", "123456789012345")
...@@ -142,22 +143,20 @@ class StringTestCase(unittest.TestCase): ...@@ -142,22 +143,20 @@ class StringTestCase(unittest.TestCase):
# One char too long values: # One char too long values:
self.assertRaises(ValueError, setattr, cs, "value", "1234567") self.assertRaises(ValueError, setattr, cs, "value", "1234567")
## def test_perf(self): @unittest.skip('test disabled')
## check_perf() def test_perf(self):
check_perf()
try: @need_symbol('c_wchar')
c_wchar class WStringTestCase(unittest.TestCase):
except NameError:
pass
else:
class WStringTestCase(unittest.TestCase):
def test_wchar(self): def test_wchar(self):
c_wchar(u"x") c_wchar(u"x")
repr(byref(c_wchar(u"x"))) repr(byref(c_wchar(u"x")))
c_wchar("x") c_wchar("x")
def X_test_basic_wstrings(self): @unittest.skip('test disabled')
def test_basic_wstrings(self):
cs = c_wstring(u"abcdef") cs = c_wstring(u"abcdef")
# XXX This behaviour is about to change: # XXX This behaviour is about to change:
...@@ -183,7 +182,8 @@ else: ...@@ -183,7 +182,8 @@ else:
self.assertRaises(TypeError, c_wstring, "123") self.assertRaises(TypeError, c_wstring, "123")
self.assertRaises(ValueError, c_wstring, 0) self.assertRaises(ValueError, c_wstring, 0)
def X_test_toolong(self): @unittest.skip('test disabled')
def test_toolong(self):
cs = c_wstring(u"abcdef") cs = c_wstring(u"abcdef")
# Much too long string: # Much too long string:
self.assertRaises(ValueError, setattr, cs, "value", u"123456789012345") self.assertRaises(ValueError, setattr, cs, "value", u"123456789012345")
......
import unittest import unittest
from ctypes import * from ctypes import *
from ctypes.test import need_symbol
from struct import calcsize from struct import calcsize
import _testcapi import _testcapi
...@@ -291,12 +292,8 @@ class StructureTestCase(unittest.TestCase): ...@@ -291,12 +292,8 @@ class StructureTestCase(unittest.TestCase):
self.assertEqual(p.phone.number, "5678") self.assertEqual(p.phone.number, "5678")
self.assertEqual(p.age, 5) self.assertEqual(p.age, 5)
@need_symbol('c_wchar')
def test_structures_with_wchar(self): def test_structures_with_wchar(self):
try:
c_wchar
except NameError:
return # no unicode
class PersonW(Structure): class PersonW(Structure):
_fields_ = [("name", c_wchar * 12), _fields_ = [("name", c_wchar * 12),
("age", c_int)] ("age", c_int)]
...@@ -360,14 +357,14 @@ class StructureTestCase(unittest.TestCase): ...@@ -360,14 +357,14 @@ class StructureTestCase(unittest.TestCase):
except Exception, detail: except Exception, detail:
return detail.__class__, str(detail) return detail.__class__, str(detail)
@unittest.skip('test disabled')
## def test_subclass_creation(self): def test_subclass_creation(self):
## meta = type(Structure) meta = type(Structure)
## # same as 'class X(Structure): pass' # same as 'class X(Structure): pass'
## # fails, since we need either a _fields_ or a _abstract_ attribute # fails, since we need either a _fields_ or a _abstract_ attribute
## cls, msg = self.get_except(meta, "X", (Structure,), {}) cls, msg = self.get_except(meta, "X", (Structure,), {})
## self.assertEqual((cls, msg), self.assertEqual((cls, msg),
## (AttributeError, "class must define a '_fields_' attribute")) (AttributeError, "class must define a '_fields_' attribute"))
def test_abstract_class(self): def test_abstract_class(self):
class X(Structure): class X(Structure):
......
# coding: latin-1 # coding: latin-1
import unittest import unittest
import ctypes import ctypes
from ctypes.test import need_symbol
import _ctypes_test
try: @need_symbol('c_wchar')
ctypes.c_wchar class UnicodeTestCase(unittest.TestCase):
except AttributeError: @classmethod
pass def setUpClass(cls):
else:
import _ctypes_test
dll = ctypes.CDLL(_ctypes_test.__file__) dll = ctypes.CDLL(_ctypes_test.__file__)
wcslen = dll.my_wcslen cls.wcslen = dll.my_wcslen
wcslen.argtypes = [ctypes.c_wchar_p] cls.wcslen.argtypes = [ctypes.c_wchar_p]
class UnicodeTestCase(unittest.TestCase):
def setUp(self): def setUp(self):
self.prev_conv_mode = ctypes.set_conversion_mode("ascii", "strict") self.prev_conv_mode = ctypes.set_conversion_mode("ascii", "strict")
...@@ -21,6 +18,7 @@ else: ...@@ -21,6 +18,7 @@ else:
ctypes.set_conversion_mode(*self.prev_conv_mode) ctypes.set_conversion_mode(*self.prev_conv_mode)
def test_ascii_strict(self): def test_ascii_strict(self):
wcslen = self.wcslen
ctypes.set_conversion_mode("ascii", "strict") ctypes.set_conversion_mode("ascii", "strict")
# no conversions take place with unicode arguments # no conversions take place with unicode arguments
self.assertEqual(wcslen(u"abc"), 3) self.assertEqual(wcslen(u"abc"), 3)
...@@ -30,6 +28,7 @@ else: ...@@ -30,6 +28,7 @@ else:
self.assertRaises(ctypes.ArgumentError, wcslen, "ab") self.assertRaises(ctypes.ArgumentError, wcslen, "ab")
def test_ascii_replace(self): def test_ascii_replace(self):
wcslen = self.wcslen
ctypes.set_conversion_mode("ascii", "replace") ctypes.set_conversion_mode("ascii", "replace")
self.assertEqual(wcslen(u"abc"), 3) self.assertEqual(wcslen(u"abc"), 3)
self.assertEqual(wcslen(u"ab\u2070"), 3) self.assertEqual(wcslen(u"ab\u2070"), 3)
...@@ -37,6 +36,7 @@ else: ...@@ -37,6 +36,7 @@ else:
self.assertEqual(wcslen("ab"), 3) self.assertEqual(wcslen("ab"), 3)
def test_ascii_ignore(self): def test_ascii_ignore(self):
wcslen = self.wcslen
ctypes.set_conversion_mode("ascii", "ignore") ctypes.set_conversion_mode("ascii", "ignore")
self.assertEqual(wcslen(u"abc"), 3) self.assertEqual(wcslen(u"abc"), 3)
self.assertEqual(wcslen(u"ab\u2070"), 3) self.assertEqual(wcslen(u"ab\u2070"), 3)
...@@ -45,6 +45,7 @@ else: ...@@ -45,6 +45,7 @@ else:
self.assertEqual(wcslen(""), 0) self.assertEqual(wcslen(""), 0)
def test_latin1_strict(self): def test_latin1_strict(self):
wcslen = self.wcslen
ctypes.set_conversion_mode("latin-1", "strict") ctypes.set_conversion_mode("latin-1", "strict")
self.assertEqual(wcslen(u"abc"), 3) self.assertEqual(wcslen(u"abc"), 3)
self.assertEqual(wcslen(u"ab\u2070"), 3) self.assertEqual(wcslen(u"ab\u2070"), 3)
...@@ -73,33 +74,41 @@ else: ...@@ -73,33 +74,41 @@ else:
self.assertEqual(buf[::2], u"a\0\0") self.assertEqual(buf[::2], u"a\0\0")
self.assertEqual(buf[6:5:-1], u"") self.assertEqual(buf[6:5:-1], u"")
import _ctypes_test @need_symbol('c_wchar')
func = ctypes.CDLL(_ctypes_test.__file__)._testfunc_p_p class StringTestCase(UnicodeTestCase):
@classmethod
def setUpClass(cls):
super(StringTestCase, cls).setUpClass()
cls.func = ctypes.CDLL(_ctypes_test.__file__)._testfunc_p_p
class StringTestCase(UnicodeTestCase):
def setUp(self): def setUp(self):
func = self.func
self.prev_conv_mode = ctypes.set_conversion_mode("ascii", "strict") self.prev_conv_mode = ctypes.set_conversion_mode("ascii", "strict")
func.argtypes = [ctypes.c_char_p] func.argtypes = [ctypes.c_char_p]
func.restype = ctypes.c_char_p func.restype = ctypes.c_char_p
def tearDown(self): def tearDown(self):
func = self.func
ctypes.set_conversion_mode(*self.prev_conv_mode) ctypes.set_conversion_mode(*self.prev_conv_mode)
func.argtypes = None func.argtypes = None
func.restype = ctypes.c_int func.restype = ctypes.c_int
def test_ascii_replace(self): def test_ascii_replace(self):
func = self.func
ctypes.set_conversion_mode("ascii", "strict") ctypes.set_conversion_mode("ascii", "strict")
self.assertEqual(func("abc"), "abc") self.assertEqual(func("abc"), "abc")
self.assertEqual(func(u"abc"), "abc") self.assertEqual(func(u"abc"), "abc")
self.assertRaises(ctypes.ArgumentError, func, u"ab") self.assertRaises(ctypes.ArgumentError, func, u"ab")
def test_ascii_ignore(self): def test_ascii_ignore(self):
func = self.func
ctypes.set_conversion_mode("ascii", "ignore") ctypes.set_conversion_mode("ascii", "ignore")
self.assertEqual(func("abc"), "abc") self.assertEqual(func("abc"), "abc")
self.assertEqual(func(u"abc"), "abc") self.assertEqual(func(u"abc"), "abc")
self.assertEqual(func(u""), "") self.assertEqual(func(u""), "")
def test_ascii_replace(self): def test_ascii_replace(self):
func = self.func
ctypes.set_conversion_mode("ascii", "replace") ctypes.set_conversion_mode("ascii", "replace")
self.assertEqual(func("abc"), "abc") self.assertEqual(func("abc"), "abc")
self.assertEqual(func(u"abc"), "abc") self.assertEqual(func(u"abc"), "abc")
......
...@@ -3,6 +3,7 @@ A testcase which accesses *values* in a dll. ...@@ -3,6 +3,7 @@ A testcase which accesses *values* in a dll.
""" """
import unittest import unittest
import sys
from ctypes import * from ctypes import *
import _ctypes_test import _ctypes_test
...@@ -21,7 +22,8 @@ class ValuesTestCase(unittest.TestCase): ...@@ -21,7 +22,8 @@ class ValuesTestCase(unittest.TestCase):
ctdll = CDLL(_ctypes_test.__file__) ctdll = CDLL(_ctypes_test.__file__)
self.assertRaises(ValueError, c_int.in_dll, ctdll, "Undefined_Symbol") self.assertRaises(ValueError, c_int.in_dll, ctdll, "Undefined_Symbol")
class Win_ValuesTestCase(unittest.TestCase): @unittest.skipUnless(sys.platform == 'win32', 'Windows-specific test')
class Win_ValuesTestCase(unittest.TestCase):
"""This test only works when python itself is a dll/shared library""" """This test only works when python itself is a dll/shared library"""
def test_optimizeflag(self): def test_optimizeflag(self):
...@@ -32,7 +34,7 @@ class ValuesTestCase(unittest.TestCase): ...@@ -32,7 +34,7 @@ class ValuesTestCase(unittest.TestCase):
# if not given, it is 0 and __debug__ is 1. # if not given, it is 0 and __debug__ is 1.
# If -O is given, the flag is 1, for -OO it is 2. # If -O is given, the flag is 1, for -OO it is 2.
# docstrings are also removed in the latter case. # docstrings are also removed in the latter case.
opt = c_int.in_dll(pydll, "Py_OptimizeFlag").value opt = c_int.in_dll(pythonapi, "Py_OptimizeFlag").value
if __debug__: if __debug__:
self.assertEqual(opt, 0) self.assertEqual(opt, 0)
elif ValuesTestCase.__doc__ is not None: elif ValuesTestCase.__doc__ is not None:
...@@ -55,7 +57,7 @@ class ValuesTestCase(unittest.TestCase): ...@@ -55,7 +57,7 @@ class ValuesTestCase(unittest.TestCase):
("size", c_int)] ("size", c_int)]
FrozenTable = POINTER(struct_frozen) FrozenTable = POINTER(struct_frozen)
ft = FrozenTable.in_dll(pydll, "PyImport_FrozenModules") ft = FrozenTable.in_dll(pythonapi, "PyImport_FrozenModules")
# ft is a pointer to the struct_frozen entries: # ft is a pointer to the struct_frozen entries:
items = [] items = []
for entry in ft: for entry in ft:
...@@ -65,18 +67,18 @@ class ValuesTestCase(unittest.TestCase): ...@@ -65,18 +67,18 @@ class ValuesTestCase(unittest.TestCase):
if entry.name is None: if entry.name is None:
break break
items.append((entry.name, entry.size)) items.append((entry.name, entry.size))
import sys
if sys.version_info[:2] >= (2, 3): expected = [("__hello__", 104),
expected = [("__hello__", 104), ("__phello__", -104), ("__phello__.spam", 104)] ("__phello__", -104),
else: ("__phello__.spam", 104)]
expected = [("__hello__", 100), ("__phello__", -100), ("__phello__.spam", 100)]
self.assertEqual(items, expected) self.assertEqual(items, expected)
from ctypes import _pointer_type_cache from ctypes import _pointer_type_cache
del _pointer_type_cache[struct_frozen] del _pointer_type_cache[struct_frozen]
def test_undefined(self): def test_undefined(self):
self.assertRaises(ValueError, c_int.in_dll, pydll, "Undefined_Symbol") self.assertRaises(ValueError, c_int.in_dll, pythonapi,
"Undefined_Symbol")
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()
# Windows specific tests # Windows specific tests
from ctypes import * from ctypes import *
from ctypes.test import is_resource_enabled from ctypes.test import requires
import unittest, sys import unittest, sys
from test import test_support as support from test import test_support as support
import _ctypes_test import _ctypes_test
if sys.platform == "win32" and sizeof(c_void_p) == sizeof(c_int): # Only windows 32-bit has different calling conventions.
# Only windows 32-bit has different calling conventions. @unittest.skipUnless(sys.platform == "win32", 'Windows-specific test')
@unittest.skipUnless(sizeof(c_void_p) == sizeof(c_int),
class WindowsTestCase(unittest.TestCase): "sizeof c_void_p and c_int differ")
class WindowsTestCase(unittest.TestCase):
def test_callconv_1(self): def test_callconv_1(self):
# Testing stdcall function # Testing stdcall function
IsWindow = windll.user32.IsWindow IsWindow = windll.user32.IsWindow
# ValueError: Procedure probably called with not enough arguments (4 bytes missing) # ValueError: Procedure probably called with not enough arguments
# (4 bytes missing)
self.assertRaises(ValueError, IsWindow) self.assertRaises(ValueError, IsWindow)
# This one should succeed... # This one should succeed...
self.assertEqual(0, IsWindow(0)) self.assertEqual(0, IsWindow(0))
# ValueError: Procedure probably called with too many arguments (8 bytes in excess) # ValueError: Procedure probably called with too many arguments
# (8 bytes in excess)
self.assertRaises(ValueError, IsWindow, 0, 0, 0) self.assertRaises(ValueError, IsWindow, 0, 0, 0)
def test_callconv_2(self): def test_callconv_2(self):
...@@ -29,14 +32,13 @@ if sys.platform == "win32" and sizeof(c_void_p) == sizeof(c_int): ...@@ -29,14 +32,13 @@ if sys.platform == "win32" and sizeof(c_void_p) == sizeof(c_int):
IsWindow = cdll.user32.IsWindow IsWindow = cdll.user32.IsWindow
# ValueError: Procedure called with not enough arguments (4 bytes missing) # ValueError: Procedure called with not enough arguments
# or wrong calling convention # (4 bytes missing) or wrong calling convention
self.assertRaises(ValueError, IsWindow, None) self.assertRaises(ValueError, IsWindow, None)
if sys.platform == "win32": @unittest.skipUnless(sys.platform == "win32", 'Windows-specific test')
class FunctionCallTestCase(unittest.TestCase): class FunctionCallTestCase(unittest.TestCase):
@requires("SEH")
if is_resource_enabled("SEH"):
def test_SEH(self): def test_SEH(self):
# Call functions with invalid arguments, and make sure # Call functions with invalid arguments, and make sure
# that access violations are trapped and raise an # that access violations are trapped and raise an
...@@ -47,7 +49,8 @@ if sys.platform == "win32": ...@@ -47,7 +49,8 @@ if sys.platform == "win32":
# This is a special case on win32 x64 # This is a special case on win32 x64
windll.user32.GetDesktopWindow() windll.user32.GetDesktopWindow()
class TestWintypes(unittest.TestCase): @unittest.skipUnless(sys.platform == "win32", 'Windows-specific test')
class TestWintypes(unittest.TestCase):
def test_HWND(self): def test_HWND(self):
from ctypes import wintypes from ctypes import wintypes
self.assertEqual(sizeof(wintypes.HWND), sizeof(c_void_p)) self.assertEqual(sizeof(wintypes.HWND), sizeof(c_void_p))
...@@ -71,7 +74,6 @@ if sys.platform == "win32": ...@@ -71,7 +74,6 @@ if sys.platform == "win32":
self.assertEqual(ex.details, ("details",)) self.assertEqual(ex.details, ("details",))
class Structures(unittest.TestCase): class Structures(unittest.TestCase):
def test_struct_by_value(self): def test_struct_by_value(self):
class POINT(Structure): class POINT(Structure):
_fields_ = [("x", c_long), _fields_ = [("x", c_long),
......
import sys import sys
import unittest import unittest
if not sys.platform.startswith('win'):
raise unittest.SkipTest('Windows-only test')
from ctypes import * from ctypes import *
from ctypes import wintypes
@unittest.skipUnless(sys.platform.startswith('win'), 'Windows-only test')
class WinTypesTest(unittest.TestCase): class WinTypesTest(unittest.TestCase):
def test_variant_bool(self): def test_variant_bool(self):
from ctypes import wintypes
# reads 16-bits from memory, anything non-zero is True # reads 16-bits from memory, anything non-zero is True
for true_value in (1, 32767, 32768, 65535, 65537): for true_value in (1, 32767, 32768, 65535, 65537):
true = POINTER(c_int16)(c_int16(true_value)) true = POINTER(c_int16)(c_int16(true_value))
......
...@@ -67,6 +67,9 @@ IDLE ...@@ -67,6 +67,9 @@ IDLE
Tests Tests
----- -----
- Issue #19493: Refactored the ctypes test package to skip tests explicitly
rather than silently.
- Issue #18492: All resources are now allowed when tests are not run by - Issue #18492: All resources are now allowed when tests are not run by
regrtest.py. regrtest.py.
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment