Debian Codegraph @

tests/test_api_coverage.py

raw symbols SCIP
1 #!/usr/bin/env python3
2
3 import sys
4 import libvirt
5 import unittest
6 import os
7
8
9 def get_libvirt_api_xml_path():
10 import subprocess
11 args = ["pkg-config", "--variable", "libvirt_api", "libvirt"]
12 proc = subprocess.Popen(args, stdout=subprocess.PIPE)
13 stdout, _ = proc.communicate()
14 if proc.returncode:
15 sys.exit(proc.returncode)
16 return stdout.splitlines()[0]
17
18 # Identify all functions and enums in public API
19 def identify_functions_enums(tree):
20 enumvals = {} # type: dict[str, dict[str, int]]
21 second_pass = [] # type: list[str]
22 wantenums = [] # type: list[str]
23 wantfunctions = [] # type: list[str]
24
25 wantfunctions = tree.xpath('/api/files/file/exports[@type="function"]/@symbol')
26
27 for n in tree.xpath('/api/symbols/enum'):
28 typ = n.attrib['type']
29 name = n.attrib['name']
30 val = n.attrib['value']
31
32 if typ not in enumvals:
33 enumvals[typ] = {}
34
35 # If the value cannot be converted to int, it is reference to
36 # another enum and needs to be sorted out later on
37 try:
38 val = int(val)
39 except ValueError:
40 second_pass.append(n)
41 continue
42
43 enumvals[typ][name] = int(val)
44
45 for n in second_pass:
46 typ = n.attrib['type']
47 name = n.attrib['name']
48 val = n.attrib['value']
49
50 for v in enumvals.values():
51 if val in v:
52 val = int(v[val])
53 break
54
55 # Version 4.0.0 was broken as missing VIR_TYPED_PARAM enums
56 # constants. This is harmless from POV of validating API
57 # coverage so ignore this error.
58 if (not isinstance(val, int) and
59 not val.startswith("VIR_TYPED_PARAM_")):
60 fail = True
61 print("Cannot get a value of enum %s (originally %s)" % (val, name))
62 enumvals[typ][name] = val
63
64 for n in tree.xpath('/api/files/file/exports[@type="enum"]/@symbol'):
65 for enumval in enumvals.values():
66 if n in enumval:
67 enumv = enumval
68 break
69 # Eliminate sentinels
70 if n.endswith('_LAST') and enumv[n] == max(enumv.values()):
71 continue
72 wantenums.append(n)
73
74 return wantfunctions, wantenums, enumvals
75
76
77 # Identify all classes and methods in the 'libvirt' python module
78 def identify_class_methods(wantenums, enumvals):
79 gotenums = [] # type: list[str]
80 gottypes = [] # type: list[str]
81 gotfunctions = {"libvirt": []} # type: dict[str, list[str]]
82
83 for name in dir(libvirt):
84 if name.startswith('_'):
85 continue
86 thing = getattr(libvirt, name)
87 # Special-case libvirtError to deal with python 2.4 difference
88 # in Exception class type reporting.
89 if isinstance(thing, int):
90 gotenums.append(name)
91 elif getattr(thing, "__module__", "") == "typing":
92 continue
93 elif type(thing) == type or name == "libvirtError":
94 gottypes.append(name)
95 gotfunctions[name] = []
96 elif callable(thing):
97 gotfunctions["libvirt"].append(name)
98
99 for enum in wantenums:
100 if enum not in gotenums:
101 fail = True
102 for typ, enumval in enumvals.items():
103 if enum in enumval:
104 raise Exception("Missing exported enum %s of type %s" % (enum, typ))
105
106 for klassname in gottypes:
107 klassobj = getattr(libvirt, klassname)
108 for name in dir(klassobj):
109 if name.startswith('_'):
110 continue
111 if name == 'c_pointer':
112 continue
113 thing = getattr(klassobj, name)
114 if callable(thing):
115 gotfunctions[klassname].append(name)
116
117 return gotfunctions, gottypes
118
119
120 # First cut at mapping of C APIs to python classes + methods
121 def basic_class_method_mapping(wantfunctions, gottypes):
122 basicklassmap = {} # type: dict[str, tuple[str, str, str]]
123
124 for cname in wantfunctions:
125 name = cname
126 # Some virConnect APIs have stupid names
127 if name[0:7] == "virNode" and name[0:13] != "virNodeDevice":
128 name = "virConnect" + name[7:]
129 if name[0:7] == "virConn" and name[0:10] != "virConnect":
130 name = "virConnect" + name[7:]
131
132 # The typed param APIs are only for internal use
133 if name[0:14] == "virTypedParams":
134 continue
135
136 if name[0:23] == "virNetworkDHCPLeaseFree":
137 continue
138
139 if name[0:28] == "virDomainStatsRecordListFree":
140 continue
141
142 if name[0:19] == "virDomainFSInfoFree":
143 continue
144
145 if name[0:25] == "virDomainIOThreadInfoFree":
146 continue
147
148 if name[0:22] == "virDomainInterfaceFree":
149 continue
150
151 if name[0:21] == "virDomainListGetStats":
152 name = "virConnectDomainListGetStats"
153
154 # These aren't functions, they're callback signatures
155 if name in ["virConnectAuthCallbackPtr", "virConnectCloseFunc",
156 "virStreamSinkFunc", "virStreamSourceFunc", "virStreamEventCallback",
157 "virEventHandleCallback", "virEventTimeoutCallback", "virFreeCallback",
158 "virStreamSinkHoleFunc", "virStreamSourceHoleFunc", "virStreamSourceSkipFunc"]:
159 continue
160 if name[0:21] == "virConnectDomainEvent" and name[-8:] == "Callback":
161 continue
162 if name[0:22] == "virConnectNetworkEvent" and name[-8:] == "Callback":
163 continue
164 if (name.startswith("virConnectStoragePoolEvent") and
165 name.endswith("Callback")):
166 continue
167 if (name.startswith("virConnectNodeDeviceEvent") and
168 name.endswith("Callback")):
169 continue
170 if (name.startswith("virConnectSecretEvent") and
171 name.endswith("Callback")):
172 continue
173
174 # virEvent APIs go into main 'libvirt' namespace not any class
175 if name[0:8] == "virEvent":
176 if name[-4:] == "Func":
177 continue
178 basicklassmap[name] = ("libvirt", name, cname)
179 else:
180 found = False
181 # To start with map APIs to classes based on the
182 # naming prefix. Mistakes will be fixed in next
183 # loop
184 for klassname in gottypes:
185 klen = len(klassname)
186 if name[0:klen] == klassname:
187 found = True
188 if name not in basicklassmap:
189 basicklassmap[name] = (klassname, name[klen:], cname)
190 elif len(basicklassmap[name]) < klen:
191 basicklassmap[name] = (klassname, name[klen:], cname)
192
193 # Anything which can't map to a class goes into the
194 # global namespaces
195 if not found:
196 basicklassmap[name] = ("libvirt", name[3:], cname)
197
198 return basicklassmap
199
200
201 # Deal with oh so many special cases in C -> python mapping
202 def fixup_class_method_mapping(basicklassmap):
203 finalklassmap = {} # type: dict[str, tuple[str, str, str]]
204
205 for name, (klass, func, cname) in sorted(basicklassmap.items()):
206 # The object lifecycle APIs are irrelevant since they're
207 # used inside the object constructors/destructors.
208 if func in ["Ref", "Free", "New", "GetConnect", "GetDomain", "GetNetwork"]:
209 if klass == "virStream" and func == "New":
210 klass = "virConnect"
211 func = "NewStream"
212 else:
213 continue
214
215 # All the error handling methods need special handling
216 if klass == "libvirt":
217 if func in ["CopyLastError", "DefaultErrorFunc",
218 "ErrorFunc", "FreeError",
219 "SaveLastError", "ResetError"]:
220 continue
221 elif func in ["GetLastError", "GetLastErrorMessage",
222 "GetLastErrorCode", "GetLastErrorDomain",
223 "ResetLastError", "Initialize"]:
224 func = "vir" + func
225 elif func == "SetErrorFunc":
226 func = "RegisterErrorHandler"
227 elif klass == "virConnect":
228 if func in ["CopyLastError", "SetErrorFunc"]:
229 continue
230 elif func in ["GetLastError", "ResetLastError"]:
231 func = "virConn" + func
232
233 # Remove 'Get' prefix from most APIs, except those in virConnect
234 # and virDomainSnapshot namespaces which stupidly used a different
235 # convention which we now can't fix without breaking API
236 if func[0:3] == "Get" and klass not in ["virConnect", "virDomainCheckpoint", "virDomainSnapshot", "libvirt"]:
237 if func not in ["GetCPUStats", "GetTime"]:
238 func = func[3:]
239
240 # The object creation and lookup APIs all have to get re-mapped
241 # into the parent class
242 if func in ["CreateXML", "CreateLinux", "CreateXMLWithFiles",
243 "DefineXML", "CreateXMLFrom", "LookupByUUID",
244 "LookupByUUIDString", "LookupByVolume" "LookupByName",
245 "LookupByID", "LookupByName", "LookupByKey", "LookupByPath",
246 "LookupByMACString", "LookupByUsage", "LookupByVolume",
247 "LookupByTargetPath", "LookupSCSIHostByWWN", "LookupByPortDev",
248 "Restore", "RestoreFlags", "RestoreParams",
249 "SaveImageDefineXML", "SaveImageGetXMLDesc", "DefineXMLFlags",
250 "CreateXMLFlags"]:
251 if klass != "virDomain":
252 func = klass[3:] + func
253
254 if klass in ["virDomainCheckpoint", "virDomainSnapshot"]:
255 klass = "virDomain"
256 func = func[6:]
257 elif klass == "virStorageVol" and func in ["StorageVolCreateXMLFrom", "StorageVolCreateXML"]:
258 klass = "virStoragePool"
259 func = func[10:]
260 elif klass == "virNetworkPort":
261 klass = "virNetwork"
262 func = func[7:]
263 elif func == "StoragePoolLookupByVolume":
264 klass = "virStorageVol"
265 elif func == "StorageVolLookupByName":
266 klass = "virStoragePool"
267 else:
268 klass = "virConnect"
269
270 # The open methods get remapped to primary namespace
271 if klass == "virConnect" and func in ["Open", "OpenAuth", "OpenReadOnly"]:
272 klass = "libvirt"
273
274 # These are inexplicably renamed in the python API
275 if func == "ListDomains":
276 func = "ListDomainsID"
277 elif func == "ListAllNodeDevices":
278 func = "ListAllDevices"
279 elif func == "ListNodeDevices":
280 func = "ListDevices"
281
282 # The virInterfaceChangeXXXX APIs go into virConnect. Stupidly
283 # they have lost their 'interface' prefix in names, but we can't
284 # fix this name
285 if func[0:6] == "Change":
286 klass = "virConnect"
287
288 # Need to special case the checkpoint and snapshot APIs
289 if klass == "virDomainSnapshot" and func in ["Current", "ListNames", "Num"]:
290 klass = "virDomain"
291 func = "snapshot" + func
292
293 # Names should start with lowercase letter...
294 func = func[0:1].lower() + func[1:]
295 if func[0:8] == "nWFilter":
296 func = "nwfilter" + func[8:]
297 if func[0:8] == "fSFreeze" or func[0:6] == "fSThaw" or func[0:6] == "fSInfo":
298 func = "fs" + func[2:]
299 if func[0:12] == "iOThreadInfo":
300 func = "ioThreadInfo"
301
302 if klass == "virNetwork":
303 func = func.replace("dHCP", "DHCP")
304
305 # ...except when they don't. More stupid naming
306 # decisions we can't fix
307 if func == "iD":
308 func = "ID"
309 if func == "uUID":
310 func = "UUID"
311 if func == "uUIDString":
312 func = "UUIDString"
313 if func == "oSType":
314 func = "OSType"
315 if func == "xMLDesc":
316 func = "XMLDesc"
317 if func == "mACString":
318 func = "MACString"
319 if func == "fDAssociate":
320 func = "FDAssociate"
321
322 finalklassmap[name] = (klass, func, cname)
323
324 return finalklassmap
325
326
327 # Validate that every C API is mapped to a python API
328 def validate_c_to_python_api_mappings(finalklassmap, gotfunctions):
329 usedfunctions = set() # type: set[str]
330 for name, (klass, func, cname) in sorted(finalklassmap.items()):
331 if func in gotfunctions[klass]:
332 usedfunctions.add("%s.%s" % (klass, func))
333 else:
334 raise Exception("%s -> %s.%s (C API not mapped to python)" % (name, klass, func))
335 return usedfunctions
336
337
338 # Validate that every python API has a corresponding C API
339 def validate_python_to_c_api_mappings(gotfunctions, usedfunctions):
340 for klass in gotfunctions:
341 if klass == "libvirtError":
342 continue
343 for func in sorted(gotfunctions[klass]):
344 # These are pure python methods with no C APi
345 if func in ["connect", "getConnect", "domain", "getDomain",
346 "virEventInvokeFreeCallback", "network",
347 "sparseRecvAll", "sparseSendAll"]:
348 continue
349
350 key = "%s.%s" % (klass, func)
351 if key not in usedfunctions:
352 raise Exception("%s.%s (Python API not mapped to C)" % (klass, func))
353
354
355 # Validate that all the low level C APIs have binding
356 def validate_c_api_bindings_present(finalklassmap):
357 for name, (klass, func, cname) in sorted(finalklassmap.items()):
358 pyname = cname
359 if pyname == "virSetErrorFunc":
360 pyname = "virRegisterErrorHandler"
361 elif pyname == "virConnectListDomains":
362 pyname = "virConnectListDomainsID"
363
364 # These exist in C and exist in python, but we've got
365 # a pure-python impl so don't check them
366 if name in ["virStreamRecvAll", "virStreamSendAll",
367 "virStreamSparseRecvAll", "virStreamSparseSendAll"]:
368 continue
369
370 try:
371 thing = getattr(libvirt.libvirtmod, pyname)
372 except AttributeError:
373 raise Exception("libvirt.libvirtmod.%s (C binding does not exist)" % pyname)
374
375 # Historically python lxml is incompatible with any other
376 # use of libxml2 in the same process. Merely importing
377 # 'lxml.etree' will result in libvirt's use of libxml2
378 # triggering a SEGV:
379 #
380 # https://bugs.launchpad.net/lxml/+bug/1748019
381 #
382 # per the last comment though, it was somewhat improved by
383 #
384 # https://github.com/lxml/lxml/commit/fa1d856cad369d0ac64323ddec14b02281491706
385 #
386 # so if we have version >= 4.5.2, we are safe to import
387 # lxml.etree for the purposes of unit tests at least
388 def broken_lxml():
389 import lxml
390
391 if not hasattr(lxml, "__version__"):
392 return True
393
394 digits = [int(d) for d in lxml.__version__.split(".")]
395
396 # We have 3 digits in versions today, but be paranoid
397 # for possible future changes.
398 if len(digits) != 3:
399 return False
400
401 version = (digits[0] * 1000 * 1000) + (digits[1] * 1000) + digits[2]
402 if version < 4005002:
403 return True
404
405 return False
406
407 api_test_flag = unittest.skipUnless(
408 os.environ.get('LIBVIRT_API_COVERAGE', False),
409 "API coverage test is only for upstream maintainers",
410 )
411
412 lxml_broken_flag = unittest.skipIf(
413 broken_lxml(),
414 "lxml version clashes with libxml usage from libvirt"
415 )
416
417 @api_test_flag
418 @lxml_broken_flag
419 class LibvirtAPICoverage(unittest.TestCase):
420 def test_libvirt_api(self):
421 xml = get_libvirt_api_xml_path()
422
423 import lxml.etree
424 with open(xml, "r") as fp:
425 tree = lxml.etree.parse(fp)
426
427 wantfunctions, wantenums, enumvals = identify_functions_enums(tree)
428 gotfunctions, gottypes = identify_class_methods(wantenums, enumvals)
429 basicklassmap = basic_class_method_mapping(wantfunctions, gottypes)
430 finalklassmap = fixup_class_method_mapping(basicklassmap)
431 usedfunctions = validate_c_to_python_api_mappings(finalklassmap, gotfunctions)
432 validate_python_to_c_api_mappings(gotfunctions, usedfunctions)
433 validate_c_api_bindings_present(finalklassmap)