this repo has no description
at trunk 99 lines 3.3 kB view raw
1#!/usr/bin/env python3 2# Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com) 3import _ctypes 4import unittest 5 6 7class UnderCtypesTests(unittest.TestCase): 8 def test_ctypes_imports_cleanly(self): 9 # Importing ctypes exercises a lot of the functionality in _ctypes 10 # (e.g. type size sanity-checking) 11 import ctypes 12 13 self.assertIsNotNone(ctypes) 14 15 def test_simple_c_data_class(self): 16 class py_object(_ctypes._SimpleCData): 17 _type_ = "O" 18 19 self.assertEqual(py_object._type_, "O") 20 21 def test_simple_c_data_class_with_no_type_raises_attribute_error(self): 22 with self.assertRaises(AttributeError) as context: 23 24 class CType(_ctypes._SimpleCData): 25 pass 26 27 self.assertEqual( 28 str(context.exception), "class must define a '_type_' attribute" 29 ) 30 31 def test_simple_c_data_class_with_nonstr_type_raises_type_error(self): 32 with self.assertRaises(TypeError) as context: 33 34 class CType(_ctypes._SimpleCData): 35 _type_ = 1 36 37 self.assertEqual( 38 context.exception, "class must define a '_type_' string attribute" 39 ) 40 41 def test_simple_c_data_class_with_long_str_type_raises_value_error(self): 42 with self.assertRaises(ValueError) as context: 43 44 class CType(_ctypes._SimpleCData): 45 _type_ = "oo" 46 47 self.assertEqual( 48 str(context.exception), 49 "class must define a '_type_' attribute which must be a string of length 1", 50 ) 51 52 def test_simple_c_data_class_with_unsupported_type_raises_attribute_error(self): 53 with self.assertRaises(AttributeError) as context: 54 55 class CType(_ctypes._SimpleCData): 56 _type_ = "A" 57 58 self.assertEqual( 59 str(context.exception), 60 "class must define a '_type_' attribute which must be\n" 61 + "a single character string containing one of 'cbBhHiIlLdfuzZqQPXOv?g'.", 62 ) 63 64 def test_dlopen_with_none_returns_handle(self): 65 handle = _ctypes.dlopen(None, _ctypes.RTLD_LOCAL) 66 self.assertIsInstance(handle, int) 67 self.assertNotEqual(handle, 0) 68 69 def test_POINTER_with_type_returns_pointer(self): 70 class c_byte(_ctypes._SimpleCData): 71 _type_ = "b" 72 73 p = _ctypes.POINTER(c_byte) 74 self.assertEqual(p.__name__, "LP_c_byte") 75 self.assertEqual(_ctypes._pointer_type_cache[c_byte], p) 76 77 def test_POINTER_with_str_returns_pointer(self): 78 name = "my_class" 79 p = _ctypes.POINTER(name) 80 self.assertEqual(p.__name__, "LP_my_class") 81 self.assertEqual(_ctypes._pointer_type_cache[id(p)], p) 82 83 def test_POINTER_with_int_raises_type_error(self): 84 with self.assertRaises(TypeError) as context: 85 _ctypes.POINTER(1) 86 87 self.assertEqual(str(context.exception), "must be a ctypes type") 88 89 def test_sizeof_with_type_returns_correct_size(self): 90 class c_byte(_ctypes._SimpleCData): 91 _type_ = "b" 92 93 from struct import calcsize 94 95 self.assertEqual(_ctypes.sizeof(c_byte), calcsize(c_byte._type_)) 96 97 98if __name__ == "__main__": 99 unittest.main()