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
30 builddir
= os
.path
.normpath(os
.environ
["DBUS_TOP_BUILDDIR"])
31 pydir
= os
.path
.normpath(os
.environ
["DBUS_TOP_SRCDIR"])
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"]],
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
):
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')
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
)
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")
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
):
114 print "\n********* Introspection Test ************"
115 print self
.remote_object
.Introspect(dbus_interface
="org.freedesktop.DBus.Introspectable")
116 print "Introspection test passed"
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
):
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 ************"
153 print self
.iface
.GetComplexArray()
156 print "Delta: %f" % (b
- a
)
159 def testAsyncCalls(self
):
160 #test sending python types and getting them back async
161 print "\n********* Testing Async Calls ***********"
164 main_loop
= gobject
.MainLoop()
167 def __init__(self
, test_controler
, expected_result
, do_exit
, utf8
):
168 self
.expected_result
= expected_result
169 self
.do_exit
= do_exit
171 self
.test_controler
= test_controler
173 def callback(self
, val
):
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
)
183 elif not self
.utf8
and isinstance(val
, dbus
.UTF8String
):
184 failures
.append('%r should not have been utf8' % val
)
187 failures
.append("%s:\n%s" % (e
.__class
__, e
))
189 def error_handler(self
, error
):
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
,
202 recv_val
= self
.iface
.Echo(send_val
,
203 reply_handler
=check
.callback
,
204 error_handler
=check
.error_handler
,
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
= ["", ("",""), ("","",""), [], {}, ["",""], ["","",""]]
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
)):
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
))
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
)):
251 self
.iface
.EmitSignal(signal
, value
)
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
))
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
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):
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
)
282 self
.assert_(fail
, '%s: %s' % (e
.__class
__, e
))
283 print "Expected failure: %s: %s" % (e
.__class
__, e
)
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
__
298 share_type
= dbus
.Bus(bus_type
=type)
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()
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")
354 for (name
, succeed
) in test
:
356 print "requesting %s" % name
357 busname
= dbus
.service
.BusName(name
)
359 print "%s:\n%s" % (e
.__class
__, e
)
360 self
.assert_(not succeed
, 'did not expect registering bus name %s to fail' % name
)
363 self
.assert_(succeed
, 'expected registering bus name %s to fail'% name
)
365 self
.assert_(names
[name
] == busname
, 'got a new instance for same name %s' % name
)
366 print "instance of %s re-used, good!" % name
368 names
[name
] = busname
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):
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):
395 print "\n********* Introspection Test ************"
396 print self.remote_object.Introspect(dbus_interface="org.freedesktop.DBus.Introspectable")
397 print "Introspection test passed"
401 print "\n********* Call Test ************"
402 result = self.iface.ManyArgs(1000, 'Hello GLib', 2)
404 self.assert_(result == [2002.0, 'HELLO GLIB'])
406 arg0 = {"Dude": 1, "john": "palmieri", "python": 2.4}
407 result = self.iface.ManyStringify(arg0)
410 print "Call test passed"
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()