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"
51 /* -------------------------------------------------------------------------- */
52 /* Utility: Wait until object has a single ref */
61 on_weak_notify_timeout (gpointer user_data)
63 WeakNotifyData *data = user_data;
64 data->timed_out = TRUE;
65 g_main_loop_quit (data->loop);
70 dispose_on_idle (gpointer object)
72 g_object_run_dispose (object);
73 g_object_unref (object);
78 _g_object_dispose_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 (dispose_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);
99 g_warning ("Weak notify timeout, object ref_count=%d\n",
100 G_OBJECT (object)->ref_count);
104 g_source_remove (timeout_id);
107 g_main_loop_unref (data.loop);
108 return data.timed_out;
111 /* -------------------------------------------------------------------------- */
112 /* Utilities to cleanup the mess in the case unit test process crash */
116 /* This could be interesting to expose in public API */
118 _g_test_watcher_add_pid (GPid pid)
120 static gsize started = 0;
123 if (g_once_init_enter (&started))
125 JOBOBJECT_EXTENDED_LIMIT_INFORMATION info;
127 job = CreateJobObjectW (NULL, NULL);
128 memset (&info, 0, sizeof (info));
129 info.BasicLimitInformation.LimitFlags = 0x2000 /* JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE */;
131 if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, &info, sizeof (info)))
132 g_warning ("Can't enable JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE: %s", g_win32_error_message (GetLastError()));
134 g_once_init_leave (&started,(gsize)job);
137 job = (HANDLE)started;
139 if (!AssignProcessToJobObject(job, pid))
140 g_warning ("Can't assign process to job: %s", g_win32_error_message (GetLastError()));
144 _g_test_watcher_remove_pid (GPid pid)
146 /* No need to unassign the process from the job object as the process
147 will be killed anyway */
152 #define ADD_PID_FORMAT "add pid %d\n"
153 #define REMOVE_PID_FORMAT "remove pid %d\n"
156 watch_parent (gint fd)
160 GArray *pids_to_kill;
162 channel = g_io_channel_unix_new (fd);
165 fds[0].events = G_IO_HUP | G_IO_IN;
168 pids_to_kill = g_array_new (FALSE, FALSE, sizeof (guint));
173 gchar *command = NULL;
176 GError *error = NULL;
178 num_events = g_poll (fds, 1, -1);
182 if (fds[0].revents == G_IO_HUP)
184 /* Parent quit, cleanup the mess and exit */
185 for (n = 0; n < pids_to_kill->len; n++)
187 pid = g_array_index (pids_to_kill, guint, n);
188 g_print ("cleaning up pid %d\n", pid);
192 g_array_unref (pids_to_kill);
193 g_io_channel_shutdown (channel, FALSE, &error);
194 g_assert_no_error (error);
195 g_io_channel_unref (channel);
200 /* Read the command from the input */
201 g_io_channel_read_line (channel, &command, NULL, NULL, &error);
202 g_assert_no_error (error);
204 /* Check for known commands */
205 if (sscanf (command, ADD_PID_FORMAT, &pid) == 1)
207 g_array_append_val (pids_to_kill, pid);
209 else if (sscanf (command, REMOVE_PID_FORMAT, &pid) == 1)
211 for (n = 0; n < pids_to_kill->len; n++)
213 if (g_array_index (pids_to_kill, guint, n) == pid)
215 g_array_remove_index (pids_to_kill, n);
222 g_warning ("unknown pid %d to remove", pid);
227 g_warning ("unknown command from parent '%s'", command);
238 static gsize started = 0;
239 static GIOChannel *channel = NULL;
241 if (g_once_init_enter (&started))
245 /* fork a child to clean up when we are killed */
246 if (pipe (pipe_fds) != 0)
248 g_warning ("pipe() failed: %m");
249 g_assert_not_reached ();
255 g_warning ("fork() failed: %m");
256 g_assert_not_reached ();
262 watch_parent (pipe_fds[0]);
268 channel = g_io_channel_unix_new (pipe_fds[1]);
271 g_once_init_leave (&started, 1);
278 watcher_send_command (const gchar *command)
281 GError *error = NULL;
283 channel = watcher_init ();
285 g_io_channel_write_chars (channel, command, -1, NULL, &error);
286 g_assert_no_error (error);
288 g_io_channel_flush (channel, &error);
289 g_assert_no_error (error);
292 /* This could be interesting to expose in public API */
294 _g_test_watcher_add_pid (GPid pid)
298 command = g_strdup_printf (ADD_PID_FORMAT, (guint) pid);
299 watcher_send_command (command);
304 _g_test_watcher_remove_pid (GPid pid)
308 command = g_strdup_printf (REMOVE_PID_FORMAT, (guint) pid);
309 watcher_send_command (command);
315 /* -------------------------------------------------------------------------- */
316 /* GTestDBus object implementation */
320 * @short_description: D-Bus testing helper
321 * @include: gio/gio.h
323 * A helper class for testing code which uses D-Bus without touching the user's
326 * <refsect2 id="gio-D-Bus-Test-Scaffolding">
327 * <title>Creating unit tests using GTestDBus</title>
329 * Testing of D-Bus services can be tricky because normally we only ever run
330 * D-Bus services over an existing instance of the D-Bus daemon thus we
331 * usually don't activate D-Bus services that are not yet installed into the
332 * target system. The #GTestDBus object makes this easier for us by taking care
333 * of the lower level tasks such as running a private D-Bus daemon and looking
334 * up uninstalled services in customizable locations, typically in your source code tree.
337 * The first thing you will need is a separate service description file for the
338 * D-Bus daemon. Typically a 'services' subdirectory of your 'tests' directory
339 * is a good place to put this file.
342 * The service file should list your service along with an absolute path to the
343 * uninstalled service executable in your source tree. Using autotools we would
344 * achieve this by adding a file such as 'my-server.service.in' in the services
345 * directory and have it processed by configure.
346 * <informalexample><programlisting>
348 * Name=org.gtk.GDBus.Examples.ObjectManager
349 * Exec=@abs_top_builddir@/gio/tests/gdbus-example-objectmanager-server
350 * </programlisting></informalexample>
351 * You will also need to indicate this service directory in your test
352 * fixtures, so you will need to pass the path while compiling your
353 * test cases. Typically this is done with autotools with an added
354 * preprocessor flag specified to compile your tests such as:
355 * <informalexample><programlisting>
356 * -DTEST_SERVICES=\""$(abs_top_builddir)/tests/services"\"
357 * </programlisting></informalexample>
360 * Once you have a service definition file which is local to your source tree,
361 * you can proceed to setup a GTest fixture using the GTestDBus scaffolding.
362 * <example id="gdbus-test-fixture">
363 * <title>Test Fixture for D-Bus services</title>
365 * <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-test-fixture.c">
366 * <xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback>
372 * Note that these examples only deal with isolating the D-Bus aspect of your
373 * service. To successfully run isolated unit tests on your service you may need
374 * some additional modifications to your test case fixture. For example; if your
375 * service uses GSettings and installs a schema then it is important that your test service
376 * not load the schema in the ordinary installed location (chances are that your service
377 * and schema files are not yet installed, or worse; there is an older version of the
378 * schema file sitting in the install location).
381 * Most of the time we can work around these obstacles using the environment. Since the
382 * environment is inherited by the D-Bus daemon created by GTestDBus and then in turn
383 * inherited by any services the D-Bus daemon activates, using the setup routine for your
384 * fixture is a practical place to help sandbox your runtime environment. For the rather
385 * typical GSettings case we can work around this by setting GSETTINGS_SCHEMA_DIR to the
386 * in tree directory holding your schemas in the above fixture_setup() routine.
389 * The GSettings schemas need to be locally pre-compiled for this to work. This can be achieved
390 * by compiling the schemas locally as a step before running test cases, an autotools setup might
391 * do the following in the directory holding schemas:
392 * <informalexample><programlisting>
394 * $(GLIB_COMPILE_SCHEMAS) .
396 * CLEANFILES += gschemas.compiled
397 * </programlisting></informalexample>
402 typedef struct _GTestDBusClass GTestDBusClass;
403 typedef struct _GTestDBusPrivate GTestDBusPrivate;
408 * The #GTestDBus structure contains only private data and
409 * should only be accessed using the provided API.
416 GTestDBusPrivate *priv;
419 struct _GTestDBusClass {
420 GObjectClass parent_class;
423 struct _GTestDBusPrivate
425 GTestDBusFlags flags;
426 GPtrArray *service_dirs;
438 G_DEFINE_TYPE_WITH_PRIVATE (GTestDBus, g_test_dbus, G_TYPE_OBJECT)
441 g_test_dbus_init (GTestDBus *self)
443 self->priv = g_test_dbus_get_instance_private (self);
444 self->priv->service_dirs = g_ptr_array_new_with_free_func (g_free);
448 g_test_dbus_dispose (GObject *object)
450 GTestDBus *self = (GTestDBus *) object;
453 g_test_dbus_down (self);
455 G_OBJECT_CLASS (g_test_dbus_parent_class)->dispose (object);
459 g_test_dbus_finalize (GObject *object)
461 GTestDBus *self = (GTestDBus *) object;
463 g_ptr_array_unref (self->priv->service_dirs);
464 g_free (self->priv->bus_address);
466 G_OBJECT_CLASS (g_test_dbus_parent_class)->finalize (object);
470 g_test_dbus_get_property (GObject *object,
475 GTestDBus *self = (GTestDBus *) object;
480 g_value_set_flags (value, g_test_dbus_get_flags (self));
483 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
489 g_test_dbus_set_property (GObject *object,
494 GTestDBus *self = (GTestDBus *) object;
499 self->priv->flags = g_value_get_flags (value);
502 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
508 g_test_dbus_class_init (GTestDBusClass *klass)
510 GObjectClass *object_class = G_OBJECT_CLASS (klass);
512 object_class->dispose = g_test_dbus_dispose;
513 object_class->finalize = g_test_dbus_finalize;
514 object_class->get_property = g_test_dbus_get_property;
515 object_class->set_property = g_test_dbus_set_property;
520 * #GTestDBusFlags specifying the behaviour of the dbus session
524 g_object_class_install_property (object_class, PROP_FLAGS,
525 g_param_spec_flags ("flags",
526 P_("dbus session flags"),
527 P_("Flags specifying the behaviour of the dbus session"),
528 G_TYPE_TEST_DBUS_FLAGS, G_TEST_DBUS_NONE,
529 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
530 G_PARAM_STATIC_STRINGS));
535 write_config_file (GTestDBus *self)
540 GError *error = NULL;
543 fd = g_file_open_tmp ("g-test-dbus-XXXXXX", &path, &error);
544 g_assert_no_error (error);
546 contents = g_string_new (NULL);
547 g_string_append (contents,
549 " <type>session</type>\n"
551 " <listen>nonce-tcp:</listen>\n"
553 " <listen>unix:tmpdir=/tmp</listen>\n"
557 for (i = 0; i < self->priv->service_dirs->len; i++)
559 const gchar *dir_path = g_ptr_array_index (self->priv->service_dirs, i);
561 g_string_append_printf (contents,
562 " <servicedir>%s</servicedir>\n", dir_path);
565 g_string_append (contents,
566 " <policy context=\"default\">\n"
567 " <!-- Allow everything to be sent -->\n"
568 " <allow send_destination=\"*\" eavesdrop=\"true\"/>\n"
569 " <!-- Allow everything to be received -->\n"
570 " <allow eavesdrop=\"true\"/>\n"
571 " <!-- Allow anyone to own anything -->\n"
572 " <allow own=\"*\"/>\n"
576 g_file_set_contents (path, contents->str, contents->len, &error);
577 g_assert_no_error (error);
579 g_string_free (contents, TRUE);
587 start_daemon (GTestDBus *self)
589 const gchar *argv[] = {"dbus-daemon", "--print-address", "--config-file=foo", NULL};
595 GError *error = NULL;
597 if (g_getenv ("G_TEST_DBUS_DAEMON") != NULL)
598 argv[0] = (gchar *)g_getenv ("G_TEST_DBUS_DAEMON");
600 /* Write config file and set its path in argv */
601 config_path = write_config_file (self);
602 config_arg = g_strdup_printf ("--config-file=%s", config_path);
603 argv[2] = config_arg;
605 /* Spawn dbus-daemon */
606 g_spawn_async_with_pipes (NULL,
610 /* We Need this to get the pid returned on win32 */
611 G_SPAWN_DO_NOT_REAP_CHILD |
616 &self->priv->bus_pid,
621 g_assert_no_error (error);
623 _g_test_watcher_add_pid (self->priv->bus_pid);
625 /* Read bus address from daemon' stdout */
626 channel = g_io_channel_unix_new (stdout_fd);
627 g_io_channel_read_line (channel, &self->priv->bus_address, NULL,
629 g_assert_no_error (error);
630 self->priv->bus_address[termpos] = '\0';
632 /* start dbus-monitor */
633 if (g_getenv ("G_DBUS_MONITOR") != NULL)
637 command = g_strdup_printf ("dbus-monitor --address %s",
638 self->priv->bus_address);
639 g_spawn_command_line_async (command, NULL);
642 g_usleep (500 * 1000);
646 g_io_channel_shutdown (channel, FALSE, &error);
647 g_assert_no_error (error);
648 g_io_channel_unref (channel);
650 /* Don't use g_file_delete since it calls into gvfs */
651 if (g_unlink (config_path) != 0)
652 g_assert_not_reached ();
654 g_free (config_path);
659 stop_daemon (GTestDBus *self)
662 if (!TerminateProcess (self->priv->bus_pid, 0))
663 g_warning ("Can't terminate process: %s", g_win32_error_message (GetLastError()));
665 kill (self->priv->bus_pid, SIGTERM);
667 _g_test_watcher_remove_pid (self->priv->bus_pid);
668 g_spawn_close_pid (self->priv->bus_pid);
669 self->priv->bus_pid = 0;
671 g_free (self->priv->bus_address);
672 self->priv->bus_address = NULL;
677 * @flags: a #GTestDBusFlags
679 * Create a new #GTestDBus object.
681 * Returns: (transfer full): a new #GTestDBus.
684 g_test_dbus_new (GTestDBusFlags flags)
686 return g_object_new (G_TYPE_TEST_DBUS,
692 * g_test_dbus_get_flags:
693 * @self: a #GTestDBus
695 * Gets the flags of the #GTestDBus object.
697 * Returns: the value of #GTestDBus:flags property
700 g_test_dbus_get_flags (GTestDBus *self)
702 g_return_val_if_fail (G_IS_TEST_DBUS (self), G_TEST_DBUS_NONE);
704 return self->priv->flags;
708 * g_test_dbus_get_bus_address:
709 * @self: a #GTestDBus
711 * Get the address on which dbus-daemon is running. if g_test_dbus_up() has not
712 * been called yet, %NULL is returned. This can be used with
713 * g_dbus_connection_new_for_address()
715 * Returns: the address of the bus, or %NULL.
718 g_test_dbus_get_bus_address (GTestDBus *self)
720 g_return_val_if_fail (G_IS_TEST_DBUS (self), NULL);
722 return self->priv->bus_address;
726 * g_test_dbus_add_service_dir:
727 * @self: a #GTestDBus
728 * @path: path to a directory containing .service files
730 * Add a path where dbus-daemon will lookup for .services files. This can't be
731 * called after g_test_dbus_up().
734 g_test_dbus_add_service_dir (GTestDBus *self,
737 g_return_if_fail (G_IS_TEST_DBUS (self));
738 g_return_if_fail (self->priv->bus_address == NULL);
740 g_ptr_array_add (self->priv->service_dirs, g_strdup (path));
745 * @self: a #GTestDBus
747 * Start a dbus-daemon instance and set DBUS_SESSION_BUS_ADDRESS. After this
748 * call, it is safe for unit tests to start sending messages on the session bus.
750 * If this function is called from setup callback of g_test_add(),
751 * g_test_dbus_down() must be called in its teardown callback.
753 * If this function is called from unit test's main(), then g_test_dbus_down()
754 * must be called after g_test_run().
757 g_test_dbus_up (GTestDBus *self)
759 g_return_if_fail (G_IS_TEST_DBUS (self));
760 g_return_if_fail (self->priv->bus_address == NULL);
761 g_return_if_fail (!self->priv->up);
765 g_test_dbus_unset ();
766 g_setenv ("DBUS_SESSION_BUS_ADDRESS", self->priv->bus_address, TRUE);
767 self->priv->up = TRUE;
773 * @self: a #GTestDBus
775 * Stop the session bus started by g_test_dbus_up().
777 * Unlike g_test_dbus_down(), this won't verify the #GDBusConnection
778 * singleton returned by g_bus_get() or g_bus_get_sync() is destroyed. Unit
779 * tests wanting to verify behaviour after the session bus has been stopped
780 * can use this function but should still call g_test_dbus_down() when done.
783 g_test_dbus_stop (GTestDBus *self)
785 g_return_if_fail (G_IS_TEST_DBUS (self));
786 g_return_if_fail (self->priv->bus_address != NULL);
793 * @self: a #GTestDBus
795 * Stop the session bus started by g_test_dbus_up().
797 * This will wait for the singleton returned by g_bus_get() or g_bus_get_sync()
798 * is destroyed. This is done to ensure that the next unit test won't get a
799 * leaked singleton from this test.
802 g_test_dbus_down (GTestDBus *self)
804 GDBusConnection *connection;
806 g_return_if_fail (G_IS_TEST_DBUS (self));
807 g_return_if_fail (self->priv->up);
809 connection = _g_bus_get_singleton_if_exists (G_BUS_TYPE_SESSION);
810 if (connection != NULL)
811 g_dbus_connection_set_exit_on_close (connection, FALSE);
813 if (self->priv->bus_address != NULL)
816 if (connection != NULL)
817 _g_object_dispose_and_wait_weak_notify (connection);
819 g_test_dbus_unset ();
820 self->priv->up = FALSE;
826 * Unset DISPLAY and DBUS_SESSION_BUS_ADDRESS env variables to ensure the test
827 * won't use user's session bus.
829 * This is useful for unit tests that want to verify behaviour when no session
830 * bus is running. It is not necessary to call this if unit test already calls
831 * g_test_dbus_up() before acquiring the session bus.
834 g_test_dbus_unset (void)
836 g_unsetenv ("DISPLAY");
837 g_unsetenv ("DBUS_SESSION_BUS_ADDRESS");
838 g_unsetenv ("DBUS_STARTER_ADDRESS");
839 g_unsetenv ("DBUS_STARTER_BUS_TYPE");