26ce375c0b95a1acd0c8f7efa12e39f87c2a06eb
[platform/upstream/dbus.git] / test / python / test-client.py
1 #!/usr/bin/env python
2 import sys
3 import os
4 import unittest
5 import time
6
7 builddir = os.environ["DBUS_TOP_BUILDDIR"]
8 pydir = builddir + "/python"
9
10 sys.path.insert(0, pydir)
11 sys.path.insert(0, pydir + "/.libs")
12
13 import dbus
14 import dbus_bindings
15 import gobject
16 import dbus.glib
17 import dbus.service
18
19 if not dbus.__file__.startswith(pydir):
20     raise Exception("DBus modules are not being picked up from the package")
21
22 if not dbus_bindings.__file__.startswith(pydir):
23     raise Exception("DBus modules are not being picked up from the package")
24
25 test_types_vals = [1, 12323231, 3.14159265, 99999999.99,
26                  "dude", "123", "What is all the fuss about?", "gob@gob.com",
27                  u'\\u310c\\u310e\\u3114', u'\\u0413\\u0414\\u0415',
28                  u'\\u2200software \\u2203crack', u'\\xf4\\xe5\\xe8',
29                  [1,2,3], ["how", "are", "you"], [1.23,2.3], [1], ["Hello"],
30                  (1,2,3), (1,), (1,"2",3), ("2", "what"), ("you", 1.2),
31                  {1:"a", 2:"b"}, {"a":1, "b":2}, #{"a":(1,"B")},
32                  {1:1.1, 2:2.2}, [[1,2,3],[2,3,4]], [["a","b"],["c","d"]],
33                  True, False,
34                  #([1,2,3],"c", 1.2, ["a","b","c"], {"a": (1,"v"), "b": (2,"d")})
35                  ]
36
37 class TestDBusBindings(unittest.TestCase):
38     def setUp(self):
39         self.bus = dbus.SessionBus()
40         self.remote_object = self.bus.get_object("org.freedesktop.DBus.TestSuitePythonService", "/org/freedesktop/DBus/TestSuitePythonObject")
41         self.iface = dbus.Interface(self.remote_object, "org.freedesktop.DBus.TestSuiteInterface")
42
43     def testInterfaceKeyword(self):
44         #test dbus_interface parameter
45         print self.remote_object.Echo("dbus_interface on Proxy test Passed", dbus_interface = "org.freedesktop.DBus.TestSuiteInterface")
46         print self.iface.Echo("dbus_interface on Interface test Passed", dbus_interface = "org.freedesktop.DBus.TestSuiteInterface")
47         self.assert_(True)
48         
49     def testIntrospection(self):
50         #test introspection
51         print "\n********* Introspection Test ************"
52         print self.remote_object.Introspect(dbus_interface="org.freedesktop.DBus.Introspectable")
53         print "Introspection test passed"
54         self.assert_(True)
55
56     def testPythonTypes(self):
57         #test sending python types and getting them back
58         print "\n********* Testing Python Types ***********"
59                  
60         for send_val in test_types_vals:
61             print "Testing %s"% str(send_val)
62             recv_val = self.iface.Echo(send_val)
63             self.assertEquals(send_val, recv_val)
64
65     def testBenchmarkIntrospect(self):
66         print "\n********* Benchmark Introspect ************"
67         a = time.time()
68         print a
69         print self.iface.GetComplexArray()
70         b = time.time()
71         print b
72         print "Delta: %f" % (b - a)
73         self.assert_(True)
74
75     def testAsyncCalls(self):
76         #test sending python types and getting them back async
77         print "\n********* Testing Async Calls ***********"
78
79         
80         main_loop = gobject.MainLoop()
81         class async_check:
82             def __init__(self, test_controler, expected_result, do_exit):
83                 self.expected_result = expected_result
84                 self.do_exit = do_exit
85                 self.test_controler = test_controler
86
87             def callback(self, val):
88                 try:
89                     if self.do_exit:
90                         main_loop.quit()
91
92                     self.test_controler.assertEquals(val, self.expected_result)
93                 except Exception, e:
94                     print "%s:\n%s" % (e.__class__, e)
95
96             def error_handler(self, error):
97                 print error
98                 if self.do_exit:
99                     main_loop.quit()
100
101                 self.test_controler.assert_(val, False)
102         
103         last_type = test_types_vals[-1]
104         for send_val in test_types_vals:
105             print "Testing %s"% str(send_val)
106             check = async_check(self, send_val, last_type == send_val) 
107             recv_val = self.iface.Echo(send_val, 
108                                        reply_handler = check.callback,
109                                        error_handler = check.error_handler)
110             
111         main_loop.run()
112
113     def testReturnMarshalling(self):
114         print "\n********* Testing return marshalling ***********"
115
116         # these values are the same as in the server, and the
117         # methods should only succeed when they are called with
118         # the right value number, because they have out_signature
119         # decorations, and return an unmatching type when called
120         # with a different number
121         values = ["", ("",""), ("","",""), [], {}, ["",""], ["","",""]]
122         methods = [
123                     (self.iface.ReturnOneString, set([0]), set([0])),
124                     (self.iface.ReturnTwoStrings, set([1, 5]), set([5])),
125                     (self.iface.ReturnStruct, set([1, 5]), set([1])),
126                     # all of our test values are sequences so will marshall correctly into an array :P
127                     (self.iface.ReturnArray, set(range(len(values))), set([3, 5, 6])),
128                     (self.iface.ReturnDict, set([0, 3, 4]), set([4]))
129                 ]
130
131         for (method, success_values, return_values) in methods:
132             print "\nTrying correct behaviour of", method._method_name
133             for value in range(len(values)):
134                 try:
135                     ret = method(value)
136                 except Exception, e:
137                     print "%s(%s) raised %s" % (method._method_name, repr(values[value]), e.__class__)
138
139                     # should fail if it tried to marshal the wrong type
140                     self.assert_(value not in success_values, "%s should succeed when we ask it to return %s\n%s" % (method._method_name, repr(values[value]), e))
141                 else:
142                     print "%s(%s) returned %s" % (method._method_name, repr(values[value]), repr(ret))
143
144                     # should only succeed if it's the right return type
145                     self.assert_(value in success_values, "%s should fail when we ask it to return %s" % (method._method_name, repr(values[value])))
146
147                     # check the value is right too :D
148                     returns = map(lambda n: values[n], return_values)
149                     self.assert_(ret in returns, "%s should return one of %s" % (method._method_name, repr(returns)))
150         print
151
152     def testInheritance(self):
153         print "\n********* Testing inheritance from dbus.method.Interface ***********"
154         ret = self.iface.CheckInheritance()
155         print "CheckInheritance returned %s" % ret
156         self.assert_(ret, "overriding CheckInheritance from TestInterface failed")
157
158     def testAsyncMethods(self):
159         print "\n********* Testing asynchronous method implementation *******"
160         for (async, fail) in ((False, False), (False, True), (True, False), (True, True)):
161             try:
162                 val = ('a', 1, False, [1,2], {1:2})
163                 print "calling AsynchronousMethod with %s %s %s" % (async, fail, val)
164                 ret = self.iface.AsynchronousMethod(async, fail, val)
165             except Exception, e:
166                 print "%s:\n%s" % (e.__class__, e)
167                 self.assert_(fail)
168             else:
169                 self.assert_(not fail)
170                 print val, ret
171                 self.assert_(val == ret)
172
173     def testBusInstanceCaching(self):
174         print "\n********* Testing dbus.Bus instance sharing *********"
175
176         # unfortunately we can't test the system bus here
177         # but the codepaths are the same
178         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)):
179             print "\nTesting %s:" % cls.__name__
180
181             share_cls = cls()
182             share_type = dbus.Bus(bus_type=type)
183             share_func = func()
184
185             private_cls = cls(private=True)
186             private_type = dbus.Bus(bus_type=type, private=True)
187             private_func = func(private=True)
188
189             print " - checking shared instances are the same..."
190             self.assert_(share_cls == share_type, '%s should equal %s' % (share_cls, share_type))
191             self.assert_(share_type == share_func, '%s should equal %s' % (share_type, share_func))
192
193             print " - checking private instances are distinct from the shared instance..."
194             self.assert_(share_cls != private_cls, '%s should not equal %s' % (share_cls, private_cls))
195             self.assert_(share_type != private_type, '%s should not equal %s' % (share_type, private_type))
196             self.assert_(share_func != private_func, '%s should not equal %s' % (share_func, private_func))
197
198             print " - checking private instances are distinct from each other..."
199             self.assert_(private_cls != private_type, '%s should not equal %s' % (private_cls, private_type))
200             self.assert_(private_type != private_func, '%s should not equal %s' % (private_type, private_func))
201             self.assert_(private_func != private_cls, '%s should not equal %s' % (private_func, private_cls))
202
203     def testBusNameCreation(self):
204         print '\n******** Testing BusName creation ********'
205         test = [('org.freedesktop.DBus.Python.TestName', True),
206                 ('org.freedesktop.DBus.Python.TestName', True),
207                 ('org.freedesktop.DBus.Python.InvalidName&^*%$', False),
208                 ('org.freedesktop.DBus.TestSuitePythonService', False)]
209         # For some reason this actually succeeds
210         # ('org.freedesktop.DBus', False)]
211
212         # make a method call to ensure the test service is active
213         self.iface.Echo("foo")
214
215         names = {}
216         for (name, succeed) in test:
217             try:
218                 print "requesting %s" % name
219                 busname = dbus.service.BusName(name)
220             except Exception, e:
221                 print "%s:\n%s" % (e.__class__, e)
222                 self.assert_(not succeed, 'did not expect registering bus name %s to fail' % name)
223             else:
224                 print busname
225                 self.assert_(succeed, 'expected registering bus name %s to fail'% name)
226                 if name in names:
227                     self.assert_(names[name] == busname, 'got a new instance for same name %s' % name)
228                     print "instance of %s re-used, good!" % name
229                 else:
230                     names[name] = busname
231
232 class TestDBusPythonToGLibBindings(unittest.TestCase):
233     def setUp(self):
234         self.bus = dbus.SessionBus()
235         self.remote_object = self.bus.get_object("org.freedesktop.DBus.TestSuiteGLibService", "/org/freedesktop/DBus/Tests/MyTestObject")
236         self.iface = dbus.Interface(self.remote_object, "org.freedesktop.DBus.Tests.MyObject")
237                             
238     def testIntrospection(self):
239         #test introspection
240         print "\n********* Introspection Test ************"
241         print self.remote_object.Introspect(dbus_interface="org.freedesktop.DBus.Introspectable")
242         print "Introspection test passed"
243         self.assert_(True)
244
245     def testCalls(self):
246         print "\n********* Call Test ************"
247         result =  self.iface.ManyArgs(1000, 'Hello GLib', 2)
248         print result
249         self.assert_(result == [2002.0, 'HELLO GLIB'])
250         
251         arg0 = {"Dude": 1, "john": "palmieri", "python": 2.4}
252         result = self.iface.ManyStringify(arg0)
253         print result
254        
255         print "Call test passed"
256         self.assert_(True)
257
258     def testPythonTypes(self):
259         print "\n********* Testing Python Types ***********"
260                  
261         for send_val in test_types_vals:
262             print "Testing %s"% str(send_val)
263             recv_val = self.iface.EchoVariant(send_val)
264             self.assertEquals(send_val, recv_val)
265
266 if __name__ == '__main__':
267     gobject.threads_init()
268     dbus.glib.init_threads()
269
270     unittest.main()