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>
36 #include "gdbusconnection.h"
37 #include "gdbusprivate.h"
39 #include "gioenumtypes.h"
40 #include "gtestdbus.h"
45 #define _WIN32_WINNT 0x0500
49 /* -------------------------------------------------------------------------- */
50 /* Utility: Wait until object has a single ref */
59 on_weak_notify_timeout (gpointer user_data)
61 WeakNotifyData *data = user_data;
62 data->timed_out = TRUE;
63 g_main_loop_quit (data->loop);
68 unref_on_idle (gpointer object)
70 g_object_unref (object);
75 _g_object_unref_and_wait_weak_notify (gpointer object)
80 data.loop = g_main_loop_new (NULL, FALSE);
81 data.timed_out = FALSE;
83 g_object_weak_ref (object, (GWeakNotify) g_main_loop_quit, data.loop);
85 /* Drop the ref in an idle callback, this is to make sure the mainloop
86 * is already running when weak notify happens */
87 g_idle_add (unref_on_idle, object);
89 /* Make sure we don't block forever */
90 timeout_id = g_timeout_add (30 * 1000, on_weak_notify_timeout, &data);
92 g_main_loop_run (data.loop);
94 g_source_remove (timeout_id);
98 g_warning ("Weak notify timeout, object ref_count=%d\n",
99 G_OBJECT (object)->ref_count);
102 return data.timed_out;
105 /* -------------------------------------------------------------------------- */
106 /* Utilities to cleanup the mess in the case unit test process crash */
110 /* This could be interesting to expose in public API */
112 _g_test_watcher_add_pid (GPid pid)
114 static gsize started = 0;
117 if (g_once_init_enter (&started))
119 JOBOBJECT_EXTENDED_LIMIT_INFORMATION info;
121 job = CreateJobObjectW (NULL, NULL);
122 memset (&info, 0, sizeof (info));
123 info.BasicLimitInformation.LimitFlags = 0x2000 /* JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE */;
125 if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, &info, sizeof (info)))
126 g_warning ("Can't enable JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE: %s", g_win32_error_message (GetLastError()));
128 g_once_init_leave (&started,(gsize)job);
131 job = (HANDLE)started;
133 if (!AssignProcessToJobObject(job, pid))
134 g_warning ("Can't assign process to job: %s", g_win32_error_message (GetLastError()));
138 _g_test_watcher_remove_pid (GPid pid)
140 /* No need to unassign the process from the job object as the process
141 will be killed anyway */
146 #define ADD_PID_FORMAT "add pid %d\n"
147 #define REMOVE_PID_FORMAT "remove pid %d\n"
150 watch_parent (gint fd)
154 GArray *pids_to_kill;
156 channel = g_io_channel_unix_new (fd);
159 fds[0].events = G_IO_HUP | G_IO_IN;
162 pids_to_kill = g_array_new (FALSE, FALSE, sizeof (guint));
167 gchar *command = NULL;
170 GError *error = NULL;
172 num_events = g_poll (fds, 1, -1);
176 if (fds[0].revents == G_IO_HUP)
178 /* Parent quit, cleanup the mess and exit */
179 for (n = 0; n < pids_to_kill->len; n++)
181 pid = g_array_index (pids_to_kill, guint, n);
182 g_print ("cleaning up pid %d\n", pid);
186 g_array_unref (pids_to_kill);
187 g_io_channel_shutdown (channel, FALSE, &error);
188 g_assert_no_error (error);
189 g_io_channel_unref (channel);
194 /* Read the command from the input */
195 g_io_channel_read_line (channel, &command, NULL, NULL, &error);
196 g_assert_no_error (error);
198 /* Check for known commands */
199 if (sscanf (command, ADD_PID_FORMAT, &pid) == 1)
201 g_array_append_val (pids_to_kill, pid);
203 else if (sscanf (command, REMOVE_PID_FORMAT, &pid) == 1)
205 for (n = 0; n < pids_to_kill->len; n++)
207 if (g_array_index (pids_to_kill, guint, n) == pid)
209 g_array_remove_index (pids_to_kill, n);
216 g_warning ("unknown pid %d to remove", pid);
221 g_warning ("unknown command from parent '%s'", command);
232 static gsize started = 0;
233 static GIOChannel *channel = NULL;
235 if (g_once_init_enter (&started))
239 /* fork a child to clean up when we are killed */
240 if (pipe (pipe_fds) != 0)
242 g_warning ("pipe() failed: %m");
243 g_assert_not_reached ();
249 g_warning ("fork() failed: %m");
250 g_assert_not_reached ();
256 watch_parent (pipe_fds[0]);
262 channel = g_io_channel_unix_new (pipe_fds[1]);
265 g_once_init_leave (&started, 1);
272 watcher_send_command (const gchar *command)
275 GError *error = NULL;
277 channel = watcher_init ();
279 g_io_channel_write_chars (channel, command, -1, NULL, &error);
280 g_assert_no_error (error);
282 g_io_channel_flush (channel, &error);
283 g_assert_no_error (error);
286 /* This could be interesting to expose in public API */
288 _g_test_watcher_add_pid (GPid pid)
292 command = g_strdup_printf (ADD_PID_FORMAT, (guint) pid);
293 watcher_send_command (command);
298 _g_test_watcher_remove_pid (GPid pid)
302 command = g_strdup_printf (REMOVE_PID_FORMAT, (guint) pid);
303 watcher_send_command (command);
309 /* -------------------------------------------------------------------------- */
310 /* GTestDBus object implementation */
314 * @short_description: D-Bus testing helper
315 * @include: gio/gio.h
317 * Helper to test D-Bus code wihtout messing up with user' session bus.
320 typedef struct _GTestDBusClass GTestDBusClass;
321 typedef struct _GTestDBusPrivate GTestDBusPrivate;
326 * The #GTestDBus structure contains only private data and
327 * should only be accessed using the provided API.
334 GTestDBusPrivate *priv;
337 struct _GTestDBusClass {
338 GObjectClass parent_class;
341 struct _GTestDBusPrivate
343 GTestDBusFlags flags;
344 GPtrArray *service_dirs;
356 G_DEFINE_TYPE (GTestDBus, g_test_dbus, G_TYPE_OBJECT)
359 g_test_dbus_init (GTestDBus *self)
361 self->priv = G_TYPE_INSTANCE_GET_PRIVATE ((self), G_TYPE_TEST_DBUS,
364 self->priv->service_dirs = g_ptr_array_new_with_free_func (g_free);
368 g_test_dbus_dispose (GObject *object)
370 GTestDBus *self = (GTestDBus *) object;
373 g_test_dbus_down (self);
375 G_OBJECT_CLASS (g_test_dbus_parent_class)->dispose (object);
379 g_test_dbus_finalize (GObject *object)
381 GTestDBus *self = (GTestDBus *) object;
383 g_ptr_array_unref (self->priv->service_dirs);
384 g_free (self->priv->bus_address);
386 G_OBJECT_CLASS (g_test_dbus_parent_class)->finalize (object);
390 g_test_dbus_get_property (GObject *object,
395 GTestDBus *self = (GTestDBus *) object;
400 g_value_set_flags (value, g_test_dbus_get_flags (self));
403 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
409 g_test_dbus_set_property (GObject *object,
414 GTestDBus *self = (GTestDBus *) object;
419 self->priv->flags = g_value_get_flags (value);
422 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
428 g_test_dbus_class_init (GTestDBusClass *klass)
430 GObjectClass *object_class = G_OBJECT_CLASS (klass);
432 object_class->dispose = g_test_dbus_dispose;
433 object_class->finalize = g_test_dbus_finalize;
434 object_class->get_property = g_test_dbus_get_property;
435 object_class->set_property = g_test_dbus_set_property;
437 g_type_class_add_private (object_class, sizeof (GTestDBusPrivate));
442 * #GTestDBusFlags specifying the behaviour of the dbus session
446 g_object_class_install_property (object_class, PROP_FLAGS,
447 g_param_spec_flags ("flags",
448 P_("dbus session flags"),
449 P_("Flags specifying the behaviour of the dbus session"),
450 G_TYPE_TEST_DBUS_FLAGS, G_TEST_DBUS_NONE,
451 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
452 G_PARAM_STATIC_STRINGS));
457 write_config_file (GTestDBus *self)
462 GError *error = NULL;
465 fd = g_file_open_tmp ("g-test-dbus-XXXXXX", &path, &error);
466 g_assert_no_error (error);
468 contents = g_string_new (NULL);
469 g_string_append (contents,
471 " <type>session</type>\n"
473 " <listen>nonce-tcp:</listen>\n"
475 " <listen>unix:tmpdir=/tmp</listen>\n"
479 for (i = 0; i < self->priv->service_dirs->len; i++)
481 const gchar *path = g_ptr_array_index (self->priv->service_dirs, i);
483 g_string_append_printf (contents,
484 " <servicedir>%s</servicedir>\n", path);
487 g_string_append (contents,
488 " <policy context=\"default\">\n"
489 " <!-- Allow everything to be sent -->\n"
490 " <allow send_destination=\"*\" eavesdrop=\"true\"/>\n"
491 " <!-- Allow everything to be received -->\n"
492 " <allow eavesdrop=\"true\"/>\n"
493 " <!-- Allow anyone to own anything -->\n"
494 " <allow own=\"*\"/>\n"
498 g_file_set_contents (path, contents->str, contents->len, &error);
499 g_assert_no_error (error);
501 g_string_free (contents, TRUE);
509 start_daemon (GTestDBus *self)
511 gchar *argv[] = {"dbus-daemon", "--print-address", "--config-file=foo", NULL};
517 GError *error = NULL;
519 if (g_getenv ("G_TEST_DBUS_DAEMON") != NULL)
520 argv[0] = (gchar *)g_getenv ("G_TEST_DBUS_DAEMON");
522 /* Write config file and set its path in argv */
523 config_path = write_config_file (self);
524 config_arg = g_strdup_printf ("--config-file=%s", config_path);
525 argv[2] = config_arg;
527 /* Spawn dbus-daemon */
528 g_spawn_async_with_pipes (NULL,
532 /* We Need this to get the pid returned on win32 */
533 G_SPAWN_DO_NOT_REAP_CHILD |
538 &self->priv->bus_pid,
543 g_assert_no_error (error);
545 _g_test_watcher_add_pid (self->priv->bus_pid);
547 /* Read bus address from daemon' stdout */
548 channel = g_io_channel_unix_new (stdout_fd);
549 g_io_channel_read_line (channel, &self->priv->bus_address, NULL,
551 g_assert_no_error (error);
552 self->priv->bus_address[termpos] = '\0';
554 /* start dbus-monitor */
555 if (g_getenv ("G_DBUS_MONITOR") != NULL)
559 command = g_strdup_printf ("dbus-monitor --address %s",
560 self->priv->bus_address);
561 g_spawn_command_line_async (command, NULL);
564 g_usleep (500 * 1000);
568 g_io_channel_shutdown (channel, FALSE, &error);
569 g_assert_no_error (error);
570 g_io_channel_unref (channel);
572 /* Don't use g_file_delete since it calls into gvfs */
573 if (g_unlink (config_path) != 0)
574 g_assert_not_reached ();
576 g_free (config_path);
581 stop_daemon (GTestDBus *self)
584 if (!TerminateProcess (self->priv->bus_pid, 0))
585 g_warning ("Can't terminate process: %s", g_win32_error_message (GetLastError()));
587 kill (self->priv->bus_pid, SIGTERM);
589 _g_test_watcher_remove_pid (self->priv->bus_pid);
590 g_spawn_close_pid (self->priv->bus_pid);
591 self->priv->bus_pid = 0;
593 g_free (self->priv->bus_address);
594 self->priv->bus_address = NULL;
599 * @flags: a #GTestDBusFlags
601 * Create a new #GTestDBus object.
603 * Returns: (transfer full): a new #GTestDBus.
606 g_test_dbus_new (GTestDBusFlags flags)
608 return g_object_new (G_TYPE_TEST_DBUS,
614 * g_test_dbus_get_flags:
615 * @self: a #GTestDBus
617 * Returns: the value of #GTestDBus:flags property
620 g_test_dbus_get_flags (GTestDBus *self)
622 g_return_val_if_fail (G_IS_TEST_DBUS (self), G_TEST_DBUS_NONE);
624 return self->priv->flags;
628 * g_test_dbus_get_bus_address:
629 * @self: a #GTestDBus
631 * Get the address on which dbus-daemon is running. if g_test_dbus_up() has not
632 * been called yet, %NULL is returned. This can be used with
633 * g_dbus_connection_new_for_address()
635 * Returns: the address of the bus, or %NULL.
638 g_test_dbus_get_bus_address (GTestDBus *self)
640 g_return_val_if_fail (G_IS_TEST_DBUS (self), NULL);
642 return self->priv->bus_address;
646 * g_test_dbus_add_service_dir:
647 * @self: a #GTestDBus
648 * @path: path to a directory containing .service files
650 * Add a path where dbus-daemon will lookup for .services files. This can't be
651 * called after g_test_dbus_up().
654 g_test_dbus_add_service_dir (GTestDBus *self,
657 g_return_if_fail (G_IS_TEST_DBUS (self));
658 g_return_if_fail (self->priv->bus_address == NULL);
660 g_ptr_array_add (self->priv->service_dirs, g_strdup (path));
665 * @self: a #GTestDBus
667 * Start a dbus-daemon instance and set DBUS_SESSION_BUS_ADDRESS. After this
668 * call, it is safe for unit tests to start sending messages on the session bug.
670 * If this function is called from setup callback of g_test_add(),
671 * g_test_dbus_down() must be called in its teardown callback.
673 * If this function is called from unit test's main(), then g_test_dbus_down()
674 * must be called after g_test_run().
677 g_test_dbus_up (GTestDBus *self)
679 g_return_if_fail (G_IS_TEST_DBUS (self));
680 g_return_if_fail (self->priv->bus_address == NULL);
681 g_return_if_fail (!self->priv->up);
685 g_setenv ("DBUS_SESSION_BUS_ADDRESS", self->priv->bus_address, TRUE);
686 self->priv->up = TRUE;
692 * @self: a #GTestDBus
694 * Stop the session bus started by g_test_dbus_up().
696 * Unlike g_test_dbus_down(), this won't verify the #GDBusConnection
697 * singleton returned by g_bus_get() or g_bus_get_sync() is destroyed. Unit
698 * tests wanting to verify behaviour after the session bus has been stopped
699 * can use this function but should still call g_test_dbus_down() when done.
702 g_test_dbus_stop (GTestDBus *self)
704 g_return_if_fail (G_IS_TEST_DBUS (self));
705 g_return_if_fail (self->priv->bus_address != NULL);
712 * @self: a #GTestDBus
714 * Stop the session bus started by g_test_dbus_up().
716 * This will wait for the singleton returned by g_bus_get() or g_bus_get_sync()
717 * is destroyed. This is done to ensure that the next unit test won't get a
718 * leaked singleton from this test.
721 g_test_dbus_down (GTestDBus *self)
723 GDBusConnection *connection;
725 g_return_if_fail (G_IS_TEST_DBUS (self));
726 g_return_if_fail (self->priv->up);
728 connection = _g_bus_get_singleton_if_exists (G_BUS_TYPE_SESSION);
729 if (connection != NULL)
730 g_dbus_connection_set_exit_on_close (connection, FALSE);
732 if (self->priv->bus_address != NULL)
735 if (connection != NULL)
736 _g_object_unref_and_wait_weak_notify (connection);
738 g_unsetenv ("DBUS_SESSION_BUS_ADDRESS");
739 self->priv->up = FALSE;
745 * Unset DISPLAY and DBUS_SESSION_BUS_ADDRESS env variables to ensure the test
746 * won't use user's session bus.
748 * This is useful for unit tests that want to verify behaviour when no session
749 * bus is running. It is not necessary to call this if unit test already calls
750 * g_test_dbus_up() before acquiring the session bus.
753 g_test_dbus_unset (void)
755 g_unsetenv ("DISPLAY");
756 g_unsetenv ("DBUS_SESSION_BUS_ADDRESS");