1 /* GLib testing framework examples and tests
3 * Copyright (C) 2008-2010 Red Hat, Inc.
5 * SPDX-License-Identifier: LGPL-2.1-or-later
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General
18 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
20 * Author: David Zeuthen <davidz@redhat.com>
27 #include "gdbus-tests.h"
29 /* all tests rely on a global connection */
30 static GDBusConnection *c = NULL;
34 GMainContext *context;
39 timeout_cb (gpointer user_data)
41 TimeoutData *data = user_data;
43 data->timed_out = TRUE;
44 g_main_context_wakeup (data->context);
46 return G_SOURCE_REMOVE;
50 wakeup_cb (gpointer user_data)
52 /* nothing to do here */
53 return G_SOURCE_CONTINUE;
56 /* Check that the given @connection has only one ref, waiting to let any pending
57 * unrefs complete first. This is typically used on the shared connection, to
58 * ensure it’s in a correct state before beginning the next test. */
60 (assert_connection_has_one_ref) (GDBusConnection *connection,
61 GMainContext *context,
62 const gchar *calling_function)
64 GSource *timeout_source = NULL;
65 GSource *wakeup_source = NULL;
66 TimeoutData data = { context, FALSE };
68 if (g_atomic_int_get (&G_OBJECT (connection)->ref_count) == 1)
71 /* Use two timeout sources: @timeout_source to set a deadline after which the
72 * test will fail if the @connection doesn’t have the right number of refs;
73 * and @wakeup_source to periodically wake the @context up to allow the
74 * termination condition to be checked. This allows the termination condition
75 * to be fulfilled by something which doesn’t wake @context up, such as an
76 * unref happening in the GDBus worker thread. */
77 timeout_source = g_timeout_source_new_seconds (3);
78 g_source_set_callback (timeout_source, timeout_cb, &data, NULL);
79 g_source_attach (timeout_source, context);
81 wakeup_source = g_timeout_source_new (50 /* ms */);
82 g_source_set_callback (wakeup_source, wakeup_cb, NULL, NULL);
83 g_source_attach (wakeup_source, context);
85 while (g_atomic_int_get (&G_OBJECT (connection)->ref_count) != 1 && !data.timed_out)
87 g_debug ("refcount of %p is not right (%u rather than 1) in %s(), sleeping",
88 connection, g_atomic_int_get (&G_OBJECT (connection)->ref_count), calling_function);
89 g_main_context_iteration (NULL, TRUE);
92 g_source_destroy (wakeup_source);
93 g_source_unref (wakeup_source);
95 g_source_destroy (timeout_source);
96 g_source_unref (timeout_source);
98 if (g_atomic_int_get (&G_OBJECT (connection)->ref_count) != 1)
99 g_error ("connection %p had too many refs (%u rather than 1) in %s()",
100 connection, g_atomic_int_get (&G_OBJECT (connection)->ref_count), calling_function);
103 /* Macro wrapper to add in the calling function name */
104 #define assert_connection_has_one_ref(connection, context) \
105 (assert_connection_has_one_ref) (connection, context, G_STRFUNC)
107 /* ---------------------------------------------------------------------------------------------------- */
108 /* Ensure that signal and method replies are delivered in the right thread */
109 /* ---------------------------------------------------------------------------------------------------- */
113 GMainContext *context;
115 gboolean unsubscribe_complete;
116 GAsyncResult *async_result;
120 async_result_cb (GDBusConnection *connection,
124 DeliveryData *data = user_data;
126 data->async_result = g_object_ref (res);
128 g_assert_true (g_thread_self () == data->thread);
130 g_main_context_wakeup (data->context);
134 signal_handler (GDBusConnection *connection,
135 const gchar *sender_name,
136 const gchar *object_path,
137 const gchar *interface_name,
138 const gchar *signal_name,
139 GVariant *parameters,
142 DeliveryData *data = user_data;
144 g_assert_true (g_thread_self () == data->thread);
146 data->signal_count++;
148 g_main_context_wakeup (data->context);
152 signal_data_free_cb (gpointer user_data)
154 DeliveryData *data = user_data;
156 g_assert_true (g_thread_self () == data->thread);
158 data->unsubscribe_complete = TRUE;
160 g_main_context_wakeup (data->context);
164 test_delivery_in_thread_func (gpointer _data)
166 GMainContext *thread_context;
169 guint subscription_id;
170 GError *error = NULL;
171 GVariant *result_variant = NULL;
173 thread_context = g_main_context_new ();
174 g_main_context_push_thread_default (thread_context);
176 data.thread = g_thread_self ();
177 data.context = thread_context;
178 data.signal_count = 0;
179 data.unsubscribe_complete = FALSE;
180 data.async_result = NULL;
182 /* ---------------------------------------------------------------------------------------------------- */
185 * Check that we get a reply to the GetId() method call.
187 g_dbus_connection_call (c,
188 "org.freedesktop.DBus", /* bus_name */
189 "/org/freedesktop/DBus", /* object path */
190 "org.freedesktop.DBus", /* interface name */
191 "GetId", /* method name */
193 G_DBUS_CALL_FLAGS_NONE,
196 (GAsyncReadyCallback) async_result_cb,
198 while (data.async_result == NULL)
199 g_main_context_iteration (thread_context, TRUE);
201 result_variant = g_dbus_connection_call_finish (c, data.async_result, &error);
202 g_assert_no_error (error);
203 g_assert_nonnull (result_variant);
204 g_clear_pointer (&result_variant, g_variant_unref);
205 g_clear_object (&data.async_result);
208 * Check that we never actually send a message if the GCancellable
209 * is already cancelled - i.e. we should get G_IO_ERROR_CANCELLED
210 * when the actual connection is not up.
212 ca = g_cancellable_new ();
213 g_cancellable_cancel (ca);
214 g_dbus_connection_call (c,
215 "org.freedesktop.DBus", /* bus_name */
216 "/org/freedesktop/DBus", /* object path */
217 "org.freedesktop.DBus", /* interface name */
218 "GetId", /* method name */
220 G_DBUS_CALL_FLAGS_NONE,
223 (GAsyncReadyCallback) async_result_cb,
225 while (data.async_result == NULL)
226 g_main_context_iteration (thread_context, TRUE);
228 result_variant = g_dbus_connection_call_finish (c, data.async_result, &error);
229 g_assert_error (error, G_IO_ERROR, G_IO_ERROR_CANCELLED);
230 g_assert_false (g_dbus_error_is_remote_error (error));
231 g_clear_error (&error);
232 g_assert_null (result_variant);
233 g_clear_object (&data.async_result);
238 * Check that cancellation works when the message is already in flight.
240 ca = g_cancellable_new ();
241 g_dbus_connection_call (c,
242 "org.freedesktop.DBus", /* bus_name */
243 "/org/freedesktop/DBus", /* object path */
244 "org.freedesktop.DBus", /* interface name */
245 "GetId", /* method name */
247 G_DBUS_CALL_FLAGS_NONE,
250 (GAsyncReadyCallback) async_result_cb,
252 g_cancellable_cancel (ca);
254 while (data.async_result == NULL)
255 g_main_context_iteration (thread_context, TRUE);
257 result_variant = g_dbus_connection_call_finish (c, data.async_result, &error);
258 g_assert_error (error, G_IO_ERROR, G_IO_ERROR_CANCELLED);
259 g_assert_false (g_dbus_error_is_remote_error (error));
260 g_clear_error (&error);
261 g_assert_null (result_variant);
262 g_clear_object (&data.async_result);
267 * Check that signals are delivered to the correct thread.
269 * First we subscribe to the signal, then we call EmitSignal(). This should
270 * cause a TestSignal emission from the testserver.
272 subscription_id = g_dbus_connection_signal_subscribe (c,
273 "com.example.TestService", /* sender */
274 "com.example.Frob", /* interface */
275 "TestSignal", /* member */
276 "/com/example/TestObject", /* path */
278 G_DBUS_SIGNAL_FLAGS_NONE,
281 signal_data_free_cb);
282 g_assert_cmpuint (subscription_id, !=, 0);
283 g_assert_cmpuint (data.signal_count, ==, 0);
285 g_dbus_connection_call (c,
286 "com.example.TestService", /* bus_name */
287 "/com/example/TestObject", /* object path */
288 "com.example.Frob", /* interface name */
289 "EmitSignal", /* method name */
290 g_variant_new_parsed ("('hello', @o '/com/example/TestObject')"),
292 G_DBUS_CALL_FLAGS_NONE,
295 (GAsyncReadyCallback) async_result_cb,
297 while (data.async_result == NULL || data.signal_count < 1)
298 g_main_context_iteration (thread_context, TRUE);
300 result_variant = g_dbus_connection_call_finish (c, data.async_result, &error);
301 g_assert_no_error (error);
302 g_assert_nonnull (result_variant);
303 g_clear_pointer (&result_variant, g_variant_unref);
304 g_clear_object (&data.async_result);
306 g_assert_cmpuint (data.signal_count, ==, 1);
308 g_dbus_connection_signal_unsubscribe (c, subscription_id);
311 while (!data.unsubscribe_complete)
312 g_main_context_iteration (thread_context, TRUE);
313 g_assert_true (data.unsubscribe_complete);
315 /* ---------------------------------------------------------------------------------------------------- */
317 g_main_context_pop_thread_default (thread_context);
318 g_main_context_unref (thread_context);
324 test_delivery_in_thread (void)
328 thread = g_thread_new ("deliver",
329 test_delivery_in_thread_func,
332 g_thread_join (thread);
334 assert_connection_has_one_ref (c, NULL);
337 /* ---------------------------------------------------------------------------------------------------- */
345 GMainLoop *thread_loop;
350 sleep_cb (GDBusProxy *proxy,
354 SyncThreadData *data = user_data;
359 result = g_dbus_proxy_call_finish (proxy,
362 g_assert_no_error (error);
363 g_assert_nonnull (result);
364 g_assert_cmpstr (g_variant_get_type_string (result), ==, "()");
365 g_variant_unref (result);
367 g_assert_true (data->thread == g_thread_self ());
369 g_main_loop_quit (data->thread_loop);
371 //g_debug ("async cb (%p)", g_thread_self ());
375 test_sleep_in_thread_func (gpointer _data)
377 SyncThreadData *data = _data;
378 GMainContext *thread_context;
381 thread_context = g_main_context_new ();
382 data->thread_loop = g_main_loop_new (thread_context, FALSE);
383 g_main_context_push_thread_default (thread_context);
385 data->thread = g_thread_self ();
387 for (n = 0; n < data->num; n++)
391 //g_debug ("invoking async (%p)", g_thread_self ());
392 g_dbus_proxy_call (data->proxy,
394 g_variant_new ("(i)", data->msec),
395 G_DBUS_CALL_FLAGS_NONE,
398 (GAsyncReadyCallback) sleep_cb,
400 g_main_loop_run (data->thread_loop);
401 if (g_test_verbose ())
403 //g_debug ("done invoking async (%p)", g_thread_self ());
411 //g_debug ("invoking sync (%p)", g_thread_self ());
412 result = g_dbus_proxy_call_sync (data->proxy,
414 g_variant_new ("(i)", data->msec),
415 G_DBUS_CALL_FLAGS_NONE,
419 if (g_test_verbose ())
421 //g_debug ("done invoking sync (%p)", g_thread_self ());
422 g_assert_no_error (error);
423 g_assert_nonnull (result);
424 g_assert_cmpstr (g_variant_get_type_string (result), ==, "()");
425 g_variant_unref (result);
429 g_main_context_pop_thread_default (thread_context);
430 g_main_loop_unref (data->thread_loop);
431 g_main_context_unref (thread_context);
437 test_method_calls_on_proxy (GDBusProxy *proxy)
442 * Check that multiple threads can do calls without interfering with
443 * each other. We do this by creating three threads that call the
444 * Sleep() method on the server (which handles it asynchronously, e.g.
445 * it won't block other requests) with different sleep durations and
446 * a number of times. We do this so each set of calls add up to 4000
449 * The dbus test server that this code calls into uses glib timeouts
450 * to do the sleeping which have only a granularity of 1ms. It is
451 * therefore possible to lose as much as 40ms; the test could finish
452 * in slightly less than 4 seconds.
454 * We run this test twice - first with async calls in each thread, then
455 * again with sync calls
458 if (g_test_thorough ())
463 for (n = 0; n < 2; n++)
469 SyncThreadData data1;
470 SyncThreadData data2;
471 SyncThreadData data3;
472 gint64 start_time, end_time;
477 start_time = g_get_real_time ();
481 data1.num = 100 / divisor;
482 data1.async = do_async;
483 thread1 = g_thread_new ("sleep",
484 test_sleep_in_thread_func,
489 data2.num = 200 / divisor;
490 data2.async = do_async;
491 thread2 = g_thread_new ("sleep2",
492 test_sleep_in_thread_func,
497 data3.num = 40 / divisor;
498 data3.async = do_async;
499 thread3 = g_thread_new ("sleep3",
500 test_sleep_in_thread_func,
503 g_thread_join (thread1);
504 g_thread_join (thread2);
505 g_thread_join (thread3);
507 end_time = g_get_real_time ();
509 elapsed_msec = (end_time - start_time) / 1000;
511 //g_debug ("Elapsed time for %s = %d msec", n == 0 ? "async" : "sync", elapsed_msec);
513 /* elapsed_msec should be 4000 msec +/- change for overhead/inaccuracy */
514 g_assert_cmpint (elapsed_msec, >=, 3950 / divisor);
515 g_assert_cmpint (elapsed_msec, <, 30000 / divisor);
517 if (g_test_verbose ())
523 test_method_calls_in_thread (void)
526 GDBusConnection *connection;
530 connection = g_bus_get_sync (G_BUS_TYPE_SESSION,
533 g_assert_no_error (error);
535 proxy = g_dbus_proxy_new_sync (connection,
536 G_DBUS_PROXY_FLAGS_NONE,
537 NULL, /* GDBusInterfaceInfo */
538 "com.example.TestService", /* name */
539 "/com/example/TestObject", /* object path */
540 "com.example.Frob", /* interface */
541 NULL, /* GCancellable */
543 g_assert_no_error (error);
545 test_method_calls_on_proxy (proxy);
547 g_object_unref (proxy);
548 g_object_unref (connection);
550 if (g_test_verbose ())
553 assert_connection_has_one_ref (c, NULL);
556 #define SLEEP_MIN_USEC 1
557 #define SLEEP_MAX_USEC 10
559 /* Can run in any thread */
561 ensure_connection_works (GDBusConnection *conn)
564 GError *error = NULL;
566 v = g_dbus_connection_call_sync (conn, "org.freedesktop.DBus",
567 "/org/freedesktop/DBus", "org.freedesktop.DBus", "GetId", NULL, NULL, 0, -1,
569 g_assert_no_error (error);
570 g_assert_nonnull (v);
571 g_assert_true (g_variant_is_of_type (v, G_VARIANT_TYPE ("(s)")));
576 * get_sync_in_thread:
577 * @data: (type guint): delay in microseconds
579 * Sleep for a short time, then get a session bus connection and call
582 * Runs in a non-main thread.
584 * Returns: (transfer full): the connection
587 get_sync_in_thread (gpointer data)
589 guint delay = GPOINTER_TO_UINT (data);
590 GError *error = NULL;
591 GDBusConnection *conn;
595 conn = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, &error);
596 g_assert_no_error (error);
598 ensure_connection_works (conn);
604 test_threaded_singleton (void)
607 guint unref_wins = 0;
610 if (g_test_thorough ())
615 for (i = 0; i < n; i++)
618 guint unref_delay, get_delay;
619 GDBusConnection *new_conn;
621 /* We want to be the last ref, so let it finish setting up */
622 assert_connection_has_one_ref (c, NULL);
624 if (g_test_verbose () && (i % (n/50)) == 0)
625 g_printerr ("%u%%\n", ((i * 100) / n));
627 /* Delay for a random time on each side of the race, to perturb the
628 * timing. Ideally, we want each side to win half the races; these
629 * timings are about right on smcv's laptop.
631 unref_delay = g_random_int_range (SLEEP_MIN_USEC, SLEEP_MAX_USEC);
632 get_delay = g_random_int_range (SLEEP_MIN_USEC / 2, SLEEP_MAX_USEC / 2);
634 /* One half of the race is to call g_bus_get_sync... */
635 thread = g_thread_new ("get_sync_in_thread", get_sync_in_thread,
636 GUINT_TO_POINTER (get_delay));
638 /* ... and the other half is to unref the shared connection, which must
639 * have exactly one ref at this point
641 g_usleep (unref_delay);
644 /* Wait for the thread to run; see what it got */
645 new_conn = g_thread_join (thread);
647 /* If the thread won the race, it will have kept the same connection,
648 * and it'll have one ref
657 /* c is invalid now, but new_conn is suitable for the
663 ensure_connection_works (c);
666 if (g_test_verbose ())
667 g_printerr ("Unref won %u races; Get won %u races\n", unref_wins, get_wins);
670 /* ---------------------------------------------------------------------------------------------------- */
680 g_test_init (&argc, &argv, G_TEST_OPTION_ISOLATE_DIRS, NULL);
684 /* this is safe; testserver will exit once the bus goes away */
685 path = g_test_build_filename (G_TEST_BUILT, "gdbus-testserver", NULL);
686 g_assert_true (g_spawn_command_line_async (path, NULL));
689 /* Create the connection in the main thread */
691 c = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, &error);
692 g_assert_no_error (error);
693 g_assert_nonnull (c);
695 ensure_gdbus_testserver_up (c, NULL);
697 g_test_add_func ("/gdbus/delivery-in-thread", test_delivery_in_thread);
698 g_test_add_func ("/gdbus/method-calls-in-thread", test_method_calls_in_thread);
699 g_test_add_func ("/gdbus/threaded-singleton", test_threaded_singleton);