Debian Codegraph @

tests/scripts/test-simple-service-1

raw
1 #!/bin/python3
2 # GDBus++ - glib2 GDBus C++ wrapper
3 #
4 # SPDX-License-Identifier: AGPL-3.0-only
5 #
6 # Copyright (C) OpenVPN Inc <[email protected]>
7 # Copyright (C) David Sommerseth <[email protected]>
8
9 ##
10 # @file tests/scripts/test-simple-service-1
11 #
12 # @brief Runs a series of tests against the tests/simple-service.cpp
13 # test service
14 #
15
16 import dbus
17 import sys
18 import xmltodict
19
20
21
22 class IntrospectionParser(object):
23 """
24 Runs a recursive D-Bus introspection against a D-Bus service, mapping
25 all the found D-Bus objects with their interfaces and the methods,
26 properties and signals found there with their sigantures
27 """
28
29 ##
30 # Creates the IntrospectionParser object
31 #
32 # @param bus Must be a dbus.SessionBus() or dbus.SystemBus()
33 # connection object
34 # @param service Well-known bus name for the service to introspect
35 #
36 def __init__(self, bus, service):
37 self.__bus = bus
38 self.__service = service
39
40 self.RunIntrospection()
41
42
43 ##
44 # Internal parser helper. This will run the Introspect D-Bus method
45 # on the given D-Bus path and parse the XML response into a Python
46 # dictionaries. This dictionary is further processed to extract the
47 # information in a more condenced way
48 #
49 # @param path D-Bus path where to start the introspection process
50 # Defaults to '/'
51 #
52 # @see @RunIntrospection for details on the return structure
53 #
54 def __inspect_path(self, path = '/'):
55 obj = self.__bus.get_object(self.__service, path)
56 introspect_interface = dbus.Interface(obj,
57 dbus_interface='org.freedesktop.DBus.Introspectable')
58
59 # Retrieve the D-Bus Introspection data, which is an XML string ...
60 introspection_xml = introspect_interface.Introspect()
61 # ... and parse that XML into a more Python compliant data structure
62 parsed = xmltodict.parse(introspection_xml,
63 force_list=('node','interface','method','property','signal','arg'))
64
65 return self.__inspect_node(path, parsed['node'])
66
67
68 ##
69 # Internal helper function, parsing the dictionary for a specific
70 # D-Bus path
71 #
72 # If child objects are found, they will be introspected recursively
73 # by calling the @__inspect_path() method on the D-Bus path of the
74 # child object
75 #
76 # @param path D-Bus path of the current node being inspected
77 # @param start_node A dictionary of the root 'node' element for a
78 # specific D-Bus object
79 #
80 # @returns a partial dictionary of the currently parsed object.
81 # If children objects was found, they are appended to the
82 # result dictionary
83 #
84 def __inspect_node(self, path, start_node):
85 ret = {}
86 for node in start_node:
87 if node is None:
88 continue
89
90 found_interfaces = {}
91 if 'interface' in node:
92 for intf in node['interface']:
93 if intf['@name'].startswith('org.freedesktop.DBus.'):
94 # These are default interfaces; skip them
95 continue
96
97 found_methods = {}
98 if 'method' in intf.keys():
99 for method in intf['method']:
100 m_args = {}
101 if 'arg' in method:
102 for arg in method['arg']:
103 m_args[str(arg['@name'])] = {
104 'type': str(arg['@type']),
105 'dir': str(arg['@direction'])}
106 found_methods[str(method['@name'])] = m_args
107
108 found_props = {}
109 if 'property' in intf.keys():
110 for prop in intf['property']:
111 found_props[str(prop['@name'])] = {
112 'type': str(prop['@type']),
113 'access': str(prop['@access'])
114 }
115
116 found_signals = {}
117 if 'signal' in intf.keys():
118 for signal in intf['signal']:
119 s_args = {}
120 if 'arg' in signal:
121 for arg in signal['arg']:
122 s_args[str(arg['@name'])] = {
123 'type': str(arg['@type'])
124 }
125 found_signals[str(signal['@name'])] = s_args;
126
127 found_interfaces[str(intf['@name'])] = {
128 'methods': found_methods,
129 'properties': found_props,
130 'signals': found_signals
131 }
132
133 # Skip paths with no interfaces;
134 # thus no methods, properties nor signals
135 if len(found_interfaces) > 0:
136 ret[path] = found_interfaces
137
138 if 'node' in node:
139 for child in node['node']:
140 if path == '/':
141 path = ''
142 r = self.__inspect_path(path + '/' + child['@name'])
143 if r is not None:
144 ret.update(r)
145 return ret
146
147
148 ##
149 # Runs a full, recursive introspection on the service
150 #
151 # @returns a dictionary with the following structure:
152 #
153 # {"/full/dbus/path":
154 # {"interface.identifier":
155 # "methods": {
156 # "method_name": {
157 # "argument_name": {
158 # "type": "dbus-type-string",
159 # "dir": "direction (in/out)"
160 # },
161 # ...
162 # },
163 # ....
164 # },
165 # "properties": {
166 # "property_name": {
167 # "type": "dbus-type-string",
168 # "access": "read/readwrite"
169 # },
170 # ...
171 # },
172 # "signals": {
173 # "signal_name": {
174 # "arg_name": {"type": "dbus-type-string"},
175 # ...
176 # },
177 # ...
178 # },
179 # },
180 # ...
181 # }
182 #
183 def RunIntrospection(self):
184 self.__introspection = self.__inspect_path()
185 return self.__introspection
186
187
188 ##
189 # Retrieve all the "sections" in specific object path and interface
190 # group. A section is typically the "methods", "properties" or "signals"
191 # groups
192 #
193 # @param path D-Bus path to retrieve information from
194 # @param interface D-Bus object interface group to access
195 #
196 # @returns a list of strings with available sections
197 #
198 def GetSections(self, path, interface):
199 try:
200 return self.__introspection[path][interface].keys()
201 except KeyError:
202 return None
203
204
205 ##
206 # Retrieve the type declaration fragment of a specific D-Bus section
207 # for a specific member.
208 #
209 # @param path D-Bus path to retrieve information from
210 # @param interface D-Bus object interface group to access
211 # @param section The introspection section to retrive data from
212 # @param name Name of the member to retrieve the type declaration
213 #
214 # @returns a dictionary with the "type", "dir" or "access" members and
215 # and their assignments from the introspection
216 #
217 def GetFragment(self, path, interface, section, name):
218 fragment = self.__introspection[path][interface]
219 if section in fragment and name in fragment[section]:
220 return fragment[section][name]
221 else:
222 return None
223
224 ##
225 # Retrieve the last full introspection performed
226 # @see @RunIntrospection for details on the returned data
227 #
228 def GetIntrospection(self):
229 return self.__introspection
230
231
232 class TestMethod(object):
233 """
234 Tests a specific D-Bus method, where the expected input/output
235 information is provided as well as test input data with the expected
236 result being returned back.
237 """
238 def __init__(self, name, input_type, output_type, input_data, result):
239 self.__name = name
240 self.__in_type = input_type
241 self.__out_type = output_type
242 self.__in_data = input_data
243 self.__expect_res = result
244
245
246 def GetName(self):
247 return self.__name
248
249 def CheckIntrospection(self, introsp):
250 if len(introsp) == 0:
251 return True
252
253 for argname, spec in introsp.items():
254 if spec['dir'] == 'in' and argname in self.__in_type:
255 if self.__in_type[argname] != spec['type']:
256 return False
257 elif spec['dir'] == 'out' and argname in self.__out_type:
258 if self.__out_type[argname] != spec['type']:
259 return False
260 return True
261
262
263 def Run(self, bus, service, path, interface):
264 obj = bus.get_object(service, path)
265 obj_intf = dbus.Interface(obj, dbus_interface=interface)
266 method = obj_intf.get_dbus_method(self.__name)
267
268 result = False
269 try:
270 result = self.__expect_res == method(self.__in_data)
271 except dbus.exceptions.DBusException as err:
272 print(' Calling {name} failed'.format(name=self.__name))
273 print(' Error: {}'.format(str(err)))
274 result = False
275
276 text = ' {name}({in_data}) - Result: {result}'
277 print(text.format(name=self.__name,
278 in_data=str(self.__in_data),
279 result=result and "Pass" or "FAIL"))
280 return result
281
282
283 class TestFailingMethod(object):
284 """
285 This is similar to the TestMethod() class, but this tests methods
286 which are expected to fail. Such D-Bus methods should not normally
287 be found in a service, but is used to test the behaviour when an internal
288 error happens on the service side
289 """
290 def __init__(self, name, input_type, output_type, input_data):
291 self.__name = name
292 self.__in_type = input_type
293 self.__out_type = output_type
294 self.__in_data = input_data
295
296 def GetName(self):
297 return self.__name
298
299 def CheckIntrospection(self, introsp):
300 if len(introsp) == 0:
301 return True
302
303 for argname, spec in introsp.items():
304 if spec['dir'] == 'in' and argname in self.__in_type:
305 if self.__in_type[argname] != spec['type']:
306 return False
307 elif spec['dir'] == 'out' and argname in self.__out_type:
308 if self.__out_type[argname] != spec['type']:
309 return False
310 return True
311
312
313 def Run(self, bus, service, path, interface):
314 obj = bus.get_object(service, path)
315 obj_intf = dbus.Interface(obj, dbus_interface=interface)
316 method = obj_intf.get_dbus_method(self.__name)
317
318 result = False
319 try:
320 method(self.__in_data)
321 result = False
322 except dbus.exceptions.DBusException as err:
323 result = True
324
325 text = ' {name}({in_data}) - Result: {result}'
326 print(text.format(name=self.__name,
327 in_data=str(self.__in_data),
328 result=result and "Pass" or "FAIL"))
329 return result
330
331
332
333
334 class TestProperty(object):
335 """
336 Checks and validates specific D-Bus object properties. If a new value
337 is provided, it will also attempt changing to that value and set it back
338 to the initial value.
339 """
340
341
342 def __init__(self, name, value_type, init_val, new_val):
343 self.__name = name
344 self.__type = value_type
345 self.__init_val = init_val
346 self.__new_val = new_val
347
348
349 def GetName(self):
350 return self.__name
351
352
353 def CheckIntrospection(self, introsp):
354 if (self.__new_val is not None and introsp["access"] == "readwrite") \
355 or (self.__new_val is None and introsp["access"] == "read"):
356 if introsp["type"] == self.__type:
357 return True
358 return False
359
360
361 def Run(self, bus, service, path, interface):
362 obj = bus.get_object(service, path)
363 prop_intf = dbus.Interface(obj, dbus_interface="org.freedesktop.DBus.Properties")
364
365 test_result = True
366 propval = prop_intf.Get(interface, self.__name)
367 result = self.__init_val == propval
368
369 text = ' {name} ... Initial value - Result: {result}'
370 print(text.format(name=self.__name, result=result and "Pass" or "FAIL"))
371 if result is False:
372 print(' Expected: {}'.format(self.__init_val))
373 print(' Received: {}'.format(propval))
374 test_result = test_result and result
375
376 if self.__new_val is not None:
377 prop_intf.Set(interface, self.__name, self.__new_val)
378 propval = prop_intf.Get(interface, self.__name)
379 result = self.__new_val == propval
380 text = ' {name} ... Changing property - Result: {result}'
381 print(text.format(name=self.__name, result=result and "Pass" or "FAIL"))
382
383 test_result = test_result and result
384 prop_intf.Set(interface, self.__name, self.__init_val)
385 propval = prop_intf.Get(interface, self.__name)
386 result = self.__init_val == propval
387 text = ' {name} ... Changing back to initial value - Result: {result}'
388 print(text.format(name=self.__name, result=result and "Pass" or "FAIL"))
389 test_result = test_result and result
390
391 return test_result
392
393
394
395 class ExpectObject(object):
396 """
397 Declaration a D-Bus object expected to be found in a D-Bus service, with
398 a specific interface group.
399
400 This is used to collect TestMethod, TestFailingMethod and TestProperty
401 objects which will be run when exectuting the RunTests() method
402 """
403 def __init__(self, bus, service, path, interface):
404 self.__bus = bus
405 self.__service = service
406 self.__path = path
407 self.__interface = interface
408
409 self.__tests = []
410
411
412 def GetInfo(self):
413 return (self.__path, self.__interface, "ExpectObject")
414
415 def AddTest(self, tester_obj):
416 self.__tests.append(tester_obj)
417
418 def RunTests(self, introspection):
419 test_result = True
420 for runtest in self.__tests:
421 name = runtest.GetName()
422
423 try:
424 for section in introspection.GetSections(self.__path, self.__interface):
425 intrsp_fragm = introspection.GetFragment(self.__path,
426 self.__interface, section, name)
427 if intrsp_fragm is None:
428 continue
429
430 introsp_test = runtest.CheckIntrospection(intrsp_fragm)
431
432 text = ' [{section}] -- {name} ... Introspection test: {result}'
433 print(text.format(section=section, name=name, result=introsp_test and "Pass" or "FAIL"))
434
435 text = ' [{section}] -- {name} ... Testing functionality:'
436 print(text.format(section=section, name=name))
437 obj_test = runtest.Run(self.__bus, self.__service, self.__path, self.__interface)
438 text = ' [{section}] -- {name} ... Functionality test restult: {result}\n'
439 print(text.format(section=section, name=name, result=obj_test and "Pass" or "FAIL"))
440
441 test_result = test_result and introsp_test and obj_test
442 except TypeError:
443 text = ' {name}, path={path}, interface={interf} ... Introspection failed'
444 print(text.format(name=name, path=self.__path, interf=self.__interface))
445 test_result = False
446 return test_result
447
448
449
450 class ExpectMissingObject(object):
451 """
452 Declaration of a test to check if a D-Bus object is missing.
453 """
454 def __init__(self, bus, service, path, interface):
455 self.__bus = bus
456 self.__service = service
457 self.__path = path
458 self.__interface = interface
459
460
461 def GetInfo(self):
462 return (self.__path, self.__interface, "ExpectMissingObject")
463
464 def RunTests(self, introspection):
465 result = introspection.GetSections(self.__path, self.__interface) == None
466 text = ' Checking object is not available ... Introspection test: {result}'
467 print(text.format(result=result and "Pass" or "FAIL"))
468 return result
469
470
471
472 class TestService(object):
473 """
474 Declaration of a service to test. This contains a collection of
475 ExpectedObject objects which will be accessed when running the
476 RunTests() method
477 """
478 def __init__(self, bus, service):
479 self.__bus = bus
480 self.__service = service
481
482 self.__expect_objects = []
483
484
485 def ExpectObject(self, path, interface):
486 expobj = ExpectObject(self.__bus, self.__service, path, interface)
487 self.__expect_objects.append(expobj)
488 return expobj
489
490
491 def ExpectMissingObject(self, path, interface):
492 expobj = ExpectMissingObject(self.__bus, self.__service, path, interface)
493 self.__expect_objects.append(expobj)
494 return expobj
495
496
497 def RunTests(self):
498 result = True
499 for obj in self.__expect_objects:
500 info = obj.GetInfo()
501
502 # Retrieve a new introspection per test object; it may have
503 # changed in prior tests
504 introspection = IntrospectionParser(self.__bus, self.__service)
505 text = '>>> Running test: [{testname}] path={path}, interface={intf}'
506 print(text.format(path=info[0], intf=info[1], testname=info[2]))
507 result = result and obj.RunTests(introspection)
508
509 print(' Test Result: {result}'.format(result=result and "Pass" or "FAIL"))
510 print()
511 return result
512
513
514
515
516 if __name__ == "__main__":
517 """
518 Main test driver for the tests/simple-service.cpp D-Bus service
519
520 This service is expected to be found on the session bus prior to running
521 this test, under the 'net.openvpn.gdbuspp.test.simple' well-known bus name
522 """
523
524 session_bus = dbus.SessionBus()
525 tests = TestService(session_bus, 'net.openvpn.gdbuspp.test.simple')
526
527 #
528 # Test methods expecting to fail
529 # Run these tests early, to see if it triggers a service crash
530 #
531 failing_methods = tests.ExpectObject('/gdbuspp/tests/simple1/method_failures','gdbuspp.test.simple1')
532 failing_methods.AddTest(TestFailingMethod('InputMismatch',{'not_an_int': 's'}, {'failed': 'b'}, dbus.String('not a number')))
533 failing_methods.AddTest(TestFailingMethod('OutputMismatch',{}, {'failed': 'b'}, None))
534
535
536
537 #
538 # Test various methods
539 #
540 simple1_methods = tests.ExpectObject('/gdbuspp/tests/simple1/methods', 'gdbuspp.test.simple1')
541 simple1_methods.AddTest(TestMethod('MethodNoArgs',
542 {},
543 {},
544 None,
545 None))
546
547 simple1_methods.AddTest(TestMethod('GetCallerBusName',
548 {},
549 {'caller_busname': 's'},
550 None,
551 dbus.String(session_bus.get_unique_name())))
552
553 simple1_methods.AddTest(TestMethod('StringLength',
554 {'string': 's'},
555 {'length': 'i'},
556 dbus.String('A little and short test'),
557 dbus.Int32(23)))
558
559 simple1_methods.AddTest(TestMethod('CreateSimpleObject',
560 {'string': 's'},
561 {'path': 'o'},
562 dbus.String('testscript1'),
563 dbus.ObjectPath('/gdbuspp/tests/simple1/childs/testscript1')))
564
565 # Preparing a child object for the simple1_child test further below
566 simple1_methods.AddTest(TestMethod('CreateSimpleObject',
567 {'string': 's'},
568 {'path': 'o'},
569 dbus.String('child_test'),
570 dbus.ObjectPath('/gdbuspp/tests/simple1/childs/child_test')))
571
572 simple1_methods.AddTest(TestMethod('RemoveSimpleObject',
573 {'string': 's'},
574 None,
575 dbus.String('testscript1'),
576 None))
577
578 tests.ExpectMissingObject('/gdbuspp/tests/simple1/childs/testscript1', 'gdbuspp.test.simple1.child')
579
580 simple1_methods.AddTest(TestMethod('GetRemovedObjects',
581 {},
582 {'paths': 'ao'},
583 None,
584 dbus.Array([dbus.ObjectPath('/gdbuspp/tests/simple1/childs/testscript1')], signature=dbus.Signature('o'))))
585
586 #
587 # Testing a child object
588 #
589 simple1_child = tests.ExpectObject('/gdbuspp/tests/simple1/childs/child_test', 'gdbuspp.test.simple1.child')
590 simple1_child.AddTest(TestMethod('GetMyName',
591 {},
592 {'name': 's'},
593 None,
594 dbus.String('child_test')))
595 simple1_child.AddTest(TestProperty('my_path', 'o', '/gdbuspp/tests/simple1/childs/child_test', None))
596 simple1_child.AddTest(TestMethod('RemoveMe',
597 {'name': 's'},
598 {},
599 dbus.String('child_test'),
600 None))
601 tests.ExpectMissingObject('/gdbuspp/tests/simple1/childs/child_test', 'gdbuspp.test.simple1.child')
602
603 #
604 # Test properties storing single data types
605 #
606 simple1_props = tests.ExpectObject('/gdbuspp/tests/simple1/properties', 'gdbuspp.test.simple1')
607 simple1_props.AddTest(TestProperty('bool_val', 'b', dbus.Boolean(True), dbus.Boolean(False)))
608 simple1_props.AddTest(TestProperty('int_val', 'i', dbus.Int32(-345), dbus.Int32(65000)))
609 simple1_props.AddTest(TestProperty('uint_val', 'u', dbus.UInt32(123), dbus.UInt32(16)))
610 simple1_props.AddTest(TestProperty('long_val', 'x', dbus.Int64(9223372036854775807), dbus.Int64(-9223372036854775806)))
611 simple1_props.AddTest(TestProperty('ulong_val', 't', dbus.UInt64(18446744073709551615), dbus.UInt64(32)))
612 simple1_props.AddTest(TestProperty('string_val', 's', dbus.String('Initial string'), dbus.String('Test script string value')))
613
614 #
615 # Test properties storing arrays of various types
616 #
617 int_array_init = dbus.Array([dbus.Int32(-10), dbus.Int32(3), dbus.Int32(16), dbus.Int32(9388)], 'i')
618 int_array_new = dbus.Array([dbus.Int32(-9481), dbus.Int32(3134), dbus.Int32(4), dbus.Int32(-10394)], 'i')
619 simple1_props.AddTest(TestProperty('int_array', 'ai', int_array_init, int_array_new))
620
621 uint_array_init = dbus.Array([dbus.UInt32(0), dbus.UInt32(15), dbus.UInt32(16), dbus.UInt32(31), dbus.UInt32(32), dbus.UInt32(65534), dbus.UInt32(65535)], 'u')
622 uint_array_new = dbus.Array([dbus.UInt32(9481), dbus.UInt32(333134), dbus.UInt32(14), dbus.UInt32(85710394)], 'u')
623 simple1_props.AddTest(TestProperty('uint_array', 'au', uint_array_init, uint_array_new))
624
625 string_array_init = dbus.Array([dbus.String('line 1'), dbus.String('line 2'), dbus.String('line 3')])
626 string_array_new = dbus.Array([dbus.String('text line A'),dbus.String('text line B'),dbus.String('TEXT LINE c'),dbus.String('extended array')])
627 simple1_props.AddTest(TestProperty('string_array', 'as', string_array_init, string_array_new))
628
629 #
630 # Test property storing a struct of more data types
631 #
632 complex_init = dbus.Struct([dbus.Boolean(True), dbus.Int32(98877), dbus.String('Initial complex string value')])
633 complex_new = dbus.Struct([dbus.Boolean(False), dbus.Int32(-304922), dbus.String('New complex value set by test script')])
634 simple1_props.AddTest(TestProperty('complex', '(bis)', complex_init, complex_new))
635 simple1_props.AddTest(TestProperty('complex_readonly', '(bis)', complex_init, None))
636
637 ##
638 ## Run all the tests
639 ##
640 test_res = tests.RunTests()
641 print("======== OVERALL RESULT: %s" % (test_res and "PASS" or "FAILED"))
642
643 if test_res == True:
644 sys.exit(0)
645 else:
646 sys.exit(1)