Don't run the examples during "make check" - timing/startup issues cause intermittent...
[dbus-python-phuang.git] / test / test-client.py
blob04706df63db8cd66bb4a1ebecc2a4abcde88500e
1 #!/usr/bin/env python
3 # Copyright (C) 2004 Red Hat Inc. <http://www.redhat.com/>
4 # Copyright (C) 2005, 2006 Collabora Ltd. <http://www.collabora.co.uk/>
6 # Licensed under the Academic Free License version 2.1
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 2 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program; if not, write to the Free Software
20 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 import sys
24 import os
25 import unittest
26 import time
27 import logging
28 import weakref
30 builddir = os.path.normpath(os.environ["DBUS_TOP_BUILDDIR"])
31 pydir = os.path.normpath(os.environ["DBUS_TOP_SRCDIR"])
33 import dbus
34 import _dbus_bindings
35 import gobject
36 import dbus.glib
37 import dbus.service
40 logging.basicConfig()
43 pkg = dbus.__file__
44 if not pkg.startswith(pydir):
45 raise Exception("DBus modules (%s) are not being picked up from the package"%pkg)
47 if not _dbus_bindings.__file__.startswith(builddir):
48 raise Exception("DBus modules (%s) are not being picked up from the package"%_dbus_bindings.__file__)
50 test_types_vals = [1, 12323231, 3.14159265, 99999999.99,
51 "dude", "123", "What is all the fuss about?", "gob@gob.com",
52 u'\\u310c\\u310e\\u3114', u'\\u0413\\u0414\\u0415',
53 u'\\u2200software \\u2203crack', u'\\xf4\\xe5\\xe8',
54 [1,2,3], ["how", "are", "you"], [1.23,2.3], [1], ["Hello"],
55 (1,2,3), (1,), (1,"2",3), ("2", "what"), ("you", 1.2),
56 {1:"a", 2:"b"}, {"a":1, "b":2}, #{"a":(1,"B")},
57 {1:1.1, 2:2.2}, [[1,2,3],[2,3,4]], [["a","b"],["c","d"]],
58 True, False,
59 dbus.Int16(-10), dbus.UInt16(10), 'SENTINEL',
60 #([1,2,3],"c", 1.2, ["a","b","c"], {"a": (1,"v"), "b": (2,"d")})
63 NAME = "org.freedesktop.DBus.TestSuitePythonService"
64 IFACE = "org.freedesktop.DBus.TestSuiteInterface"
65 OBJECT = "/org/freedesktop/DBus/TestSuitePythonObject"
67 class TestDBusBindings(unittest.TestCase):
68 def setUp(self):
69 self.bus = dbus.SessionBus()
70 self.remote_object = self.bus.get_object(NAME, OBJECT)
71 self.iface = dbus.Interface(self.remote_object, IFACE)
73 def testGObject(self):
74 print "Testing ExportedGObject... ",
75 remote_gobject = self.bus.get_object(NAME, OBJECT + '/GObject')
76 iface = dbus.Interface(remote_gobject, IFACE)
77 print "introspection, ",
78 remote_gobject.Introspect(dbus_interface=dbus.INTROSPECTABLE_IFACE)
79 print "method call, ",
80 self.assertEquals(iface.Echo('123'), '123')
81 print "... OK"
83 def testWeakRefs(self):
84 # regression test for Sugar crash caused by smcv getting weak refs
85 # wrong - pre-bugfix, this would segfault
86 bus = dbus.SessionBus(private=True)
87 ref = weakref.ref(bus)
88 self.assert_(ref() is bus)
89 del bus
90 self.assert_(ref() is None)
92 def testInterfaceKeyword(self):
93 #test dbus_interface parameter
94 print self.remote_object.Echo("dbus_interface on Proxy test Passed", dbus_interface = "org.freedesktop.DBus.TestSuiteInterface")
95 print self.iface.Echo("dbus_interface on Interface test Passed", dbus_interface = "org.freedesktop.DBus.TestSuiteInterface")
96 self.assert_(True)
98 def testGetDBusMethod(self):
99 self.assertEquals(self.iface.get_dbus_method('AcceptListOfByte')('\1\2\3'), [1,2,3])
100 self.assertEquals(self.remote_object.get_dbus_method('AcceptListOfByte', dbus_interface='org.freedesktop.DBus.TestSuiteInterface')('\1\2\3'), [1,2,3])
102 def testCallingConventionOptions(self):
103 self.assertEquals(self.iface.AcceptListOfByte('\1\2\3'), [1,2,3])
104 self.assertEquals(self.iface.AcceptListOfByte('\1\2\3', byte_arrays=True), '\1\2\3')
105 self.assertEquals(self.iface.AcceptByteArray('\1\2\3'), [1,2,3])
106 self.assertEquals(self.iface.AcceptByteArray('\1\2\3', byte_arrays=True), '\1\2\3')
107 self.assert_(isinstance(self.iface.AcceptUTF8String('abc'), unicode))
108 self.assert_(isinstance(self.iface.AcceptUTF8String('abc', utf8_strings=True), str))
109 self.assert_(isinstance(self.iface.AcceptUnicodeString('abc'), unicode))
110 self.assert_(isinstance(self.iface.AcceptUnicodeString('abc', utf8_strings=True), str))
112 def testIntrospection(self):
113 #test introspection
114 print "\n********* Introspection Test ************"
115 print self.remote_object.Introspect(dbus_interface="org.freedesktop.DBus.Introspectable")
116 print "Introspection test passed"
117 self.assert_(True)
119 def testPythonTypes(self):
120 #test sending python types and getting them back
121 print "\n********* Testing Python Types ***********"
123 for send_val in test_types_vals:
124 print "Testing %s"% str(send_val)
125 recv_val = self.iface.Echo(send_val)
126 self.assertEquals(send_val, recv_val)
127 self.assertEquals(recv_val.variant_level, 1)
129 def testMethodExtraInfoKeywords(self):
130 print "Testing MethodExtraInfoKeywords..."
131 sender, path, destination, message_cls = self.iface.MethodExtraInfoKeywords()
132 self.assert_(sender.startswith(':'))
133 self.assertEquals(path, '/org/freedesktop/DBus/TestSuitePythonObject')
134 # we're using the "early binding" form of get_object (without
135 # follow_name_owner_changes), so the destination we actually sent it
136 # to will be the unique name
137 self.assert_(destination.startswith(':'))
138 self.assertEquals(message_cls, 'dbus.lowlevel.MethodCallMessage')
140 def testUtf8StringsSync(self):
141 send_val = u'foo'
142 recv_val = self.iface.Echo(send_val, utf8_strings=True)
143 self.assert_(isinstance(recv_val, str))
144 self.assert_(isinstance(recv_val, dbus.UTF8String))
145 recv_val = self.iface.Echo(send_val, utf8_strings=False)
146 self.assert_(isinstance(recv_val, unicode))
147 self.assert_(isinstance(recv_val, dbus.String))
149 def testBenchmarkIntrospect(self):
150 print "\n********* Benchmark Introspect ************"
151 a = time.time()
152 print a
153 print self.iface.GetComplexArray()
154 b = time.time()
155 print b
156 print "Delta: %f" % (b - a)
157 self.assert_(True)
159 def testAsyncCalls(self):
160 #test sending python types and getting them back async
161 print "\n********* Testing Async Calls ***********"
163 failures = []
164 main_loop = gobject.MainLoop()
166 class async_check:
167 def __init__(self, test_controler, expected_result, do_exit, utf8):
168 self.expected_result = expected_result
169 self.do_exit = do_exit
170 self.utf8 = utf8
171 self.test_controler = test_controler
173 def callback(self, val):
174 try:
175 if self.do_exit:
176 main_loop.quit()
178 self.test_controler.assertEquals(val, self.expected_result)
179 self.test_controler.assertEquals(val.variant_level, 1)
180 if self.utf8 and not isinstance(val, dbus.UTF8String):
181 failures.append('%r should have been utf8 but was not' % val)
182 return
183 elif not self.utf8 and isinstance(val, dbus.UTF8String):
184 failures.append('%r should not have been utf8' % val)
185 return
186 except Exception, e:
187 failures.append("%s:\n%s" % (e.__class__, e))
189 def error_handler(self, error):
190 print error
191 if self.do_exit:
192 main_loop.quit()
194 failures.append('%s: %s' % (error.__class__, error))
196 last_type = test_types_vals[-1]
197 for send_val in test_types_vals:
198 print "Testing %s" % str(send_val)
199 utf8 = (send_val == 'gob@gob.com')
200 check = async_check(self, send_val, last_type == send_val,
201 utf8)
202 recv_val = self.iface.Echo(send_val,
203 reply_handler=check.callback,
204 error_handler=check.error_handler,
205 utf8_strings=utf8)
206 main_loop.run()
207 if failures:
208 self.assert_(False, failures)
210 def testStrictMarshalling(self):
211 print "\n********* Testing strict return & signal marshalling ***********"
213 # these values are the same as in the server, and the
214 # methods should only succeed when they are called with
215 # the right value number, because they have out_signature
216 # decorations, and return an unmatching type when called
217 # with a different number
218 values = ["", ("",""), ("","",""), [], {}, ["",""], ["","",""]]
219 methods = [
220 (self.iface.ReturnOneString, 'SignalOneString', set([0]), set([0])),
221 (self.iface.ReturnTwoStrings, 'SignalTwoStrings', set([1, 5]), set([1])),
222 (self.iface.ReturnStruct, 'SignalStruct', set([1, 5]), set([1])),
223 # all of our test values are sequences so will marshall correctly into an array :P
224 (self.iface.ReturnArray, 'SignalArray', set(range(len(values))), set([3, 5, 6])),
225 (self.iface.ReturnDict, 'SignalDict', set([0, 3, 4]), set([4]))
228 for (method, signal, success_values, return_values) in methods:
229 print "\nTrying correct behaviour of", method._method_name
230 for value in range(len(values)):
231 try:
232 ret = method(value)
233 except Exception, e:
234 print "%s(%r) raised %s: %s" % (method._method_name, values[value], e.__class__, e)
236 # should fail if it tried to marshal the wrong type
237 self.assert_(value not in success_values, "%s should succeed when we ask it to return %r\n%s\n%s" % (method._method_name, values[value], e.__class__, e))
238 else:
239 print "%s(%r) returned %r" % (method._method_name, values[value], ret)
241 # should only succeed if it's the right return type
242 self.assert_(value in success_values, "%s should fail when we ask it to return %r" % (method._method_name, values[value]))
244 # check the value is right too :D
245 returns = map(lambda n: values[n], return_values)
246 self.assert_(ret in returns, "%s should return one of %r but it returned %r instead" % (method._method_name, returns, ret))
248 print "\nTrying correct emission of", signal
249 for value in range(len(values)):
250 try:
251 self.iface.EmitSignal(signal, value)
252 except Exception, e:
253 print "EmitSignal(%s, %r) raised %s" % (signal, values[value], e.__class__)
255 # should fail if it tried to marshal the wrong type
256 self.assert_(value not in success_values, "EmitSignal(%s) should succeed when we ask it to return %r\n%s\n%s" % (signal, values[value], e.__class__, e))
257 else:
258 print "EmitSignal(%s, %r) appeared to succeed" % (signal, values[value])
260 # should only succeed if it's the right return type
261 self.assert_(value in success_values, "EmitSignal(%s) should fail when we ask it to return %r" % (signal, values[value]))
263 # FIXME: wait for the signal here
265 print
267 def testInheritance(self):
268 print "\n********* Testing inheritance from dbus.method.Interface ***********"
269 ret = self.iface.CheckInheritance()
270 print "CheckInheritance returned %s" % ret
271 self.assert_(ret, "overriding CheckInheritance from TestInterface failed")
273 def testAsyncMethods(self):
274 print "\n********* Testing asynchronous method implementation *******"
275 for async in (True, False):
276 for fail in (True, False):
277 try:
278 val = ('a', 1, False, [1,2], {1:2})
279 print "calling AsynchronousMethod with %s %s %s" % (async, fail, val)
280 ret = self.iface.AsynchronousMethod(async, fail, val)
281 except Exception, e:
282 self.assert_(fail, '%s: %s' % (e.__class__, e))
283 print "Expected failure: %s: %s" % (e.__class__, e)
284 else:
285 self.assert_(not fail, 'Expected failure but succeeded?!')
286 self.assertEquals(val, ret)
287 self.assertEquals(1, ret.variant_level)
289 def testBusInstanceCaching(self):
290 print "\n********* Testing dbus.Bus instance sharing *********"
292 # unfortunately we can't test the system bus here
293 # but the codepaths are the same
294 for (cls, type, func) in ((dbus.SessionBus, dbus.Bus.TYPE_SESSION, dbus.Bus.get_session), (dbus.StarterBus, dbus.Bus.TYPE_STARTER, dbus.Bus.get_starter)):
295 print "\nTesting %s:" % cls.__name__
297 share_cls = cls()
298 share_type = dbus.Bus(bus_type=type)
299 share_func = func()
301 private_cls = cls(private=True)
302 private_type = dbus.Bus(bus_type=type, private=True)
303 private_func = func(private=True)
305 print " - checking shared instances are the same..."
306 self.assert_(share_cls == share_type, '%s should equal %s' % (share_cls, share_type))
307 self.assert_(share_type == share_func, '%s should equal %s' % (share_type, share_func))
309 print " - checking private instances are distinct from the shared instance..."
310 self.assert_(share_cls != private_cls, '%s should not equal %s' % (share_cls, private_cls))
311 self.assert_(share_type != private_type, '%s should not equal %s' % (share_type, private_type))
312 self.assert_(share_func != private_func, '%s should not equal %s' % (share_func, private_func))
314 print " - checking private instances are distinct from each other..."
315 self.assert_(private_cls != private_type, '%s should not equal %s' % (private_cls, private_type))
316 self.assert_(private_type != private_func, '%s should not equal %s' % (private_type, private_func))
317 self.assert_(private_func != private_cls, '%s should not equal %s' % (private_func, private_cls))
319 def testSenderName(self):
320 print '\n******** Testing sender name keyword ********'
321 myself = self.iface.WhoAmI()
322 print "I am", myself
324 def testBusGetNameOwner(self):
325 ret = self.bus.get_name_owner(NAME)
326 self.assert_(ret.startswith(':'), ret)
328 def testBusListNames(self):
329 ret = self.bus.list_names()
330 self.assert_(NAME in ret, ret)
332 def testBusListActivatableNames(self):
333 ret = self.bus.list_activatable_names()
334 self.assert_(NAME in ret, ret)
336 def testBusNameHasOwner(self):
337 self.assert_(self.bus.name_has_owner(NAME))
338 self.assert_(not self.bus.name_has_owner('badger.mushroom.snake'))
340 def testBusNameCreation(self):
341 print '\n******** Testing BusName creation ********'
342 test = [('org.freedesktop.DBus.Python.TestName', True),
343 ('org.freedesktop.DBus.Python.TestName', True),
344 ('org.freedesktop.DBus.Python.InvalidName&^*%$', False)]
345 # Do some more intelligent handling/testing of queueing vs success?
346 # ('org.freedesktop.DBus.TestSuitePythonService', False)]
347 # For some reason this actually succeeds
348 # ('org.freedesktop.DBus', False)]
350 # make a method call to ensure the test service is active
351 self.iface.Echo("foo")
353 names = {}
354 for (name, succeed) in test:
355 try:
356 print "requesting %s" % name
357 busname = dbus.service.BusName(name)
358 except Exception, e:
359 print "%s:\n%s" % (e.__class__, e)
360 self.assert_(not succeed, 'did not expect registering bus name %s to fail' % name)
361 else:
362 print busname
363 self.assert_(succeed, 'expected registering bus name %s to fail'% name)
364 if name in names:
365 self.assert_(names[name] == busname, 'got a new instance for same name %s' % name)
366 print "instance of %s re-used, good!" % name
367 else:
368 names[name] = busname
370 del busname
372 print
374 del names
376 bus = dbus.Bus()
377 ret = bus.name_has_owner('org.freedesktop.DBus.Python.TestName')
378 self.assert_(not ret, 'deleting reference failed to release BusName org.freedesktop.DBus.Python.TestName')
380 def testMultipleReturnWithoutSignature(self):
381 # https://bugs.freedesktop.org/show_bug.cgi?id=10174
382 ret = self.iface.MultipleReturnWithoutSignature()
383 self.assert_(not isinstance(ret, dbus.Struct), repr(ret))
384 self.assertEquals(ret, ('abc', 123))
386 """ Remove this for now
387 class TestDBusPythonToGLibBindings(unittest.TestCase):
388 def setUp(self):
389 self.bus = dbus.SessionBus()
390 self.remote_object = self.bus.get_object("org.freedesktop.DBus.TestSuiteGLibService", "/org/freedesktop/DBus/Tests/MyTestObject")
391 self.iface = dbus.Interface(self.remote_object, "org.freedesktop.DBus.Tests.MyObject")
393 def testIntrospection(self):
394 #test introspection
395 print "\n********* Introspection Test ************"
396 print self.remote_object.Introspect(dbus_interface="org.freedesktop.DBus.Introspectable")
397 print "Introspection test passed"
398 self.assert_(True)
400 def testCalls(self):
401 print "\n********* Call Test ************"
402 result = self.iface.ManyArgs(1000, 'Hello GLib', 2)
403 print result
404 self.assert_(result == [2002.0, 'HELLO GLIB'])
406 arg0 = {"Dude": 1, "john": "palmieri", "python": 2.4}
407 result = self.iface.ManyStringify(arg0)
408 print result
410 print "Call test passed"
411 self.assert_(True)
413 def testPythonTypes(self):
414 print "\n********* Testing Python Types ***********"
416 for send_val in test_types_vals:
417 print "Testing %s"% str(send_val)
418 recv_val = self.iface.EchoVariant(send_val)
419 self.assertEquals(send_val, recv_val.object)
421 if __name__ == '__main__':
422 gobject.threads_init()
423 dbus.glib.init_threads()
425 unittest.main()