Improvde #include order consistency
[glib.git] / gio / gtestdbus.c
blob2315451a4d5c4ae48449acd55c74d234513a740b
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>
25 #include "config.h"
27 #include <stdlib.h>
28 #include <stdio.h>
29 #include <gstdio.h>
30 #ifdef HAVE_UNISTD_H
31 #include <unistd.h>
32 #endif
33 #ifdef G_OS_WIN32
34 #include <io.h>
35 #endif
37 #include <glib.h>
39 #include "gdbusconnection.h"
40 #include "gdbusprivate.h"
41 #include "gfile.h"
42 #include "gioenumtypes.h"
43 #include "gtestdbus.h"
45 #include "glibintl.h"
47 #ifdef G_OS_WIN32
48 #include <windows.h>
49 #endif
51 /* -------------------------------------------------------------------------- */
52 /* Utility: Wait until object has a single ref */
54 typedef struct
56 GMainLoop *loop;
57 gboolean timed_out;
58 } WeakNotifyData;
60 static gboolean
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);
66 return FALSE;
69 static gboolean
70 unref_on_idle (gpointer object)
72 g_object_unref (object);
73 return FALSE;
76 static gboolean
77 _g_object_unref_and_wait_weak_notify (gpointer object)
79 WeakNotifyData data;
80 guint timeout_id;
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);
96 g_source_remove (timeout_id);
98 if (data.timed_out)
100 g_warning ("Weak notify timeout, object ref_count=%d\n",
101 G_OBJECT (object)->ref_count);
104 return data.timed_out;
107 /* -------------------------------------------------------------------------- */
108 /* Utilities to cleanup the mess in the case unit test process crash */
110 #ifdef G_OS_WIN32
112 /* This could be interesting to expose in public API */
113 static void
114 _g_test_watcher_add_pid (GPid pid)
116 static gsize started = 0;
117 HANDLE job;
119 if (g_once_init_enter (&started))
121 JOBOBJECT_EXTENDED_LIMIT_INFORMATION info;
123 job = CreateJobObjectW (NULL, NULL);
124 memset (&info, 0, sizeof (info));
125 info.BasicLimitInformation.LimitFlags = 0x2000 /* JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE */;
127 if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, &info, sizeof (info)))
128 g_warning ("Can't enable JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE: %s", g_win32_error_message (GetLastError()));
130 g_once_init_leave (&started,(gsize)job);
133 job = (HANDLE)started;
135 if (!AssignProcessToJobObject(job, pid))
136 g_warning ("Can't assign process to job: %s", g_win32_error_message (GetLastError()));
139 static void
140 _g_test_watcher_remove_pid (GPid pid)
142 /* No need to unassign the process from the job object as the process
143 will be killed anyway */
146 #else
148 #define ADD_PID_FORMAT "add pid %d\n"
149 #define REMOVE_PID_FORMAT "remove pid %d\n"
151 static void
152 watch_parent (gint fd)
154 GIOChannel *channel;
155 GPollFD fds[1];
156 GArray *pids_to_kill;
158 channel = g_io_channel_unix_new (fd);
160 fds[0].fd = fd;
161 fds[0].events = G_IO_HUP | G_IO_IN;
162 fds[0].revents = 0;
164 pids_to_kill = g_array_new (FALSE, FALSE, sizeof (guint));
168 gint num_events;
169 gchar *command = NULL;
170 guint pid;
171 guint n;
172 GError *error = NULL;
174 num_events = g_poll (fds, 1, -1);
175 if (num_events == 0)
176 continue;
178 if (fds[0].revents == G_IO_HUP)
180 /* Parent quit, cleanup the mess and exit */
181 for (n = 0; n < pids_to_kill->len; n++)
183 pid = g_array_index (pids_to_kill, guint, n);
184 g_print ("cleaning up pid %d\n", pid);
185 kill (pid, SIGTERM);
188 g_array_unref (pids_to_kill);
189 g_io_channel_shutdown (channel, FALSE, &error);
190 g_assert_no_error (error);
191 g_io_channel_unref (channel);
193 exit (0);
196 /* Read the command from the input */
197 g_io_channel_read_line (channel, &command, NULL, NULL, &error);
198 g_assert_no_error (error);
200 /* Check for known commands */
201 if (sscanf (command, ADD_PID_FORMAT, &pid) == 1)
203 g_array_append_val (pids_to_kill, pid);
205 else if (sscanf (command, REMOVE_PID_FORMAT, &pid) == 1)
207 for (n = 0; n < pids_to_kill->len; n++)
209 if (g_array_index (pids_to_kill, guint, n) == pid)
211 g_array_remove_index (pids_to_kill, n);
212 pid = 0;
213 break;
216 if (pid != 0)
218 g_warning ("unknown pid %d to remove", pid);
221 else
223 g_warning ("unknown command from parent '%s'", command);
226 g_free (command);
228 while (TRUE);
231 static GIOChannel *
232 watcher_init (void)
234 static gsize started = 0;
235 static GIOChannel *channel = NULL;
237 if (g_once_init_enter (&started))
239 gint pipe_fds[2];
241 /* fork a child to clean up when we are killed */
242 if (pipe (pipe_fds) != 0)
244 g_warning ("pipe() failed: %m");
245 g_assert_not_reached ();
248 switch (fork ())
250 case -1:
251 g_warning ("fork() failed: %m");
252 g_assert_not_reached ();
253 break;
255 case 0:
256 /* child */
257 close (pipe_fds[1]);
258 watch_parent (pipe_fds[0]);
259 break;
261 default:
262 /* parent */
263 close (pipe_fds[0]);
264 channel = g_io_channel_unix_new (pipe_fds[1]);
267 g_once_init_leave (&started, 1);
270 return channel;
273 static void
274 watcher_send_command (const gchar *command)
276 GIOChannel *channel;
277 GError *error = NULL;
279 channel = watcher_init ();
281 g_io_channel_write_chars (channel, command, -1, NULL, &error);
282 g_assert_no_error (error);
284 g_io_channel_flush (channel, &error);
285 g_assert_no_error (error);
288 /* This could be interesting to expose in public API */
289 static void
290 _g_test_watcher_add_pid (GPid pid)
292 gchar *command;
294 command = g_strdup_printf (ADD_PID_FORMAT, (guint) pid);
295 watcher_send_command (command);
296 g_free (command);
299 static void
300 _g_test_watcher_remove_pid (GPid pid)
302 gchar *command;
304 command = g_strdup_printf (REMOVE_PID_FORMAT, (guint) pid);
305 watcher_send_command (command);
306 g_free (command);
309 #endif
311 /* -------------------------------------------------------------------------- */
312 /* GTestDBus object implementation */
315 * SECTION:gtestdbus
316 * @short_description: D-Bus testing helper
317 * @include: gio/gio.h
319 * A helper class for testing code which uses D-Bus without touching the user's
320 * session bus.
323 typedef struct _GTestDBusClass GTestDBusClass;
324 typedef struct _GTestDBusPrivate GTestDBusPrivate;
327 * GTestDBus:
329 * The #GTestDBus structure contains only private data and
330 * should only be accessed using the provided API.
332 * Since: 2.34
334 struct _GTestDBus {
335 GObject parent;
337 GTestDBusPrivate *priv;
340 struct _GTestDBusClass {
341 GObjectClass parent_class;
344 struct _GTestDBusPrivate
346 GTestDBusFlags flags;
347 GPtrArray *service_dirs;
348 GPid bus_pid;
349 gchar *bus_address;
350 gboolean up;
353 enum
355 PROP_0,
356 PROP_FLAGS,
359 G_DEFINE_TYPE (GTestDBus, g_test_dbus, G_TYPE_OBJECT)
361 static void
362 g_test_dbus_init (GTestDBus *self)
364 self->priv = G_TYPE_INSTANCE_GET_PRIVATE ((self), G_TYPE_TEST_DBUS,
365 GTestDBusPrivate);
367 self->priv->service_dirs = g_ptr_array_new_with_free_func (g_free);
370 static void
371 g_test_dbus_dispose (GObject *object)
373 GTestDBus *self = (GTestDBus *) object;
375 if (self->priv->up)
376 g_test_dbus_down (self);
378 G_OBJECT_CLASS (g_test_dbus_parent_class)->dispose (object);
381 static void
382 g_test_dbus_finalize (GObject *object)
384 GTestDBus *self = (GTestDBus *) object;
386 g_ptr_array_unref (self->priv->service_dirs);
387 g_free (self->priv->bus_address);
389 G_OBJECT_CLASS (g_test_dbus_parent_class)->finalize (object);
392 static void
393 g_test_dbus_get_property (GObject *object,
394 guint property_id,
395 GValue *value,
396 GParamSpec *pspec)
398 GTestDBus *self = (GTestDBus *) object;
400 switch (property_id)
402 case PROP_FLAGS:
403 g_value_set_flags (value, g_test_dbus_get_flags (self));
404 break;
405 default:
406 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
407 break;
411 static void
412 g_test_dbus_set_property (GObject *object,
413 guint property_id,
414 const GValue *value,
415 GParamSpec *pspec)
417 GTestDBus *self = (GTestDBus *) object;
419 switch (property_id)
421 case PROP_FLAGS:
422 self->priv->flags = g_value_get_flags (value);
423 break;
424 default:
425 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
426 break;
430 static void
431 g_test_dbus_class_init (GTestDBusClass *klass)
433 GObjectClass *object_class = G_OBJECT_CLASS (klass);
435 object_class->dispose = g_test_dbus_dispose;
436 object_class->finalize = g_test_dbus_finalize;
437 object_class->get_property = g_test_dbus_get_property;
438 object_class->set_property = g_test_dbus_set_property;
440 g_type_class_add_private (object_class, sizeof (GTestDBusPrivate));
443 * GTestDBus:flags:
445 * #GTestDBusFlags specifying the behaviour of the dbus session
447 * Since: 2.34
449 g_object_class_install_property (object_class, PROP_FLAGS,
450 g_param_spec_flags ("flags",
451 P_("dbus session flags"),
452 P_("Flags specifying the behaviour of the dbus session"),
453 G_TYPE_TEST_DBUS_FLAGS, G_TEST_DBUS_NONE,
454 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
455 G_PARAM_STATIC_STRINGS));
459 static gchar *
460 write_config_file (GTestDBus *self)
462 GString *contents;
463 gint fd;
464 guint i;
465 GError *error = NULL;
466 gchar *path = NULL;
468 fd = g_file_open_tmp ("g-test-dbus-XXXXXX", &path, &error);
469 g_assert_no_error (error);
471 contents = g_string_new (NULL);
472 g_string_append (contents,
473 "<busconfig>\n"
474 " <type>session</type>\n"
475 #ifdef G_OS_WIN32
476 " <listen>nonce-tcp:</listen>\n"
477 #else
478 " <listen>unix:tmpdir=/tmp</listen>\n"
479 #endif
482 for (i = 0; i < self->priv->service_dirs->len; i++)
484 const gchar *path = g_ptr_array_index (self->priv->service_dirs, i);
486 g_string_append_printf (contents,
487 " <servicedir>%s</servicedir>\n", path);
490 g_string_append (contents,
491 " <policy context=\"default\">\n"
492 " <!-- Allow everything to be sent -->\n"
493 " <allow send_destination=\"*\" eavesdrop=\"true\"/>\n"
494 " <!-- Allow everything to be received -->\n"
495 " <allow eavesdrop=\"true\"/>\n"
496 " <!-- Allow anyone to own anything -->\n"
497 " <allow own=\"*\"/>\n"
498 " </policy>\n"
499 "</busconfig>\n");
501 g_file_set_contents (path, contents->str, contents->len, &error);
502 g_assert_no_error (error);
504 g_string_free (contents, TRUE);
506 close (fd);
508 return path;
511 static void
512 start_daemon (GTestDBus *self)
514 gchar *argv[] = {"dbus-daemon", "--print-address", "--config-file=foo", NULL};
515 gchar *config_path;
516 gchar *config_arg;
517 gint stdout_fd;
518 GIOChannel *channel;
519 gsize termpos;
520 GError *error = NULL;
522 if (g_getenv ("G_TEST_DBUS_DAEMON") != NULL)
523 argv[0] = (gchar *)g_getenv ("G_TEST_DBUS_DAEMON");
525 /* Write config file and set its path in argv */
526 config_path = write_config_file (self);
527 config_arg = g_strdup_printf ("--config-file=%s", config_path);
528 argv[2] = config_arg;
530 /* Spawn dbus-daemon */
531 g_spawn_async_with_pipes (NULL,
532 argv,
533 NULL,
534 #ifdef G_OS_WIN32
535 /* We Need this to get the pid returned on win32 */
536 G_SPAWN_DO_NOT_REAP_CHILD |
537 #endif
538 G_SPAWN_SEARCH_PATH,
539 NULL,
540 NULL,
541 &self->priv->bus_pid,
542 NULL,
543 &stdout_fd,
544 NULL,
545 &error);
546 g_assert_no_error (error);
548 _g_test_watcher_add_pid (self->priv->bus_pid);
550 /* Read bus address from daemon' stdout */
551 channel = g_io_channel_unix_new (stdout_fd);
552 g_io_channel_read_line (channel, &self->priv->bus_address, NULL,
553 &termpos, &error);
554 g_assert_no_error (error);
555 self->priv->bus_address[termpos] = '\0';
557 /* start dbus-monitor */
558 if (g_getenv ("G_DBUS_MONITOR") != NULL)
560 gchar *command;
562 command = g_strdup_printf ("dbus-monitor --address %s",
563 self->priv->bus_address);
564 g_spawn_command_line_async (command, NULL);
565 g_free (command);
567 g_usleep (500 * 1000);
570 /* Cleanup */
571 g_io_channel_shutdown (channel, FALSE, &error);
572 g_assert_no_error (error);
573 g_io_channel_unref (channel);
575 /* Don't use g_file_delete since it calls into gvfs */
576 if (g_unlink (config_path) != 0)
577 g_assert_not_reached ();
579 g_free (config_path);
580 g_free (config_arg);
583 static void
584 stop_daemon (GTestDBus *self)
586 #ifdef G_OS_WIN32
587 if (!TerminateProcess (self->priv->bus_pid, 0))
588 g_warning ("Can't terminate process: %s", g_win32_error_message (GetLastError()));
589 #else
590 kill (self->priv->bus_pid, SIGTERM);
591 #endif
592 _g_test_watcher_remove_pid (self->priv->bus_pid);
593 g_spawn_close_pid (self->priv->bus_pid);
594 self->priv->bus_pid = 0;
596 g_free (self->priv->bus_address);
597 self->priv->bus_address = NULL;
601 * g_test_dbus_new:
602 * @flags: a #GTestDBusFlags
604 * Create a new #GTestDBus object.
606 * Returns: (transfer full): a new #GTestDBus.
608 GTestDBus *
609 g_test_dbus_new (GTestDBusFlags flags)
611 return g_object_new (G_TYPE_TEST_DBUS,
612 "flags", flags,
613 NULL);
617 * g_test_dbus_get_flags:
618 * @self: a #GTestDBus
620 * Gets the flags of the #GTestDBus object.
622 * Returns: the value of #GTestDBus:flags property
624 GTestDBusFlags
625 g_test_dbus_get_flags (GTestDBus *self)
627 g_return_val_if_fail (G_IS_TEST_DBUS (self), G_TEST_DBUS_NONE);
629 return self->priv->flags;
633 * g_test_dbus_get_bus_address:
634 * @self: a #GTestDBus
636 * Get the address on which dbus-daemon is running. if g_test_dbus_up() has not
637 * been called yet, %NULL is returned. This can be used with
638 * g_dbus_connection_new_for_address()
640 * Returns: the address of the bus, or %NULL.
642 const gchar *
643 g_test_dbus_get_bus_address (GTestDBus *self)
645 g_return_val_if_fail (G_IS_TEST_DBUS (self), NULL);
647 return self->priv->bus_address;
651 * g_test_dbus_add_service_dir:
652 * @self: a #GTestDBus
653 * @path: path to a directory containing .service files
655 * Add a path where dbus-daemon will lookup for .services files. This can't be
656 * called after g_test_dbus_up().
658 void
659 g_test_dbus_add_service_dir (GTestDBus *self,
660 const gchar *path)
662 g_return_if_fail (G_IS_TEST_DBUS (self));
663 g_return_if_fail (self->priv->bus_address == NULL);
665 g_ptr_array_add (self->priv->service_dirs, g_strdup (path));
669 * g_test_dbus_up:
670 * @self: a #GTestDBus
672 * Start a dbus-daemon instance and set DBUS_SESSION_BUS_ADDRESS. After this
673 * call, it is safe for unit tests to start sending messages on the session bus.
675 * If this function is called from setup callback of g_test_add(),
676 * g_test_dbus_down() must be called in its teardown callback.
678 * If this function is called from unit test's main(), then g_test_dbus_down()
679 * must be called after g_test_run().
681 void
682 g_test_dbus_up (GTestDBus *self)
684 g_return_if_fail (G_IS_TEST_DBUS (self));
685 g_return_if_fail (self->priv->bus_address == NULL);
686 g_return_if_fail (!self->priv->up);
688 start_daemon (self);
690 g_setenv ("DBUS_SESSION_BUS_ADDRESS", self->priv->bus_address, TRUE);
691 self->priv->up = TRUE;
696 * g_test_dbus_stop:
697 * @self: a #GTestDBus
699 * Stop the session bus started by g_test_dbus_up().
701 * Unlike g_test_dbus_down(), this won't verify the #GDBusConnection
702 * singleton returned by g_bus_get() or g_bus_get_sync() is destroyed. Unit
703 * tests wanting to verify behaviour after the session bus has been stopped
704 * can use this function but should still call g_test_dbus_down() when done.
706 void
707 g_test_dbus_stop (GTestDBus *self)
709 g_return_if_fail (G_IS_TEST_DBUS (self));
710 g_return_if_fail (self->priv->bus_address != NULL);
712 stop_daemon (self);
716 * g_test_dbus_down:
717 * @self: a #GTestDBus
719 * Stop the session bus started by g_test_dbus_up().
721 * This will wait for the singleton returned by g_bus_get() or g_bus_get_sync()
722 * is destroyed. This is done to ensure that the next unit test won't get a
723 * leaked singleton from this test.
725 void
726 g_test_dbus_down (GTestDBus *self)
728 GDBusConnection *connection;
730 g_return_if_fail (G_IS_TEST_DBUS (self));
731 g_return_if_fail (self->priv->up);
733 connection = _g_bus_get_singleton_if_exists (G_BUS_TYPE_SESSION);
734 if (connection != NULL)
735 g_dbus_connection_set_exit_on_close (connection, FALSE);
737 if (self->priv->bus_address != NULL)
738 stop_daemon (self);
740 if (connection != NULL)
741 _g_object_unref_and_wait_weak_notify (connection);
743 g_unsetenv ("DBUS_SESSION_BUS_ADDRESS");
744 self->priv->up = FALSE;
748 * g_test_dbus_unset:
750 * Unset DISPLAY and DBUS_SESSION_BUS_ADDRESS env variables to ensure the test
751 * won't use user's session bus.
753 * This is useful for unit tests that want to verify behaviour when no session
754 * bus is running. It is not necessary to call this if unit test already calls
755 * g_test_dbus_up() before acquiring the session bus.
757 void
758 g_test_dbus_unset (void)
760 g_unsetenv ("DISPLAY");
761 g_unsetenv ("DBUS_SESSION_BUS_ADDRESS");