| 1 |
import ctypes |
| 2 |
import unittest |
| 3 |
import warnings |
| 4 |
from ctypes import Structure, POINTER, pointer, c_char_p |
| 5 |
|
| 6 |
# String-based "incomplete pointers" were implemented in ctypes 0.6.3 (2003, when |
| 7 |
# ctypes was an external project). They made obsolete by the current |
| 8 |
# incomplete *types* (setting `_fields_` late) in 0.9.5 (2005). |
| 9 |
# ctypes was added to Python 2.5 (2006), without any mention in docs. |
| 10 |
|
| 11 |
# This tests incomplete pointer example from the old tutorial |
| 12 |
# (https://svn.python.org/projects/ctypes/tags/release_0_6_3/ctypes/docs/tutorial.stx) |
| 13 |
class TestSetPointerType(unittest.TestCase): |
| 14 |
def tearDown(self): |
| 15 |
ctypes._pointer_type_cache_fallback.clear() |
| 16 |
|
| 17 |
def test_incomplete_example(self): |
| 18 |
with self.assertWarns(DeprecationWarning): |
| 19 |
lpcell = POINTER("cell") |
| 20 |
class cell(Structure): |
| 21 |
_fields_ = [("name", c_char_p), |
| 22 |
("next", lpcell)] |
| 23 |
|
| 24 |
with warnings.catch_warnings(): |
| 25 |
warnings.simplefilter('ignore', DeprecationWarning) |
| 26 |
ctypes.SetPointerType(lpcell, cell) |
| 27 |
|
| 28 |
self.assertIs(POINTER(cell), lpcell) |
| 29 |
|
| 30 |
c1 = cell() |
| 31 |
c1.name = b"foo" |
| 32 |
c2 = cell() |
| 33 |
c2.name = b"bar" |
| 34 |
|
| 35 |
c1.next = pointer(c2) |
| 36 |
c2.next = pointer(c1) |
| 37 |
|
| 38 |
p = c1 |
| 39 |
|
| 40 |
result = [] |
| 41 |
for i in range(8): |
| 42 |
result.append(p.name) |
| 43 |
p = p.next[0] |
| 44 |
self.assertEqual(result, [b"foo", b"bar"] * 4) |
| 45 |
|
| 46 |
def test_deprecation(self): |
| 47 |
with self.assertWarns(DeprecationWarning): |
| 48 |
lpcell = POINTER("cell") |
| 49 |
class cell(Structure): |
| 50 |
_fields_ = [("name", c_char_p), |
| 51 |
("next", lpcell)] |
| 52 |
|
| 53 |
with self.assertWarns(DeprecationWarning): |
| 54 |
ctypes.SetPointerType(lpcell, cell) |
| 55 |
|
| 56 |
self.assertIs(POINTER(cell), lpcell) |
| 57 |
|
| 58 |
if __name__ == '__main__': |
| 59 |
unittest.main() |