Add an example of asynchronous calls. Run the examples during 'make check'.
[dbus-python-phuang.git] / test / test-client.py
blob5471b6bd2afcdc70f4bb553141cf1c6df56185da
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 # This program is free software; you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 2 of the License, or
13 # (at your option) any later version.
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
20 # You should have received a copy of the GNU General Public License
21 # along with this program; if not, write to the Free Software
22 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 import sys
26 import os
27 import unittest
28 import time
29 import logging
30 import weakref
32 builddir = os.path.normpath(os.environ["DBUS_TOP_BUILDDIR"])
33 pydir = os.path.normpath(os.environ["DBUS_TOP_SRCDIR"])
35 import dbus
36 import _dbus_bindings
37 import gobject
38 import dbus.glib
39 import dbus.service
42 logging.basicConfig()
45 pkg = dbus.__file__
46 if not pkg.startswith(pydir):
47 raise Exception("DBus modules (%s) are not being picked up from the package"%pkg)
49 if not _dbus_bindings.__file__.startswith(builddir):
50 raise Exception("DBus modules (%s) are not being picked up from the package"%_dbus_bindings.__file__)
52 test_types_vals = [1, 12323231, 3.14159265, 99999999.99,
53 "dude", "123", "What is all the fuss about?", "gob@gob.com",
54 u'\\u310c\\u310e\\u3114', u'\\u0413\\u0414\\u0415',
55 u'\\u2200software \\u2203crack', u'\\xf4\\xe5\\xe8',
56 [1,2,3], ["how", "are", "you"], [1.23,2.3], [1], ["Hello"],
57 (1,2,3), (1,), (1,"2",3), ("2", "what"), ("you", 1.2),
58 {1:"a", 2:"b"}, {"a":1, "b":2}, #{"a":(1,"B")},
59 {1:1.1, 2:2.2}, [[1,2,3],[2,3,4]], [["a","b"],["c","d"]],
60 True, False,
61 dbus.Int16(-10), dbus.UInt16(10), 'SENTINEL',
62 #([1,2,3],"c", 1.2, ["a","b","c"], {"a": (1,"v"), "b": (2,"d")})
65 class TestDBusBindings(unittest.TestCase):
66 def setUp(self):
67 self.bus = dbus.SessionBus()
68 self.remote_object = self.bus.get_object("org.freedesktop.DBus.TestSuitePythonService", "/org/freedesktop/DBus/TestSuitePythonObject")
69 self.iface = dbus.Interface(self.remote_object, "org.freedesktop.DBus.TestSuiteInterface")
71 def testWeakRefs(self):
72 # regression test for Sugar crash caused by smcv getting weak refs
73 # wrong - pre-bugfix, this would segfault
74 bus = dbus.SessionBus(private=True)
75 ref = weakref.ref(bus)
76 self.assert_(ref() is bus)
77 del bus
78 self.assert_(ref() is None)
80 def testInterfaceKeyword(self):
81 #test dbus_interface parameter
82 print self.remote_object.Echo("dbus_interface on Proxy test Passed", dbus_interface = "org.freedesktop.DBus.TestSuiteInterface")
83 print self.iface.Echo("dbus_interface on Interface test Passed", dbus_interface = "org.freedesktop.DBus.TestSuiteInterface")
84 self.assert_(True)
86 def testCallingConventionOptions(self):
87 self.assertEquals(self.iface.AcceptListOfByte('\1\2\3'), [1,2,3])
88 self.assertEquals(self.iface.AcceptListOfByte('\1\2\3', byte_arrays=True), '\1\2\3')
89 self.assertEquals(self.iface.AcceptByteArray('\1\2\3'), [1,2,3])
90 self.assertEquals(self.iface.AcceptByteArray('\1\2\3', byte_arrays=True), '\1\2\3')
91 self.assert_(isinstance(self.iface.AcceptUTF8String('abc'), unicode))
92 self.assert_(isinstance(self.iface.AcceptUTF8String('abc', utf8_strings=True), str))
93 self.assert_(isinstance(self.iface.AcceptUnicodeString('abc'), unicode))
94 self.assert_(isinstance(self.iface.AcceptUnicodeString('abc', utf8_strings=True), str))
96 def testIntrospection(self):
97 #test introspection
98 print "\n********* Introspection Test ************"
99 print self.remote_object.Introspect(dbus_interface="org.freedesktop.DBus.Introspectable")
100 print "Introspection test passed"
101 self.assert_(True)
103 def testPythonTypes(self):
104 #test sending python types and getting them back
105 print "\n********* Testing Python Types ***********"
107 for send_val in test_types_vals:
108 print "Testing %s"% str(send_val)
109 recv_val = self.iface.Echo(send_val)
110 self.assertEquals(send_val, recv_val)
111 self.assertEquals(recv_val.variant_level, 1)
113 def testUtf8StringsSync(self):
114 send_val = u'foo'
115 recv_val = self.iface.Echo(send_val, utf8_strings=True)
116 self.assert_(isinstance(recv_val, str))
117 self.assert_(isinstance(recv_val, dbus.UTF8String))
118 recv_val = self.iface.Echo(send_val, utf8_strings=False)
119 self.assert_(isinstance(recv_val, unicode))
120 self.assert_(isinstance(recv_val, dbus.String))
122 def testBenchmarkIntrospect(self):
123 print "\n********* Benchmark Introspect ************"
124 a = time.time()
125 print a
126 print self.iface.GetComplexArray()
127 b = time.time()
128 print b
129 print "Delta: %f" % (b - a)
130 self.assert_(True)
132 def testAsyncCalls(self):
133 #test sending python types and getting them back async
134 print "\n********* Testing Async Calls ***********"
136 failures = []
137 main_loop = gobject.MainLoop()
139 class async_check:
140 def __init__(self, test_controler, expected_result, do_exit, utf8):
141 self.expected_result = expected_result
142 self.do_exit = do_exit
143 self.utf8 = utf8
144 self.test_controler = test_controler
146 def callback(self, val):
147 try:
148 if self.do_exit:
149 main_loop.quit()
151 self.test_controler.assertEquals(val, self.expected_result)
152 self.test_controler.assertEquals(val.variant_level, 1)
153 if self.utf8 and not isinstance(val, dbus.UTF8String):
154 failures.append('%r should have been utf8 but was not' % val)
155 return
156 elif not self.utf8 and isinstance(val, dbus.UTF8String):
157 failures.append('%r should not have been utf8' % val)
158 return
159 except Exception, e:
160 failures.append("%s:\n%s" % (e.__class__, e))
162 def error_handler(self, error):
163 print error
164 if self.do_exit:
165 main_loop.quit()
167 failures.append('%s: %s' % (error.__class__, error))
169 last_type = test_types_vals[-1]
170 for send_val in test_types_vals:
171 print "Testing %s" % str(send_val)
172 utf8 = (send_val == 'gob@gob.com')
173 check = async_check(self, send_val, last_type == send_val,
174 utf8)
175 recv_val = self.iface.Echo(send_val,
176 reply_handler=check.callback,
177 error_handler=check.error_handler,
178 utf8_strings=utf8)
179 main_loop.run()
180 if failures:
181 self.assert_(False, failures)
183 def testStrictMarshalling(self):
184 print "\n********* Testing strict return & signal marshalling ***********"
186 # these values are the same as in the server, and the
187 # methods should only succeed when they are called with
188 # the right value number, because they have out_signature
189 # decorations, and return an unmatching type when called
190 # with a different number
191 values = ["", ("",""), ("","",""), [], {}, ["",""], ["","",""]]
192 methods = [
193 (self.iface.ReturnOneString, 'SignalOneString', set([0]), set([0])),
194 (self.iface.ReturnTwoStrings, 'SignalTwoStrings', set([1, 5]), set([1])),
195 (self.iface.ReturnStruct, 'SignalStruct', set([1, 5]), set([1])),
196 # all of our test values are sequences so will marshall correctly into an array :P
197 (self.iface.ReturnArray, 'SignalArray', set(range(len(values))), set([3, 5, 6])),
198 (self.iface.ReturnDict, 'SignalDict', set([0, 3, 4]), set([4]))
201 for (method, signal, success_values, return_values) in methods:
202 print "\nTrying correct behaviour of", method._method_name
203 for value in range(len(values)):
204 try:
205 ret = method(value)
206 except Exception, e:
207 print "%s(%r) raised %s: %s" % (method._method_name, values[value], e.__class__, e)
209 # should fail if it tried to marshal the wrong type
210 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))
211 else:
212 print "%s(%r) returned %r" % (method._method_name, values[value], ret)
214 # should only succeed if it's the right return type
215 self.assert_(value in success_values, "%s should fail when we ask it to return %r" % (method._method_name, values[value]))
217 # check the value is right too :D
218 returns = map(lambda n: values[n], return_values)
219 self.assert_(ret in returns, "%s should return one of %r but it returned %r instead" % (method._method_name, returns, ret))
221 print "\nTrying correct emission of", signal
222 for value in range(len(values)):
223 try:
224 self.iface.EmitSignal(signal, value)
225 except Exception, e:
226 print "EmitSignal(%s, %r) raised %s" % (signal, values[value], e.__class__)
228 # should fail if it tried to marshal the wrong type
229 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))
230 else:
231 print "EmitSignal(%s, %r) appeared to succeed" % (signal, values[value])
233 # should only succeed if it's the right return type
234 self.assert_(value in success_values, "EmitSignal(%s) should fail when we ask it to return %r" % (signal, values[value]))
236 # FIXME: wait for the signal here
238 print
240 def testInheritance(self):
241 print "\n********* Testing inheritance from dbus.method.Interface ***********"
242 ret = self.iface.CheckInheritance()
243 print "CheckInheritance returned %s" % ret
244 self.assert_(ret, "overriding CheckInheritance from TestInterface failed")
246 def testAsyncMethods(self):
247 print "\n********* Testing asynchronous method implementation *******"
248 for async in (True, False):
249 for fail in (True, False):
250 try:
251 val = ('a', 1, False, [1,2], {1:2})
252 print "calling AsynchronousMethod with %s %s %s" % (async, fail, val)
253 ret = self.iface.AsynchronousMethod(async, fail, val)
254 except Exception, e:
255 self.assert_(fail, '%s: %s' % (e.__class__, e))
256 print "Expected failure: %s: %s" % (e.__class__, e)
257 else:
258 self.assert_(not fail, 'Expected failure but succeeded?!')
259 self.assertEquals(val, ret)
260 self.assertEquals(1, ret.variant_level)
262 def testBusInstanceCaching(self):
263 print "\n********* Testing dbus.Bus instance sharing *********"
265 # unfortunately we can't test the system bus here
266 # but the codepaths are the same
267 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)):
268 print "\nTesting %s:" % cls.__name__
270 share_cls = cls()
271 share_type = dbus.Bus(bus_type=type)
272 share_func = func()
274 private_cls = cls(private=True)
275 private_type = dbus.Bus(bus_type=type, private=True)
276 private_func = func(private=True)
278 print " - checking shared instances are the same..."
279 self.assert_(share_cls == share_type, '%s should equal %s' % (share_cls, share_type))
280 self.assert_(share_type == share_func, '%s should equal %s' % (share_type, share_func))
282 print " - checking private instances are distinct from the shared instance..."
283 self.assert_(share_cls != private_cls, '%s should not equal %s' % (share_cls, private_cls))
284 self.assert_(share_type != private_type, '%s should not equal %s' % (share_type, private_type))
285 self.assert_(share_func != private_func, '%s should not equal %s' % (share_func, private_func))
287 print " - checking private instances are distinct from each other..."
288 self.assert_(private_cls != private_type, '%s should not equal %s' % (private_cls, private_type))
289 self.assert_(private_type != private_func, '%s should not equal %s' % (private_type, private_func))
290 self.assert_(private_func != private_cls, '%s should not equal %s' % (private_func, private_cls))
292 def testSenderName(self):
293 print '\n******** Testing sender name keyword ********'
294 myself = self.iface.WhoAmI()
295 print "I am", myself
297 def testBusNameCreation(self):
298 print '\n******** Testing BusName creation ********'
299 test = [('org.freedesktop.DBus.Python.TestName', True),
300 ('org.freedesktop.DBus.Python.TestName', True),
301 ('org.freedesktop.DBus.Python.InvalidName&^*%$', False)]
302 # Do some more intelligent handling/testing of queueing vs success?
303 # ('org.freedesktop.DBus.TestSuitePythonService', False)]
304 # For some reason this actually succeeds
305 # ('org.freedesktop.DBus', False)]
307 # make a method call to ensure the test service is active
308 self.iface.Echo("foo")
310 names = {}
311 for (name, succeed) in test:
312 try:
313 print "requesting %s" % name
314 busname = dbus.service.BusName(name)
315 except Exception, e:
316 print "%s:\n%s" % (e.__class__, e)
317 self.assert_(not succeed, 'did not expect registering bus name %s to fail' % name)
318 else:
319 print busname
320 self.assert_(succeed, 'expected registering bus name %s to fail'% name)
321 if name in names:
322 self.assert_(names[name] == busname, 'got a new instance for same name %s' % name)
323 print "instance of %s re-used, good!" % name
324 else:
325 names[name] = busname
327 del busname
329 print
331 del names
333 bus = dbus.Bus()
334 ret = bus.name_has_owner('org.freedesktop.DBus.Python.TestName')
335 self.assert_(not ret, 'deleting reference failed to release BusName org.freedesktop.DBus.Python.TestName')
337 """ Remove this for now
338 class TestDBusPythonToGLibBindings(unittest.TestCase):
339 def setUp(self):
340 self.bus = dbus.SessionBus()
341 self.remote_object = self.bus.get_object("org.freedesktop.DBus.TestSuiteGLibService", "/org/freedesktop/DBus/Tests/MyTestObject")
342 self.iface = dbus.Interface(self.remote_object, "org.freedesktop.DBus.Tests.MyObject")
344 def testIntrospection(self):
345 #test introspection
346 print "\n********* Introspection Test ************"
347 print self.remote_object.Introspect(dbus_interface="org.freedesktop.DBus.Introspectable")
348 print "Introspection test passed"
349 self.assert_(True)
351 def testCalls(self):
352 print "\n********* Call Test ************"
353 result = self.iface.ManyArgs(1000, 'Hello GLib', 2)
354 print result
355 self.assert_(result == [2002.0, 'HELLO GLIB'])
357 arg0 = {"Dude": 1, "john": "palmieri", "python": 2.4}
358 result = self.iface.ManyStringify(arg0)
359 print result
361 print "Call test passed"
362 self.assert_(True)
364 def testPythonTypes(self):
365 print "\n********* Testing Python Types ***********"
367 for send_val in test_types_vals:
368 print "Testing %s"% str(send_val)
369 recv_val = self.iface.EchoVariant(send_val)
370 self.assertEquals(send_val, recv_val.object)
372 if __name__ == '__main__':
373 gobject.threads_init()
374 dbus.glib.init_threads()
376 unittest.main()