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, see <http://www.gnu.org/licenses/>.
19 * Authors: David Zeuthen <davidz@redhat.com>
20 * Xavier Claessens <xavier.claessens@collabora.co.uk>
37 #include "gdbusconnection.h"
38 #include "gdbusprivate.h"
40 #include "gioenumtypes.h"
41 #include "gtestdbus.h"
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 dispose_on_idle (gpointer object)
70 g_object_run_dispose (object);
71 g_object_unref (object);
76 _g_object_dispose_and_wait_weak_notify (gpointer object)
81 data.loop = g_main_loop_new (NULL, FALSE);
82 data.timed_out = FALSE;
84 g_object_weak_ref (object, (GWeakNotify) g_main_loop_quit, data.loop);
86 /* Drop the ref in an idle callback, this is to make sure the mainloop
87 * is already running when weak notify happens */
88 g_idle_add (dispose_on_idle, object);
90 /* Make sure we don't block forever */
91 timeout_id = g_timeout_add (30 * 1000, on_weak_notify_timeout, &data);
93 g_main_loop_run (data.loop);
97 g_warning ("Weak notify timeout, object ref_count=%d\n",
98 G_OBJECT (object)->ref_count);
102 g_source_remove (timeout_id);
105 g_main_loop_unref (data.loop);
106 return data.timed_out;
109 /* -------------------------------------------------------------------------- */
110 /* Utilities to cleanup the mess in the case unit test process crash */
114 /* This could be interesting to expose in public API */
116 _g_test_watcher_add_pid (GPid pid)
118 static gsize started = 0;
121 if (g_once_init_enter (&started))
123 JOBOBJECT_EXTENDED_LIMIT_INFORMATION info;
125 job = CreateJobObjectW (NULL, NULL);
126 memset (&info, 0, sizeof (info));
127 info.BasicLimitInformation.LimitFlags = 0x2000 /* JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE */;
129 if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, &info, sizeof (info)))
130 g_warning ("Can't enable JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE: %s", g_win32_error_message (GetLastError()));
132 g_once_init_leave (&started,(gsize)job);
135 job = (HANDLE)started;
137 if (!AssignProcessToJobObject(job, pid))
138 g_warning ("Can't assign process to job: %s", g_win32_error_message (GetLastError()));
142 _g_test_watcher_remove_pid (GPid pid)
144 /* No need to unassign the process from the job object as the process
145 will be killed anyway */
150 #define ADD_PID_FORMAT "add pid %d\n"
151 #define REMOVE_PID_FORMAT "remove pid %d\n"
154 watch_parent (gint fd)
158 GArray *pids_to_kill;
160 channel = g_io_channel_unix_new (fd);
163 fds[0].events = G_IO_HUP | G_IO_IN;
166 pids_to_kill = g_array_new (FALSE, FALSE, sizeof (guint));
171 gchar *command = NULL;
174 GError *error = NULL;
176 num_events = g_poll (fds, 1, -1);
180 if (fds[0].revents == G_IO_HUP)
182 /* Parent quit, cleanup the mess and exit */
183 for (n = 0; n < pids_to_kill->len; n++)
185 pid = g_array_index (pids_to_kill, guint, n);
186 g_print ("cleaning up pid %d\n", pid);
190 g_array_unref (pids_to_kill);
191 g_io_channel_shutdown (channel, FALSE, &error);
192 g_assert_no_error (error);
193 g_io_channel_unref (channel);
198 /* Read the command from the input */
199 g_io_channel_read_line (channel, &command, NULL, NULL, &error);
200 g_assert_no_error (error);
202 /* Check for known commands */
203 if (sscanf (command, ADD_PID_FORMAT, &pid) == 1)
205 g_array_append_val (pids_to_kill, pid);
207 else if (sscanf (command, REMOVE_PID_FORMAT, &pid) == 1)
209 for (n = 0; n < pids_to_kill->len; n++)
211 if (g_array_index (pids_to_kill, guint, n) == pid)
213 g_array_remove_index (pids_to_kill, n);
220 g_warning ("unknown pid %d to remove", pid);
225 g_warning ("unknown command from parent '%s'", command);
236 static gsize started = 0;
237 static GIOChannel *channel = NULL;
239 if (g_once_init_enter (&started))
243 /* fork a child to clean up when we are killed */
244 if (pipe (pipe_fds) != 0)
246 g_warning ("pipe() failed: %m");
247 g_assert_not_reached ();
253 g_warning ("fork() failed: %m");
254 g_assert_not_reached ();
260 watch_parent (pipe_fds[0]);
266 channel = g_io_channel_unix_new (pipe_fds[1]);
269 g_once_init_leave (&started, 1);
276 watcher_send_command (const gchar *command)
279 GError *error = NULL;
281 channel = watcher_init ();
283 g_io_channel_write_chars (channel, command, -1, NULL, &error);
284 g_assert_no_error (error);
286 g_io_channel_flush (channel, &error);
287 g_assert_no_error (error);
290 /* This could be interesting to expose in public API */
292 _g_test_watcher_add_pid (GPid pid)
296 command = g_strdup_printf (ADD_PID_FORMAT, (guint) pid);
297 watcher_send_command (command);
302 _g_test_watcher_remove_pid (GPid pid)
306 command = g_strdup_printf (REMOVE_PID_FORMAT, (guint) pid);
307 watcher_send_command (command);
313 /* -------------------------------------------------------------------------- */
314 /* GTestDBus object implementation */
318 * @short_description: D-Bus testing helper
319 * @include: gio/gio.h
321 * A helper class for testing code which uses D-Bus without touching the user's
324 * Note that #GTestDBus modifies the user’s environment, calling setenv(). This
325 * is not thread-safe, so all #GTestDBus calls should be completed before
326 * threads are spawned, or should have appropriate locking to ensure no access
327 * conflicts to environment variables shared between #GTestDBus and other
330 * <refsect2 id="gio-D-Bus-Test-Scaffolding">
331 * <title>Creating unit tests using GTestDBus</title>
333 * Testing of D-Bus services can be tricky because normally we only ever run
334 * D-Bus services over an existing instance of the D-Bus daemon thus we
335 * usually don't activate D-Bus services that are not yet installed into the
336 * target system. The #GTestDBus object makes this easier for us by taking care
337 * of the lower level tasks such as running a private D-Bus daemon and looking
338 * up uninstalled services in customizable locations, typically in your source code tree.
341 * The first thing you will need is a separate service description file for the
342 * D-Bus daemon. Typically a <filename>services</filename> subdirectory of
343 * your <filename>tests</filename> directory
344 * is a good place to put this file.
347 * The service file should list your service along with an absolute path to the
348 * uninstalled service executable in your source tree. Using autotools we would
349 * achieve this by adding a file such as <filename>my-server.service.in</filename>
351 * directory and have it processed by configure.
352 * <informalexample><programlisting>
354 * Name=org.gtk.GDBus.Examples.ObjectManager
355 * Exec=@abs_top_builddir@/gio/tests/gdbus-example-objectmanager-server
356 * </programlisting></informalexample>
357 * You will also need to indicate this service directory in your test
358 * fixtures, so you will need to pass the path while compiling your
359 * test cases. Typically this is done with autotools with an added
360 * preprocessor flag specified to compile your tests such as:
361 * <informalexample><programlisting>
362 * -DTEST_SERVICES=\""$(abs_top_builddir)/tests/services"\"
363 * </programlisting></informalexample>
366 * Once you have a service definition file which is local to your source tree,
367 * you can proceed to set up a GTest fixture using the #GTestDBus scaffolding.
368 * <example id="gdbus-test-fixture">
369 * <title>Test Fixture for D-Bus services</title>
371 * <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-test-fixture.c">
372 * <xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback>
378 * Note that these examples only deal with isolating the D-Bus aspect of your
379 * service. To successfully run isolated unit tests on your service you may need
380 * some additional modifications to your test case fixture. For example; if your
381 * service uses GSettings and installs a schema then it is important that your test service
382 * not load the schema in the ordinary installed location (chances are that your service
383 * and schema files are not yet installed, or worse; there is an older version of the
384 * schema file sitting in the install location).
387 * Most of the time we can work around these obstacles using the environment. Since the
388 * environment is inherited by the D-Bus daemon created by #GTestDBus and then in turn
389 * inherited by any services the D-Bus daemon activates, using the setup routine for your
390 * fixture is a practical place to help sandbox your runtime environment. For the rather
391 * typical GSettings case we can work around this by setting <envar>GSETTINGS_SCHEMA_DIR</envar> to the
392 * in tree directory holding your schemas in the above fixture_setup() routine.
395 * The GSettings schemas need to be locally pre-compiled for this to work. This can be achieved
396 * by compiling the schemas locally as a step before running test cases, an autotools setup might
397 * do the following in the directory holding schemas:
398 * <informalexample><programlisting>
400 * $(GLIB_COMPILE_SCHEMAS) .
402 * CLEANFILES += gschemas.compiled
403 * </programlisting></informalexample>
408 typedef struct _GTestDBusClass GTestDBusClass;
409 typedef struct _GTestDBusPrivate GTestDBusPrivate;
414 * The #GTestDBus structure contains only private data and
415 * should only be accessed using the provided API.
422 GTestDBusPrivate *priv;
425 struct _GTestDBusClass {
426 GObjectClass parent_class;
429 struct _GTestDBusPrivate
431 GTestDBusFlags flags;
432 GPtrArray *service_dirs;
444 G_DEFINE_TYPE_WITH_PRIVATE (GTestDBus, g_test_dbus, G_TYPE_OBJECT)
447 g_test_dbus_init (GTestDBus *self)
449 self->priv = g_test_dbus_get_instance_private (self);
450 self->priv->service_dirs = g_ptr_array_new_with_free_func (g_free);
454 g_test_dbus_dispose (GObject *object)
456 GTestDBus *self = (GTestDBus *) object;
459 g_test_dbus_down (self);
461 G_OBJECT_CLASS (g_test_dbus_parent_class)->dispose (object);
465 g_test_dbus_finalize (GObject *object)
467 GTestDBus *self = (GTestDBus *) object;
469 g_ptr_array_unref (self->priv->service_dirs);
470 g_free (self->priv->bus_address);
472 G_OBJECT_CLASS (g_test_dbus_parent_class)->finalize (object);
476 g_test_dbus_get_property (GObject *object,
481 GTestDBus *self = (GTestDBus *) object;
486 g_value_set_flags (value, g_test_dbus_get_flags (self));
489 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
495 g_test_dbus_set_property (GObject *object,
500 GTestDBus *self = (GTestDBus *) object;
505 self->priv->flags = g_value_get_flags (value);
508 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
514 g_test_dbus_class_init (GTestDBusClass *klass)
516 GObjectClass *object_class = G_OBJECT_CLASS (klass);
518 object_class->dispose = g_test_dbus_dispose;
519 object_class->finalize = g_test_dbus_finalize;
520 object_class->get_property = g_test_dbus_get_property;
521 object_class->set_property = g_test_dbus_set_property;
526 * #GTestDBusFlags specifying the behaviour of the D-Bus session.
530 g_object_class_install_property (object_class, PROP_FLAGS,
531 g_param_spec_flags ("flags",
532 P_("D-Bus session flags"),
533 P_("Flags specifying the behaviour of the D-Bus session"),
534 G_TYPE_TEST_DBUS_FLAGS, G_TEST_DBUS_NONE,
535 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
536 G_PARAM_STATIC_STRINGS));
541 write_config_file (GTestDBus *self)
546 GError *error = NULL;
549 fd = g_file_open_tmp ("g-test-dbus-XXXXXX", &path, &error);
550 g_assert_no_error (error);
552 contents = g_string_new (NULL);
553 g_string_append (contents,
555 " <type>session</type>\n"
557 " <listen>nonce-tcp:</listen>\n"
559 " <listen>unix:tmpdir=/tmp</listen>\n"
563 for (i = 0; i < self->priv->service_dirs->len; i++)
565 const gchar *dir_path = g_ptr_array_index (self->priv->service_dirs, i);
567 g_string_append_printf (contents,
568 " <servicedir>%s</servicedir>\n", dir_path);
571 g_string_append (contents,
572 " <policy context=\"default\">\n"
573 " <!-- Allow everything to be sent -->\n"
574 " <allow send_destination=\"*\" eavesdrop=\"true\"/>\n"
575 " <!-- Allow everything to be received -->\n"
576 " <allow eavesdrop=\"true\"/>\n"
577 " <!-- Allow anyone to own anything -->\n"
578 " <allow own=\"*\"/>\n"
582 g_file_set_contents (path, contents->str, contents->len, &error);
583 g_assert_no_error (error);
585 g_string_free (contents, TRUE);
593 start_daemon (GTestDBus *self)
595 const gchar *argv[] = {"dbus-daemon", "--print-address", "--config-file=foo", NULL};
601 GError *error = NULL;
603 if (g_getenv ("G_TEST_DBUS_DAEMON") != NULL)
604 argv[0] = (gchar *)g_getenv ("G_TEST_DBUS_DAEMON");
606 /* Write config file and set its path in argv */
607 config_path = write_config_file (self);
608 config_arg = g_strdup_printf ("--config-file=%s", config_path);
609 argv[2] = config_arg;
611 /* Spawn dbus-daemon */
612 g_spawn_async_with_pipes (NULL,
616 /* We Need this to get the pid returned on win32 */
617 G_SPAWN_DO_NOT_REAP_CHILD |
622 &self->priv->bus_pid,
627 g_assert_no_error (error);
629 _g_test_watcher_add_pid (self->priv->bus_pid);
631 /* Read bus address from daemon' stdout */
632 channel = g_io_channel_unix_new (stdout_fd);
633 g_io_channel_read_line (channel, &self->priv->bus_address, NULL,
635 g_assert_no_error (error);
636 self->priv->bus_address[termpos] = '\0';
638 /* start dbus-monitor */
639 if (g_getenv ("G_DBUS_MONITOR") != NULL)
643 command = g_strdup_printf ("dbus-monitor --address %s",
644 self->priv->bus_address);
645 g_spawn_command_line_async (command, NULL);
648 g_usleep (500 * 1000);
652 g_io_channel_shutdown (channel, FALSE, &error);
653 g_assert_no_error (error);
654 g_io_channel_unref (channel);
656 /* Don't use g_file_delete since it calls into gvfs */
657 if (g_unlink (config_path) != 0)
658 g_assert_not_reached ();
660 g_free (config_path);
665 stop_daemon (GTestDBus *self)
668 if (!TerminateProcess (self->priv->bus_pid, 0))
669 g_warning ("Can't terminate process: %s", g_win32_error_message (GetLastError()));
671 kill (self->priv->bus_pid, SIGTERM);
673 _g_test_watcher_remove_pid (self->priv->bus_pid);
674 g_spawn_close_pid (self->priv->bus_pid);
675 self->priv->bus_pid = 0;
677 g_free (self->priv->bus_address);
678 self->priv->bus_address = NULL;
683 * @flags: a #GTestDBusFlags
685 * Create a new #GTestDBus object.
687 * Returns: (transfer full): a new #GTestDBus.
690 g_test_dbus_new (GTestDBusFlags flags)
692 return g_object_new (G_TYPE_TEST_DBUS,
698 * g_test_dbus_get_flags:
699 * @self: a #GTestDBus
701 * Get the flags of the #GTestDBus object.
703 * Returns: the value of #GTestDBus:flags property
706 g_test_dbus_get_flags (GTestDBus *self)
708 g_return_val_if_fail (G_IS_TEST_DBUS (self), G_TEST_DBUS_NONE);
710 return self->priv->flags;
714 * g_test_dbus_get_bus_address:
715 * @self: a #GTestDBus
717 * Get the address on which dbus-daemon is running. If g_test_dbus_up() has not
718 * been called yet, %NULL is returned. This can be used with
719 * g_dbus_connection_new_for_address().
721 * Returns: (allow-none): the address of the bus, or %NULL.
724 g_test_dbus_get_bus_address (GTestDBus *self)
726 g_return_val_if_fail (G_IS_TEST_DBUS (self), NULL);
728 return self->priv->bus_address;
732 * g_test_dbus_add_service_dir:
733 * @self: a #GTestDBus
734 * @path: path to a directory containing .service files
736 * Add a path where dbus-daemon will look up .service files. This can't be
737 * called after g_test_dbus_up().
740 g_test_dbus_add_service_dir (GTestDBus *self,
743 g_return_if_fail (G_IS_TEST_DBUS (self));
744 g_return_if_fail (self->priv->bus_address == NULL);
746 g_ptr_array_add (self->priv->service_dirs, g_strdup (path));
751 * @self: a #GTestDBus
753 * Start a dbus-daemon instance and set DBUS_SESSION_BUS_ADDRESS. After this
754 * call, it is safe for unit tests to start sending messages on the session bus.
756 * If this function is called from setup callback of g_test_add(),
757 * g_test_dbus_down() must be called in its teardown callback.
759 * If this function is called from unit test's main(), then g_test_dbus_down()
760 * must be called after g_test_run().
763 g_test_dbus_up (GTestDBus *self)
765 g_return_if_fail (G_IS_TEST_DBUS (self));
766 g_return_if_fail (self->priv->bus_address == NULL);
767 g_return_if_fail (!self->priv->up);
771 g_test_dbus_unset ();
772 g_setenv ("DBUS_SESSION_BUS_ADDRESS", self->priv->bus_address, TRUE);
773 self->priv->up = TRUE;
779 * @self: a #GTestDBus
781 * Stop the session bus started by g_test_dbus_up().
783 * Unlike g_test_dbus_down(), this won't verify the #GDBusConnection
784 * singleton returned by g_bus_get() or g_bus_get_sync() is destroyed. Unit
785 * tests wanting to verify behaviour after the session bus has been stopped
786 * can use this function but should still call g_test_dbus_down() when done.
789 g_test_dbus_stop (GTestDBus *self)
791 g_return_if_fail (G_IS_TEST_DBUS (self));
792 g_return_if_fail (self->priv->bus_address != NULL);
799 * @self: a #GTestDBus
801 * Stop the session bus started by g_test_dbus_up().
803 * This will wait for the singleton returned by g_bus_get() or g_bus_get_sync()
804 * is destroyed. This is done to ensure that the next unit test won't get a
805 * leaked singleton from this test.
808 g_test_dbus_down (GTestDBus *self)
810 GDBusConnection *connection;
812 g_return_if_fail (G_IS_TEST_DBUS (self));
813 g_return_if_fail (self->priv->up);
815 connection = _g_bus_get_singleton_if_exists (G_BUS_TYPE_SESSION);
816 if (connection != NULL)
817 g_dbus_connection_set_exit_on_close (connection, FALSE);
819 if (self->priv->bus_address != NULL)
822 if (connection != NULL)
823 _g_object_dispose_and_wait_weak_notify (connection);
825 g_test_dbus_unset ();
826 self->priv->up = FALSE;
832 * Unset DISPLAY and DBUS_SESSION_BUS_ADDRESS env variables to ensure the test
833 * won't use user's session bus.
835 * This is useful for unit tests that want to verify behaviour when no session
836 * bus is running. It is not necessary to call this if unit test already calls
837 * g_test_dbus_up() before acquiring the session bus.
840 g_test_dbus_unset (void)
842 g_unsetenv ("DISPLAY");
843 g_unsetenv ("DBUS_SESSION_BUS_ADDRESS");
844 g_unsetenv ("DBUS_STARTER_ADDRESS");
845 g_unsetenv ("DBUS_STARTER_BUS_TYPE");