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>
39 #include "gdbusconnection.h"
40 #include "gdbusprivate.h"
42 #include "gioenumtypes.h"
43 #include "gtestdbus.h"
48 #define _WIN32_WINNT 0x0500
52 /* -------------------------------------------------------------------------- */
53 /* Utility: Wait until object has a single ref */
62 on_weak_notify_timeout (gpointer user_data)
64 WeakNotifyData *data = user_data;
65 data->timed_out = TRUE;
66 g_main_loop_quit (data->loop);
71 unref_on_idle (gpointer object)
73 g_object_unref (object);
78 _g_object_unref_and_wait_weak_notify (gpointer object)
83 data.loop = g_main_loop_new (NULL, FALSE);
84 data.timed_out = FALSE;
86 g_object_weak_ref (object, (GWeakNotify) g_main_loop_quit, data.loop);
88 /* Drop the ref in an idle callback, this is to make sure the mainloop
89 * is already running when weak notify happens */
90 g_idle_add (unref_on_idle, object);
92 /* Make sure we don't block forever */
93 timeout_id = g_timeout_add (30 * 1000, on_weak_notify_timeout, &data);
95 g_main_loop_run (data.loop);
97 g_source_remove (timeout_id);
101 g_warning ("Weak notify timeout, object ref_count=%d\n",
102 G_OBJECT (object)->ref_count);
105 return data.timed_out;
108 /* -------------------------------------------------------------------------- */
109 /* Utilities to cleanup the mess in the case unit test process crash */
113 /* This could be interesting to expose in public API */
115 _g_test_watcher_add_pid (GPid pid)
117 static gsize started = 0;
120 if (g_once_init_enter (&started))
122 JOBOBJECT_EXTENDED_LIMIT_INFORMATION info;
124 job = CreateJobObjectW (NULL, NULL);
125 memset (&info, 0, sizeof (info));
126 info.BasicLimitInformation.LimitFlags = 0x2000 /* JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE */;
128 if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, &info, sizeof (info)))
129 g_warning ("Can't enable JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE: %s", g_win32_error_message (GetLastError()));
131 g_once_init_leave (&started,(gsize)job);
134 job = (HANDLE)started;
136 if (!AssignProcessToJobObject(job, pid))
137 g_warning ("Can't assign process to job: %s", g_win32_error_message (GetLastError()));
141 _g_test_watcher_remove_pid (GPid pid)
143 /* No need to unassign the process from the job object as the process
144 will be killed anyway */
149 #define ADD_PID_FORMAT "add pid %d\n"
150 #define REMOVE_PID_FORMAT "remove pid %d\n"
153 watch_parent (gint fd)
157 GArray *pids_to_kill;
159 channel = g_io_channel_unix_new (fd);
162 fds[0].events = G_IO_HUP | G_IO_IN;
165 pids_to_kill = g_array_new (FALSE, FALSE, sizeof (guint));
170 gchar *command = NULL;
173 GError *error = NULL;
175 num_events = g_poll (fds, 1, -1);
179 if (fds[0].revents == G_IO_HUP)
181 /* Parent quit, cleanup the mess and exit */
182 for (n = 0; n < pids_to_kill->len; n++)
184 pid = g_array_index (pids_to_kill, guint, n);
185 g_print ("cleaning up pid %d\n", pid);
189 g_array_unref (pids_to_kill);
190 g_io_channel_shutdown (channel, FALSE, &error);
191 g_assert_no_error (error);
192 g_io_channel_unref (channel);
197 /* Read the command from the input */
198 g_io_channel_read_line (channel, &command, NULL, NULL, &error);
199 g_assert_no_error (error);
201 /* Check for known commands */
202 if (sscanf (command, ADD_PID_FORMAT, &pid) == 1)
204 g_array_append_val (pids_to_kill, pid);
206 else if (sscanf (command, REMOVE_PID_FORMAT, &pid) == 1)
208 for (n = 0; n < pids_to_kill->len; n++)
210 if (g_array_index (pids_to_kill, guint, n) == pid)
212 g_array_remove_index (pids_to_kill, n);
219 g_warning ("unknown pid %d to remove", pid);
224 g_warning ("unknown command from parent '%s'", command);
235 static gsize started = 0;
236 static GIOChannel *channel = NULL;
238 if (g_once_init_enter (&started))
242 /* fork a child to clean up when we are killed */
243 if (pipe (pipe_fds) != 0)
245 g_warning ("pipe() failed: %m");
246 g_assert_not_reached ();
252 g_warning ("fork() failed: %m");
253 g_assert_not_reached ();
259 watch_parent (pipe_fds[0]);
265 channel = g_io_channel_unix_new (pipe_fds[1]);
268 g_once_init_leave (&started, 1);
275 watcher_send_command (const gchar *command)
278 GError *error = NULL;
280 channel = watcher_init ();
282 g_io_channel_write_chars (channel, command, -1, NULL, &error);
283 g_assert_no_error (error);
285 g_io_channel_flush (channel, &error);
286 g_assert_no_error (error);
289 /* This could be interesting to expose in public API */
291 _g_test_watcher_add_pid (GPid pid)
295 command = g_strdup_printf (ADD_PID_FORMAT, (guint) pid);
296 watcher_send_command (command);
301 _g_test_watcher_remove_pid (GPid pid)
305 command = g_strdup_printf (REMOVE_PID_FORMAT, (guint) pid);
306 watcher_send_command (command);
312 /* -------------------------------------------------------------------------- */
313 /* GTestDBus object implementation */
317 * @short_description: D-Bus testing helper
318 * @include: gio/gio.h
320 * Helper to test D-Bus code wihtout messing up with user' session bus.
323 typedef struct _GTestDBusClass GTestDBusClass;
324 typedef struct _GTestDBusPrivate GTestDBusPrivate;
329 * The #GTestDBus structure contains only private data and
330 * should only be accessed using the provided API.
337 GTestDBusPrivate *priv;
340 struct _GTestDBusClass {
341 GObjectClass parent_class;
344 struct _GTestDBusPrivate
346 GTestDBusFlags flags;
347 GPtrArray *service_dirs;
359 G_DEFINE_TYPE (GTestDBus, g_test_dbus, G_TYPE_OBJECT)
362 g_test_dbus_init (GTestDBus *self)
364 self->priv = G_TYPE_INSTANCE_GET_PRIVATE ((self), G_TYPE_TEST_DBUS,
367 self->priv->service_dirs = g_ptr_array_new_with_free_func (g_free);
371 g_test_dbus_dispose (GObject *object)
373 GTestDBus *self = (GTestDBus *) object;
376 g_test_dbus_down (self);
378 G_OBJECT_CLASS (g_test_dbus_parent_class)->dispose (object);
382 g_test_dbus_finalize (GObject *object)
384 GTestDBus *self = (GTestDBus *) object;
386 g_ptr_array_unref (self->priv->service_dirs);
387 g_free (self->priv->bus_address);
389 G_OBJECT_CLASS (g_test_dbus_parent_class)->finalize (object);
393 g_test_dbus_get_property (GObject *object,
398 GTestDBus *self = (GTestDBus *) object;
403 g_value_set_flags (value, g_test_dbus_get_flags (self));
406 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
412 g_test_dbus_set_property (GObject *object,
417 GTestDBus *self = (GTestDBus *) object;
422 self->priv->flags = g_value_get_flags (value);
425 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
431 g_test_dbus_class_init (GTestDBusClass *klass)
433 GObjectClass *object_class = G_OBJECT_CLASS (klass);
435 object_class->dispose = g_test_dbus_dispose;
436 object_class->finalize = g_test_dbus_finalize;
437 object_class->get_property = g_test_dbus_get_property;
438 object_class->set_property = g_test_dbus_set_property;
440 g_type_class_add_private (object_class, sizeof (GTestDBusPrivate));
445 * #GTestDBusFlags specifying the behaviour of the dbus session
449 g_object_class_install_property (object_class, PROP_FLAGS,
450 g_param_spec_flags ("flags",
451 P_("dbus session flags"),
452 P_("Flags specifying the behaviour of the dbus session"),
453 G_TYPE_TEST_DBUS_FLAGS, G_TEST_DBUS_NONE,
454 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
455 G_PARAM_STATIC_STRINGS));
460 write_config_file (GTestDBus *self)
465 GError *error = NULL;
468 fd = g_file_open_tmp ("g-test-dbus-XXXXXX", &path, &error);
469 g_assert_no_error (error);
471 contents = g_string_new (NULL);
472 g_string_append (contents,
474 " <type>session</type>\n"
476 " <listen>nonce-tcp:</listen>\n"
478 " <listen>unix:tmpdir=/tmp</listen>\n"
482 for (i = 0; i < self->priv->service_dirs->len; i++)
484 const gchar *path = g_ptr_array_index (self->priv->service_dirs, i);
486 g_string_append_printf (contents,
487 " <servicedir>%s</servicedir>\n", path);
490 g_string_append (contents,
491 " <policy context=\"default\">\n"
492 " <!-- Allow everything to be sent -->\n"
493 " <allow send_destination=\"*\" eavesdrop=\"true\"/>\n"
494 " <!-- Allow everything to be received -->\n"
495 " <allow eavesdrop=\"true\"/>\n"
496 " <!-- Allow anyone to own anything -->\n"
497 " <allow own=\"*\"/>\n"
501 g_file_set_contents (path, contents->str, contents->len, &error);
502 g_assert_no_error (error);
504 g_string_free (contents, TRUE);
512 start_daemon (GTestDBus *self)
514 gchar *argv[] = {"dbus-daemon", "--print-address", "--config-file=foo", NULL};
520 GError *error = NULL;
522 if (g_getenv ("G_TEST_DBUS_DAEMON") != NULL)
523 argv[0] = (gchar *)g_getenv ("G_TEST_DBUS_DAEMON");
525 /* Write config file and set its path in argv */
526 config_path = write_config_file (self);
527 config_arg = g_strdup_printf ("--config-file=%s", config_path);
528 argv[2] = config_arg;
530 /* Spawn dbus-daemon */
531 g_spawn_async_with_pipes (NULL,
535 /* We Need this to get the pid returned on win32 */
536 G_SPAWN_DO_NOT_REAP_CHILD |
541 &self->priv->bus_pid,
546 g_assert_no_error (error);
548 _g_test_watcher_add_pid (self->priv->bus_pid);
550 /* Read bus address from daemon' stdout */
551 channel = g_io_channel_unix_new (stdout_fd);
552 g_io_channel_read_line (channel, &self->priv->bus_address, NULL,
554 g_assert_no_error (error);
555 self->priv->bus_address[termpos] = '\0';
557 /* start dbus-monitor */
558 if (g_getenv ("G_DBUS_MONITOR") != NULL)
562 command = g_strdup_printf ("dbus-monitor --address %s",
563 self->priv->bus_address);
564 g_spawn_command_line_async (command, NULL);
567 g_usleep (500 * 1000);
571 g_io_channel_shutdown (channel, FALSE, &error);
572 g_assert_no_error (error);
573 g_io_channel_unref (channel);
575 /* Don't use g_file_delete since it calls into gvfs */
576 if (g_unlink (config_path) != 0)
577 g_assert_not_reached ();
579 g_free (config_path);
584 stop_daemon (GTestDBus *self)
587 if (!TerminateProcess (self->priv->bus_pid, 0))
588 g_warning ("Can't terminate process: %s", g_win32_error_message (GetLastError()));
590 kill (self->priv->bus_pid, SIGTERM);
592 _g_test_watcher_remove_pid (self->priv->bus_pid);
593 g_spawn_close_pid (self->priv->bus_pid);
594 self->priv->bus_pid = 0;
596 g_free (self->priv->bus_address);
597 self->priv->bus_address = NULL;
602 * @flags: a #GTestDBusFlags
604 * Create a new #GTestDBus object.
606 * Returns: (transfer full): a new #GTestDBus.
609 g_test_dbus_new (GTestDBusFlags flags)
611 return g_object_new (G_TYPE_TEST_DBUS,
617 * g_test_dbus_get_flags:
618 * @self: a #GTestDBus
620 * Returns: the value of #GTestDBus:flags property
623 g_test_dbus_get_flags (GTestDBus *self)
625 g_return_val_if_fail (G_IS_TEST_DBUS (self), G_TEST_DBUS_NONE);
627 return self->priv->flags;
631 * g_test_dbus_get_bus_address:
632 * @self: a #GTestDBus
634 * Get the address on which dbus-daemon is running. if g_test_dbus_up() has not
635 * been called yet, %NULL is returned. This can be used with
636 * g_dbus_connection_new_for_address()
638 * Returns: the address of the bus, or %NULL.
641 g_test_dbus_get_bus_address (GTestDBus *self)
643 g_return_val_if_fail (G_IS_TEST_DBUS (self), NULL);
645 return self->priv->bus_address;
649 * g_test_dbus_add_service_dir:
650 * @self: a #GTestDBus
651 * @path: path to a directory containing .service files
653 * Add a path where dbus-daemon will lookup for .services files. This can't be
654 * called after g_test_dbus_up().
657 g_test_dbus_add_service_dir (GTestDBus *self,
660 g_return_if_fail (G_IS_TEST_DBUS (self));
661 g_return_if_fail (self->priv->bus_address == NULL);
663 g_ptr_array_add (self->priv->service_dirs, g_strdup (path));
668 * @self: a #GTestDBus
670 * Start a dbus-daemon instance and set DBUS_SESSION_BUS_ADDRESS. After this
671 * call, it is safe for unit tests to start sending messages on the session bug.
673 * If this function is called from setup callback of g_test_add(),
674 * g_test_dbus_down() must be called in its teardown callback.
676 * If this function is called from unit test's main(), then g_test_dbus_down()
677 * must be called after g_test_run().
680 g_test_dbus_up (GTestDBus *self)
682 g_return_if_fail (G_IS_TEST_DBUS (self));
683 g_return_if_fail (self->priv->bus_address == NULL);
684 g_return_if_fail (!self->priv->up);
688 g_setenv ("DBUS_SESSION_BUS_ADDRESS", self->priv->bus_address, TRUE);
689 self->priv->up = TRUE;
695 * @self: a #GTestDBus
697 * Stop the session bus started by g_test_dbus_up().
699 * Unlike g_test_dbus_down(), this won't verify the #GDBusConnection
700 * singleton returned by g_bus_get() or g_bus_get_sync() is destroyed. Unit
701 * tests wanting to verify behaviour after the session bus has been stopped
702 * can use this function but should still call g_test_dbus_down() when done.
705 g_test_dbus_stop (GTestDBus *self)
707 g_return_if_fail (G_IS_TEST_DBUS (self));
708 g_return_if_fail (self->priv->bus_address != NULL);
715 * @self: a #GTestDBus
717 * Stop the session bus started by g_test_dbus_up().
719 * This will wait for the singleton returned by g_bus_get() or g_bus_get_sync()
720 * is destroyed. This is done to ensure that the next unit test won't get a
721 * leaked singleton from this test.
724 g_test_dbus_down (GTestDBus *self)
726 GDBusConnection *connection;
728 g_return_if_fail (G_IS_TEST_DBUS (self));
729 g_return_if_fail (self->priv->up);
731 connection = _g_bus_get_singleton_if_exists (G_BUS_TYPE_SESSION);
732 if (connection != NULL)
733 g_dbus_connection_set_exit_on_close (connection, FALSE);
735 if (self->priv->bus_address != NULL)
738 if (connection != NULL)
739 _g_object_unref_and_wait_weak_notify (connection);
741 g_unsetenv ("DBUS_SESSION_BUS_ADDRESS");
742 self->priv->up = FALSE;
748 * Unset DISPLAY and DBUS_SESSION_BUS_ADDRESS env variables to ensure the test
749 * won't use user's session bus.
751 * This is useful for unit tests that want to verify behaviour when no session
752 * bus is running. It is not necessary to call this if unit test already calls
753 * g_test_dbus_up() before acquiring the session bus.
756 g_test_dbus_unset (void)
758 g_unsetenv ("DISPLAY");
759 g_unsetenv ("DBUS_SESSION_BUS_ADDRESS");