dbus/_bus_mixin.py: Add bindings for ListNames, ListActivatableNames, GetNameOwner too
[dbus-python-phuang.git] / test / test-client.py
blobb9d2242fe55b8ddcd5a2ae697461ef5e5df1c39a
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 testWeakRefs(self):
74 # regression test for Sugar crash caused by smcv getting weak refs
75 # wrong - pre-bugfix, this would segfault
76 bus = dbus.SessionBus(private=True)
77 ref = weakref.ref(bus)
78 self.assert_(ref() is bus)
79 del bus
80 self.assert_(ref() is None)
82 def testInterfaceKeyword(self):
83 #test dbus_interface parameter
84 print self.remote_object.Echo("dbus_interface on Proxy test Passed", dbus_interface = "org.freedesktop.DBus.TestSuiteInterface")
85 print self.iface.Echo("dbus_interface on Interface test Passed", dbus_interface = "org.freedesktop.DBus.TestSuiteInterface")
86 self.assert_(True)
88 def testGetDBusMethod(self):
89 self.assertEquals(self.iface.get_dbus_method('AcceptListOfByte')('\1\2\3'), [1,2,3])
90 self.assertEquals(self.remote_object.get_dbus_method('AcceptListOfByte', dbus_interface='org.freedesktop.DBus.TestSuiteInterface')('\1\2\3'), [1,2,3])
92 def testCallingConventionOptions(self):
93 self.assertEquals(self.iface.AcceptListOfByte('\1\2\3'), [1,2,3])
94 self.assertEquals(self.iface.AcceptListOfByte('\1\2\3', byte_arrays=True), '\1\2\3')
95 self.assertEquals(self.iface.AcceptByteArray('\1\2\3'), [1,2,3])
96 self.assertEquals(self.iface.AcceptByteArray('\1\2\3', byte_arrays=True), '\1\2\3')
97 self.assert_(isinstance(self.iface.AcceptUTF8String('abc'), unicode))
98 self.assert_(isinstance(self.iface.AcceptUTF8String('abc', utf8_strings=True), str))
99 self.assert_(isinstance(self.iface.AcceptUnicodeString('abc'), unicode))
100 self.assert_(isinstance(self.iface.AcceptUnicodeString('abc', utf8_strings=True), str))
102 def testIntrospection(self):
103 #test introspection
104 print "\n********* Introspection Test ************"
105 print self.remote_object.Introspect(dbus_interface="org.freedesktop.DBus.Introspectable")
106 print "Introspection test passed"
107 self.assert_(True)
109 def testPythonTypes(self):
110 #test sending python types and getting them back
111 print "\n********* Testing Python Types ***********"
113 for send_val in test_types_vals:
114 print "Testing %s"% str(send_val)
115 recv_val = self.iface.Echo(send_val)
116 self.assertEquals(send_val, recv_val)
117 self.assertEquals(recv_val.variant_level, 1)
119 def testMethodExtraInfoKeywords(self):
120 print "Testing MethodExtraInfoKeywords..."
121 sender, path, destination, message_cls = self.iface.MethodExtraInfoKeywords()
122 self.assert_(sender.startswith(':'))
123 self.assertEquals(path, '/org/freedesktop/DBus/TestSuitePythonObject')
124 # we're using the "early binding" form of get_object (without
125 # follow_name_owner_changes), so the destination we actually sent it
126 # to will be the unique name
127 self.assert_(destination.startswith(':'))
128 self.assertEquals(message_cls, 'dbus.lowlevel.MethodCallMessage')
130 def testUtf8StringsSync(self):
131 send_val = u'foo'
132 recv_val = self.iface.Echo(send_val, utf8_strings=True)
133 self.assert_(isinstance(recv_val, str))
134 self.assert_(isinstance(recv_val, dbus.UTF8String))
135 recv_val = self.iface.Echo(send_val, utf8_strings=False)
136 self.assert_(isinstance(recv_val, unicode))
137 self.assert_(isinstance(recv_val, dbus.String))
139 def testBenchmarkIntrospect(self):
140 print "\n********* Benchmark Introspect ************"
141 a = time.time()
142 print a
143 print self.iface.GetComplexArray()
144 b = time.time()
145 print b
146 print "Delta: %f" % (b - a)
147 self.assert_(True)
149 def testAsyncCalls(self):
150 #test sending python types and getting them back async
151 print "\n********* Testing Async Calls ***********"
153 failures = []
154 main_loop = gobject.MainLoop()
156 class async_check:
157 def __init__(self, test_controler, expected_result, do_exit, utf8):
158 self.expected_result = expected_result
159 self.do_exit = do_exit
160 self.utf8 = utf8
161 self.test_controler = test_controler
163 def callback(self, val):
164 try:
165 if self.do_exit:
166 main_loop.quit()
168 self.test_controler.assertEquals(val, self.expected_result)
169 self.test_controler.assertEquals(val.variant_level, 1)
170 if self.utf8 and not isinstance(val, dbus.UTF8String):
171 failures.append('%r should have been utf8 but was not' % val)
172 return
173 elif not self.utf8 and isinstance(val, dbus.UTF8String):
174 failures.append('%r should not have been utf8' % val)
175 return
176 except Exception, e:
177 failures.append("%s:\n%s" % (e.__class__, e))
179 def error_handler(self, error):
180 print error
181 if self.do_exit:
182 main_loop.quit()
184 failures.append('%s: %s' % (error.__class__, error))
186 last_type = test_types_vals[-1]
187 for send_val in test_types_vals:
188 print "Testing %s" % str(send_val)
189 utf8 = (send_val == 'gob@gob.com')
190 check = async_check(self, send_val, last_type == send_val,
191 utf8)
192 recv_val = self.iface.Echo(send_val,
193 reply_handler=check.callback,
194 error_handler=check.error_handler,
195 utf8_strings=utf8)
196 main_loop.run()
197 if failures:
198 self.assert_(False, failures)
200 def testStrictMarshalling(self):
201 print "\n********* Testing strict return & signal marshalling ***********"
203 # these values are the same as in the server, and the
204 # methods should only succeed when they are called with
205 # the right value number, because they have out_signature
206 # decorations, and return an unmatching type when called
207 # with a different number
208 values = ["", ("",""), ("","",""), [], {}, ["",""], ["","",""]]
209 methods = [
210 (self.iface.ReturnOneString, 'SignalOneString', set([0]), set([0])),
211 (self.iface.ReturnTwoStrings, 'SignalTwoStrings', set([1, 5]), set([1])),
212 (self.iface.ReturnStruct, 'SignalStruct', set([1, 5]), set([1])),
213 # all of our test values are sequences so will marshall correctly into an array :P
214 (self.iface.ReturnArray, 'SignalArray', set(range(len(values))), set([3, 5, 6])),
215 (self.iface.ReturnDict, 'SignalDict', set([0, 3, 4]), set([4]))
218 for (method, signal, success_values, return_values) in methods:
219 print "\nTrying correct behaviour of", method._method_name
220 for value in range(len(values)):
221 try:
222 ret = method(value)
223 except Exception, e:
224 print "%s(%r) raised %s: %s" % (method._method_name, values[value], e.__class__, e)
226 # should fail if it tried to marshal the wrong type
227 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))
228 else:
229 print "%s(%r) returned %r" % (method._method_name, values[value], ret)
231 # should only succeed if it's the right return type
232 self.assert_(value in success_values, "%s should fail when we ask it to return %r" % (method._method_name, values[value]))
234 # check the value is right too :D
235 returns = map(lambda n: values[n], return_values)
236 self.assert_(ret in returns, "%s should return one of %r but it returned %r instead" % (method._method_name, returns, ret))
238 print "\nTrying correct emission of", signal
239 for value in range(len(values)):
240 try:
241 self.iface.EmitSignal(signal, value)
242 except Exception, e:
243 print "EmitSignal(%s, %r) raised %s" % (signal, values[value], e.__class__)
245 # should fail if it tried to marshal the wrong type
246 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))
247 else:
248 print "EmitSignal(%s, %r) appeared to succeed" % (signal, values[value])
250 # should only succeed if it's the right return type
251 self.assert_(value in success_values, "EmitSignal(%s) should fail when we ask it to return %r" % (signal, values[value]))
253 # FIXME: wait for the signal here
255 print
257 def testInheritance(self):
258 print "\n********* Testing inheritance from dbus.method.Interface ***********"
259 ret = self.iface.CheckInheritance()
260 print "CheckInheritance returned %s" % ret
261 self.assert_(ret, "overriding CheckInheritance from TestInterface failed")
263 def testAsyncMethods(self):
264 print "\n********* Testing asynchronous method implementation *******"
265 for async in (True, False):
266 for fail in (True, False):
267 try:
268 val = ('a', 1, False, [1,2], {1:2})
269 print "calling AsynchronousMethod with %s %s %s" % (async, fail, val)
270 ret = self.iface.AsynchronousMethod(async, fail, val)
271 except Exception, e:
272 self.assert_(fail, '%s: %s' % (e.__class__, e))
273 print "Expected failure: %s: %s" % (e.__class__, e)
274 else:
275 self.assert_(not fail, 'Expected failure but succeeded?!')
276 self.assertEquals(val, ret)
277 self.assertEquals(1, ret.variant_level)
279 def testBusInstanceCaching(self):
280 print "\n********* Testing dbus.Bus instance sharing *********"
282 # unfortunately we can't test the system bus here
283 # but the codepaths are the same
284 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)):
285 print "\nTesting %s:" % cls.__name__
287 share_cls = cls()
288 share_type = dbus.Bus(bus_type=type)
289 share_func = func()
291 private_cls = cls(private=True)
292 private_type = dbus.Bus(bus_type=type, private=True)
293 private_func = func(private=True)
295 print " - checking shared instances are the same..."
296 self.assert_(share_cls == share_type, '%s should equal %s' % (share_cls, share_type))
297 self.assert_(share_type == share_func, '%s should equal %s' % (share_type, share_func))
299 print " - checking private instances are distinct from the shared instance..."
300 self.assert_(share_cls != private_cls, '%s should not equal %s' % (share_cls, private_cls))
301 self.assert_(share_type != private_type, '%s should not equal %s' % (share_type, private_type))
302 self.assert_(share_func != private_func, '%s should not equal %s' % (share_func, private_func))
304 print " - checking private instances are distinct from each other..."
305 self.assert_(private_cls != private_type, '%s should not equal %s' % (private_cls, private_type))
306 self.assert_(private_type != private_func, '%s should not equal %s' % (private_type, private_func))
307 self.assert_(private_func != private_cls, '%s should not equal %s' % (private_func, private_cls))
309 def testSenderName(self):
310 print '\n******** Testing sender name keyword ********'
311 myself = self.iface.WhoAmI()
312 print "I am", myself
314 def testBusGetNameOwner(self):
315 ret = self.bus.get_name_owner(NAME)
316 self.assert_(ret.startswith(':'), ret)
318 def testBusListNames(self):
319 ret = self.bus.list_names()
320 self.assert_(NAME in ret, ret)
322 def testBusListActivatableNames(self):
323 ret = self.bus.list_activatable_names()
324 self.assert_(NAME in ret, ret)
326 def testBusNameHasOwner(self):
327 self.assert_(self.bus.name_has_owner(NAME))
328 self.assert_(not self.bus.name_has_owner('badger.mushroom.snake'))
330 def testBusNameCreation(self):
331 print '\n******** Testing BusName creation ********'
332 test = [('org.freedesktop.DBus.Python.TestName', True),
333 ('org.freedesktop.DBus.Python.TestName', True),
334 ('org.freedesktop.DBus.Python.InvalidName&^*%$', False)]
335 # Do some more intelligent handling/testing of queueing vs success?
336 # ('org.freedesktop.DBus.TestSuitePythonService', False)]
337 # For some reason this actually succeeds
338 # ('org.freedesktop.DBus', False)]
340 # make a method call to ensure the test service is active
341 self.iface.Echo("foo")
343 names = {}
344 for (name, succeed) in test:
345 try:
346 print "requesting %s" % name
347 busname = dbus.service.BusName(name)
348 except Exception, e:
349 print "%s:\n%s" % (e.__class__, e)
350 self.assert_(not succeed, 'did not expect registering bus name %s to fail' % name)
351 else:
352 print busname
353 self.assert_(succeed, 'expected registering bus name %s to fail'% name)
354 if name in names:
355 self.assert_(names[name] == busname, 'got a new instance for same name %s' % name)
356 print "instance of %s re-used, good!" % name
357 else:
358 names[name] = busname
360 del busname
362 print
364 del names
366 bus = dbus.Bus()
367 ret = bus.name_has_owner('org.freedesktop.DBus.Python.TestName')
368 self.assert_(not ret, 'deleting reference failed to release BusName org.freedesktop.DBus.Python.TestName')
370 def testMultipleReturnWithoutSignature(self):
371 # https://bugs.freedesktop.org/show_bug.cgi?id=10174
372 ret = self.iface.MultipleReturnWithoutSignature()
373 self.assert_(not isinstance(ret, dbus.Struct), repr(ret))
374 self.assertEquals(ret, ('abc', 123))
376 """ Remove this for now
377 class TestDBusPythonToGLibBindings(unittest.TestCase):
378 def setUp(self):
379 self.bus = dbus.SessionBus()
380 self.remote_object = self.bus.get_object("org.freedesktop.DBus.TestSuiteGLibService", "/org/freedesktop/DBus/Tests/MyTestObject")
381 self.iface = dbus.Interface(self.remote_object, "org.freedesktop.DBus.Tests.MyObject")
383 def testIntrospection(self):
384 #test introspection
385 print "\n********* Introspection Test ************"
386 print self.remote_object.Introspect(dbus_interface="org.freedesktop.DBus.Introspectable")
387 print "Introspection test passed"
388 self.assert_(True)
390 def testCalls(self):
391 print "\n********* Call Test ************"
392 result = self.iface.ManyArgs(1000, 'Hello GLib', 2)
393 print result
394 self.assert_(result == [2002.0, 'HELLO GLIB'])
396 arg0 = {"Dude": 1, "john": "palmieri", "python": 2.4}
397 result = self.iface.ManyStringify(arg0)
398 print result
400 print "Call test passed"
401 self.assert_(True)
403 def testPythonTypes(self):
404 print "\n********* Testing Python Types ***********"
406 for send_val in test_types_vals:
407 print "Testing %s"% str(send_val)
408 recv_val = self.iface.EchoVariant(send_val)
409 self.assertEquals(send_val, recv_val.object)
411 if __name__ == '__main__':
412 gobject.threads_init()
413 dbus.glib.init_threads()
415 unittest.main()