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