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