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 unref_on_idle (gpointer object)
72 g_object_unref (object);
77 _g_object_unref_and_wait_weak_notify (gpointer object)
82 data.loop = g_main_loop_new (NULL, FALSE);
83 data.timed_out = FALSE;
85 g_object_weak_ref (object, (GWeakNotify) g_main_loop_quit, data.loop);
87 /* Drop the ref in an idle callback, this is to make sure the mainloop
88 * is already running when weak notify happens */
89 g_idle_add (unref_on_idle, object);
91 /* Make sure we don't block forever */
92 timeout_id = g_timeout_add (30 * 1000, on_weak_notify_timeout, &data);
94 g_main_loop_run (data.loop);
98 g_warning ("Weak notify timeout, object ref_count=%d\n",
99 G_OBJECT (object)->ref_count);
103 g_source_remove (timeout_id);
106 g_main_loop_unref (data.loop);
107 return data.timed_out;
110 /* -------------------------------------------------------------------------- */
111 /* Utilities to cleanup the mess in the case unit test process crash */
115 /* This could be interesting to expose in public API */
117 _g_test_watcher_add_pid (GPid pid)
119 static gsize started = 0;
122 if (g_once_init_enter (&started))
124 JOBOBJECT_EXTENDED_LIMIT_INFORMATION info;
126 job = CreateJobObjectW (NULL, NULL);
127 memset (&info, 0, sizeof (info));
128 info.BasicLimitInformation.LimitFlags = 0x2000 /* JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE */;
130 if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, &info, sizeof (info)))
131 g_warning ("Can't enable JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE: %s", g_win32_error_message (GetLastError()));
133 g_once_init_leave (&started,(gsize)job);
136 job = (HANDLE)started;
138 if (!AssignProcessToJobObject(job, pid))
139 g_warning ("Can't assign process to job: %s", g_win32_error_message (GetLastError()));
143 _g_test_watcher_remove_pid (GPid pid)
145 /* No need to unassign the process from the job object as the process
146 will be killed anyway */
151 #define ADD_PID_FORMAT "add pid %d\n"
152 #define REMOVE_PID_FORMAT "remove pid %d\n"
155 watch_parent (gint fd)
159 GArray *pids_to_kill;
161 channel = g_io_channel_unix_new (fd);
164 fds[0].events = G_IO_HUP | G_IO_IN;
167 pids_to_kill = g_array_new (FALSE, FALSE, sizeof (guint));
172 gchar *command = NULL;
175 GError *error = NULL;
177 num_events = g_poll (fds, 1, -1);
181 if (fds[0].revents == G_IO_HUP)
183 /* Parent quit, cleanup the mess and exit */
184 for (n = 0; n < pids_to_kill->len; n++)
186 pid = g_array_index (pids_to_kill, guint, n);
187 g_print ("cleaning up pid %d\n", pid);
191 g_array_unref (pids_to_kill);
192 g_io_channel_shutdown (channel, FALSE, &error);
193 g_assert_no_error (error);
194 g_io_channel_unref (channel);
199 /* Read the command from the input */
200 g_io_channel_read_line (channel, &command, NULL, NULL, &error);
201 g_assert_no_error (error);
203 /* Check for known commands */
204 if (sscanf (command, ADD_PID_FORMAT, &pid) == 1)
206 g_array_append_val (pids_to_kill, pid);
208 else if (sscanf (command, REMOVE_PID_FORMAT, &pid) == 1)
210 for (n = 0; n < pids_to_kill->len; n++)
212 if (g_array_index (pids_to_kill, guint, n) == pid)
214 g_array_remove_index (pids_to_kill, n);
221 g_warning ("unknown pid %d to remove", pid);
226 g_warning ("unknown command from parent '%s'", command);
237 static gsize started = 0;
238 static GIOChannel *channel = NULL;
240 if (g_once_init_enter (&started))
244 /* fork a child to clean up when we are killed */
245 if (pipe (pipe_fds) != 0)
247 g_warning ("pipe() failed: %m");
248 g_assert_not_reached ();
254 g_warning ("fork() failed: %m");
255 g_assert_not_reached ();
261 watch_parent (pipe_fds[0]);
267 channel = g_io_channel_unix_new (pipe_fds[1]);
270 g_once_init_leave (&started, 1);
277 watcher_send_command (const gchar *command)
280 GError *error = NULL;
282 channel = watcher_init ();
284 g_io_channel_write_chars (channel, command, -1, NULL, &error);
285 g_assert_no_error (error);
287 g_io_channel_flush (channel, &error);
288 g_assert_no_error (error);
291 /* This could be interesting to expose in public API */
293 _g_test_watcher_add_pid (GPid pid)
297 command = g_strdup_printf (ADD_PID_FORMAT, (guint) pid);
298 watcher_send_command (command);
303 _g_test_watcher_remove_pid (GPid pid)
307 command = g_strdup_printf (REMOVE_PID_FORMAT, (guint) pid);
308 watcher_send_command (command);
314 /* -------------------------------------------------------------------------- */
315 /* GTestDBus object implementation */
319 * @short_description: D-Bus testing helper
320 * @include: gio/gio.h
322 * A helper class for testing code which uses D-Bus without touching the user's
325 * <refsect2 id="gio-D-Bus-Test-Scaffolding">
326 * <title>Creating unit tests using GTestDBus</title>
328 * Testing of D-Bus services can be tricky because normally we only ever run
329 * D-Bus services over an existing instance of the D-Bus daemon thus we
330 * usually don't activate D-Bus services that are not yet installed into the
331 * target system. The #GTestDBus object makes this easier for us by taking care
332 * of the lower level tasks such as running a private D-Bus daemon and looking
333 * up uninstalled services in customizable locations, typically in your source code tree.
336 * The first thing you will need is a separate service description file for the
337 * D-Bus daemon. Typically a 'services' subdirectory of your 'tests' directory
338 * is a good place to put this file.
341 * The service file should list your service along with an absolute path to the
342 * uninstalled service executable in your source tree. Using autotools we would
343 * achieve this by adding a file such as 'my-server.service.in' in the services
344 * directory and have it processed by configure.
345 * <informalexample><programlisting>
347 * Name=org.gtk.GDBus.Examples.ObjectManager
348 * Exec=@abs_top_builddir@/gio/tests/gdbus-example-objectmanager-server
349 * </programlisting></informalexample>
350 * You will also need to indicate this service directory in your test
351 * fixtures, so you will need to pass the path while compiling your
352 * test cases. Typically this is done with autotools with an added
353 * preprocessor flag specified to compile your tests such as:
354 * <informalexample><programlisting>
355 * -DTEST_SERVICES=\""$(abs_top_builddir)/tests/services"\"
356 * </programlisting></informalexample>
359 * Once you have a service definition file which is local to your source tree,
360 * you can proceed to setup a GTest fixture using the GTestDBus scaffolding.
361 * <example id="gdbus-test-fixture">
362 * <title>Test Fixture for D-Bus services</title>
364 * <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-test-fixture.c">
365 * <xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback>
371 * Note that these examples only deal with isolating the D-Bus aspect of your
372 * service. To successfully run isolated unit tests on your service you may need
373 * some additional modifications to your test case fixture. For example; if your
374 * service uses GSettings and installs a schema then it is important that your test service
375 * not load the schema in the ordinary installed location (chances are that your service
376 * and schema files are not yet installed, or worse; there is an older version of the
377 * schema file sitting in the install location).
380 * Most of the time we can work around these obstacles using the environment. Since the
381 * environment is inherited by the D-Bus daemon created by GTestDBus and then in turn
382 * inherited by any services the D-Bus daemon activates, using the setup routine for your
383 * fixture is a practical place to help sandbox your runtime environment. For the rather
384 * typical GSettings case we can work around this by setting GSETTINGS_SCHEMA_DIR to the
385 * in tree directory holding your schemas in the above fixture_setup() routine.
388 * The GSettings schemas need to be locally pre-compiled for this to work. This can be achieved
389 * by compiling the schemas locally as a step before running test cases, an autotools setup might
390 * do the following in the directory holding schemas:
391 * <informalexample><programlisting>
393 * $(GLIB_COMPILE_SCHEMAS) .
395 * CLEANFILES += gschemas.compiled
396 * </programlisting></informalexample>
401 typedef struct _GTestDBusClass GTestDBusClass;
402 typedef struct _GTestDBusPrivate GTestDBusPrivate;
407 * The #GTestDBus structure contains only private data and
408 * should only be accessed using the provided API.
415 GTestDBusPrivate *priv;
418 struct _GTestDBusClass {
419 GObjectClass parent_class;
422 struct _GTestDBusPrivate
424 GTestDBusFlags flags;
425 GPtrArray *service_dirs;
437 G_DEFINE_TYPE_WITH_PRIVATE (GTestDBus, g_test_dbus, G_TYPE_OBJECT)
440 g_test_dbus_init (GTestDBus *self)
442 self->priv = g_test_dbus_get_instance_private (self);
443 self->priv->service_dirs = g_ptr_array_new_with_free_func (g_free);
447 g_test_dbus_dispose (GObject *object)
449 GTestDBus *self = (GTestDBus *) object;
452 g_test_dbus_down (self);
454 G_OBJECT_CLASS (g_test_dbus_parent_class)->dispose (object);
458 g_test_dbus_finalize (GObject *object)
460 GTestDBus *self = (GTestDBus *) object;
462 g_ptr_array_unref (self->priv->service_dirs);
463 g_free (self->priv->bus_address);
465 G_OBJECT_CLASS (g_test_dbus_parent_class)->finalize (object);
469 g_test_dbus_get_property (GObject *object,
474 GTestDBus *self = (GTestDBus *) object;
479 g_value_set_flags (value, g_test_dbus_get_flags (self));
482 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
488 g_test_dbus_set_property (GObject *object,
493 GTestDBus *self = (GTestDBus *) object;
498 self->priv->flags = g_value_get_flags (value);
501 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
507 g_test_dbus_class_init (GTestDBusClass *klass)
509 GObjectClass *object_class = G_OBJECT_CLASS (klass);
511 object_class->dispose = g_test_dbus_dispose;
512 object_class->finalize = g_test_dbus_finalize;
513 object_class->get_property = g_test_dbus_get_property;
514 object_class->set_property = g_test_dbus_set_property;
519 * #GTestDBusFlags specifying the behaviour of the dbus session
523 g_object_class_install_property (object_class, PROP_FLAGS,
524 g_param_spec_flags ("flags",
525 P_("dbus session flags"),
526 P_("Flags specifying the behaviour of the dbus session"),
527 G_TYPE_TEST_DBUS_FLAGS, G_TEST_DBUS_NONE,
528 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
529 G_PARAM_STATIC_STRINGS));
534 write_config_file (GTestDBus *self)
539 GError *error = NULL;
542 fd = g_file_open_tmp ("g-test-dbus-XXXXXX", &path, &error);
543 g_assert_no_error (error);
545 contents = g_string_new (NULL);
546 g_string_append (contents,
548 " <type>session</type>\n"
550 " <listen>nonce-tcp:</listen>\n"
552 " <listen>unix:tmpdir=/tmp</listen>\n"
556 for (i = 0; i < self->priv->service_dirs->len; i++)
558 const gchar *path = g_ptr_array_index (self->priv->service_dirs, i);
560 g_string_append_printf (contents,
561 " <servicedir>%s</servicedir>\n", path);
564 g_string_append (contents,
565 " <policy context=\"default\">\n"
566 " <!-- Allow everything to be sent -->\n"
567 " <allow send_destination=\"*\" eavesdrop=\"true\"/>\n"
568 " <!-- Allow everything to be received -->\n"
569 " <allow eavesdrop=\"true\"/>\n"
570 " <!-- Allow anyone to own anything -->\n"
571 " <allow own=\"*\"/>\n"
575 g_file_set_contents (path, contents->str, contents->len, &error);
576 g_assert_no_error (error);
578 g_string_free (contents, TRUE);
586 start_daemon (GTestDBus *self)
588 gchar *argv[] = {"dbus-daemon", "--print-address", "--config-file=foo", NULL};
594 GError *error = NULL;
596 if (g_getenv ("G_TEST_DBUS_DAEMON") != NULL)
597 argv[0] = (gchar *)g_getenv ("G_TEST_DBUS_DAEMON");
599 /* Write config file and set its path in argv */
600 config_path = write_config_file (self);
601 config_arg = g_strdup_printf ("--config-file=%s", config_path);
602 argv[2] = config_arg;
604 /* Spawn dbus-daemon */
605 g_spawn_async_with_pipes (NULL,
609 /* We Need this to get the pid returned on win32 */
610 G_SPAWN_DO_NOT_REAP_CHILD |
615 &self->priv->bus_pid,
620 g_assert_no_error (error);
622 _g_test_watcher_add_pid (self->priv->bus_pid);
624 /* Read bus address from daemon' stdout */
625 channel = g_io_channel_unix_new (stdout_fd);
626 g_io_channel_read_line (channel, &self->priv->bus_address, NULL,
628 g_assert_no_error (error);
629 self->priv->bus_address[termpos] = '\0';
631 /* start dbus-monitor */
632 if (g_getenv ("G_DBUS_MONITOR") != NULL)
636 command = g_strdup_printf ("dbus-monitor --address %s",
637 self->priv->bus_address);
638 g_spawn_command_line_async (command, NULL);
641 g_usleep (500 * 1000);
645 g_io_channel_shutdown (channel, FALSE, &error);
646 g_assert_no_error (error);
647 g_io_channel_unref (channel);
649 /* Don't use g_file_delete since it calls into gvfs */
650 if (g_unlink (config_path) != 0)
651 g_assert_not_reached ();
653 g_free (config_path);
658 stop_daemon (GTestDBus *self)
661 if (!TerminateProcess (self->priv->bus_pid, 0))
662 g_warning ("Can't terminate process: %s", g_win32_error_message (GetLastError()));
664 kill (self->priv->bus_pid, SIGTERM);
666 _g_test_watcher_remove_pid (self->priv->bus_pid);
667 g_spawn_close_pid (self->priv->bus_pid);
668 self->priv->bus_pid = 0;
670 g_free (self->priv->bus_address);
671 self->priv->bus_address = NULL;
676 * @flags: a #GTestDBusFlags
678 * Create a new #GTestDBus object.
680 * Returns: (transfer full): a new #GTestDBus.
683 g_test_dbus_new (GTestDBusFlags flags)
685 return g_object_new (G_TYPE_TEST_DBUS,
691 * g_test_dbus_get_flags:
692 * @self: a #GTestDBus
694 * Gets the flags of the #GTestDBus object.
696 * Returns: the value of #GTestDBus:flags property
699 g_test_dbus_get_flags (GTestDBus *self)
701 g_return_val_if_fail (G_IS_TEST_DBUS (self), G_TEST_DBUS_NONE);
703 return self->priv->flags;
707 * g_test_dbus_get_bus_address:
708 * @self: a #GTestDBus
710 * Get the address on which dbus-daemon is running. if g_test_dbus_up() has not
711 * been called yet, %NULL is returned. This can be used with
712 * g_dbus_connection_new_for_address()
714 * Returns: the address of the bus, or %NULL.
717 g_test_dbus_get_bus_address (GTestDBus *self)
719 g_return_val_if_fail (G_IS_TEST_DBUS (self), NULL);
721 return self->priv->bus_address;
725 * g_test_dbus_add_service_dir:
726 * @self: a #GTestDBus
727 * @path: path to a directory containing .service files
729 * Add a path where dbus-daemon will lookup for .services files. This can't be
730 * called after g_test_dbus_up().
733 g_test_dbus_add_service_dir (GTestDBus *self,
736 g_return_if_fail (G_IS_TEST_DBUS (self));
737 g_return_if_fail (self->priv->bus_address == NULL);
739 g_ptr_array_add (self->priv->service_dirs, g_strdup (path));
744 * @self: a #GTestDBus
746 * Start a dbus-daemon instance and set DBUS_SESSION_BUS_ADDRESS. After this
747 * call, it is safe for unit tests to start sending messages on the session bus.
749 * If this function is called from setup callback of g_test_add(),
750 * g_test_dbus_down() must be called in its teardown callback.
752 * If this function is called from unit test's main(), then g_test_dbus_down()
753 * must be called after g_test_run().
756 g_test_dbus_up (GTestDBus *self)
758 g_return_if_fail (G_IS_TEST_DBUS (self));
759 g_return_if_fail (self->priv->bus_address == NULL);
760 g_return_if_fail (!self->priv->up);
764 g_test_dbus_unset ();
765 g_setenv ("DBUS_SESSION_BUS_ADDRESS", self->priv->bus_address, TRUE);
766 self->priv->up = TRUE;
772 * @self: a #GTestDBus
774 * Stop the session bus started by g_test_dbus_up().
776 * Unlike g_test_dbus_down(), this won't verify the #GDBusConnection
777 * singleton returned by g_bus_get() or g_bus_get_sync() is destroyed. Unit
778 * tests wanting to verify behaviour after the session bus has been stopped
779 * can use this function but should still call g_test_dbus_down() when done.
782 g_test_dbus_stop (GTestDBus *self)
784 g_return_if_fail (G_IS_TEST_DBUS (self));
785 g_return_if_fail (self->priv->bus_address != NULL);
792 * @self: a #GTestDBus
794 * Stop the session bus started by g_test_dbus_up().
796 * This will wait for the singleton returned by g_bus_get() or g_bus_get_sync()
797 * is destroyed. This is done to ensure that the next unit test won't get a
798 * leaked singleton from this test.
801 g_test_dbus_down (GTestDBus *self)
803 GDBusConnection *connection;
805 g_return_if_fail (G_IS_TEST_DBUS (self));
806 g_return_if_fail (self->priv->up);
808 connection = _g_bus_get_singleton_if_exists (G_BUS_TYPE_SESSION);
809 if (connection != NULL)
810 g_dbus_connection_set_exit_on_close (connection, FALSE);
812 if (self->priv->bus_address != NULL)
815 if (connection != NULL)
816 _g_object_unref_and_wait_weak_notify (connection);
818 g_test_dbus_unset ();
819 self->priv->up = FALSE;
825 * Unset DISPLAY and DBUS_SESSION_BUS_ADDRESS env variables to ensure the test
826 * won't use user's session bus.
828 * This is useful for unit tests that want to verify behaviour when no session
829 * bus is running. It is not necessary to call this if unit test already calls
830 * g_test_dbus_up() before acquiring the session bus.
833 g_test_dbus_unset (void)
835 g_unsetenv ("DISPLAY");
836 g_unsetenv ("DBUS_SESSION_BUS_ADDRESS");
837 g_unsetenv ("DBUS_STARTER_ADDRESS");
838 g_unsetenv ("DBUS_STARTER_BUS_TYPE");