Blame gio/gtestdbus.c

Packit ae235b
/* GIO testing utilities
Packit ae235b
 *
Packit ae235b
 * Copyright (C) 2008-2010 Red Hat, Inc.
Packit ae235b
 * Copyright (C) 2012 Collabora Ltd. <http://www.collabora.co.uk/>
Packit ae235b
 *
Packit ae235b
 * This library is free software; you can redistribute it and/or
Packit ae235b
 * modify it under the terms of the GNU Lesser General Public
Packit ae235b
 * License as published by the Free Software Foundation; either
Packit ae235b
 * version 2.1 of the License, or (at your option) any later version.
Packit ae235b
 *
Packit ae235b
 * This library is distributed in the hope that it will be useful,
Packit ae235b
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
Packit ae235b
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Packit ae235b
 * Lesser General Public License for more details.
Packit ae235b
 *
Packit ae235b
 * You should have received a copy of the GNU Lesser General
Packit ae235b
 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
Packit ae235b
 *
Packit ae235b
 * Authors: David Zeuthen <davidz@redhat.com>
Packit ae235b
 *          Xavier Claessens <xavier.claessens@collabora.co.uk>
Packit ae235b
 */
Packit ae235b
Packit ae235b
#include "config.h"
Packit ae235b
Packit ae235b
#include <stdlib.h>
Packit ae235b
#include <stdio.h>
Packit ae235b
#include <errno.h>
Packit ae235b
#include <string.h>
Packit ae235b
#include <gstdio.h>
Packit ae235b
#ifdef G_OS_UNIX
Packit ae235b
#include <unistd.h>
Packit ae235b
#endif
Packit ae235b
#ifdef G_OS_WIN32
Packit ae235b
#include <io.h>
Packit ae235b
#endif
Packit ae235b
Packit ae235b
#include <glib.h>
Packit ae235b
Packit ae235b
#include "gdbusconnection.h"
Packit ae235b
#include "gdbusprivate.h"
Packit ae235b
#include "gfile.h"
Packit ae235b
#include "gioenumtypes.h"
Packit ae235b
#include "gtestdbus.h"
Packit ae235b
Packit ae235b
#include "glibintl.h"
Packit ae235b
Packit ae235b
#ifdef G_OS_WIN32
Packit ae235b
#include <windows.h>
Packit ae235b
#endif
Packit ae235b
Packit ae235b
/* -------------------------------------------------------------------------- */
Packit ae235b
/* Utility: Wait until object has a single ref  */
Packit ae235b
Packit ae235b
typedef struct
Packit ae235b
{
Packit ae235b
  GMainLoop *loop;
Packit ae235b
  gboolean   timed_out;
Packit ae235b
} WeakNotifyData;
Packit ae235b
Packit ae235b
static gboolean
Packit ae235b
on_weak_notify_timeout (gpointer user_data)
Packit ae235b
{
Packit ae235b
  WeakNotifyData *data = user_data;
Packit ae235b
  data->timed_out = TRUE;
Packit ae235b
  g_main_loop_quit (data->loop);
Packit ae235b
  return FALSE;
Packit ae235b
}
Packit ae235b
Packit ae235b
static gboolean
Packit ae235b
dispose_on_idle (gpointer object)
Packit ae235b
{
Packit ae235b
  g_object_run_dispose (object);
Packit ae235b
  g_object_unref (object);
Packit ae235b
  return FALSE;
Packit ae235b
}
Packit ae235b
Packit ae235b
static gboolean
Packit ae235b
_g_object_dispose_and_wait_weak_notify (gpointer object)
Packit ae235b
{
Packit ae235b
  WeakNotifyData data;
Packit ae235b
  guint timeout_id;
Packit ae235b
Packit ae235b
  data.loop = g_main_loop_new (NULL, FALSE);
Packit ae235b
  data.timed_out = FALSE;
Packit ae235b
Packit ae235b
  g_object_weak_ref (object, (GWeakNotify) g_main_loop_quit, data.loop);
Packit ae235b
Packit ae235b
  /* Drop the ref in an idle callback, this is to make sure the mainloop
Packit ae235b
   * is already running when weak notify happens */
Packit ae235b
  g_idle_add (dispose_on_idle, object);
Packit ae235b
Packit ae235b
  /* Make sure we don't block forever */
Packit ae235b
  timeout_id = g_timeout_add (30 * 1000, on_weak_notify_timeout, &data);
Packit ae235b
Packit ae235b
  g_main_loop_run (data.loop);
Packit ae235b
Packit ae235b
  if (data.timed_out)
Packit ae235b
    {
Packit ae235b
      g_warning ("Weak notify timeout, object ref_count=%d\n",
Packit ae235b
          G_OBJECT (object)->ref_count);
Packit ae235b
    }
Packit ae235b
  else
Packit ae235b
    {
Packit ae235b
      g_source_remove (timeout_id);
Packit ae235b
    }
Packit ae235b
Packit ae235b
  g_main_loop_unref (data.loop);
Packit ae235b
  return data.timed_out;
Packit ae235b
}
Packit ae235b
Packit ae235b
/* -------------------------------------------------------------------------- */
Packit ae235b
/* Utilities to cleanup the mess in the case unit test process crash */
Packit ae235b
Packit ae235b
#ifdef G_OS_WIN32
Packit ae235b
Packit ae235b
/* This could be interesting to expose in public API */
Packit ae235b
static void
Packit ae235b
_g_test_watcher_add_pid (GPid pid)
Packit ae235b
{
Packit ae235b
  static gsize started = 0;
Packit ae235b
  HANDLE job;
Packit ae235b
Packit ae235b
  if (g_once_init_enter (&started))
Packit ae235b
    {
Packit ae235b
      JOBOBJECT_EXTENDED_LIMIT_INFORMATION info;
Packit ae235b
Packit ae235b
      job = CreateJobObjectW (NULL, NULL);
Packit ae235b
      memset (&info, 0, sizeof (info));
Packit ae235b
      info.BasicLimitInformation.LimitFlags = 0x2000 /* JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE */;
Packit ae235b
Packit ae235b
      if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, &info, sizeof (info)))
Packit ae235b
	g_warning ("Can't enable JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE: %s", g_win32_error_message (GetLastError()));
Packit ae235b
Packit ae235b
      g_once_init_leave (&started,(gsize)job);
Packit ae235b
    }
Packit ae235b
Packit ae235b
  job = (HANDLE)started;
Packit ae235b
Packit ae235b
  if (!AssignProcessToJobObject(job, pid))
Packit ae235b
    g_warning ("Can't assign process to job: %s", g_win32_error_message (GetLastError()));
Packit ae235b
}
Packit ae235b
Packit ae235b
static void
Packit ae235b
_g_test_watcher_remove_pid (GPid pid)
Packit ae235b
{
Packit ae235b
  /* No need to unassign the process from the job object as the process
Packit ae235b
     will be killed anyway */
Packit ae235b
}
Packit ae235b
Packit ae235b
#else
Packit ae235b
Packit ae235b
#define ADD_PID_FORMAT "add pid %d\n"
Packit ae235b
#define REMOVE_PID_FORMAT "remove pid %d\n"
Packit ae235b
Packit ae235b
static void
Packit ae235b
watch_parent (gint fd)
Packit ae235b
{
Packit ae235b
  GIOChannel *channel;
Packit ae235b
  GPollFD fds[1];
Packit ae235b
  GArray *pids_to_kill;
Packit ae235b
Packit ae235b
  channel = g_io_channel_unix_new (fd);
Packit ae235b
Packit ae235b
  fds[0].fd = fd;
Packit ae235b
  fds[0].events = G_IO_HUP | G_IO_IN;
Packit ae235b
  fds[0].revents = 0;
Packit ae235b
Packit ae235b
  pids_to_kill = g_array_new (FALSE, FALSE, sizeof (guint));
Packit ae235b
Packit ae235b
  do
Packit ae235b
    {
Packit ae235b
      gint num_events;
Packit ae235b
      gchar *command = NULL;
Packit ae235b
      guint pid;
Packit ae235b
      guint n;
Packit ae235b
      GError *error = NULL;
Packit ae235b
Packit ae235b
      num_events = g_poll (fds, 1, -1);
Packit ae235b
      if (num_events == 0)
Packit ae235b
        continue;
Packit ae235b
Packit ae235b
      if (fds[0].revents == G_IO_HUP)
Packit ae235b
        {
Packit ae235b
          /* Parent quit, cleanup the mess and exit */
Packit ae235b
          for (n = 0; n < pids_to_kill->len; n++)
Packit ae235b
            {
Packit ae235b
              pid = g_array_index (pids_to_kill, guint, n);
Packit ae235b
              g_printerr ("cleaning up pid %d\n", pid);
Packit ae235b
              kill (pid, SIGTERM);
Packit ae235b
            }
Packit ae235b
Packit ae235b
          g_array_unref (pids_to_kill);
Packit ae235b
          g_io_channel_shutdown (channel, FALSE, &error);
Packit ae235b
          g_assert_no_error (error);
Packit ae235b
          g_io_channel_unref (channel);
Packit ae235b
Packit ae235b
          exit (0);
Packit ae235b
        }
Packit ae235b
Packit ae235b
      /* Read the command from the input */
Packit ae235b
      g_io_channel_read_line (channel, &command, NULL, NULL, &error);
Packit ae235b
      g_assert_no_error (error);
Packit ae235b
Packit ae235b
      /* Check for known commands */
Packit ae235b
      if (sscanf (command, ADD_PID_FORMAT, &pid) == 1)
Packit ae235b
        {
Packit ae235b
          g_array_append_val (pids_to_kill, pid);
Packit ae235b
        }
Packit ae235b
      else if (sscanf (command, REMOVE_PID_FORMAT, &pid) == 1)
Packit ae235b
        {
Packit ae235b
          for (n = 0; n < pids_to_kill->len; n++)
Packit ae235b
            {
Packit ae235b
              if (g_array_index (pids_to_kill, guint, n) == pid)
Packit ae235b
                {
Packit ae235b
                  g_array_remove_index (pids_to_kill, n);
Packit ae235b
                  pid = 0;
Packit ae235b
                  break;
Packit ae235b
                }
Packit ae235b
            }
Packit ae235b
          if (pid != 0)
Packit ae235b
            {
Packit ae235b
              g_warning ("unknown pid %d to remove", pid);
Packit ae235b
            }
Packit ae235b
        }
Packit ae235b
      else
Packit ae235b
        {
Packit ae235b
          g_warning ("unknown command from parent '%s'", command);
Packit ae235b
        }
Packit ae235b
Packit ae235b
      g_free (command);
Packit ae235b
    }
Packit ae235b
  while (TRUE);
Packit ae235b
}
Packit ae235b
Packit ae235b
static GIOChannel *
Packit ae235b
watcher_init (void)
Packit ae235b
{
Packit ae235b
  static gsize started = 0;
Packit ae235b
  static GIOChannel *channel = NULL;
Packit ae235b
  int errsv;
Packit ae235b
Packit ae235b
  if (g_once_init_enter (&started))
Packit ae235b
    {
Packit ae235b
      gint pipe_fds[2];
Packit ae235b
Packit ae235b
      /* fork a child to clean up when we are killed */
Packit ae235b
      if (pipe (pipe_fds) != 0)
Packit ae235b
        {
Packit ae235b
          errsv = errno;
Packit ae235b
          g_warning ("pipe() failed: %s", g_strerror (errsv));
Packit ae235b
          g_assert_not_reached ();
Packit ae235b
        }
Packit ae235b
Packit ae235b
      switch (fork ())
Packit ae235b
        {
Packit ae235b
        case -1:
Packit ae235b
          errsv = errno;
Packit ae235b
          g_warning ("fork() failed: %s", g_strerror (errsv));
Packit ae235b
          g_assert_not_reached ();
Packit ae235b
          break;
Packit ae235b
Packit ae235b
        case 0:
Packit ae235b
          /* child */
Packit ae235b
          close (pipe_fds[1]);
Packit ae235b
          watch_parent (pipe_fds[0]);
Packit ae235b
          break;
Packit ae235b
Packit ae235b
        default:
Packit ae235b
          /* parent */
Packit ae235b
          close (pipe_fds[0]);
Packit ae235b
          channel = g_io_channel_unix_new (pipe_fds[1]);
Packit ae235b
        }
Packit ae235b
Packit ae235b
      g_once_init_leave (&started, 1);
Packit ae235b
    }
Packit ae235b
Packit ae235b
  return channel;
Packit ae235b
}
Packit ae235b
Packit ae235b
static void
Packit ae235b
watcher_send_command (const gchar *command)
Packit ae235b
{
Packit ae235b
  GIOChannel *channel;
Packit ae235b
  GError *error = NULL;
Packit ae235b
Packit ae235b
  channel = watcher_init ();
Packit ae235b
Packit ae235b
  g_io_channel_write_chars (channel, command, -1, NULL, &error);
Packit ae235b
  g_assert_no_error (error);
Packit ae235b
Packit ae235b
  g_io_channel_flush (channel, &error);
Packit ae235b
  g_assert_no_error (error);
Packit ae235b
}
Packit ae235b
Packit ae235b
/* This could be interesting to expose in public API */
Packit ae235b
static void
Packit ae235b
_g_test_watcher_add_pid (GPid pid)
Packit ae235b
{
Packit ae235b
  gchar *command;
Packit ae235b
Packit ae235b
  command = g_strdup_printf (ADD_PID_FORMAT, (guint) pid);
Packit ae235b
  watcher_send_command (command);
Packit ae235b
  g_free (command);
Packit ae235b
}
Packit ae235b
Packit ae235b
static void
Packit ae235b
_g_test_watcher_remove_pid (GPid pid)
Packit ae235b
{
Packit ae235b
  gchar *command;
Packit ae235b
Packit ae235b
  command = g_strdup_printf (REMOVE_PID_FORMAT, (guint) pid);
Packit ae235b
  watcher_send_command (command);
Packit ae235b
  g_free (command);
Packit ae235b
}
Packit ae235b
Packit ae235b
#endif
Packit ae235b
Packit ae235b
/* -------------------------------------------------------------------------- */
Packit ae235b
/* GTestDBus object implementation */
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * SECTION:gtestdbus
Packit ae235b
 * @short_description: D-Bus testing helper
Packit ae235b
 * @include: gio/gio.h
Packit ae235b
 *
Packit ae235b
 * A helper class for testing code which uses D-Bus without touching the user's
Packit ae235b
 * session bus.
Packit ae235b
 *
Packit ae235b
 * Note that #GTestDBus modifies the user’s environment, calling setenv().
Packit ae235b
 * This is not thread-safe, so all #GTestDBus calls should be completed before
Packit ae235b
 * threads are spawned, or should have appropriate locking to ensure no access
Packit ae235b
 * conflicts to environment variables shared between #GTestDBus and other
Packit ae235b
 * threads.
Packit ae235b
 *
Packit ae235b
 * ## Creating unit tests using GTestDBus
Packit ae235b
 * 
Packit ae235b
 * Testing of D-Bus services can be tricky because normally we only ever run
Packit ae235b
 * D-Bus services over an existing instance of the D-Bus daemon thus we
Packit ae235b
 * usually don't activate D-Bus services that are not yet installed into the
Packit ae235b
 * target system. The #GTestDBus object makes this easier for us by taking care
Packit ae235b
 * of the lower level tasks such as running a private D-Bus daemon and looking
Packit ae235b
 * up uninstalled services in customizable locations, typically in your source
Packit ae235b
 * code tree.
Packit ae235b
 *
Packit ae235b
 * The first thing you will need is a separate service description file for the
Packit ae235b
 * D-Bus daemon. Typically a `services` subdirectory of your `tests` directory
Packit ae235b
 * is a good place to put this file.
Packit ae235b
 *
Packit ae235b
 * The service file should list your service along with an absolute path to the
Packit ae235b
 * uninstalled service executable in your source tree. Using autotools we would
Packit ae235b
 * achieve this by adding a file such as `my-server.service.in` in the services
Packit ae235b
 * directory and have it processed by configure.
Packit ae235b
 * |[
Packit ae235b
 *     [D-BUS Service]
Packit ae235b
 *     Name=org.gtk.GDBus.Examples.ObjectManager
Packit ae235b
 *     Exec=@abs_top_builddir@/gio/tests/gdbus-example-objectmanager-server
Packit ae235b
 * ]|
Packit ae235b
 * You will also need to indicate this service directory in your test
Packit ae235b
 * fixtures, so you will need to pass the path while compiling your
Packit ae235b
 * test cases. Typically this is done with autotools with an added
Packit ae235b
 * preprocessor flag specified to compile your tests such as:
Packit ae235b
 * |[
Packit ae235b
 *     -DTEST_SERVICES=\""$(abs_top_builddir)/tests/services"\"
Packit ae235b
 * ]|
Packit ae235b
 *     Once you have a service definition file which is local to your source tree,
Packit ae235b
 * you can proceed to set up a GTest fixture using the #GTestDBus scaffolding.
Packit ae235b
 *
Packit ae235b
 * An example of a test fixture for D-Bus services can be found
Packit ae235b
 * here:
Packit ae235b
 * [gdbus-test-fixture.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-test-fixture.c)
Packit ae235b
 *
Packit ae235b
 * Note that these examples only deal with isolating the D-Bus aspect of your
Packit ae235b
 * service. To successfully run isolated unit tests on your service you may need
Packit ae235b
 * some additional modifications to your test case fixture. For example; if your
Packit ae235b
 * service uses GSettings and installs a schema then it is important that your test service
Packit ae235b
 * not load the schema in the ordinary installed location (chances are that your service
Packit ae235b
 * and schema files are not yet installed, or worse; there is an older version of the
Packit ae235b
 * schema file sitting in the install location).
Packit ae235b
 *
Packit ae235b
 * Most of the time we can work around these obstacles using the
Packit ae235b
 * environment. Since the environment is inherited by the D-Bus daemon
Packit ae235b
 * created by #GTestDBus and then in turn inherited by any services the
Packit ae235b
 * D-Bus daemon activates, using the setup routine for your fixture is
Packit ae235b
 * a practical place to help sandbox your runtime environment. For the
Packit ae235b
 * rather typical GSettings case we can work around this by setting
Packit ae235b
 * `GSETTINGS_SCHEMA_DIR` to the in tree directory holding your schemas
Packit ae235b
 * in the above fixture_setup() routine.
Packit ae235b
 *
Packit ae235b
 * The GSettings schemas need to be locally pre-compiled for this to work. This can be achieved
Packit ae235b
 * by compiling the schemas locally as a step before running test cases, an autotools setup might
Packit ae235b
 * do the following in the directory holding schemas:
Packit ae235b
 * |[
Packit ae235b
 *     all-am:
Packit ae235b
 *             $(GLIB_COMPILE_SCHEMAS) .
Packit ae235b
 *
Packit ae235b
 *     CLEANFILES += gschemas.compiled
Packit ae235b
 * ]|
Packit ae235b
 */
Packit ae235b
Packit ae235b
typedef struct _GTestDBusClass   GTestDBusClass;
Packit ae235b
typedef struct _GTestDBusPrivate GTestDBusPrivate;
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * GTestDBus:
Packit ae235b
 *
Packit ae235b
 * The #GTestDBus structure contains only private data and
Packit ae235b
 * should only be accessed using the provided API.
Packit ae235b
 *
Packit ae235b
 * Since: 2.34
Packit ae235b
 */
Packit ae235b
struct _GTestDBus {
Packit ae235b
  GObject parent;
Packit ae235b
Packit ae235b
  GTestDBusPrivate *priv;
Packit ae235b
};
Packit ae235b
Packit ae235b
struct _GTestDBusClass {
Packit ae235b
  GObjectClass parent_class;
Packit ae235b
};
Packit ae235b
Packit ae235b
struct _GTestDBusPrivate
Packit ae235b
{
Packit ae235b
  GTestDBusFlags flags;
Packit ae235b
  GPtrArray *service_dirs;
Packit ae235b
  GPid bus_pid;
Packit ae235b
  gint bus_stdout_fd;
Packit ae235b
  gchar *bus_address;
Packit ae235b
  gboolean up;
Packit ae235b
};
Packit ae235b
Packit ae235b
enum
Packit ae235b
{
Packit ae235b
  PROP_0,
Packit ae235b
  PROP_FLAGS,
Packit ae235b
};
Packit ae235b
Packit ae235b
G_DEFINE_TYPE_WITH_PRIVATE (GTestDBus, g_test_dbus, G_TYPE_OBJECT)
Packit ae235b
Packit ae235b
static void
Packit ae235b
g_test_dbus_init (GTestDBus *self)
Packit ae235b
{
Packit ae235b
  self->priv = g_test_dbus_get_instance_private (self);
Packit ae235b
  self->priv->service_dirs = g_ptr_array_new_with_free_func (g_free);
Packit ae235b
}
Packit ae235b
Packit ae235b
static void
Packit ae235b
g_test_dbus_dispose (GObject *object)
Packit ae235b
{
Packit ae235b
  GTestDBus *self = (GTestDBus *) object;
Packit ae235b
Packit ae235b
  if (self->priv->up)
Packit ae235b
    g_test_dbus_down (self);
Packit ae235b
Packit ae235b
  G_OBJECT_CLASS (g_test_dbus_parent_class)->dispose (object);
Packit ae235b
}
Packit ae235b
Packit ae235b
static void
Packit ae235b
g_test_dbus_finalize (GObject *object)
Packit ae235b
{
Packit ae235b
  GTestDBus *self = (GTestDBus *) object;
Packit ae235b
Packit ae235b
  g_ptr_array_unref (self->priv->service_dirs);
Packit ae235b
  g_free (self->priv->bus_address);
Packit ae235b
Packit ae235b
  G_OBJECT_CLASS (g_test_dbus_parent_class)->finalize (object);
Packit ae235b
}
Packit ae235b
Packit ae235b
static void
Packit ae235b
g_test_dbus_get_property (GObject *object,
Packit ae235b
    guint property_id,
Packit ae235b
    GValue *value,
Packit ae235b
    GParamSpec *pspec)
Packit ae235b
{
Packit ae235b
  GTestDBus *self = (GTestDBus *) object;
Packit ae235b
Packit ae235b
  switch (property_id)
Packit ae235b
    {
Packit ae235b
      case PROP_FLAGS:
Packit ae235b
        g_value_set_flags (value, g_test_dbus_get_flags (self));
Packit ae235b
        break;
Packit ae235b
      default:
Packit ae235b
        G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
Packit ae235b
        break;
Packit ae235b
    }
Packit ae235b
}
Packit ae235b
Packit ae235b
static void
Packit ae235b
g_test_dbus_set_property (GObject *object,
Packit ae235b
    guint property_id,
Packit ae235b
    const GValue *value,
Packit ae235b
    GParamSpec *pspec)
Packit ae235b
{
Packit ae235b
  GTestDBus *self = (GTestDBus *) object;
Packit ae235b
Packit ae235b
  switch (property_id)
Packit ae235b
    {
Packit ae235b
      case PROP_FLAGS:
Packit ae235b
        self->priv->flags = g_value_get_flags (value);
Packit ae235b
        break;
Packit ae235b
      default:
Packit ae235b
        G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
Packit ae235b
        break;
Packit ae235b
    }
Packit ae235b
}
Packit ae235b
Packit ae235b
static void
Packit ae235b
g_test_dbus_class_init (GTestDBusClass *klass)
Packit ae235b
{
Packit ae235b
  GObjectClass *object_class = G_OBJECT_CLASS (klass);
Packit ae235b
Packit ae235b
  object_class->dispose = g_test_dbus_dispose;
Packit ae235b
  object_class->finalize = g_test_dbus_finalize;
Packit ae235b
  object_class->get_property = g_test_dbus_get_property;
Packit ae235b
  object_class->set_property = g_test_dbus_set_property;
Packit ae235b
Packit ae235b
  /**
Packit ae235b
   * GTestDBus:flags:
Packit ae235b
   *
Packit ae235b
   * #GTestDBusFlags specifying the behaviour of the D-Bus session.
Packit ae235b
   *
Packit ae235b
   * Since: 2.34
Packit ae235b
   */
Packit ae235b
  g_object_class_install_property (object_class, PROP_FLAGS,
Packit ae235b
    g_param_spec_flags ("flags",
Packit ae235b
                        P_("D-Bus session flags"),
Packit ae235b
                        P_("Flags specifying the behaviour of the D-Bus session"),
Packit ae235b
                        G_TYPE_TEST_DBUS_FLAGS, G_TEST_DBUS_NONE,
Packit ae235b
                        G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
Packit ae235b
                        G_PARAM_STATIC_STRINGS));
Packit ae235b
Packit ae235b
}
Packit ae235b
Packit ae235b
static gchar *
Packit ae235b
write_config_file (GTestDBus *self)
Packit ae235b
{
Packit ae235b
  GString *contents;
Packit ae235b
  gint fd;
Packit ae235b
  guint i;
Packit ae235b
  GError *error = NULL;
Packit ae235b
  gchar *path = NULL;
Packit ae235b
Packit ae235b
  fd = g_file_open_tmp ("g-test-dbus-XXXXXX", &path, &error);
Packit ae235b
  g_assert_no_error (error);
Packit ae235b
Packit ae235b
  contents = g_string_new (NULL);
Packit ae235b
  g_string_append (contents,
Packit ae235b
      "<busconfig>\n"
Packit ae235b
      "  <type>session</type>\n"
Packit ae235b
#ifdef G_OS_WIN32
Packit ae235b
      "  <listen>nonce-tcp:</listen>\n"
Packit ae235b
#else
Packit ae235b
      "  <listen>unix:tmpdir=/tmp</listen>\n"
Packit ae235b
#endif
Packit ae235b
		   );
Packit ae235b
Packit ae235b
  for (i = 0; i < self->priv->service_dirs->len; i++)
Packit ae235b
    {
Packit ae235b
      const gchar *dir_path = g_ptr_array_index (self->priv->service_dirs, i);
Packit ae235b
Packit ae235b
      g_string_append_printf (contents,
Packit ae235b
          "  <servicedir>%s</servicedir>\n", dir_path);
Packit ae235b
    }
Packit ae235b
Packit ae235b
  g_string_append (contents,
Packit ae235b
      "  <policy context=\"default\">\n"
Packit ae235b
      "    \n"
Packit ae235b
      "    <allow send_destination=\"*\" eavesdrop=\"true\"/>\n"
Packit ae235b
      "    \n"
Packit ae235b
      "    <allow eavesdrop=\"true\"/>\n"
Packit ae235b
      "    \n"
Packit ae235b
      "    <allow own=\"*\"/>\n"
Packit ae235b
      "  </policy>\n"
Packit ae235b
      "</busconfig>\n");
Packit ae235b
Packit ae235b
  close (fd);
Packit ae235b
  g_file_set_contents (path, contents->str, contents->len, &error);
Packit ae235b
  g_assert_no_error (error);
Packit ae235b
Packit ae235b
  g_string_free (contents, TRUE);
Packit ae235b
Packit ae235b
  return path;
Packit ae235b
}
Packit ae235b
Packit ae235b
static void
Packit ae235b
start_daemon (GTestDBus *self)
Packit ae235b
{
Packit ae235b
  const gchar *argv[] = {"dbus-daemon", "--print-address", "--config-file=foo", NULL};
Packit ae235b
  gchar *config_path;
Packit ae235b
  gchar *config_arg;
Packit ae235b
  GIOChannel *channel;
Packit ae235b
  gint stdout_fd2;
Packit ae235b
  gsize termpos;
Packit ae235b
  GError *error = NULL;
Packit ae235b
Packit ae235b
  if (g_getenv ("G_TEST_DBUS_DAEMON") != NULL)
Packit ae235b
    argv[0] = (gchar *)g_getenv ("G_TEST_DBUS_DAEMON");
Packit ae235b
Packit ae235b
  /* Write config file and set its path in argv */
Packit ae235b
  config_path = write_config_file (self);
Packit ae235b
  config_arg = g_strdup_printf ("--config-file=%s", config_path);
Packit ae235b
  argv[2] = config_arg;
Packit ae235b
Packit ae235b
  /* Spawn dbus-daemon */
Packit ae235b
  g_spawn_async_with_pipes (NULL,
Packit ae235b
                            (gchar **) argv,
Packit ae235b
                            NULL,
Packit ae235b
#ifdef G_OS_WIN32
Packit ae235b
                            /* We Need this to get the pid returned on win32 */
Packit ae235b
                            G_SPAWN_DO_NOT_REAP_CHILD |
Packit ae235b
#endif
Packit ae235b
                            G_SPAWN_SEARCH_PATH,
Packit ae235b
                            NULL,
Packit ae235b
                            NULL,
Packit ae235b
                            &self->priv->bus_pid,
Packit ae235b
                            NULL,
Packit ae235b
                            &self->priv->bus_stdout_fd,
Packit ae235b
                            NULL,
Packit ae235b
                            &error);
Packit ae235b
  g_assert_no_error (error);
Packit ae235b
Packit ae235b
  _g_test_watcher_add_pid (self->priv->bus_pid);
Packit ae235b
Packit ae235b
  /* Read bus address from daemon' stdout. We have to be careful to avoid
Packit ae235b
   * closing the FD, as it is passed to any D-Bus service activated processes,
Packit ae235b
   * and if we close it, they will get a SIGPIPE and die when they try to write
Packit ae235b
   * to their stdout. */
Packit ae235b
  stdout_fd2 = dup (self->priv->bus_stdout_fd);
Packit ae235b
  g_assert_cmpint (stdout_fd2, >=, 0);
Packit ae235b
  channel = g_io_channel_unix_new (stdout_fd2);
Packit ae235b
Packit ae235b
  g_io_channel_read_line (channel, &self->priv->bus_address, NULL,
Packit ae235b
      &termpos, &error);
Packit ae235b
  g_assert_no_error (error);
Packit ae235b
  self->priv->bus_address[termpos] = '\0';
Packit ae235b
Packit ae235b
  /* start dbus-monitor */
Packit ae235b
  if (g_getenv ("G_DBUS_MONITOR") != NULL)
Packit ae235b
    {
Packit ae235b
      gchar *command;
Packit ae235b
Packit ae235b
      command = g_strdup_printf ("dbus-monitor --address %s",
Packit ae235b
          self->priv->bus_address);
Packit ae235b
      g_spawn_command_line_async (command, NULL);
Packit ae235b
      g_free (command);
Packit ae235b
Packit ae235b
      g_usleep (500 * 1000);
Packit ae235b
    }
Packit ae235b
Packit ae235b
  /* Cleanup */
Packit ae235b
  g_io_channel_shutdown (channel, FALSE, &error);
Packit ae235b
  g_assert_no_error (error);
Packit ae235b
  g_io_channel_unref (channel);
Packit ae235b
Packit ae235b
  /* Don't use g_file_delete since it calls into gvfs */
Packit ae235b
  if (g_unlink (config_path) != 0)
Packit ae235b
    g_assert_not_reached ();
Packit ae235b
Packit ae235b
  g_free (config_path);
Packit ae235b
  g_free (config_arg);
Packit ae235b
}
Packit ae235b
Packit ae235b
static void
Packit ae235b
stop_daemon (GTestDBus *self)
Packit ae235b
{
Packit ae235b
#ifdef G_OS_WIN32
Packit ae235b
  if (!TerminateProcess (self->priv->bus_pid, 0))
Packit ae235b
    g_warning ("Can't terminate process: %s", g_win32_error_message (GetLastError()));
Packit ae235b
#else
Packit ae235b
  kill (self->priv->bus_pid, SIGTERM);
Packit ae235b
#endif
Packit ae235b
  _g_test_watcher_remove_pid (self->priv->bus_pid);
Packit ae235b
  g_spawn_close_pid (self->priv->bus_pid);
Packit ae235b
  self->priv->bus_pid = 0;
Packit ae235b
  close (self->priv->bus_stdout_fd);
Packit ae235b
  self->priv->bus_stdout_fd = -1;
Packit ae235b
Packit ae235b
  g_free (self->priv->bus_address);
Packit ae235b
  self->priv->bus_address = NULL;
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_test_dbus_new:
Packit ae235b
 * @flags: a #GTestDBusFlags
Packit ae235b
 *
Packit ae235b
 * Create a new #GTestDBus object.
Packit ae235b
 *
Packit ae235b
 * Returns: (transfer full): a new #GTestDBus.
Packit ae235b
 */
Packit ae235b
GTestDBus *
Packit ae235b
g_test_dbus_new (GTestDBusFlags flags)
Packit ae235b
{
Packit ae235b
  return g_object_new (G_TYPE_TEST_DBUS,
Packit ae235b
      "flags", flags,
Packit ae235b
      NULL);
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_test_dbus_get_flags:
Packit ae235b
 * @self: a #GTestDBus
Packit ae235b
 *
Packit ae235b
 * Get the flags of the #GTestDBus object.
Packit ae235b
 *
Packit ae235b
 * Returns: the value of #GTestDBus:flags property
Packit ae235b
 */
Packit ae235b
GTestDBusFlags
Packit ae235b
g_test_dbus_get_flags (GTestDBus *self)
Packit ae235b
{
Packit ae235b
  g_return_val_if_fail (G_IS_TEST_DBUS (self), G_TEST_DBUS_NONE);
Packit ae235b
Packit ae235b
  return self->priv->flags;
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_test_dbus_get_bus_address:
Packit ae235b
 * @self: a #GTestDBus
Packit ae235b
 *
Packit ae235b
 * Get the address on which dbus-daemon is running. If g_test_dbus_up() has not
Packit ae235b
 * been called yet, %NULL is returned. This can be used with
Packit ae235b
 * g_dbus_connection_new_for_address().
Packit ae235b
 *
Packit ae235b
 * Returns: (nullable): the address of the bus, or %NULL.
Packit ae235b
 */
Packit ae235b
const gchar *
Packit ae235b
g_test_dbus_get_bus_address (GTestDBus *self)
Packit ae235b
{
Packit ae235b
  g_return_val_if_fail (G_IS_TEST_DBUS (self), NULL);
Packit ae235b
Packit ae235b
  return self->priv->bus_address;
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_test_dbus_add_service_dir:
Packit ae235b
 * @self: a #GTestDBus
Packit ae235b
 * @path: path to a directory containing .service files
Packit ae235b
 *
Packit ae235b
 * Add a path where dbus-daemon will look up .service files. This can't be
Packit ae235b
 * called after g_test_dbus_up().
Packit ae235b
 */
Packit ae235b
void
Packit ae235b
g_test_dbus_add_service_dir (GTestDBus *self,
Packit ae235b
    const gchar *path)
Packit ae235b
{
Packit ae235b
  g_return_if_fail (G_IS_TEST_DBUS (self));
Packit ae235b
  g_return_if_fail (self->priv->bus_address == NULL);
Packit ae235b
Packit ae235b
  g_ptr_array_add (self->priv->service_dirs, g_strdup (path));
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_test_dbus_up:
Packit ae235b
 * @self: a #GTestDBus
Packit ae235b
 *
Packit ae235b
 * Start a dbus-daemon instance and set DBUS_SESSION_BUS_ADDRESS. After this
Packit ae235b
 * call, it is safe for unit tests to start sending messages on the session bus.
Packit ae235b
 *
Packit ae235b
 * If this function is called from setup callback of g_test_add(),
Packit ae235b
 * g_test_dbus_down() must be called in its teardown callback.
Packit ae235b
 *
Packit ae235b
 * If this function is called from unit test's main(), then g_test_dbus_down()
Packit ae235b
 * must be called after g_test_run().
Packit ae235b
 */
Packit ae235b
void
Packit ae235b
g_test_dbus_up (GTestDBus *self)
Packit ae235b
{
Packit ae235b
  g_return_if_fail (G_IS_TEST_DBUS (self));
Packit ae235b
  g_return_if_fail (self->priv->bus_address == NULL);
Packit ae235b
  g_return_if_fail (!self->priv->up);
Packit ae235b
Packit ae235b
  start_daemon (self);
Packit ae235b
Packit ae235b
  g_test_dbus_unset ();
Packit ae235b
  g_setenv ("DBUS_SESSION_BUS_ADDRESS", self->priv->bus_address, TRUE);
Packit ae235b
  self->priv->up = TRUE;
Packit ae235b
}
Packit ae235b
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_test_dbus_stop:
Packit ae235b
 * @self: a #GTestDBus
Packit ae235b
 *
Packit ae235b
 * Stop the session bus started by g_test_dbus_up().
Packit ae235b
 *
Packit ae235b
 * Unlike g_test_dbus_down(), this won't verify the #GDBusConnection
Packit ae235b
 * singleton returned by g_bus_get() or g_bus_get_sync() is destroyed. Unit
Packit ae235b
 * tests wanting to verify behaviour after the session bus has been stopped
Packit ae235b
 * can use this function but should still call g_test_dbus_down() when done.
Packit ae235b
 */
Packit ae235b
void
Packit ae235b
g_test_dbus_stop (GTestDBus *self)
Packit ae235b
{
Packit ae235b
  g_return_if_fail (G_IS_TEST_DBUS (self));
Packit ae235b
  g_return_if_fail (self->priv->bus_address != NULL);
Packit ae235b
Packit ae235b
  stop_daemon (self);
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_test_dbus_down:
Packit ae235b
 * @self: a #GTestDBus
Packit ae235b
 *
Packit ae235b
 * Stop the session bus started by g_test_dbus_up().
Packit ae235b
 *
Packit ae235b
 * This will wait for the singleton returned by g_bus_get() or g_bus_get_sync()
Packit ae235b
 * is destroyed. This is done to ensure that the next unit test won't get a
Packit ae235b
 * leaked singleton from this test.
Packit ae235b
 */
Packit ae235b
void
Packit ae235b
g_test_dbus_down (GTestDBus *self)
Packit ae235b
{
Packit ae235b
  GDBusConnection *connection;
Packit ae235b
Packit ae235b
  g_return_if_fail (G_IS_TEST_DBUS (self));
Packit ae235b
  g_return_if_fail (self->priv->up);
Packit ae235b
Packit ae235b
  connection = _g_bus_get_singleton_if_exists (G_BUS_TYPE_SESSION);
Packit ae235b
  if (connection != NULL)
Packit ae235b
    g_dbus_connection_set_exit_on_close (connection, FALSE);
Packit ae235b
Packit ae235b
  if (self->priv->bus_address != NULL)
Packit ae235b
    stop_daemon (self);
Packit ae235b
Packit ae235b
  if (connection != NULL)
Packit ae235b
    _g_object_dispose_and_wait_weak_notify (connection);
Packit ae235b
Packit ae235b
  g_test_dbus_unset ();
Packit ae235b
  self->priv->up = FALSE;
Packit ae235b
}
Packit ae235b
Packit ae235b
/**
Packit ae235b
 * g_test_dbus_unset:
Packit ae235b
 *
Packit ae235b
 * Unset DISPLAY and DBUS_SESSION_BUS_ADDRESS env variables to ensure the test
Packit ae235b
 * won't use user's session bus.
Packit ae235b
 *
Packit ae235b
 * This is useful for unit tests that want to verify behaviour when no session
Packit ae235b
 * bus is running. It is not necessary to call this if unit test already calls
Packit ae235b
 * g_test_dbus_up() before acquiring the session bus.
Packit ae235b
 */
Packit ae235b
void
Packit ae235b
g_test_dbus_unset (void)
Packit ae235b
{
Packit ae235b
  g_unsetenv ("DISPLAY");
Packit ae235b
  g_unsetenv ("DBUS_SESSION_BUS_ADDRESS");
Packit ae235b
  g_unsetenv ("DBUS_STARTER_ADDRESS");
Packit ae235b
  g_unsetenv ("DBUS_STARTER_BUS_TYPE");
Packit ae235b
  /* avoid using XDG_RUNTIME_DIR/bus */
Packit ae235b
  g_unsetenv ("XDG_RUNTIME_DIR");
Packit ae235b
}