g_thread_new: never fail
[platform/upstream/glib.git] / gio / tests / gdbus-threading.c
1 /* GLib testing framework examples and tests
2  *
3  * Copyright (C) 2008-2010 Red Hat, Inc.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General
16  * Public License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18  * Boston, MA 02111-1307, USA.
19  *
20  * Author: David Zeuthen <davidz@redhat.com>
21  */
22
23 #include <gio/gio.h>
24 #include <unistd.h>
25 #include <string.h>
26
27 #include "gdbus-tests.h"
28
29 /* all tests rely on a global connection */
30 static GDBusConnection *c = NULL;
31
32 /* all tests rely on a shared mainloop */
33 static GMainLoop *loop = NULL;
34
35 /* ---------------------------------------------------------------------------------------------------- */
36 /* Ensure that signal and method replies are delivered in the right thread */
37 /* ---------------------------------------------------------------------------------------------------- */
38
39 typedef struct {
40   GThread *thread;
41   GMainLoop *thread_loop;
42   guint signal_count;
43 } DeliveryData;
44
45 static void
46 msg_cb_expect_success (GDBusConnection *connection,
47                        GAsyncResult    *res,
48                        gpointer         user_data)
49 {
50   DeliveryData *data = user_data;
51   GError *error;
52   GVariant *result;
53
54   error = NULL;
55   result = g_dbus_connection_call_finish (connection,
56                                           res,
57                                           &error);
58   g_assert_no_error (error);
59   g_assert (result != NULL);
60   g_variant_unref (result);
61
62   g_assert (g_thread_self () == data->thread);
63
64   g_main_loop_quit (data->thread_loop);
65 }
66
67 static void
68 msg_cb_expect_error_cancelled (GDBusConnection *connection,
69                                GAsyncResult    *res,
70                                gpointer         user_data)
71 {
72   DeliveryData *data = user_data;
73   GError *error;
74   GVariant *result;
75
76   error = NULL;
77   result = g_dbus_connection_call_finish (connection,
78                                           res,
79                                           &error);
80   g_assert_error (error, G_IO_ERROR, G_IO_ERROR_CANCELLED);
81   g_assert (!g_dbus_error_is_remote_error (error));
82   g_error_free (error);
83   g_assert (result == NULL);
84
85   g_assert (g_thread_self () == data->thread);
86
87   g_main_loop_quit (data->thread_loop);
88 }
89
90 static void
91 signal_handler (GDBusConnection *connection,
92                 const gchar      *sender_name,
93                 const gchar      *object_path,
94                 const gchar      *interface_name,
95                 const gchar      *signal_name,
96                 GVariant         *parameters,
97                 gpointer         user_data)
98 {
99   DeliveryData *data = user_data;
100
101   g_assert (g_thread_self () == data->thread);
102
103   data->signal_count++;
104
105   g_main_loop_quit (data->thread_loop);
106 }
107
108 static gpointer
109 test_delivery_in_thread_func (gpointer _data)
110 {
111   GMainLoop *thread_loop;
112   GMainContext *thread_context;
113   DeliveryData data;
114   GCancellable *ca;
115   guint subscription_id;
116   GDBusConnection *priv_c;
117   GError *error;
118
119   error = NULL;
120
121   thread_context = g_main_context_new ();
122   thread_loop = g_main_loop_new (thread_context, FALSE);
123   g_main_context_push_thread_default (thread_context);
124
125   data.thread = g_thread_self ();
126   data.thread_loop = thread_loop;
127   data.signal_count = 0;
128
129   /* ---------------------------------------------------------------------------------------------------- */
130
131   /*
132    * Check that we get a reply to the GetId() method call.
133    */
134   g_dbus_connection_call (c,
135                           "org.freedesktop.DBus",  /* bus_name */
136                           "/org/freedesktop/DBus", /* object path */
137                           "org.freedesktop.DBus",  /* interface name */
138                           "GetId",                 /* method name */
139                           NULL, NULL,
140                           G_DBUS_CALL_FLAGS_NONE,
141                           -1,
142                           NULL,
143                           (GAsyncReadyCallback) msg_cb_expect_success,
144                           &data);
145   g_main_loop_run (thread_loop);
146
147   /*
148    * Check that we never actually send a message if the GCancellable
149    * is already cancelled - i.e.  we should get #G_IO_ERROR_CANCELLED
150    * when the actual connection is not up.
151    */
152   ca = g_cancellable_new ();
153   g_cancellable_cancel (ca);
154   g_dbus_connection_call (c,
155                           "org.freedesktop.DBus",  /* bus_name */
156                           "/org/freedesktop/DBus", /* object path */
157                           "org.freedesktop.DBus",  /* interface name */
158                           "GetId",                 /* method name */
159                           NULL, NULL,
160                           G_DBUS_CALL_FLAGS_NONE,
161                           -1,
162                           ca,
163                           (GAsyncReadyCallback) msg_cb_expect_error_cancelled,
164                           &data);
165   g_main_loop_run (thread_loop);
166   g_object_unref (ca);
167
168   /*
169    * Check that cancellation works when the message is already in flight.
170    */
171   ca = g_cancellable_new ();
172   g_dbus_connection_call (c,
173                           "org.freedesktop.DBus",  /* bus_name */
174                           "/org/freedesktop/DBus", /* object path */
175                           "org.freedesktop.DBus",  /* interface name */
176                           "GetId",                 /* method name */
177                           NULL, NULL,
178                           G_DBUS_CALL_FLAGS_NONE,
179                           -1,
180                           ca,
181                           (GAsyncReadyCallback) msg_cb_expect_error_cancelled,
182                           &data);
183   g_cancellable_cancel (ca);
184   g_main_loop_run (thread_loop);
185   g_object_unref (ca);
186
187   /*
188    * Check that signals are delivered to the correct thread.
189    *
190    * First we subscribe to the signal, then we create a a private
191    * connection. This should cause a NameOwnerChanged message from
192    * the message bus.
193    */
194   subscription_id = g_dbus_connection_signal_subscribe (c,
195                                                         "org.freedesktop.DBus",  /* sender */
196                                                         "org.freedesktop.DBus",  /* interface */
197                                                         "NameOwnerChanged",      /* member */
198                                                         "/org/freedesktop/DBus", /* path */
199                                                         NULL,
200                                                         G_DBUS_SIGNAL_FLAGS_NONE,
201                                                         signal_handler,
202                                                         &data,
203                                                         NULL);
204   g_assert (subscription_id != 0);
205   g_assert (data.signal_count == 0);
206
207   priv_c = _g_bus_get_priv (G_BUS_TYPE_SESSION, NULL, &error);
208   g_assert_no_error (error);
209   g_assert (priv_c != NULL);
210
211   g_main_loop_run (thread_loop);
212   g_assert (data.signal_count == 1);
213
214   g_object_unref (priv_c);
215
216   g_dbus_connection_signal_unsubscribe (c, subscription_id);
217
218   /* ---------------------------------------------------------------------------------------------------- */
219
220   g_main_context_pop_thread_default (thread_context);
221   g_main_loop_unref (thread_loop);
222   g_main_context_unref (thread_context);
223
224   g_main_loop_quit (loop);
225
226   return NULL;
227 }
228
229 static void
230 test_delivery_in_thread (void)
231 {
232   GThread *thread;
233
234   thread = g_thread_new ("deliver",
235                          test_delivery_in_thread_func,
236                          NULL);
237
238   /* run the event loop - it is needed to dispatch D-Bus messages */
239   g_main_loop_run (loop);
240
241   g_thread_join (thread);
242 }
243
244 /* ---------------------------------------------------------------------------------------------------- */
245
246 typedef struct {
247   GDBusProxy *proxy;
248   gint msec;
249   guint num;
250   gboolean async;
251
252   GMainLoop *thread_loop;
253   GThread *thread;
254
255   gboolean done;
256 } SyncThreadData;
257
258 static void
259 sleep_cb (GDBusProxy   *proxy,
260           GAsyncResult *res,
261           gpointer      user_data)
262 {
263   SyncThreadData *data = user_data;
264   GError *error;
265   GVariant *result;
266
267   error = NULL;
268   result = g_dbus_proxy_call_finish (proxy,
269                                      res,
270                                      &error);
271   g_assert_no_error (error);
272   g_assert (result != NULL);
273   g_assert_cmpstr (g_variant_get_type_string (result), ==, "()");
274   g_variant_unref (result);
275
276   g_assert (data->thread == g_thread_self ());
277
278   g_main_loop_quit (data->thread_loop);
279
280   //g_debug ("async cb (%p)", g_thread_self ());
281 }
282
283 static gpointer
284 test_sleep_in_thread_func (gpointer _data)
285 {
286   SyncThreadData *data = _data;
287   GMainContext *thread_context;
288   guint n;
289
290   thread_context = g_main_context_new ();
291   data->thread_loop = g_main_loop_new (thread_context, FALSE);
292   g_main_context_push_thread_default (thread_context);
293
294   data->thread = g_thread_self ();
295
296   for (n = 0; n < data->num; n++)
297     {
298       if (data->async)
299         {
300           //g_debug ("invoking async (%p)", g_thread_self ());
301           g_dbus_proxy_call (data->proxy,
302                              "Sleep",
303                              g_variant_new ("(i)", data->msec),
304                              G_DBUS_CALL_FLAGS_NONE,
305                              -1,
306                              NULL,
307                              (GAsyncReadyCallback) sleep_cb,
308                              data);
309           g_main_loop_run (data->thread_loop);
310           g_print ("A");
311           //g_debug ("done invoking async (%p)", g_thread_self ());
312         }
313       else
314         {
315           GError *error;
316           GVariant *result;
317
318           error = NULL;
319           //g_debug ("invoking sync (%p)", g_thread_self ());
320           result = g_dbus_proxy_call_sync (data->proxy,
321                                            "Sleep",
322                                            g_variant_new ("(i)", data->msec),
323                                            G_DBUS_CALL_FLAGS_NONE,
324                                            -1,
325                                            NULL,
326                                            &error);
327           g_print ("S");
328           //g_debug ("done invoking sync (%p)", g_thread_self ());
329           g_assert_no_error (error);
330           g_assert (result != NULL);
331           g_assert_cmpstr (g_variant_get_type_string (result), ==, "()");
332           g_variant_unref (result);
333         }
334     }
335
336   g_main_context_pop_thread_default (thread_context);
337   g_main_loop_unref (data->thread_loop);
338   g_main_context_unref (thread_context);
339
340   data->done = TRUE;
341   g_main_loop_quit (loop);
342
343   return NULL;
344 }
345
346 static void
347 test_method_calls_on_proxy (GDBusProxy *proxy)
348 {
349   guint n;
350
351   /*
352    * Check that multiple threads can do calls without interferring with
353    * each other. We do this by creating three threads that call the
354    * Sleep() method on the server (which handles it asynchronously, e.g.
355    * it won't block other requests) with different sleep durations and
356    * a number of times. We do this so each set of calls add up to 4000
357    * milliseconds.
358    *
359    * The dbus test server that this code calls into uses glib timeouts
360    * to do the sleeping which have only a granularity of 1ms.  It is
361    * therefore possible to lose as much as 40ms; the test could finish
362    * in slightly less than 4 seconds.
363    *
364    * We run this test twice - first with async calls in each thread, then
365    * again with sync calls
366    */
367
368   for (n = 0; n < 2; n++)
369     {
370       gboolean do_async;
371       GThread *thread1;
372       GThread *thread2;
373       GThread *thread3;
374       SyncThreadData data1;
375       SyncThreadData data2;
376       SyncThreadData data3;
377       GTimeVal start_time;
378       GTimeVal end_time;
379       guint elapsed_msec;
380
381       do_async = (n == 0);
382
383       g_get_current_time (&start_time);
384
385       data1.proxy = proxy;
386       data1.msec = 40;
387       data1.num = 100;
388       data1.async = do_async;
389       data1.done = FALSE;
390       thread1 = g_thread_new ("sleep",
391                               test_sleep_in_thread_func,
392                               &data1);
393
394       data2.proxy = proxy;
395       data2.msec = 20;
396       data2.num = 200;
397       data2.async = do_async;
398       data2.done = FALSE;
399       thread2 = g_thread_new ("sleep2",
400                               test_sleep_in_thread_func,
401                               &data2);
402
403       data3.proxy = proxy;
404       data3.msec = 100;
405       data3.num = 40;
406       data3.async = do_async;
407       data3.done = FALSE;
408       thread3 = g_thread_new ("sleep3",
409                               test_sleep_in_thread_func,
410                               &data3);
411
412       /* we handle messages in the main loop - threads will quit it when they are done */
413       while (!(data1.done && data2.done && data3.done))
414         g_main_loop_run (loop);
415
416       g_thread_join (thread1);
417       g_thread_join (thread2);
418       g_thread_join (thread3);
419
420       g_get_current_time (&end_time);
421
422       elapsed_msec = ((end_time.tv_sec * G_USEC_PER_SEC + end_time.tv_usec) -
423                       (start_time.tv_sec * G_USEC_PER_SEC + start_time.tv_usec)) / 1000;
424
425       //g_debug ("Elapsed time for %s = %d msec", n == 0 ? "async" : "sync", elapsed_msec);
426
427       /* elapsed_msec should be 4000 msec +/- change for overhead/inaccuracy */
428       g_assert_cmpint (elapsed_msec, >=, 3950);
429       g_assert_cmpint (elapsed_msec,  <, 6000);
430
431       g_print (" ");
432     }
433
434   g_main_loop_quit (loop);
435 }
436
437 static void
438 test_method_calls_in_thread (void)
439 {
440   GDBusProxy *proxy;
441   GDBusConnection *connection;
442   GError *error;
443   gchar *name_owner;
444
445   error = NULL;
446   connection = g_bus_get_sync (G_BUS_TYPE_SESSION,
447                                NULL,
448                                &error);
449   g_assert_no_error (error);
450   error = NULL;
451   proxy = g_dbus_proxy_new_sync (connection,
452                                  G_DBUS_PROXY_FLAGS_NONE,
453                                  NULL,                      /* GDBusInterfaceInfo */
454                                  "com.example.TestService", /* name */
455                                  "/com/example/TestObject", /* object path */
456                                  "com.example.Frob",        /* interface */
457                                  NULL, /* GCancellable */
458                                  &error);
459   g_assert_no_error (error);
460
461   name_owner = g_dbus_proxy_get_name_owner (proxy);
462   g_assert_cmpstr (name_owner, !=, NULL);
463   g_free (name_owner);
464
465   test_method_calls_on_proxy (proxy);
466
467   g_object_unref (proxy);
468   g_object_unref (connection);
469 }
470
471 /* ---------------------------------------------------------------------------------------------------- */
472
473 int
474 main (int   argc,
475       char *argv[])
476 {
477   GError *error;
478   gint ret;
479
480   g_type_init ();
481   g_test_init (&argc, &argv, NULL);
482
483   /* all the tests rely on a shared main loop */
484   loop = g_main_loop_new (NULL, FALSE);
485
486   /* all the tests use a session bus with a well-known address that we can bring up and down
487    * using session_bus_up() and session_bus_down().
488    */
489   g_unsetenv ("DISPLAY");
490   g_setenv ("DBUS_SESSION_BUS_ADDRESS", session_bus_get_temporary_address (), TRUE);
491
492   session_bus_up ();
493
494   /* TODO: wait a bit for the bus to come up.. ideally session_bus_up() won't return
495    * until one can connect to the bus but that's not how things work right now
496    */
497   usleep (500 * 1000);
498
499   /* this is safe; testserver will exit once the bus goes away */
500   g_assert (g_spawn_command_line_async (SRCDIR "/gdbus-testserver.py", NULL));
501
502   /* wait for the service to come up */
503   usleep (500 * 1000);
504
505   /* Create the connection in the main thread */
506   error = NULL;
507   c = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, &error);
508   g_assert_no_error (error);
509   g_assert (c != NULL);
510
511   g_test_add_func ("/gdbus/delivery-in-thread", test_delivery_in_thread);
512   g_test_add_func ("/gdbus/method-calls-in-thread", test_method_calls_in_thread);
513
514   ret = g_test_run();
515
516   g_object_unref (c);
517
518   /* tear down bus */
519   session_bus_down ();
520
521   return ret;
522 }