diff --git a/Lib/test/test_ctypes/test_anon.py b/Lib/test/test_ctypes/test_anon.py index 704f7a3d38a..b36397b510f 100644 --- a/Lib/test/test_ctypes/test_anon.py +++ b/Lib/test/test_ctypes/test_anon.py @@ -2,6 +2,7 @@ import unittest import test.support from ctypes import c_int, Union, Structure, sizeof + class AnonTest(unittest.TestCase): def test_anon(self): @@ -69,5 +70,6 @@ class AnonTest(unittest.TestCase): self.assertEqual(Y._.offset, sizeof(c_int)) self.assertEqual(Y.y.offset, sizeof(c_int) * 2) + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_ctypes/test_array_in_pointer.py b/Lib/test/test_ctypes/test_array_in_pointer.py index a149aa9463f..b7c96b2fa49 100644 --- a/Lib/test/test_ctypes/test_array_in_pointer.py +++ b/Lib/test/test_ctypes/test_array_in_pointer.py @@ -1,21 +1,24 @@ +import binascii +import re import unittest from ctypes import c_byte, Structure, POINTER, cast -from binascii import hexlify -import re + def dump(obj): # helper function to dump memory contents in hex, with a hyphen # between the bytes. - h = hexlify(memoryview(obj)).decode() + h = binascii.hexlify(memoryview(obj)).decode() return re.sub(r"(..)", r"\1-", h)[:-1] class Value(Structure): _fields_ = [("val", c_byte)] + class Container(Structure): _fields_ = [("pvalues", POINTER(Value))] + class Test(unittest.TestCase): def test(self): # create an array of 4 values @@ -60,5 +63,6 @@ class Test(unittest.TestCase): ([1, 2, 3, 4], "01-02-03-04") ) + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_ctypes/test_as_parameter.py b/Lib/test/test_ctypes/test_as_parameter.py index 33b7bd3fade..e842d526c53 100644 --- a/Lib/test/test_ctypes/test_as_parameter.py +++ b/Lib/test/test_ctypes/test_as_parameter.py @@ -16,9 +16,11 @@ except AttributeError: # fake to enable this test on Linux CALLBACK_FUNCTYPE = CFUNCTYPE + class POINT(Structure): _fields_ = [("x", c_int), ("y", c_int)] + class BasicWrapTestCase(unittest.TestCase): def wrap(self, param): return param @@ -71,8 +73,6 @@ class BasicWrapTestCase(unittest.TestCase): f(self.wrap(2**18), self.wrap(cb)) self.assertEqual(args, expected) - ################################################################ - def test_callbacks(self): f = dll._testfunc_callback_i_if f.restype = c_int @@ -194,8 +194,6 @@ class BasicWrapTestCase(unittest.TestCase): (9*2, 8*3, 7*4, 6*5, 5*6, 4*7, 3*8, 2*9)) def test_recursive_as_param(self): - from ctypes import c_int - class A(object): pass @@ -205,8 +203,6 @@ class BasicWrapTestCase(unittest.TestCase): c_int.from_param(a) -#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - class AsParamWrapper(object): def __init__(self, param): self._as_parameter_ = param @@ -214,7 +210,6 @@ class AsParamWrapper(object): class AsParamWrapperTestCase(BasicWrapTestCase): wrap = AsParamWrapper -#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ class AsParamPropertyWrapper(object): def __init__(self, param): @@ -227,7 +222,6 @@ class AsParamPropertyWrapper(object): class AsParamPropertyWrapperTestCase(BasicWrapTestCase): wrap = AsParamPropertyWrapper -#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if __name__ == '__main__': unittest.main() diff --git a/Lib/test/test_ctypes/test_bitfields.py b/Lib/test/test_ctypes/test_bitfields.py index 9ffa634dbf7..d8eb2d668a6 100644 --- a/Lib/test/test_ctypes/test_bitfields.py +++ b/Lib/test/test_ctypes/test_bitfields.py @@ -1,13 +1,13 @@ +import _ctypes_test +import os +import unittest from ctypes import (CDLL, Structure, sizeof, POINTER, byref, alignment, LittleEndianStructure, BigEndianStructure, c_byte, c_ubyte, c_char, c_char_p, c_void_p, c_wchar, c_uint32, c_uint64, c_short, c_ushort, c_int, c_uint, c_long, c_ulong, c_longlong, c_ulonglong) from test import support -import unittest -import os -import _ctypes_test class BITS(Structure): _fields_ = [("A", c_int, 1), @@ -56,6 +56,7 @@ class C_Test(unittest.TestCase): setattr(b, name, i) self.assertEqual(getattr(b, name), func(byref(b), name.encode('ascii'))) + 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) int_types = unsigned_int_types + signed_int_types @@ -117,7 +118,6 @@ class BitFieldTest(unittest.TestCase): x.a, x.b = 0, -1 self.assertEqual((c_typ, x.a, x.b, x.c), (c_typ, 0, 7, 0)) - def fail_fields(self, *fields): return self.get_except(type(Structure), "X", (), {"_fields_": fields}) @@ -194,7 +194,6 @@ class BitFieldTest(unittest.TestCase): self.assertEqual(X.b.offset, sizeof(c_short)*1) self.assertEqual(X.c.offset, sizeof(c_short)*2) - def get_except(self, func, *args, **kw): try: func(*args, **kw) @@ -291,5 +290,6 @@ class BitFieldTest(unittest.TestCase): x.c = 2 self.assertEqual(b, b'\xab\xcd\xef\x12') + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_ctypes/test_buffers.py b/Lib/test/test_ctypes/test_buffers.py index e446f9e85f9..468f41eb7cf 100644 --- a/Lib/test/test_ctypes/test_buffers.py +++ b/Lib/test/test_ctypes/test_buffers.py @@ -1,9 +1,9 @@ +import unittest from ctypes import (create_string_buffer, create_unicode_buffer, sizeof, c_char, c_wchar) -import unittest + class StringBufferTestCase(unittest.TestCase): - def test_buffer(self): b = create_string_buffer(32) self.assertEqual(len(b), 32) diff --git a/Lib/test/test_ctypes/test_bytes.py b/Lib/test/test_ctypes/test_bytes.py index 3538ed7d719..fa11e1bbd49 100644 --- a/Lib/test/test_ctypes/test_bytes.py +++ b/Lib/test/test_ctypes/test_bytes.py @@ -1,8 +1,10 @@ """Test where byte objects are accepted""" import sys import unittest +from _ctypes import _SimpleCData from ctypes import Structure, c_char, c_char_p, c_wchar, c_wchar_p + class BytesTest(unittest.TestCase): def test_c_char(self): x = c_char(b"x") @@ -55,7 +57,6 @@ class BytesTest(unittest.TestCase): @unittest.skipUnless(sys.platform == "win32", 'Windows-specific test') def test_BSTR(self): - from _ctypes import _SimpleCData class BSTR(_SimpleCData): _type_ = "X" diff --git a/Lib/test/test_ctypes/test_byteswap.py b/Lib/test/test_ctypes/test_byteswap.py index 7507c07d8a8..2986e8a177a 100644 --- a/Lib/test/test_ctypes/test_byteswap.py +++ b/Lib/test/test_ctypes/test_byteswap.py @@ -1,6 +1,9 @@ -import sys, unittest, struct, math, ctypes -from binascii import hexlify - +import binascii +import ctypes +import math +import struct +import sys +import unittest from ctypes import (Structure, Union, LittleEndianUnion, BigEndianUnion, BigEndianStructure, LittleEndianStructure, POINTER, sizeof, cast, @@ -9,8 +12,10 @@ from ctypes import (Structure, Union, LittleEndianUnion, BigEndianUnion, c_long, c_ulong, c_longlong, c_ulonglong, c_uint32, c_float, c_double) + def bin(s): - return hexlify(memoryview(s)).decode().upper() + return binascii.hexlify(memoryview(s)).decode().upper() + # Each *simple* type that supports different byte orders has an # __ctype_be__ attribute that specifies the same type in BIG ENDIAN @@ -366,5 +371,6 @@ class Test(unittest.TestCase): self.assertEqual(s.point.x, 1) self.assertEqual(s.point.y, 2) + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_ctypes/test_callbacks.py b/Lib/test/test_ctypes/test_callbacks.py index 50c2650cb34..582677b832e 100644 --- a/Lib/test/test_ctypes/test_callbacks.py +++ b/Lib/test/test_ctypes/test_callbacks.py @@ -1,24 +1,25 @@ +import _ctypes_test +import ctypes import functools +import gc +import math import sys import unittest -from test import support - -import ctypes +from _ctypes import CTYPES_MAX_ARGCOUNT from ctypes import (CDLL, cdll, Structure, CFUNCTYPE, ArgumentError, POINTER, sizeof, c_byte, c_ubyte, c_char, c_char_p, c_short, c_ushort, c_int, c_uint, c_long, c_longlong, c_ulonglong, c_ulong, c_float, c_double, c_longdouble, py_object) -from _ctypes import CTYPES_MAX_ARGCOUNT -import _ctypes_test +from ctypes.util import find_library +from test import support class Callbacks(unittest.TestCase): functype = CFUNCTYPE ## def tearDown(self): -## import gc ## gc.collect() def callback(self, *args): @@ -81,7 +82,6 @@ class Callbacks(unittest.TestCase): def test_float(self): # only almost equal: double -> float -> double - import math self.check_type(c_float, math.e) self.check_type(c_float, -math.e) @@ -138,7 +138,6 @@ class Callbacks(unittest.TestCase): def __init__(self): self.v = proto(self.func) - import gc for i in range(32): X() gc.collect() @@ -147,7 +146,6 @@ class Callbacks(unittest.TestCase): self.assertEqual(len(live), 0) def test_issue12483(self): - import gc class Nasty: def __del__(self): gc.collect() @@ -172,8 +170,6 @@ if hasattr(ctypes, 'WINFUNCTYPE'): functype = ctypes.WINFUNCTYPE -################################################################ - class SampleCallbacksTestCase(unittest.TestCase): def test_integrate(self): @@ -197,7 +193,6 @@ class SampleCallbacksTestCase(unittest.TestCase): self.assertLess(diff, 0.01, "%s not less than 0.01" % diff) def test_issue_8959_a(self): - from ctypes.util import find_library libc_path = find_library("c") if not libc_path: self.skipTest('could not find libc') diff --git a/Lib/test/test_ctypes/test_cast.py b/Lib/test/test_ctypes/test_cast.py index abff120d8b0..604f44f03d6 100644 --- a/Lib/test/test_ctypes/test_cast.py +++ b/Lib/test/test_ctypes/test_cast.py @@ -4,8 +4,8 @@ from ctypes import (Structure, Union, POINTER, cast, sizeof, addressof, c_void_p, c_char_p, c_wchar_p, c_byte, c_short, c_int) -class Test(unittest.TestCase): +class Test(unittest.TestCase): def test_array2pointer(self): array = (c_int * 3)(42, 17, 2) @@ -80,7 +80,7 @@ class Test(unittest.TestCase): def test_wchar_p(self): s = c_wchar_p("hiho") self.assertEqual(cast(cast(s, c_void_p), c_wchar_p).value, - "hiho") + "hiho") def test_bad_type_arg(self): # The type argument must be a ctypes pointer type. @@ -95,5 +95,6 @@ class Test(unittest.TestCase): _fields_ = [("a", c_int)] self.assertRaises(TypeError, cast, array, MyUnion) + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_ctypes/test_cfuncs.py b/Lib/test/test_ctypes/test_cfuncs.py index 6969aed8189..6ff0878a35d 100644 --- a/Lib/test/test_ctypes/test_cfuncs.py +++ b/Lib/test/test_ctypes/test_cfuncs.py @@ -1,11 +1,11 @@ -import unittest +import _ctypes_test import ctypes +import unittest from ctypes import (CDLL, c_byte, c_ubyte, c_char, c_short, c_ushort, c_int, c_uint, c_long, c_ulong, c_longlong, c_ulonglong, c_float, c_double, c_longdouble) -import _ctypes_test class CFunctions(unittest.TestCase): @@ -190,6 +190,7 @@ class CFunctions(unittest.TestCase): self.assertEqual(self._dll.tv_i(-42), None) self.assertEqual(self.S(), -42) + # The following repeats the above tests with stdcall functions (where # they are available) if hasattr(ctypes, 'WinDLL'): diff --git a/Lib/test/test_ctypes/test_checkretval.py b/Lib/test/test_ctypes/test_checkretval.py index 176102d5a89..5dc9e25aa38 100644 --- a/Lib/test/test_ctypes/test_checkretval.py +++ b/Lib/test/test_ctypes/test_checkretval.py @@ -1,3 +1,4 @@ +import _ctypes_test import ctypes import unittest from ctypes import CDLL, c_int @@ -11,10 +12,7 @@ class CHECKED(c_int): class Test(unittest.TestCase): - def test_checkretval(self): - - import _ctypes_test dll = CDLL(_ctypes_test.__file__) self.assertEqual(42, dll._testfunc_p_p(42)) @@ -34,6 +32,5 @@ class Test(unittest.TestCase): self.assertRaises(OSError, oleaut32.CreateTypeLib2, 0, None, None) - if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_ctypes/test_errno.py b/Lib/test/test_ctypes/test_errno.py index 3376322299d..65d99c1e492 100644 --- a/Lib/test/test_ctypes/test_errno.py +++ b/Lib/test/test_ctypes/test_errno.py @@ -1,10 +1,12 @@ -import unittest, os, errno -import threading - import ctypes +import errno +import os +import threading +import unittest from ctypes import CDLL, c_int, c_char_p, c_wchar_p, get_errno, set_errno from ctypes.util import find_library + class Test(unittest.TestCase): def test_open(self): libc_name = find_library("c") diff --git a/Lib/test/test_ctypes/test_frombuffer.py b/Lib/test/test_ctypes/test_frombuffer.py index e3e12673878..d4e161f864d 100644 --- a/Lib/test/test_ctypes/test_frombuffer.py +++ b/Lib/test/test_ctypes/test_frombuffer.py @@ -1,7 +1,10 @@ import array import gc import unittest -from ctypes import Structure, Union, Array, sizeof, c_char, c_int +from ctypes import (Structure, Union, Array, sizeof, + _Pointer, _SimpleCData, _CFuncPtr, + c_char, c_int) + class X(Structure): _fields_ = [("c_int", c_int)] @@ -9,6 +12,7 @@ class X(Structure): def __init__(self): self._init_called = True + class Test(unittest.TestCase): def test_from_buffer(self): a = array.array("i", range(16)) @@ -121,8 +125,6 @@ class Test(unittest.TestCase): (c_int * 1).from_buffer_copy(a, 16 * sizeof(c_int)) def test_abstract(self): - from ctypes import _Pointer, _SimpleCData, _CFuncPtr - self.assertRaises(TypeError, Array.from_buffer, bytearray(10)) self.assertRaises(TypeError, Structure.from_buffer, bytearray(10)) self.assertRaises(TypeError, Union.from_buffer, bytearray(10)) @@ -137,5 +139,6 @@ class Test(unittest.TestCase): self.assertRaises(TypeError, _Pointer.from_buffer_copy, b"123") self.assertRaises(TypeError, _SimpleCData.from_buffer_copy, b"123") + if __name__ == '__main__': unittest.main() diff --git a/Lib/test/test_ctypes/test_funcptr.py b/Lib/test/test_ctypes/test_funcptr.py index 72684d6d1cd..0ea3f3581bb 100644 --- a/Lib/test/test_ctypes/test_funcptr.py +++ b/Lib/test/test_ctypes/test_funcptr.py @@ -1,9 +1,10 @@ import _ctypes_test import ctypes import unittest -from ctypes import (CDLL, Structure, CFUNCTYPE, sizeof, +from ctypes import (CDLL, Structure, CFUNCTYPE, sizeof, _CFuncPtr, c_void_p, c_char_p, c_char, c_int, c_uint, c_long) + try: WINFUNCTYPE = ctypes.WINFUNCTYPE except AttributeError: @@ -127,8 +128,6 @@ class CFuncPtrTestCase(unittest.TestCase): self.assertEqual(strtok(None, b"\n"), None) def test_abstract(self): - from ctypes import _CFuncPtr - self.assertRaises(TypeError, _CFuncPtr, 13, "name", 42, "iid") diff --git a/Lib/test/test_ctypes/test_functions.py b/Lib/test/test_ctypes/test_functions.py index 7979f0e36b3..f8591463c18 100644 --- a/Lib/test/test_ctypes/test_functions.py +++ b/Lib/test/test_ctypes/test_functions.py @@ -1,17 +1,14 @@ -""" -Here is probably the place to write the docs, since the test-cases -show how the type behave. - -Later... -""" - +import _ctypes_test import ctypes +import sys +import unittest from ctypes import (CDLL, Structure, Array, CFUNCTYPE, byref, POINTER, pointer, ArgumentError, c_char, c_wchar, c_byte, c_char_p, c_short, c_int, c_long, c_longlong, c_float, c_double, c_longdouble) -import sys, unittest +from _ctypes import _Pointer, _SimpleCData + try: WINFUNCTYPE = ctypes.WINFUNCTYPE @@ -19,16 +16,20 @@ except AttributeError: # fake to enable this test on Linux WINFUNCTYPE = CFUNCTYPE -import _ctypes_test dll = CDLL(_ctypes_test.__file__) if sys.platform == "win32": windll = ctypes.WinDLL(_ctypes_test.__file__) + class POINT(Structure): _fields_ = [("x", c_int), ("y", c_int)] + + class RECT(Structure): _fields_ = [("left", c_int), ("top", c_int), ("right", c_int), ("bottom", c_int)] + + class FunctionTestCase(unittest.TestCase): def test_mro(self): @@ -44,12 +45,10 @@ class FunctionTestCase(unittest.TestCase): _length_ = 5 _type_ = "i" - from _ctypes import _Pointer with self.assertRaises(TypeError): class X(object, _Pointer): pass - from _ctypes import _SimpleCData with self.assertRaises(TypeError): class X(object, _SimpleCData): _type_ = "i" @@ -407,5 +406,6 @@ class FunctionTestCase(unittest.TestCase): callback = proto(callback) self.assertRaises(ArgumentError, lambda: callback((1, 2, 3, 4), POINT())) + if __name__ == '__main__': unittest.main() diff --git a/Lib/test/test_ctypes/test_incomplete.py b/Lib/test/test_ctypes/test_incomplete.py index 552effaa3db..9f859793d88 100644 --- a/Lib/test/test_ctypes/test_incomplete.py +++ b/Lib/test/test_ctypes/test_incomplete.py @@ -3,13 +3,9 @@ import unittest import warnings from ctypes import Structure, POINTER, pointer, c_char_p -################################################################ -# + # The incomplete pointer example from the tutorial -# - class TestSetPointerType(unittest.TestCase): - def tearDown(self): # to not leak references, we must clean _pointer_type_cache ctypes._reset_cache() @@ -49,7 +45,6 @@ class TestSetPointerType(unittest.TestCase): with self.assertWarns(DeprecationWarning): ctypes.SetPointerType(lpcell, cell) -################################################################ if __name__ == '__main__': unittest.main() diff --git a/Lib/test/test_ctypes/test_internals.py b/Lib/test/test_ctypes/test_internals.py index 06826eb9ebd..763a5e8b0f0 100644 --- a/Lib/test/test_ctypes/test_internals.py +++ b/Lib/test/test_ctypes/test_internals.py @@ -1,7 +1,4 @@ # This tests the internal _objects attribute -import sys -import unittest -from ctypes import Structure, POINTER, c_char_p, c_int # XXX This test must be reviewed for correctness!!! @@ -14,6 +11,11 @@ from ctypes import Structure, POINTER, c_char_p, c_int # # What about pointers? +import sys +import unittest +from ctypes import Structure, POINTER, c_char_p, c_int + + class ObjectsTestCase(unittest.TestCase): def assertSame(self, a, b): self.assertEqual(id(a), id(b)) @@ -96,5 +98,6 @@ class ObjectsTestCase(unittest.TestCase): ##XXX print x.data[0] ##XXX print x.data._objects + if __name__ == '__main__': unittest.main() diff --git a/Lib/test/test_ctypes/test_keeprefs.py b/Lib/test/test_ctypes/test_keeprefs.py index 6fb0628ad3b..f93e3f26769 100644 --- a/Lib/test/test_ctypes/test_keeprefs.py +++ b/Lib/test/test_ctypes/test_keeprefs.py @@ -1,6 +1,8 @@ +import gc import sys import unittest -from ctypes import Structure, POINTER, pointer, c_char_p, c_int +from ctypes import (Structure, POINTER, pointer, _pointer_type_cache, + c_char_p, c_int) class SimpleTestCase(unittest.TestCase): @@ -20,6 +22,7 @@ class SimpleTestCase(unittest.TestCase): x = c_char_p(b"spam") self.assertEqual(x._objects, b"spam") + class StructureTestCase(unittest.TestCase): def test_cint_struct(self): class X(Structure): @@ -66,6 +69,7 @@ class StructureTestCase(unittest.TestCase): r.lr = POINT() self.assertEqual(r._objects, {'0': {}, '1': {}}) + class ArrayTestCase(unittest.TestCase): def test_cint_array(self): INTARR = c_int * 3 @@ -89,12 +93,14 @@ class ArrayTestCase(unittest.TestCase): x.a = ia self.assertEqual(x._objects, {'1': {}}) + class PointerTestCase(unittest.TestCase): def test_p_cint(self): i = c_int(42) x = pointer(i) self.assertEqual(x._objects, {'1': i}) + class DeletePointerTestCase(unittest.TestCase): @unittest.skip('test disabled') def test_X(self): @@ -112,7 +118,6 @@ class DeletePointerTestCase(unittest.TestCase): ## del x ## print "2?", sys.getrefcount(i) ## del i - import gc gc.collect() for i in range(320): c_int(99) @@ -126,6 +131,7 @@ class DeletePointerTestCase(unittest.TestCase): print("+" * 42) print(x._objects) + class PointerToStructure(unittest.TestCase): def test(self): class POINT(Structure): @@ -147,8 +153,8 @@ class PointerToStructure(unittest.TestCase): # to avoid leaking when tests are run several times # clean up the types left in the cache. - from ctypes import _pointer_type_cache del _pointer_type_cache[POINT] + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_ctypes/test_libc.py b/Lib/test/test_ctypes/test_libc.py index 8664529f094..09c76db0bd0 100644 --- a/Lib/test/test_ctypes/test_libc.py +++ b/Lib/test/test_ctypes/test_libc.py @@ -1,10 +1,10 @@ +import _ctypes_test +import math import unittest - from ctypes import (CDLL, CFUNCTYPE, POINTER, create_string_buffer, sizeof, c_void_p, c_char, c_int, c_double, c_size_t) -import _ctypes_test lib = CDLL(_ctypes_test.__file__) @@ -12,12 +12,12 @@ def three_way_cmp(x, y): """Return -1 if x < y, 0 if x == y and 1 if x > y""" return (x > y) - (x < y) + class LibTest(unittest.TestCase): def test_sqrt(self): lib.my_sqrt.argtypes = c_double, lib.my_sqrt.restype = c_double self.assertEqual(lib.my_sqrt(4.0), 2.0) - import math self.assertEqual(lib.my_sqrt(2.0), math.sqrt(2.0)) def test_qsort(self): @@ -32,5 +32,6 @@ class LibTest(unittest.TestCase): lib.my_qsort(chars, len(chars)-1, sizeof(c_char), comparefunc(sort)) self.assertEqual(chars.raw, b" ,,aaaadmmmnpppsss\x00") + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_ctypes/test_loading.py b/Lib/test/test_ctypes/test_loading.py index 0cbfcf01c0c..22db97b818c 100644 --- a/Lib/test/test_ctypes/test_loading.py +++ b/Lib/test/test_ctypes/test_loading.py @@ -1,3 +1,5 @@ +import _ctypes +import _ctypes_test import ctypes import os import shutil @@ -5,13 +7,14 @@ import subprocess import sys import test.support import unittest -from test.support import import_helper, os_helper from ctypes import CDLL, cdll, addressof, c_void_p, c_char_p from ctypes.util import find_library +from test.support import import_helper, os_helper libc_name = None + def setUpModule(): global libc_name if os.name == "nt": @@ -24,6 +27,7 @@ def setUpModule(): if test.support.verbose: print("libc_name is", libc_name) + class LoaderTest(unittest.TestCase): unknowndll = "xxrandomnamexx" @@ -33,7 +37,6 @@ class LoaderTest(unittest.TestCase): test_lib = libc_name else: if os.name == "nt": - import _ctypes_test test_lib = _ctypes_test.__file__ else: self.skipTest('could not find library to load') @@ -83,7 +86,6 @@ class LoaderTest(unittest.TestCase): @unittest.skipUnless(os.name == "nt", 'test specific to Windows') def test_load_ordinal_functions(self): - import _ctypes_test dll = ctypes.WinDLL(_ctypes_test.__file__) # We load the same function both via ordinal and name func_ord = dll[2] @@ -99,14 +101,13 @@ class LoaderTest(unittest.TestCase): @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 # NOT fit into a 32-bit integer. FreeLibrary must be able # to accept this address. # These are tests for https://bugs.python.org/issue1703286 - handle = LoadLibrary("advapi32") - FreeLibrary(handle) + handle = _ctypes.LoadLibrary("advapi32") + _ctypes.FreeLibrary(handle) @unittest.skipUnless(os.name == "nt", 'Windows-specific test') def test_1703286_B(self): @@ -114,7 +115,6 @@ class LoaderTest(unittest.TestCase): # above, the (arbitrarily selected) CloseEventLog function # also has a high address. 'call_function' should accept # addresses so large. - from _ctypes import call_function advapi32 = ctypes.windll.advapi32 # Calling CloseEventLog with a NULL argument should fail, @@ -128,7 +128,7 @@ class LoaderTest(unittest.TestCase): self.assertTrue(proc) # This is the real test: call the function via 'call_function' - self.assertEqual(0, call_function(proc, (None,))) + self.assertEqual(0, _ctypes.call_function(proc, (None,))) @unittest.skipUnless(os.name == "nt", 'test specific to Windows') diff --git a/Lib/test/test_ctypes/test_macholib.py b/Lib/test/test_ctypes/test_macholib.py index bc75f1a05a8..9d906179956 100644 --- a/Lib/test/test_ctypes/test_macholib.py +++ b/Lib/test/test_ctypes/test_macholib.py @@ -1,7 +1,3 @@ -import os -import sys -import unittest - # Bob Ippolito: # # Ok.. the code to find the filename for __getattr__ should look @@ -31,10 +27,15 @@ import unittest # # -bob +import os +import sys +import unittest + from ctypes.macholib.dyld import dyld_find from ctypes.macholib.dylib import dylib_info from ctypes.macholib.framework import framework_info + def find_lib(name): possible = ['lib'+name+'.dylib', name+'.dylib', name+'.framework/'+name] for dylib in possible: @@ -106,5 +107,6 @@ class MachOTest(unittest.TestCase): self.assertEqual(framework_info('P/F.framework/Versions/A/F_debug'), d('P', 'F.framework/Versions/A/F_debug', 'F', 'A', 'debug')) + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_ctypes/test_memfunctions.py b/Lib/test/test_ctypes/test_memfunctions.py index 9d8e156ad5e..2ff95f619e0 100644 --- a/Lib/test/test_ctypes/test_memfunctions.py +++ b/Lib/test/test_ctypes/test_memfunctions.py @@ -1,12 +1,13 @@ import sys -from test import support import unittest +from test import support from ctypes import (POINTER, sizeof, cast, create_string_buffer, string_at, create_unicode_buffer, wstring_at, memmove, memset, c_char_p, c_byte, c_ubyte, c_wchar) + class MemFunctionsTest(unittest.TestCase): @unittest.skip('test disabled') def test_overflow(self): @@ -77,5 +78,6 @@ class MemFunctionsTest(unittest.TestCase): self.assertEqual(wstring_at(a, 16), "Hello, World\0\0\0\0") self.assertEqual(wstring_at(a, 0), "") + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_ctypes/test_numbers.py b/Lib/test/test_ctypes/test_numbers.py index 061876f9f77..052900f519c 100644 --- a/Lib/test/test_ctypes/test_numbers.py +++ b/Lib/test/test_ctypes/test_numbers.py @@ -1,13 +1,14 @@ +import array import struct import sys import unittest -from array import array from operator import truth from ctypes import (byref, sizeof, alignment, _SimpleCData, c_char, c_byte, c_ubyte, c_short, c_ushort, c_int, c_uint, c_long, c_ulong, c_longlong, c_ulonglong, c_float, c_double, c_longdouble, c_bool) + def valid_ranges(*types): # given a sequence of numeric types, collect their _type_ # attribute, which is a single format character compatible with @@ -25,6 +26,7 @@ def valid_ranges(*types): result.append((min(a, b, c, d), max(a, b, c, d))) return result + ArgType = type(byref(c_int(0))) unsigned_types = [c_ubyte, c_ushort, c_uint, c_ulong, c_ulonglong] @@ -36,7 +38,6 @@ unsigned_ranges = valid_ranges(*unsigned_types) signed_ranges = valid_ranges(*signed_types) bool_values = [True, False, 0, 1, -1, 5000, 'test', [], [1]] -################################################################ class NumberTestCase(unittest.TestCase): @@ -152,10 +153,10 @@ class NumberTestCase(unittest.TestCase): # the array module doesn't support all format codes # (no 'q' or 'Q') try: - array(t._type_) + array.array(t._type_) except ValueError: continue - a = array(t._type_, [100]) + a = array.array(t._type_, [100]) # v now is an integer at an 'external' memory location v = t.from_address(a.buffer_info()[0]) @@ -169,7 +170,7 @@ class NumberTestCase(unittest.TestCase): def test_float_from_address(self): for t in float_types: - a = array(t._type_, [3.14]) + a = array.array(t._type_, [3.14]) v = t.from_address(a.buffer_info()[0]) self.assertEqual(v.value, a[0]) self.assertIs(type(v), t) @@ -178,7 +179,7 @@ class NumberTestCase(unittest.TestCase): self.assertIs(type(v), t) def test_char_from_address(self): - a = array('b', [0]) + a = array.array('b', [0]) a[0] = ord('x') v = c_char.from_address(a.buffer_info()[0]) self.assertEqual(v.value, b'x') @@ -190,7 +191,7 @@ class NumberTestCase(unittest.TestCase): # array does not support c_bool / 't' @unittest.skip('test disabled') def test_bool_from_address(self): - a = array(c_bool._type_, [True]) + a = array.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) @@ -217,10 +218,12 @@ class NumberTestCase(unittest.TestCase): def test_perf(self): check_perf() + class c_int_S(_SimpleCData): _type_ = "i" __slots__ = [] + def run_test(rep, msg, func, arg=None): ## items = [None] * rep items = range(rep) @@ -237,6 +240,7 @@ def run_test(rep, msg, func, arg=None): stop = clock() print("%15s: %.2f us" % (msg, ((stop-start)*1e6/5/rep))) + def check_perf(): # Construct 5 objects from ctypes import c_int @@ -268,6 +272,7 @@ def check_perf(): # c_int_S(): 9.87 us # c_int_S(999): 9.85 us + if __name__ == '__main__': ## check_perf() unittest.main() diff --git a/Lib/test/test_ctypes/test_objects.py b/Lib/test/test_ctypes/test_objects.py index 78b1634115b..23c92b01a11 100644 --- a/Lib/test/test_ctypes/test_objects.py +++ b/Lib/test/test_ctypes/test_objects.py @@ -51,17 +51,18 @@ of 'x' ('_b_base_' is either None, or the root object owning the memory block): >>> x.array._b_base_._objects {'0:2': b'spam spam spam'} >>> - ''' -import unittest, doctest - +import doctest +import unittest import test.test_ctypes.test_objects + class TestCase(unittest.TestCase): def test(self): failures, tests = doctest.testmod(test.test_ctypes.test_objects) self.assertFalse(failures, 'doctests failed, see output above') + if __name__ == '__main__': doctest.testmod(test.test_ctypes.test_objects) diff --git a/Lib/test/test_ctypes/test_parameters.py b/Lib/test/test_ctypes/test_parameters.py index 02a2bc3839a..f43819f0049 100644 --- a/Lib/test/test_ctypes/test_parameters.py +++ b/Lib/test/test_ctypes/test_parameters.py @@ -1,8 +1,22 @@ +import _ctypes_test import unittest import test.support +from ctypes import (CDLL, PyDLL, ArgumentError, + Structure, Array, Union, + _Pointer, _SimpleCData, _CFuncPtr, + POINTER, pointer, byref, + c_void_p, c_char_p, c_wchar_p, py_object, + c_bool, + c_char, c_wchar, + c_byte, c_ubyte, + c_short, c_ushort, + c_int, c_uint, + c_long, c_ulong, + c_longlong, c_ulonglong, + c_float, c_double, c_longdouble) + class SimpleTypesTestCase(unittest.TestCase): - def setUp(self): try: from _ctypes import set_conversion_mode @@ -20,7 +34,6 @@ class SimpleTypesTestCase(unittest.TestCase): set_conversion_mode(*self.prev_conv_mode) def test_subclasses(self): - from ctypes import c_void_p, c_char_p # ctypes 0.9.5 and before did overwrite from_param in SimpleType_new class CVOIDP(c_void_p): def from_param(cls, value): @@ -36,8 +49,6 @@ class SimpleTypesTestCase(unittest.TestCase): self.assertEqual(CCHARP.from_param("abc"), "abcabcabcabc") def test_subclasses_c_wchar_p(self): - from ctypes import c_wchar_p - class CWCHARP(c_wchar_p): def from_param(cls, value): return value * 3 @@ -47,8 +58,6 @@ class SimpleTypesTestCase(unittest.TestCase): # XXX Replace by c_char_p tests def test_cstrings(self): - from ctypes import c_char_p - # c_char_p.from_param on a Python String packs the string # into a cparam object s = b"123" @@ -65,8 +74,6 @@ class SimpleTypesTestCase(unittest.TestCase): self.assertIs(c_char_p.from_param(a), a) def test_cw_strings(self): - from ctypes import c_wchar_p - c_wchar_p.from_param("123") self.assertRaises(TypeError, c_wchar_p.from_param, 42) @@ -76,16 +83,12 @@ class SimpleTypesTestCase(unittest.TestCase): self.assertEqual(type(pa), c_wchar_p) def test_c_char(self): - from ctypes import c_char - with self.assertRaises(TypeError) as cm: c_char.from_param(b"abc") self.assertEqual(str(cm.exception), "one character bytes, bytearray or integer expected") def test_c_wchar(self): - from ctypes import c_wchar - with self.assertRaises(TypeError) as cm: c_wchar.from_param("abc") self.assertEqual(str(cm.exception), @@ -98,7 +101,6 @@ class SimpleTypesTestCase(unittest.TestCase): "unicode string expected instead of int instance") def test_int_pointers(self): - from ctypes import c_short, c_uint, c_int, c_long, POINTER, pointer LPINT = POINTER(c_int) ## p = pointer(c_int(42)) @@ -117,7 +119,6 @@ class SimpleTypesTestCase(unittest.TestCase): def test_byref_pointer(self): # The from_param class method of POINTER(typ) classes accepts what is # returned by byref(obj), it type(obj) == typ - from ctypes import c_short, c_uint, c_int, c_long, POINTER, byref LPINT = POINTER(c_int) LPINT.from_param(byref(c_int(42))) @@ -129,7 +130,6 @@ class SimpleTypesTestCase(unittest.TestCase): def test_byref_pointerpointer(self): # See above - from ctypes import c_short, c_uint, c_int, c_long, pointer, POINTER, byref LPLPINT = POINTER(POINTER(c_int)) LPLPINT.from_param(byref(pointer(c_int(42)))) @@ -140,7 +140,6 @@ class SimpleTypesTestCase(unittest.TestCase): self.assertRaises(TypeError, LPLPINT.from_param, byref(pointer(c_uint(22)))) def test_array_pointers(self): - from ctypes import c_short, c_uint, c_int, c_long, POINTER INTARRAY = c_int * 3 ia = INTARRAY() self.assertEqual(len(ia), 3) @@ -155,9 +154,6 @@ class SimpleTypesTestCase(unittest.TestCase): self.assertRaises(TypeError, LPINT.from_param, c_uint*3) def test_noctypes_argtype(self): - import _ctypes_test - from ctypes import CDLL, c_void_p, ArgumentError - func = CDLL(_ctypes_test.__file__)._testfunc_p_p func.restype = c_void_p # TypeError: has no from_param method @@ -189,9 +185,6 @@ class SimpleTypesTestCase(unittest.TestCase): self.assertRaises(ArgumentError, func, 99) def test_abstract(self): - from ctypes import (Array, Structure, Union, _Pointer, - _SimpleCData, _CFuncPtr) - self.assertRaises(TypeError, Array.from_param, 42) self.assertRaises(TypeError, Structure.from_param, 42) self.assertRaises(TypeError, Union.from_param, 42) @@ -203,7 +196,6 @@ class SimpleTypesTestCase(unittest.TestCase): def test_issue31311(self): # __setstate__ should neither raise a SystemError nor crash in case # of a bad __dict__. - from ctypes import Structure class BadStruct(Structure): @property @@ -220,27 +212,6 @@ class SimpleTypesTestCase(unittest.TestCase): WorseStruct().__setstate__({}, b'foo') def test_parameter_repr(self): - from ctypes import ( - c_bool, - c_char, - c_wchar, - c_byte, - c_ubyte, - c_short, - c_ushort, - c_int, - c_uint, - c_long, - c_ulong, - c_longlong, - c_ulonglong, - c_float, - c_double, - c_longdouble, - c_char_p, - c_wchar_p, - c_void_p, - ) self.assertRegex(repr(c_bool.from_param(True)), r"^$") self.assertEqual(repr(c_char.from_param(97)), "") self.assertRegex(repr(c_wchar.from_param('a')), r"^$") @@ -265,9 +236,6 @@ class SimpleTypesTestCase(unittest.TestCase): @test.support.cpython_only def test_from_param_result_refcount(self): # Issue #99952 - import _ctypes_test - from ctypes import PyDLL, c_int, c_void_p, py_object, Structure - class X(Structure): """This struct size is <= sizeof(void*).""" _fields_ = [("a", c_void_p)] @@ -314,7 +282,6 @@ class SimpleTypesTestCase(unittest.TestCase): self.assertEqual(trace, [1, 2, 3, 4, 5]) -################################################################ if __name__ == '__main__': unittest.main() diff --git a/Lib/test/test_ctypes/test_pep3118.py b/Lib/test/test_ctypes/test_pep3118.py index c8eb584858c..caecbc8def8 100644 --- a/Lib/test/test_ctypes/test_pep3118.py +++ b/Lib/test/test_ctypes/test_pep3118.py @@ -1,3 +1,5 @@ +import re +import sys import unittest from ctypes import (CFUNCTYPE, POINTER, sizeof, Union, Structure, LittleEndianStructure, BigEndianStructure, @@ -5,7 +7,7 @@ from ctypes import (CFUNCTYPE, POINTER, sizeof, Union, c_short, c_ushort, c_int, c_uint, c_long, c_ulong, c_longlong, c_ulonglong, c_uint64, c_bool, c_float, c_double, c_longdouble, py_object) -import re, sys + if sys.byteorder == "little": THIS_ENDIAN = "<" @@ -14,6 +16,7 @@ else: THIS_ENDIAN = ">" OTHER_ENDIAN = "<" + def normalize(format): # Remove current endian specifier and white space from a format # string @@ -22,8 +25,8 @@ def normalize(format): format = format.replace(OTHER_ENDIAN, THIS_ENDIAN) return re.sub(r"\s", "", format) -class Test(unittest.TestCase): +class Test(unittest.TestCase): def test_native_types(self): for tp, fmt, shape, itemtp in native_types: ob = tp() @@ -80,6 +83,7 @@ class Test(unittest.TestCase): print(tp) raise + # define some structure classes class Point(Structure): @@ -124,6 +128,7 @@ class Complete(Structure): PComplete = POINTER(Complete) Complete._fields_ = [("a", c_long)] + ################################################################ # # This table contains format strings as they look on little endian @@ -233,17 +238,16 @@ native_types = [ ] + class BEPoint(BigEndianStructure): _fields_ = [("x", c_long), ("y", c_long)] class LEPoint(LittleEndianStructure): _fields_ = [("x", c_long), ("y", c_long)] -################################################################ -# + # This table contains format strings as they really look, on both big # and little endian machines. -# endian_types = [ (BEPoint, "T{>l:x:>l:y:}".replace('l', s_long), (), BEPoint), (LEPoint * 1, "T{= 0 return a + def c_wbuffer(init): n = len(init) + 1 return (c_wchar * n)(*init) -class CharPointersTestCase(unittest.TestCase): +class CharPointersTestCase(unittest.TestCase): def setUp(self): func = testdll._testfunc_p_p func.restype = c_long @@ -102,7 +105,7 @@ class CharPointersTestCase(unittest.TestCase): self.assertEqual(None, func(c_char_p(None))) self.assertEqual(b"123", func(c_char_p(b"123"))) - self.assertEqual(b"123", func(c_buffer(b"123"))) + self.assertEqual(b"123", func(create_string_buffer(b"123"))) ca = c_char(b"a") self.assertEqual(ord(b"a"), func(pointer(ca))[0]) self.assertEqual(ord(b"a"), func(byref(ca))[0]) @@ -117,7 +120,7 @@ class CharPointersTestCase(unittest.TestCase): self.assertEqual(None, func(c_char_p(None))) self.assertEqual(b"123", func(c_char_p(b"123"))) - self.assertEqual(b"123", func(c_buffer(b"123"))) + self.assertEqual(b"123", func(create_string_buffer(b"123"))) ca = c_char(b"a") self.assertEqual(ord(b"a"), func(pointer(ca))[0]) self.assertEqual(ord(b"a"), func(byref(ca))[0]) @@ -132,7 +135,7 @@ class CharPointersTestCase(unittest.TestCase): self.assertEqual(b"123", func(c_char_p(b"123"))) self.assertEqual(None, func(c_char_p(None))) - self.assertEqual(b"123", func(c_buffer(b"123"))) + self.assertEqual(b"123", func(create_string_buffer(b"123"))) ca = c_char(b"a") self.assertEqual(ord(b"a"), func(pointer(ca))[0]) self.assertEqual(ord(b"a"), func(byref(ca))[0]) @@ -162,8 +165,8 @@ class CharPointersTestCase(unittest.TestCase): func.argtypes = None self.assertEqual(None, func(X())) -class WCharPointersTestCase(unittest.TestCase): +class WCharPointersTestCase(unittest.TestCase): def setUp(self): func = testdll._testfunc_p_p func.restype = c_int @@ -203,6 +206,7 @@ class WCharPointersTestCase(unittest.TestCase): self.assertEqual("a", func(pointer(ca))[0]) self.assertEqual("a", func(byref(ca))[0]) + class ArrayTest(unittest.TestCase): def test(self): func = testdll._testfunc_ai8 @@ -216,7 +220,6 @@ class ArrayTest(unittest.TestCase): def func(): pass CFUNCTYPE(None, c_int * 3)(func) -################################################################ if __name__ == '__main__': unittest.main() diff --git a/Lib/test/test_ctypes/test_python_api.py b/Lib/test/test_ctypes/test_python_api.py index c8b81196609..77da3585592 100644 --- a/Lib/test/test_ctypes/test_python_api.py +++ b/Lib/test/test_ctypes/test_python_api.py @@ -1,20 +1,12 @@ -import unittest +import _ctypes import sys +import unittest from test import support -from ctypes import (pythonapi, POINTER, c_buffer, sizeof, +from ctypes import (pythonapi, POINTER, create_string_buffer, sizeof, py_object, c_char_p, c_char, c_long, c_size_t) -################################################################ -# This section should be moved into ctypes\__init__.py, when it's ready. - -from _ctypes import PyObj_FromPtr - -################################################################ - - class PythonAPITestCase(unittest.TestCase): - def test_PyBytes_FromStringAndSize(self): PyBytes_FromStringAndSize = pythonapi.PyBytes_FromStringAndSize @@ -58,7 +50,7 @@ class PythonAPITestCase(unittest.TestCase): s = "abc def ghi jkl" ref = sys.getrefcount(s) # id(python-object) is the address - pyobj = PyObj_FromPtr(id(s)) + pyobj = _ctypes.PyObj_FromPtr(id(s)) self.assertIs(s, pyobj) self.assertEqual(sys.getrefcount(s), ref + 1) @@ -69,7 +61,7 @@ class PythonAPITestCase(unittest.TestCase): PyOS_snprintf = pythonapi.PyOS_snprintf PyOS_snprintf.argtypes = POINTER(c_char), c_size_t, c_char_p - buf = c_buffer(256) + buf = create_string_buffer(256) PyOS_snprintf(buf, sizeof(buf), b"Hello from %s", b"ctypes") self.assertEqual(buf.value, b"Hello from ctypes") diff --git a/Lib/test/test_ctypes/test_random_things.py b/Lib/test/test_ctypes/test_random_things.py index fcea8e847eb..65eb53f8647 100644 --- a/Lib/test/test_ctypes/test_random_things.py +++ b/Lib/test/test_ctypes/test_random_things.py @@ -1,3 +1,4 @@ +import _ctypes import contextlib import ctypes import sys @@ -10,14 +11,13 @@ def callback_func(arg): 42 / arg raise ValueError(arg) + @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. def test(self): - from _ctypes import call_function - kernel32 = ctypes.windll.kernel32 kernel32.LoadLibraryA.restype = c_void_p kernel32.GetProcAddress.argtypes = c_void_p, c_char_p @@ -26,9 +26,10 @@ class call_function_TestCase(unittest.TestCase): hdll = kernel32.LoadLibraryA(b"kernel32") funcaddr = kernel32.GetProcAddress(hdll, b"GetModuleHandleA") - self.assertEqual(call_function(funcaddr, (None,)), + self.assertEqual(_ctypes.call_function(funcaddr, (None,)), kernel32.GetModuleHandleA(None)) + class CallbackTracbackTestCase(unittest.TestCase): # When an exception is raised in a ctypes callback function, the C # code prints a traceback. diff --git a/Lib/test/test_ctypes/test_refcounts.py b/Lib/test/test_ctypes/test_refcounts.py index b05cad0512c..a1fe89105ae 100644 --- a/Lib/test/test_ctypes/test_refcounts.py +++ b/Lib/test/test_ctypes/test_refcounts.py @@ -1,17 +1,18 @@ +import _ctypes_test import ctypes import gc import sys import unittest from test import support + MyCallback = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int) OtherCallback = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_ulonglong) -import _ctypes_test dll = ctypes.CDLL(_ctypes_test.__file__) -class RefcountTestCase(unittest.TestCase): +class RefcountTestCase(unittest.TestCase): @support.refcount_test def test_1(self): f = dll._testfunc_callback_i_if @@ -34,7 +35,6 @@ class RefcountTestCase(unittest.TestCase): self.assertEqual(sys.getrefcount(callback), 2) - @support.refcount_test def test_refcount(self): def func(*args): @@ -82,10 +82,9 @@ class RefcountTestCase(unittest.TestCase): gc.collect() self.assertEqual(sys.getrefcount(func), 2) + class AnotherLeak(unittest.TestCase): def test_callback(self): - import sys - proto = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_int) def func(a, b): return a * b * 2 @@ -110,5 +109,6 @@ class AnotherLeak(unittest.TestCase): for _ in range(10000): func() + if __name__ == '__main__': unittest.main() diff --git a/Lib/test/test_ctypes/test_repr.py b/Lib/test/test_ctypes/test_repr.py index bb6b5ae5e79..e7587984a92 100644 --- a/Lib/test/test_ctypes/test_repr.py +++ b/Lib/test/test_ctypes/test_repr.py @@ -1,7 +1,8 @@ +import unittest from ctypes import (c_byte, c_short, c_int, c_long, c_longlong, c_ubyte, c_ushort, c_uint, c_ulong, c_ulonglong, c_float, c_double, c_longdouble, c_bool, c_char) -import unittest + subclasses = [] for base in [c_byte, c_short, c_int, c_long, c_longlong, @@ -11,11 +12,12 @@ for base in [c_byte, c_short, c_int, c_long, c_longlong, pass subclasses.append(X) + class X(c_char): pass -# This test checks if the __repr__ is correct for subclasses of simple types +# This test checks if the __repr__ is correct for subclasses of simple types class ReprTest(unittest.TestCase): def test_numbers(self): for typ in subclasses: diff --git a/Lib/test/test_ctypes/test_returnfuncptrs.py b/Lib/test/test_ctypes/test_returnfuncptrs.py index 6a624133554..4010e511e75 100644 --- a/Lib/test/test_ctypes/test_returnfuncptrs.py +++ b/Lib/test/test_ctypes/test_returnfuncptrs.py @@ -1,10 +1,9 @@ +import _ctypes_test import unittest from ctypes import CDLL, CFUNCTYPE, ArgumentError, c_char_p, c_void_p, c_char -import _ctypes_test class ReturnFuncPtrTestCase(unittest.TestCase): - def test_with_prototype(self): # The _ctypes_test shared lib/dll exports quite some functions for testing. # The get_strchr function returns a *pointer* to the C strchr function. diff --git a/Lib/test/test_ctypes/test_slicing.py b/Lib/test/test_ctypes/test_slicing.py index 30db90cd7c0..a592d911cbe 100644 --- a/Lib/test/test_ctypes/test_slicing.py +++ b/Lib/test/test_ctypes/test_slicing.py @@ -1,8 +1,8 @@ +import _ctypes_test import unittest from ctypes import (CDLL, POINTER, sizeof, c_byte, c_short, c_int, c_long, c_char, c_wchar, c_char_p) -import _ctypes_test class SlicesTestCase(unittest.TestCase): def test_getslice_cint(self): @@ -164,7 +164,6 @@ class SlicesTestCase(unittest.TestCase): self.assertEqual(res[len(s)-2:5:-7], tmpl[:5:-7]) dll.my_free(res) -################################################################ if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_ctypes/test_stringptr.py b/Lib/test/test_ctypes/test_stringptr.py index 8bf04339d44..67c61c6c3e1 100644 --- a/Lib/test/test_ctypes/test_stringptr.py +++ b/Lib/test/test_ctypes/test_stringptr.py @@ -1,14 +1,15 @@ -import unittest -import sys -from test import support -from ctypes import CDLL, Structure, POINTER, c_buffer, c_char, c_char_p - import _ctypes_test +import sys +import unittest +from test import support +from ctypes import (CDLL, Structure, POINTER, create_string_buffer, + c_char, c_char_p) + lib = CDLL(_ctypes_test.__file__) -class StringPtrTestCase(unittest.TestCase): +class StringPtrTestCase(unittest.TestCase): @support.refcount_test def test__POINTER_c_char(self): class X(Structure): @@ -17,13 +18,13 @@ class StringPtrTestCase(unittest.TestCase): # NULL pointer access self.assertRaises(ValueError, getattr, x.str, "contents") - b = c_buffer(b"Hello, World") + b = create_string_buffer(b"Hello, World") self.assertEqual(sys.getrefcount(b), 2) x.str = b self.assertEqual(sys.getrefcount(b), 3) # POINTER(c_char) and Python string is NOT compatible - # POINTER(c_char) and c_buffer() is compatible + # POINTER(c_char) and create_string_buffer() is compatible for i in range(len(b)): self.assertEqual(b[i], x.str[i]) @@ -35,11 +36,11 @@ class StringPtrTestCase(unittest.TestCase): x = X() # c_char_p and Python string is compatible - # c_char_p and c_buffer is NOT compatible + # c_char_p and create_string_buffer is NOT compatible self.assertEqual(x.str, None) x.str = b"Hello, World" self.assertEqual(x.str, b"Hello, World") - b = c_buffer(b"Hello, World") + b = create_string_buffer(b"Hello, World") self.assertRaises(TypeError, setattr, x, b"str", b) @@ -48,15 +49,16 @@ class StringPtrTestCase(unittest.TestCase): strchr.restype = c_char_p # c_char_p and Python string is compatible - # c_char_p and c_buffer are now compatible + # c_char_p and create_string_buffer are now compatible strchr.argtypes = c_char_p, c_char self.assertEqual(strchr(b"abcdef", b"c"), b"cdef") - self.assertEqual(strchr(c_buffer(b"abcdef"), b"c"), b"cdef") + self.assertEqual(strchr(create_string_buffer(b"abcdef"), b"c"), + b"cdef") # POINTER(c_char) and Python string is NOT compatible - # POINTER(c_char) and c_buffer() is compatible + # POINTER(c_char) and create_string_buffer() is compatible strchr.argtypes = POINTER(c_char), c_char - buf = c_buffer(b"abcdef") + buf = create_string_buffer(b"abcdef") self.assertEqual(strchr(buf, b"c"), b"cdef") self.assertEqual(strchr(b"abcdef", b"c"), b"cdef") @@ -65,7 +67,7 @@ class StringPtrTestCase(unittest.TestCase): # So we must keep a reference to buf separately strchr.restype = POINTER(c_char) - buf = c_buffer(b"abcdef") + buf = create_string_buffer(b"abcdef") r = strchr(buf, b"c") x = r[0], r[1], r[2], r[3], r[4] self.assertEqual(x, (b"c", b"d", b"e", b"f", b"\000")) @@ -73,5 +75,6 @@ class StringPtrTestCase(unittest.TestCase): # Because r is a pointer to memory that is freed after deleting buf, # the pointer is hanging and using it would reference freed memory. + if __name__ == '__main__': unittest.main() diff --git a/Lib/test/test_ctypes/test_strings.py b/Lib/test/test_ctypes/test_strings.py index f02d6077def..26f036adfb7 100644 --- a/Lib/test/test_ctypes/test_strings.py +++ b/Lib/test/test_ctypes/test_strings.py @@ -1,5 +1,6 @@ import unittest -from ctypes import c_buffer, sizeof, byref, c_char, c_wchar +from ctypes import create_string_buffer, sizeof, byref, c_char, c_wchar + class StringArrayTestCase(unittest.TestCase): def test(self): @@ -24,8 +25,8 @@ class StringArrayTestCase(unittest.TestCase): self.assertRaises(ValueError, setattr, buf, "value", b"aaaaaaaa") self.assertRaises(TypeError, setattr, buf, "value", 42) - def test_c_buffer_value(self): - buf = c_buffer(32) + def test_create_string_buffer_value(self): + buf = create_string_buffer(32) buf.value = b"Hello, World" self.assertEqual(buf.value, b"Hello, World") @@ -34,8 +35,8 @@ class StringArrayTestCase(unittest.TestCase): self.assertRaises(TypeError, setattr, buf, "value", memoryview(b"abc")) self.assertRaises(ValueError, setattr, buf, "raw", memoryview(b"x" * 100)) - def test_c_buffer_raw(self): - buf = c_buffer(32) + def test_create_string_buffer_raw(self): + buf = create_string_buffer(32) buf.raw = memoryview(b"Hello, World") self.assertEqual(buf.value, b"Hello, World") @@ -90,7 +91,6 @@ class WStringTestCase(unittest.TestCase): repr(byref(c_wchar("x"))) c_wchar("x") - @unittest.skip('test disabled') def test_basic_wstrings(self): cs = c_wstring("abcdef") diff --git a/Lib/test/test_ctypes/test_struct_fields.py b/Lib/test/test_ctypes/test_struct_fields.py index 17a2e69f76d..f60dfe5b42e 100644 --- a/Lib/test/test_ctypes/test_struct_fields.py +++ b/Lib/test/test_ctypes/test_struct_fields.py @@ -1,6 +1,7 @@ import unittest from ctypes import Structure, Union, sizeof, c_char, c_int + class StructFieldsTestCase(unittest.TestCase): # Structure/Union classes must get 'finalized' sooner or # later, when one of these things happen: @@ -93,5 +94,6 @@ class StructFieldsTestCase(unittest.TestCase): self.assertRaises(TypeError, MyCUnion.field.__get__, 'wrong type self', 42) + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_ctypes/test_structures.py b/Lib/test/test_ctypes/test_structures.py index 98099e8b8c0..e656d189347 100644 --- a/Lib/test/test_ctypes/test_structures.py +++ b/Lib/test/test_ctypes/test_structures.py @@ -1,4 +1,6 @@ +import _ctypes_test import platform +import struct import sys import unittest from ctypes import (CDLL, Structure, Union, POINTER, sizeof, byref, alignment, @@ -7,14 +9,15 @@ from ctypes import (CDLL, Structure, Union, POINTER, sizeof, byref, alignment, c_short, c_ushort, c_int, c_uint, c_long, c_ulong, c_longlong, c_ulonglong, c_float, c_double) from struct import calcsize -import _ctypes_test from test import support + # The following definition is meant to be used from time to time to assist # temporarily disabling tests on specific architectures while investigations # are in progress, to keep buildbots happy. MACHINE = platform.machine() + class SubclassesTest(unittest.TestCase): def test_subclass(self): class X(Structure): @@ -54,6 +57,7 @@ class SubclassesTest(unittest.TestCase): self.assertEqual(Y._fields_, [("b", c_int)]) self.assertEqual(Z._fields_, [("a", c_int)]) + class StructureTestCase(unittest.TestCase): formats = {"c": c_char, "b": c_byte, @@ -187,7 +191,6 @@ class StructureTestCase(unittest.TestCase): self.assertEqual(sizeof(X), 10) self.assertEqual(X.b.offset, 2) - import struct longlong_size = struct.calcsize("q") longlong_align = struct.calcsize("bq") - longlong_size @@ -740,6 +743,7 @@ class StructureTestCase(unittest.TestCase): self.assertEqual(ctx.exception.args[0], 'item 1 in _argtypes_ passes ' 'a union by value, which is unsupported.') + class PointerMemberTestCase(unittest.TestCase): def test(self): @@ -781,6 +785,7 @@ class PointerMemberTestCase(unittest.TestCase): s.p = None self.assertEqual(s.x, 12345678) + class TestRecursiveStructure(unittest.TestCase): def test_contains_itself(self): class Recursive(Structure): @@ -810,5 +815,6 @@ class TestRecursiveStructure(unittest.TestCase): else: self.fail("AttributeError not raised") + if __name__ == '__main__': unittest.main() diff --git a/Lib/test/test_ctypes/test_unaligned_structures.py b/Lib/test/test_ctypes/test_unaligned_structures.py index a7e1796d4d6..58a00597ef5 100644 --- a/Lib/test/test_ctypes/test_unaligned_structures.py +++ b/Lib/test/test_ctypes/test_unaligned_structures.py @@ -4,6 +4,7 @@ from ctypes import (Structure, BigEndianStructure, LittleEndianStructure, c_float, c_double, c_ushort, c_uint, c_ulong, c_ulonglong) + structures = [] byteswapped_structures = [] @@ -27,6 +28,7 @@ for typ in [c_short, c_int, c_long, c_longlong, structures.append(X) byteswapped_structures.append(Y) + class TestStructures(unittest.TestCase): def test_native(self): for typ in structures: @@ -42,5 +44,6 @@ class TestStructures(unittest.TestCase): o.value = 4 self.assertEqual(o.value, 4) + if __name__ == '__main__': unittest.main() diff --git a/Lib/test/test_ctypes/test_unicode.py b/Lib/test/test_ctypes/test_unicode.py index fe8a157f3c6..2ddc7c56544 100644 --- a/Lib/test/test_ctypes/test_unicode.py +++ b/Lib/test/test_ctypes/test_unicode.py @@ -1,7 +1,7 @@ -import unittest -import ctypes - import _ctypes_test +import ctypes +import unittest + class UnicodeTestCase(unittest.TestCase): def test_wcslen(self): diff --git a/Lib/test/test_ctypes/test_values.py b/Lib/test/test_ctypes/test_values.py index 9707e032dc3..9f8b69409cb 100644 --- a/Lib/test/test_ctypes/test_values.py +++ b/Lib/test/test_ctypes/test_values.py @@ -2,14 +2,16 @@ A testcase which accesses *values* in a dll. """ +import _ctypes_test import _imp import importlib.util -import unittest import sys -from ctypes import Structure, CDLL, POINTER, pythonapi, c_ubyte, c_char_p, c_int +import unittest +from ctypes import (Structure, CDLL, POINTER, pythonapi, + _pointer_type_cache, + c_ubyte, c_char_p, c_int) from test.support import import_helper -import _ctypes_test class ValuesTestCase(unittest.TestCase): @@ -31,6 +33,7 @@ class ValuesTestCase(unittest.TestCase): ctdll = CDLL(_ctypes_test.__file__) self.assertRaises(ValueError, c_int.in_dll, ctdll, "Undefined_Symbol") + class PythonValuesTestCase(unittest.TestCase): """This test only works when python itself is a dll/shared library""" @@ -92,12 +95,12 @@ class PythonValuesTestCase(unittest.TestCase): "_PyImport_FrozenBootstrap example " "in Doc/library/ctypes.rst may be out of date") - from ctypes import _pointer_type_cache del _pointer_type_cache[struct_frozen] def test_undefined(self): self.assertRaises(ValueError, c_int.in_dll, pythonapi, "Undefined_Symbol") + if __name__ == '__main__': unittest.main() diff --git a/Lib/test/test_ctypes/test_varsize_struct.py b/Lib/test/test_ctypes/test_varsize_struct.py index d2fa0b36c78..3e6ba6fed07 100644 --- a/Lib/test/test_ctypes/test_varsize_struct.py +++ b/Lib/test/test_ctypes/test_varsize_struct.py @@ -1,5 +1,6 @@ -from ctypes import Structure, sizeof, resize, c_int import unittest +from ctypes import Structure, sizeof, resize, c_int + class VarSizeTest(unittest.TestCase): def test_resize(self): @@ -46,5 +47,6 @@ class VarSizeTest(unittest.TestCase): self.assertRaises(IndexError, array.__setitem__, -1, None) self.assertRaises(IndexError, array.__getitem__, -1) + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_ctypes/test_win32.py b/Lib/test/test_ctypes/test_win32.py index a8987dd1da6..01e624f76f0 100644 --- a/Lib/test/test_ctypes/test_win32.py +++ b/Lib/test/test_ctypes/test_win32.py @@ -2,9 +2,11 @@ import _ctypes_test import ctypes +import errno import sys import unittest from ctypes import (CDLL, Structure, POINTER, pointer, sizeof, byref, + _pointer_type_cache, c_void_p, c_char, c_int, c_long) from test import support @@ -47,7 +49,6 @@ class ReturnStructSizesTestCase(unittest.TestCase): self.assertEqual(value, expected) - @unittest.skipUnless(sys.platform == "win32", 'Windows-specific test') class TestWintypes(unittest.TestCase): def test_HWND(self): @@ -72,11 +73,11 @@ class TestWintypes(unittest.TestCase): self.assertEqual(ex.text, "text") self.assertEqual(ex.details, ("details",)) + @unittest.skipUnless(sys.platform == "win32", 'Windows-specific test') class TestWinError(unittest.TestCase): def test_winerror(self): # see Issue 16169 - import errno ERROR_INVALID_PARAMETER = 87 msg = ctypes.FormatError(ERROR_INVALID_PARAMETER).strip() args = (errno.EINVAL, msg, None, ERROR_INVALID_PARAMETER) @@ -136,7 +137,6 @@ class Structures(unittest.TestCase): self.assertEqual(ret.bottom, bottom.value) # to not leak references, we must clean _pointer_type_cache - from ctypes import _pointer_type_cache del _pointer_type_cache[RECT] diff --git a/Lib/test/test_ctypes/test_wintypes.py b/Lib/test/test_ctypes/test_wintypes.py index 66fb8b78545..a04d725a473 100644 --- a/Lib/test/test_ctypes/test_wintypes.py +++ b/Lib/test/test_ctypes/test_wintypes.py @@ -1,10 +1,9 @@ # See # for reference. +# +# Tests also work on POSIX import unittest - -# also work on POSIX - from ctypes import POINTER, cast, c_int16 from ctypes import wintypes