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>
35 #include "gdbusconnection.h"
36 #include "gdbusprivate.h"
38 #include "gioenumtypes.h"
39 #include "gtestdbus.h"
44 #define _WIN32_WINNT 0x0500
48 /* -------------------------------------------------------------------------- */
49 /* Utility: Wait until object has a single ref */
58 on_weak_notify_timeout (gpointer user_data)
60 WeakNotifyData *data = user_data;
61 data->timed_out = TRUE;
62 g_main_loop_quit (data->loop);
67 unref_on_idle (gpointer object)
69 g_object_unref (object);
74 _g_object_unref_and_wait_weak_notify (gpointer object)
79 data.loop = g_main_loop_new (NULL, FALSE);
80 data.timed_out = FALSE;
82 g_object_weak_ref (object, (GWeakNotify) g_main_loop_quit, data.loop);
84 /* Drop the ref in an idle callback, this is to make sure the mainloop
85 * is already running when weak notify happens */
86 g_idle_add (unref_on_idle, object);
88 /* Make sure we don't block forever */
89 timeout_id = g_timeout_add (30 * 1000, on_weak_notify_timeout, &data);
91 g_main_loop_run (data.loop);
93 g_source_remove (timeout_id);
97 g_warning ("Weak notify timeout, object ref_count=%d\n",
98 G_OBJECT (object)->ref_count);
101 return data.timed_out;
104 /* -------------------------------------------------------------------------- */
105 /* Utilities to cleanup the mess in the case unit test process crash */
109 /* This could be interesting to expose in public API */
111 _g_test_watcher_add_pid (GPid pid)
113 static gsize started = 0;
116 if (g_once_init_enter (&started))
118 JOBOBJECT_EXTENDED_LIMIT_INFORMATION info;
120 job = CreateJobObjectW (NULL, NULL);
121 memset (&info, 0, sizeof (info));
122 info.BasicLimitInformation.LimitFlags = 0x2000 /* JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE */;
124 if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, &info, sizeof (info)))
125 g_warning ("Can't enable JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE: %s", g_win32_error_message (GetLastError()));
127 g_once_init_leave (&started,(gsize)job);
130 job = (HANDLE)started;
132 if (!AssignProcessToJobObject(job, pid))
133 g_warning ("Can't assign process to job: %s", g_win32_error_message (GetLastError()));
137 _g_test_watcher_remove_pid (GPid pid)
139 /* No need to unassign the process from the job object as the process
140 will be killed anyway */
145 #define ADD_PID_FORMAT "add pid %d\n"
146 #define REMOVE_PID_FORMAT "remove pid %d\n"
149 watch_parent (gint fd)
153 GArray *pids_to_kill;
155 channel = g_io_channel_unix_new (fd);
158 fds[0].events = G_IO_HUP | G_IO_IN;
161 pids_to_kill = g_array_new (FALSE, FALSE, sizeof (guint));
166 gchar *command = NULL;
169 GError *error = NULL;
171 num_events = g_poll (fds, 1, -1);
175 if (fds[0].revents == G_IO_HUP)
177 /* Parent quit, cleanup the mess and exit */
178 for (n = 0; n < pids_to_kill->len; n++)
180 pid = g_array_index (pids_to_kill, guint, n);
181 g_print ("cleaning up pid %d\n", pid);
185 g_array_unref (pids_to_kill);
186 g_io_channel_shutdown (channel, FALSE, &error);
187 g_assert_no_error (error);
188 g_io_channel_unref (channel);
193 /* Read the command from the input */
194 g_io_channel_read_line (channel, &command, NULL, NULL, &error);
195 g_assert_no_error (error);
197 /* Check for known commands */
198 if (sscanf (command, ADD_PID_FORMAT, &pid) == 1)
200 g_array_append_val (pids_to_kill, pid);
202 else if (sscanf (command, REMOVE_PID_FORMAT, &pid) == 1)
204 for (n = 0; n < pids_to_kill->len; n++)
206 if (g_array_index (pids_to_kill, guint, n) == pid)
208 g_array_remove_index (pids_to_kill, n);
215 g_warning ("unknown pid %d to remove", pid);
220 g_warning ("unknown command from parent '%s'", command);
231 static gsize started = 0;
232 static GIOChannel *channel = NULL;
234 if (g_once_init_enter (&started))
238 /* fork a child to clean up when we are killed */
239 if (pipe (pipe_fds) != 0)
241 g_warning ("pipe() failed: %m");
242 g_assert_not_reached ();
248 g_warning ("fork() failed: %m");
249 g_assert_not_reached ();
255 watch_parent (pipe_fds[0]);
261 channel = g_io_channel_unix_new (pipe_fds[1]);
264 g_once_init_leave (&started, 1);
271 watcher_send_command (const gchar *command)
274 GError *error = NULL;
276 channel = watcher_init ();
278 g_io_channel_write_chars (channel, command, -1, NULL, &error);
279 g_assert_no_error (error);
281 g_io_channel_flush (channel, &error);
282 g_assert_no_error (error);
285 /* This could be interesting to expose in public API */
287 _g_test_watcher_add_pid (GPid pid)
291 command = g_strdup_printf (ADD_PID_FORMAT, (guint) pid);
292 watcher_send_command (command);
297 _g_test_watcher_remove_pid (GPid pid)
301 command = g_strdup_printf (REMOVE_PID_FORMAT, (guint) pid);
302 watcher_send_command (command);
308 /* -------------------------------------------------------------------------- */
309 /* GTestDBus object implementation */
313 * @short_description: D-Bus testing helper
314 * @include: gio/gio.h
316 * Helper to test D-Bus code wihtout messing up with user' session bus.
319 typedef struct _GTestDBusClass GTestDBusClass;
320 typedef struct _GTestDBusPrivate GTestDBusPrivate;
325 * The #GTestDBus structure contains only private data and
326 * should only be accessed using the provided API.
333 GTestDBusPrivate *priv;
336 struct _GTestDBusClass {
337 GObjectClass parent_class;
340 struct _GTestDBusPrivate
342 GTestDBusFlags flags;
343 GPtrArray *service_dirs;
355 G_DEFINE_TYPE (GTestDBus, g_test_dbus, G_TYPE_OBJECT)
358 g_test_dbus_init (GTestDBus *self)
360 self->priv = G_TYPE_INSTANCE_GET_PRIVATE ((self), G_TYPE_TEST_DBUS,
363 self->priv->service_dirs = g_ptr_array_new_with_free_func (g_free);
367 g_test_dbus_dispose (GObject *object)
369 GTestDBus *self = (GTestDBus *) object;
372 g_test_dbus_down (self);
374 G_OBJECT_CLASS (g_test_dbus_parent_class)->dispose (object);
378 g_test_dbus_finalize (GObject *object)
380 GTestDBus *self = (GTestDBus *) object;
382 g_ptr_array_unref (self->priv->service_dirs);
383 g_free (self->priv->bus_address);
385 G_OBJECT_CLASS (g_test_dbus_parent_class)->finalize (object);
389 g_test_dbus_get_property (GObject *object,
394 GTestDBus *self = (GTestDBus *) object;
399 g_value_set_flags (value, g_test_dbus_get_flags (self));
402 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
408 g_test_dbus_set_property (GObject *object,
413 GTestDBus *self = (GTestDBus *) object;
418 self->priv->flags = g_value_get_flags (value);
421 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
427 g_test_dbus_class_init (GTestDBusClass *klass)
429 GObjectClass *object_class = G_OBJECT_CLASS (klass);
431 object_class->dispose = g_test_dbus_dispose;
432 object_class->finalize = g_test_dbus_finalize;
433 object_class->get_property = g_test_dbus_get_property;
434 object_class->set_property = g_test_dbus_set_property;
436 g_type_class_add_private (object_class, sizeof (GTestDBusPrivate));
441 * #GTestDBusFlags specifying the behaviour of the dbus session
445 g_object_class_install_property (object_class, PROP_FLAGS,
446 g_param_spec_flags ("flags",
447 P_("dbus session flags"),
448 P_("Flags specifying the behaviour of the dbus session"),
449 G_TYPE_TEST_DBUS_FLAGS, G_TEST_DBUS_NONE,
450 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
451 G_PARAM_STATIC_STRINGS));
456 write_config_file (GTestDBus *self)
460 GFileIOStream *iostream;
462 GError *error = NULL;
464 file = g_file_new_tmp ("g-test-dbus-XXXXXX", &iostream, &error);
465 g_assert_no_error (error);
466 g_object_unref (iostream);
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_replace_contents (file, contents->str, contents->len,
499 NULL, FALSE, G_FILE_CREATE_NONE, NULL, NULL, &error);
500 g_assert_no_error (error);
502 g_string_free (contents, TRUE);
508 start_daemon (GTestDBus *self)
510 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 file = write_config_file (self);
524 config_path = g_file_get_path (file);
525 config_arg = g_strdup_printf ("--config-file=%s", config_path);
526 argv[2] = config_arg;
528 /* Spawn dbus-daemon */
529 g_spawn_async_with_pipes (NULL,
533 /* We Need this to get the pid returned on win32 */
534 G_SPAWN_DO_NOT_REAP_CHILD |
539 &self->priv->bus_pid,
544 g_assert_no_error (error);
546 _g_test_watcher_add_pid (self->priv->bus_pid);
548 /* Read bus address from daemon' stdout */
549 channel = g_io_channel_unix_new (stdout_fd);
550 g_io_channel_read_line (channel, &self->priv->bus_address, NULL,
552 g_assert_no_error (error);
553 self->priv->bus_address[termpos] = '\0';
555 /* start dbus-monitor */
556 if (g_getenv ("G_DBUS_MONITOR") != NULL)
560 command = g_strdup_printf ("dbus-monitor --address %s",
561 self->priv->bus_address);
562 g_spawn_command_line_async (command, NULL);
565 g_usleep (500 * 1000);
569 g_io_channel_shutdown (channel, FALSE, &error);
570 g_assert_no_error (error);
571 g_io_channel_unref (channel);
573 g_file_delete (file, NULL, &error);
574 g_assert_no_error (error);
575 g_object_unref (file);
577 g_free (config_path);
582 stop_daemon (GTestDBus *self)
585 if (!TerminateProcess (self->priv->bus_pid, 0))
586 g_warning ("Can't terminate process: %s", g_win32_error_message (GetLastError()));
588 kill (self->priv->bus_pid, SIGTERM);
590 _g_test_watcher_remove_pid (self->priv->bus_pid);
591 g_spawn_close_pid (self->priv->bus_pid);
592 self->priv->bus_pid = 0;
594 g_free (self->priv->bus_address);
595 self->priv->bus_address = NULL;
600 * @flags: a #GTestDBusFlags
602 * Create a new #GTestDBus object.
604 * Returns: (transfer full): a new #GTestDBus.
607 g_test_dbus_new (GTestDBusFlags flags)
609 return g_object_new (G_TYPE_TEST_DBUS,
615 * g_test_dbus_get_flags:
616 * @self: a #GTestDBus
618 * Returns: the value of #GTestDBus:flags property
621 g_test_dbus_get_flags (GTestDBus *self)
623 g_return_val_if_fail (G_IS_TEST_DBUS (self), G_TEST_DBUS_NONE);
625 return self->priv->flags;
629 * g_test_dbus_get_bus_address:
630 * @self: a #GTestDBus
632 * Get the address on which dbus-daemon is running. if g_test_dbus_up() has not
633 * been called yet, %NULL is returned. This can be used with
634 * g_dbus_connection_new_for_address()
636 * Returns: the address of the bus, or %NULL.
639 g_test_dbus_get_bus_address (GTestDBus *self)
641 g_return_val_if_fail (G_IS_TEST_DBUS (self), NULL);
643 return self->priv->bus_address;
647 * g_test_dbus_add_service_dir:
648 * @self: a #GTestDBus
649 * @path: path to a directory containing .service files
651 * Add a path where dbus-daemon will lookup for .services files. This can't be
652 * called after g_test_dbus_up().
655 g_test_dbus_add_service_dir (GTestDBus *self,
658 g_return_if_fail (G_IS_TEST_DBUS (self));
659 g_return_if_fail (self->priv->bus_address == NULL);
661 g_ptr_array_add (self->priv->service_dirs, g_strdup (path));
666 * @self: a #GTestDBus
668 * Start a dbus-daemon instance and set DBUS_SESSION_BUS_ADDRESS. After this
669 * call, it is safe for unit tests to start sending messages on the session bug.
671 * If this function is called from setup callback of g_test_add(),
672 * g_test_dbus_down() must be called in its teardown callback.
674 * If this function is called from unit test's main(), then g_test_dbus_down()
675 * must be called after g_test_run().
678 g_test_dbus_up (GTestDBus *self)
680 g_return_if_fail (G_IS_TEST_DBUS (self));
681 g_return_if_fail (self->priv->bus_address == NULL);
682 g_return_if_fail (!self->priv->up);
686 g_setenv ("DBUS_SESSION_BUS_ADDRESS", self->priv->bus_address, TRUE);
687 self->priv->up = TRUE;
693 * @self: a #GTestDBus
695 * Stop the session bus started by g_test_dbus_up().
697 * Unlike g_test_dbus_down(), this won't verify the #GDBusConnection
698 * singleton returned by g_bus_get() or g_bus_get_sync() is destroyed. Unit
699 * tests wanting to verify behaviour after the session bus has been stopped
700 * can use this function but should still call g_test_dbus_down() when done.
703 g_test_dbus_stop (GTestDBus *self)
705 g_return_if_fail (G_IS_TEST_DBUS (self));
706 g_return_if_fail (self->priv->bus_address != NULL);
713 * @self: a #GTestDBus
715 * Stop the session bus started by g_test_dbus_up().
717 * This will wait for the singleton returned by g_bus_get() or g_bus_get_sync()
718 * is destroyed. This is done to ensure that the next unit test won't get a
719 * leaked singleton from this test.
722 g_test_dbus_down (GTestDBus *self)
724 GDBusConnection *connection;
726 g_return_if_fail (G_IS_TEST_DBUS (self));
727 g_return_if_fail (self->priv->up);
729 connection = _g_bus_get_singleton_if_exists (G_BUS_TYPE_SESSION);
730 if (connection != NULL)
731 g_dbus_connection_set_exit_on_close (connection, FALSE);
733 if (self->priv->bus_address != NULL)
736 if (connection != NULL)
737 _g_object_unref_and_wait_weak_notify (connection);
739 g_unsetenv ("DBUS_SESSION_BUS_ADDRESS");
740 self->priv->up = FALSE;
746 * Unset DISPLAY and DBUS_SESSION_BUS_ADDRESS env variables to ensure the test
747 * won't use user's session bus.
749 * This is useful for unit tests that want to verify behaviour when no session
750 * bus is running. It is not necessary to call this if unit test already calls
751 * g_test_dbus_up() before acquiring the session bus.
754 g_test_dbus_unset (void)
756 g_unsetenv ("DISPLAY");
757 g_unsetenv ("DBUS_SESSION_BUS_ADDRESS");