1 /* GIO testing utilities
3 * Copyright (C) 2008-2010 Red Hat, Inc.
4 * Copyright (C) 2012 Collabora Ltd. <http://www.collabora.co.uk/>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General
17 * Public License along with this library; if not, write to the
18 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
19 * Boston, MA 02111-1307, USA.
21 * Authors: David Zeuthen <davidz@redhat.com>
22 * Xavier Claessens <xavier.claessens@collabora.co.uk>
33 #include "gdbusconnection.h"
34 #include "gdbusprivate.h"
36 #include "gioenumtypes.h"
37 #include "gtestdbus.h"
41 /* -------------------------------------------------------------------------- */
42 /* Utility: Wait until object has a single ref */
51 on_weak_notify_timeout (gpointer user_data)
53 WeakNotifyData *data = user_data;
54 data->timed_out = TRUE;
55 g_main_loop_quit (data->loop);
60 unref_on_idle (gpointer object)
62 g_object_unref (object);
67 _g_object_unref_and_wait_weak_notify (gpointer object)
72 data.loop = g_main_loop_new (NULL, FALSE);
73 data.timed_out = FALSE;
75 g_object_weak_ref (object, (GWeakNotify) g_main_loop_quit, data.loop);
77 /* Drop the ref in an idle callback, this is to make sure the mainloop
78 * is already running when weak notify happens */
79 g_idle_add (unref_on_idle, object);
81 /* Make sure we don't block forever */
82 timeout_id = g_timeout_add (30 * 1000, on_weak_notify_timeout, &data);
84 g_main_loop_run (data.loop);
86 g_source_remove (timeout_id);
90 g_warning ("Weak notify timeout, object ref_count=%d\n",
91 G_OBJECT (object)->ref_count);
94 return data.timed_out;
97 /* -------------------------------------------------------------------------- */
98 /* Utilities to cleanup the mess in the case unit test process crash */
100 #define ADD_PID_FORMAT "add pid %d\n"
101 #define REMOVE_PID_FORMAT "remove pid %d\n"
104 watch_parent (gint fd)
108 GArray *pids_to_kill;
110 channel = g_io_channel_unix_new (fd);
113 fds[0].events = G_IO_HUP | G_IO_IN;
116 pids_to_kill = g_array_new (FALSE, FALSE, sizeof (guint));
121 gchar *command = NULL;
124 GError *error = NULL;
126 num_events = g_poll (fds, 1, -1);
130 if (fds[0].revents == G_IO_HUP)
132 /* Parent quit, cleanup the mess and exit */
133 for (n = 0; n < pids_to_kill->len; n++)
135 pid = g_array_index (pids_to_kill, guint, n);
136 g_print ("cleaning up pid %d\n", pid);
140 g_array_unref (pids_to_kill);
141 g_io_channel_shutdown (channel, FALSE, &error);
142 g_assert_no_error (error);
143 g_io_channel_unref (channel);
148 /* Read the command from the input */
149 g_io_channel_read_line (channel, &command, NULL, NULL, &error);
150 g_assert_no_error (error);
152 /* Check for known commands */
153 if (sscanf (command, ADD_PID_FORMAT, &pid) == 1)
155 g_array_append_val (pids_to_kill, pid);
157 else if (sscanf (command, REMOVE_PID_FORMAT, &pid) == 1)
159 for (n = 0; n < pids_to_kill->len; n++)
161 if (g_array_index (pids_to_kill, guint, n) == pid)
163 g_array_remove_index (pids_to_kill, n);
170 g_warning ("unknown pid %d to remove", pid);
175 g_warning ("unknown command from parent '%s'", command);
186 static gsize started = 0;
187 static GIOChannel *channel = NULL;
189 if (g_once_init_enter (&started))
193 /* fork a child to clean up when we are killed */
194 if (pipe (pipe_fds) != 0)
196 g_warning ("pipe() failed: %m");
197 g_assert_not_reached ();
203 g_warning ("fork() failed: %m");
204 g_assert_not_reached ();
210 watch_parent (pipe_fds[0]);
216 channel = g_io_channel_unix_new (pipe_fds[1]);
219 g_once_init_leave (&started, 1);
226 watcher_send_command (const gchar *command)
229 GError *error = NULL;
231 channel = watcher_init ();
233 g_io_channel_write_chars (channel, command, -1, NULL, &error);
234 g_assert_no_error (error);
236 g_io_channel_flush (channel, &error);
237 g_assert_no_error (error);
240 /* This could be interesting to expose in public API */
242 _g_test_watcher_add_pid (GPid pid)
246 command = g_strdup_printf (ADD_PID_FORMAT, (guint) pid);
247 watcher_send_command (command);
252 _g_test_watcher_remove_pid (GPid pid)
256 command = g_strdup_printf (REMOVE_PID_FORMAT, (guint) pid);
257 watcher_send_command (command);
261 /* -------------------------------------------------------------------------- */
262 /* GTestDBus object implementation */
266 * @short_description: D-Bus testing helper
267 * @include: gio/gio.h
269 * Helper to test D-Bus code wihtout messing up with user' session bus.
272 typedef struct _GTestDBusClass GTestDBusClass;
273 typedef struct _GTestDBusPrivate GTestDBusPrivate;
278 * The #GTestDBus structure contains only private data and
279 * should only be accessed using the provided API.
286 GTestDBusPrivate *priv;
289 struct _GTestDBusClass {
290 GObjectClass parent_class;
293 struct _GTestDBusPrivate
295 GTestDBusFlags flags;
296 GPtrArray *service_dirs;
308 G_DEFINE_TYPE (GTestDBus, g_test_dbus, G_TYPE_OBJECT)
311 g_test_dbus_init (GTestDBus *self)
313 self->priv = G_TYPE_INSTANCE_GET_PRIVATE ((self), G_TYPE_TEST_DBUS,
316 self->priv->service_dirs = g_ptr_array_new_with_free_func (g_free);
320 g_test_dbus_dispose (GObject *object)
322 GTestDBus *self = (GTestDBus *) object;
325 g_test_dbus_down (self);
327 G_OBJECT_CLASS (g_test_dbus_parent_class)->dispose (object);
331 g_test_dbus_finalize (GObject *object)
333 GTestDBus *self = (GTestDBus *) object;
335 g_ptr_array_unref (self->priv->service_dirs);
336 g_free (self->priv->bus_address);
338 G_OBJECT_CLASS (g_test_dbus_parent_class)->finalize (object);
342 g_test_dbus_get_property (GObject *object,
347 GTestDBus *self = (GTestDBus *) object;
352 g_value_set_flags (value, g_test_dbus_get_flags (self));
355 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
361 g_test_dbus_set_property (GObject *object,
366 GTestDBus *self = (GTestDBus *) object;
371 self->priv->flags = g_value_get_flags (value);
374 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
380 g_test_dbus_class_init (GTestDBusClass *klass)
382 GObjectClass *object_class = G_OBJECT_CLASS (klass);
384 object_class->dispose = g_test_dbus_dispose;
385 object_class->finalize = g_test_dbus_finalize;
386 object_class->get_property = g_test_dbus_get_property;
387 object_class->set_property = g_test_dbus_set_property;
389 g_type_class_add_private (object_class, sizeof (GTestDBusPrivate));
394 * #GTestDBusFlags specifying the behaviour of the dbus session
398 g_object_class_install_property (object_class, PROP_FLAGS,
399 g_param_spec_flags ("flags",
400 P_("dbus session flags"),
401 P_("Flags specifying the behaviour of the dbus session"),
402 G_TYPE_TEST_DBUS_FLAGS, G_TEST_DBUS_NONE,
403 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
404 G_PARAM_STATIC_STRINGS));
409 write_config_file (GTestDBus *self)
413 GFileIOStream *iostream;
415 GError *error = NULL;
417 file = g_file_new_tmp ("g-test-dbus-XXXXXX", &iostream, &error);
418 g_assert_no_error (error);
419 g_object_unref (iostream);
421 contents = g_string_new (NULL);
422 g_string_append (contents,
424 " <type>session</type>\n"
425 " <listen>unix:tmpdir=/tmp</listen>\n");
427 for (i = 0; i < self->priv->service_dirs->len; i++)
429 const gchar *path = g_ptr_array_index (self->priv->service_dirs, i);
431 g_string_append_printf (contents,
432 " <servicedir>%s</servicedir>\n", path);
435 g_string_append (contents,
436 " <policy context=\"default\">\n"
437 " <!-- Allow everything to be sent -->\n"
438 " <allow send_destination=\"*\" eavesdrop=\"true\"/>\n"
439 " <!-- Allow everything to be received -->\n"
440 " <allow eavesdrop=\"true\"/>\n"
441 " <!-- Allow anyone to own anything -->\n"
442 " <allow own=\"*\"/>\n"
446 g_file_replace_contents (file, contents->str, contents->len,
447 NULL, FALSE, G_FILE_CREATE_NONE, NULL, NULL, &error);
448 g_assert_no_error (error);
450 g_string_free (contents, TRUE);
456 start_daemon (GTestDBus *self)
458 gchar *argv[] = {"dbus-daemon", "--print-address", "--config-file=foo", NULL};
465 GError *error = NULL;
467 /* Write config file and set its path in argv */
468 file = write_config_file (self);
469 config_path = g_file_get_path (file);
470 config_arg = g_strdup_printf ("--config-file=%s", config_path);
471 argv[2] = config_arg;
473 /* Spawn dbus-daemon */
474 g_spawn_async_with_pipes (NULL,
480 &self->priv->bus_pid,
485 g_assert_no_error (error);
487 _g_test_watcher_add_pid (self->priv->bus_pid);
489 /* Read bus address from daemon' stdout */
490 channel = g_io_channel_unix_new (stdout_fd);
491 g_io_channel_read_line (channel, &self->priv->bus_address, NULL,
493 g_assert_no_error (error);
494 self->priv->bus_address[termpos] = '\0';
496 /* start dbus-monitor */
497 if (g_getenv ("G_DBUS_MONITOR") != NULL)
501 command = g_strdup_printf ("dbus-monitor --address %s",
502 self->priv->bus_address);
503 g_spawn_command_line_async (command, NULL);
510 g_io_channel_shutdown (channel, FALSE, &error);
511 g_assert_no_error (error);
512 g_io_channel_unref (channel);
514 g_file_delete (file, NULL, &error);
515 g_assert_no_error (error);
516 g_object_unref (file);
518 g_free (config_path);
523 stop_daemon (GTestDBus *self)
525 kill (self->priv->bus_pid, SIGTERM);
526 _g_test_watcher_remove_pid (self->priv->bus_pid);
527 self->priv->bus_pid = 0;
529 g_free (self->priv->bus_address);
530 self->priv->bus_address = NULL;
535 * @flags: a #GTestDBusFlags
537 * Create a new #GTestDBus object.
539 * Returns: (transfer full): a new #GTestDBus.
542 g_test_dbus_new (GTestDBusFlags flags)
544 return g_object_new (G_TYPE_TEST_DBUS,
550 * g_test_dbus_get_flags:
551 * @self: a #GTestDBus
553 * Returns: the value of #GTestDBus:flags property
556 g_test_dbus_get_flags (GTestDBus *self)
558 g_return_val_if_fail (G_IS_TEST_DBUS (self), G_TEST_DBUS_NONE);
560 return self->priv->flags;
564 * g_test_dbus_get_bus_address:
565 * @self: a #GTestDBus
567 * Get the address on which dbus-daemon is running. if g_test_dbus_up() has not
568 * been called yet, %NULL is returned. This can be used with
569 * g_dbus_connection_new_for_address()
571 * Returns: the address of the bus, or %NULL.
574 g_test_dbus_get_bus_address (GTestDBus *self)
576 g_return_val_if_fail (G_IS_TEST_DBUS (self), NULL);
578 return self->priv->bus_address;
582 * g_test_dbus_add_service_dir:
583 * @self: a #GTestDBus
584 * @path: path to a directory containing .service files
586 * Add a path where dbus-daemon will lookup for .services files. This can't be
587 * called after g_test_dbus_up().
590 g_test_dbus_add_service_dir (GTestDBus *self,
593 g_return_if_fail (G_IS_TEST_DBUS (self));
594 g_return_if_fail (self->priv->bus_address == NULL);
596 g_ptr_array_add (self->priv->service_dirs, g_strdup (path));
601 * @self: a #GTestDBus
603 * Start a dbus-daemon instance and set DBUS_SESSION_BUS_ADDRESS. After this
604 * call, it is safe for unit tests to start sending messages on the session bug.
606 * If this function is called from setup callback of g_test_add(),
607 * g_test_dbus_down() must be called in its teardown callback.
609 * If this function is called from unit test's main(), then g_test_dbus_down()
610 * must be called after g_test_run().
613 g_test_dbus_up (GTestDBus *self)
615 g_return_if_fail (G_IS_TEST_DBUS (self));
616 g_return_if_fail (self->priv->bus_address == NULL);
617 g_return_if_fail (!self->priv->up);
621 g_setenv ("DBUS_SESSION_BUS_ADDRESS", self->priv->bus_address, TRUE);
622 self->priv->up = TRUE;
628 * @self: a #GTestDBus
630 * Stop the session bus started by g_test_dbus_up().
632 * Unlike g_test_dbus_down(), this won't verify the #GDBusConnection
633 * singleton returned by g_bus_get() or g_bus_get_sync() is destroyed. Unit
634 * tests wanting to verify behaviour after the session bus has been stopped
635 * can use this function but should still call g_test_dbus_down() when done.
638 g_test_dbus_stop (GTestDBus *self)
640 g_return_if_fail (G_IS_TEST_DBUS (self));
641 g_return_if_fail (self->priv->bus_address != NULL);
648 * @self: a #GTestDBus
650 * Stop the session bus started by g_test_dbus_up().
652 * This will wait for the singleton returned by g_bus_get() or g_bus_get_sync()
653 * is destroyed. This is done to ensure that the next unit test won't get a
654 * leaked singleton from this test.
657 g_test_dbus_down (GTestDBus *self)
659 GDBusConnection *connection;
661 g_return_if_fail (G_IS_TEST_DBUS (self));
662 g_return_if_fail (self->priv->up);
664 connection = _g_bus_get_singleton_if_exists (G_BUS_TYPE_SESSION);
665 if (connection != NULL)
666 g_dbus_connection_set_exit_on_close (connection, FALSE);
668 if (self->priv->bus_address != NULL)
671 if (connection != NULL)
672 _g_object_unref_and_wait_weak_notify (connection);
674 g_unsetenv ("DBUS_SESSION_BUS_ADDRESS");
675 self->priv->up = FALSE;
681 * Unset DISPLAY and DBUS_SESSION_BUS_ADDRESS env variables to ensure the test
682 * won't use user's session bus.
684 * This is useful for unit tests that want to verify behaviour when no session
685 * bus is running. It is not necessary to call this if unit test already calls
686 * g_test_dbus_up() before acquiring the session bus.
689 g_test_dbus_unset (void)
691 g_unsetenv ("DISPLAY");
692 g_unsetenv ("DBUS_SESSION_BUS_ADDRESS");