Debian Codegraph @

extra_tests/ctypes_tests/test_commethods.py

raw symbols SCIP
1 # unittest for SOME ctypes com function calls.
2 # Can't resist from implementing some kind of mini-comtypes
3 # theller ;-)
4
5 import pytest
6 import sys
7 if sys.platform != "win32":
8 # this doesn't work, it still tries to do module-level imports
9 # pytestmark = pytest.mark.skip("skip_the_whole_module")
10 pytest.importorskip('skip_the_whole_module') # hack!
11
12
13 import ctypes, types, unittest
14 from ctypes import HRESULT
15 from _ctypes import COMError
16
17 oleaut32 = ctypes.OleDLL("oleaut32")
18
19 class UnboundMethod(object):
20 def __init__(self, func, index, name):
21 self.func = func
22 self.index = index
23 self.name = name
24 self.__doc__ = func.__doc__
25
26 def __repr__(self):
27 return "<Unbound COM method index %d: %s at %x>" % (self.index, self.name, id(self))
28
29 def __get__(self, instance, owner):
30 if instance is None:
31 return self
32 return types.MethodType(self.func, instance, owner)
33
34 def commethod(index, restype, *argtypes):
35 """A decorator that generates COM methods. The decorated function
36 itself is not used except for it's name."""
37 def make_commethod(func):
38 comfunc = ctypes.WINFUNCTYPE(restype, *argtypes)(index, func.__name__)
39 comfunc.__name__ = func.__name__
40 comfunc.__doc__ = func.__doc__
41 return UnboundMethod(comfunc, index, func.__name__)
42 return make_commethod
43
44 class ICreateTypeLib2(ctypes.c_void_p):
45
46 @commethod(1, ctypes.c_long)
47 def AddRef(self):
48 pass
49
50 @commethod(2, ctypes.c_long)
51 def Release(self):
52 pass
53
54 @commethod(4, HRESULT, ctypes.c_wchar_p)
55 def SetName(self):
56 """Set the name of the library."""
57
58 @commethod(12, HRESULT)
59 def SaveAllChanges(self):
60 pass
61
62
63 CreateTypeLib2 = oleaut32.CreateTypeLib2
64 CreateTypeLib2.argtypes = (ctypes.c_int, ctypes.c_wchar_p, ctypes.POINTER(ICreateTypeLib2))
65
66 ################################################################
67
68 def test_basic_comtypes():
69 punk = ICreateTypeLib2()
70 hr = CreateTypeLib2(0, "foobar.tlb", punk)
71 assert hr == 0
72
73 assert 2 == punk.AddRef()
74 assert 3 == punk.AddRef()
75 assert 4 == punk.AddRef()
76
77 punk.SetName("TypeLib_ByPYPY")
78 with pytest.raises(COMError):
79 punk.SetName(None)
80
81 # This would save the typelib to disk.
82 ## punk.SaveAllChanges()
83
84 assert 3 == punk.Release()
85 assert 2 == punk.Release()
86 assert 1 == punk.Release()