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 class TestDBusBindings(unittest
.TestCase
):
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
)
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")
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
):
100 print "\n********* Introspection Test ************"
101 print self
.remote_object
.Introspect(dbus_interface
="org.freedesktop.DBus.Introspectable")
102 print "Introspection test passed"
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 testUtf8StringsSync(self
):
117 recv_val
= self
.iface
.Echo(send_val
, utf8_strings
=True)
118 self
.assert_(isinstance(recv_val
, str))
119 self
.assert_(isinstance(recv_val
, dbus
.UTF8String
))
120 recv_val
= self
.iface
.Echo(send_val
, utf8_strings
=False)
121 self
.assert_(isinstance(recv_val
, unicode))
122 self
.assert_(isinstance(recv_val
, dbus
.String
))
124 def testBenchmarkIntrospect(self
):
125 print "\n********* Benchmark Introspect ************"
128 print self
.iface
.GetComplexArray()
131 print "Delta: %f" % (b
- a
)
134 def testAsyncCalls(self
):
135 #test sending python types and getting them back async
136 print "\n********* Testing Async Calls ***********"
139 main_loop
= gobject
.MainLoop()
142 def __init__(self
, test_controler
, expected_result
, do_exit
, utf8
):
143 self
.expected_result
= expected_result
144 self
.do_exit
= do_exit
146 self
.test_controler
= test_controler
148 def callback(self
, val
):
153 self
.test_controler
.assertEquals(val
, self
.expected_result
)
154 self
.test_controler
.assertEquals(val
.variant_level
, 1)
155 if self
.utf8
and not isinstance(val
, dbus
.UTF8String
):
156 failures
.append('%r should have been utf8 but was not' % val
)
158 elif not self
.utf8
and isinstance(val
, dbus
.UTF8String
):
159 failures
.append('%r should not have been utf8' % val
)
162 failures
.append("%s:\n%s" % (e
.__class
__, e
))
164 def error_handler(self
, error
):
169 failures
.append('%s: %s' % (error
.__class
__, error
))
171 last_type
= test_types_vals
[-1]
172 for send_val
in test_types_vals
:
173 print "Testing %s" % str(send_val
)
174 utf8
= (send_val
== 'gob@gob.com')
175 check
= async_check(self
, send_val
, last_type
== send_val
,
177 recv_val
= self
.iface
.Echo(send_val
,
178 reply_handler
=check
.callback
,
179 error_handler
=check
.error_handler
,
183 self
.assert_(False, failures
)
185 def testStrictMarshalling(self
):
186 print "\n********* Testing strict return & signal marshalling ***********"
188 # these values are the same as in the server, and the
189 # methods should only succeed when they are called with
190 # the right value number, because they have out_signature
191 # decorations, and return an unmatching type when called
192 # with a different number
193 values
= ["", ("",""), ("","",""), [], {}, ["",""], ["","",""]]
195 (self
.iface
.ReturnOneString
, 'SignalOneString', set([0]), set([0])),
196 (self
.iface
.ReturnTwoStrings
, 'SignalTwoStrings', set([1, 5]), set([1])),
197 (self
.iface
.ReturnStruct
, 'SignalStruct', set([1, 5]), set([1])),
198 # all of our test values are sequences so will marshall correctly into an array :P
199 (self
.iface
.ReturnArray
, 'SignalArray', set(range(len(values
))), set([3, 5, 6])),
200 (self
.iface
.ReturnDict
, 'SignalDict', set([0, 3, 4]), set([4]))
203 for (method
, signal
, success_values
, return_values
) in methods
:
204 print "\nTrying correct behaviour of", method
._method
_name
205 for value
in range(len(values
)):
209 print "%s(%r) raised %s: %s" % (method
._method
_name
, values
[value
], e
.__class
__, e
)
211 # should fail if it tried to marshal the wrong type
212 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
))
214 print "%s(%r) returned %r" % (method
._method
_name
, values
[value
], ret
)
216 # should only succeed if it's the right return type
217 self
.assert_(value
in success_values
, "%s should fail when we ask it to return %r" % (method
._method
_name
, values
[value
]))
219 # check the value is right too :D
220 returns
= map(lambda n
: values
[n
], return_values
)
221 self
.assert_(ret
in returns
, "%s should return one of %r but it returned %r instead" % (method
._method
_name
, returns
, ret
))
223 print "\nTrying correct emission of", signal
224 for value
in range(len(values
)):
226 self
.iface
.EmitSignal(signal
, value
)
228 print "EmitSignal(%s, %r) raised %s" % (signal
, values
[value
], e
.__class
__)
230 # should fail if it tried to marshal the wrong type
231 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
))
233 print "EmitSignal(%s, %r) appeared to succeed" % (signal
, values
[value
])
235 # should only succeed if it's the right return type
236 self
.assert_(value
in success_values
, "EmitSignal(%s) should fail when we ask it to return %r" % (signal
, values
[value
]))
238 # FIXME: wait for the signal here
242 def testInheritance(self
):
243 print "\n********* Testing inheritance from dbus.method.Interface ***********"
244 ret
= self
.iface
.CheckInheritance()
245 print "CheckInheritance returned %s" % ret
246 self
.assert_(ret
, "overriding CheckInheritance from TestInterface failed")
248 def testAsyncMethods(self
):
249 print "\n********* Testing asynchronous method implementation *******"
250 for async in (True, False):
251 for fail
in (True, False):
253 val
= ('a', 1, False, [1,2], {1:2})
254 print "calling AsynchronousMethod with %s %s %s" % (async, fail
, val
)
255 ret
= self
.iface
.AsynchronousMethod(async, fail
, val
)
257 self
.assert_(fail
, '%s: %s' % (e
.__class
__, e
))
258 print "Expected failure: %s: %s" % (e
.__class
__, e
)
260 self
.assert_(not fail
, 'Expected failure but succeeded?!')
261 self
.assertEquals(val
, ret
)
262 self
.assertEquals(1, ret
.variant_level
)
264 def testBusInstanceCaching(self
):
265 print "\n********* Testing dbus.Bus instance sharing *********"
267 # unfortunately we can't test the system bus here
268 # but the codepaths are the same
269 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
)):
270 print "\nTesting %s:" % cls
.__name
__
273 share_type
= dbus
.Bus(bus_type
=type)
276 private_cls
= cls(private
=True)
277 private_type
= dbus
.Bus(bus_type
=type, private
=True)
278 private_func
= func(private
=True)
280 print " - checking shared instances are the same..."
281 self
.assert_(share_cls
== share_type
, '%s should equal %s' % (share_cls
, share_type
))
282 self
.assert_(share_type
== share_func
, '%s should equal %s' % (share_type
, share_func
))
284 print " - checking private instances are distinct from the shared instance..."
285 self
.assert_(share_cls
!= private_cls
, '%s should not equal %s' % (share_cls
, private_cls
))
286 self
.assert_(share_type
!= private_type
, '%s should not equal %s' % (share_type
, private_type
))
287 self
.assert_(share_func
!= private_func
, '%s should not equal %s' % (share_func
, private_func
))
289 print " - checking private instances are distinct from each other..."
290 self
.assert_(private_cls
!= private_type
, '%s should not equal %s' % (private_cls
, private_type
))
291 self
.assert_(private_type
!= private_func
, '%s should not equal %s' % (private_type
, private_func
))
292 self
.assert_(private_func
!= private_cls
, '%s should not equal %s' % (private_func
, private_cls
))
294 def testSenderName(self
):
295 print '\n******** Testing sender name keyword ********'
296 myself
= self
.iface
.WhoAmI()
299 def testBusNameCreation(self
):
300 print '\n******** Testing BusName creation ********'
301 test
= [('org.freedesktop.DBus.Python.TestName', True),
302 ('org.freedesktop.DBus.Python.TestName', True),
303 ('org.freedesktop.DBus.Python.InvalidName&^*%$', False)]
304 # Do some more intelligent handling/testing of queueing vs success?
305 # ('org.freedesktop.DBus.TestSuitePythonService', False)]
306 # For some reason this actually succeeds
307 # ('org.freedesktop.DBus', False)]
309 # make a method call to ensure the test service is active
310 self
.iface
.Echo("foo")
313 for (name
, succeed
) in test
:
315 print "requesting %s" % name
316 busname
= dbus
.service
.BusName(name
)
318 print "%s:\n%s" % (e
.__class
__, e
)
319 self
.assert_(not succeed
, 'did not expect registering bus name %s to fail' % name
)
322 self
.assert_(succeed
, 'expected registering bus name %s to fail'% name
)
324 self
.assert_(names
[name
] == busname
, 'got a new instance for same name %s' % name
)
325 print "instance of %s re-used, good!" % name
327 names
[name
] = busname
336 ret
= bus
.name_has_owner('org.freedesktop.DBus.Python.TestName')
337 self
.assert_(not ret
, 'deleting reference failed to release BusName org.freedesktop.DBus.Python.TestName')
339 """ Remove this for now
340 class TestDBusPythonToGLibBindings(unittest.TestCase):
342 self.bus = dbus.SessionBus()
343 self.remote_object = self.bus.get_object("org.freedesktop.DBus.TestSuiteGLibService", "/org/freedesktop/DBus/Tests/MyTestObject")
344 self.iface = dbus.Interface(self.remote_object, "org.freedesktop.DBus.Tests.MyObject")
346 def testIntrospection(self):
348 print "\n********* Introspection Test ************"
349 print self.remote_object.Introspect(dbus_interface="org.freedesktop.DBus.Introspectable")
350 print "Introspection test passed"
354 print "\n********* Call Test ************"
355 result = self.iface.ManyArgs(1000, 'Hello GLib', 2)
357 self.assert_(result == [2002.0, 'HELLO GLIB'])
359 arg0 = {"Dude": 1, "john": "palmieri", "python": 2.4}
360 result = self.iface.ManyStringify(arg0)
363 print "Call test passed"
366 def testPythonTypes(self):
367 print "\n********* Testing Python Types ***********"
369 for send_val in test_types_vals:
370 print "Testing %s"% str(send_val)
371 recv_val = self.iface.EchoVariant(send_val)
372 self.assertEquals(send_val, recv_val.object)
374 if __name__
== '__main__':
375 gobject
.threads_init()
376 dbus
.glib
.init_threads()