Added examples to GTestDBus documentation
[platform/upstream/glib.git] / gio / gtestdbus.c
1 /* GIO testing utilities
2  *
3  * Copyright (C) 2008-2010 Red Hat, Inc.
4  * Copyright (C) 2012 Collabora Ltd. <http://www.collabora.co.uk/>
5  *
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.
10  *
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.
15  *
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.
20  *
21  * Authors: David Zeuthen <davidz@redhat.com>
22  *          Xavier Claessens <xavier.claessens@collabora.co.uk>
23  */
24
25 #include "config.h"
26
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
36
37 #include <glib.h>
38
39 #include "gdbusconnection.h"
40 #include "gdbusprivate.h"
41 #include "gfile.h"
42 #include "gioenumtypes.h"
43 #include "gtestdbus.h"
44
45 #include "glibintl.h"
46
47 #ifdef G_OS_WIN32
48 #include <windows.h>
49 #endif
50
51 /* -------------------------------------------------------------------------- */
52 /* Utility: Wait until object has a single ref  */
53
54 typedef struct
55 {
56   GMainLoop *loop;
57   gboolean   timed_out;
58 } WeakNotifyData;
59
60 static gboolean
61 on_weak_notify_timeout (gpointer user_data)
62 {
63   WeakNotifyData *data = user_data;
64   data->timed_out = TRUE;
65   g_main_loop_quit (data->loop);
66   return FALSE;
67 }
68
69 static gboolean
70 unref_on_idle (gpointer object)
71 {
72   g_object_unref (object);
73   return FALSE;
74 }
75
76 static gboolean
77 _g_object_unref_and_wait_weak_notify (gpointer object)
78 {
79   WeakNotifyData data;
80   guint timeout_id;
81
82   data.loop = g_main_loop_new (NULL, FALSE);
83   data.timed_out = FALSE;
84
85   g_object_weak_ref (object, (GWeakNotify) g_main_loop_quit, data.loop);
86
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);
90
91   /* Make sure we don't block forever */
92   timeout_id = g_timeout_add (30 * 1000, on_weak_notify_timeout, &data);
93
94   g_main_loop_run (data.loop);
95
96   g_source_remove (timeout_id);
97
98   if (data.timed_out)
99     {
100       g_warning ("Weak notify timeout, object ref_count=%d\n",
101           G_OBJECT (object)->ref_count);
102     }
103
104   return data.timed_out;
105 }
106
107 /* -------------------------------------------------------------------------- */
108 /* Utilities to cleanup the mess in the case unit test process crash */
109
110 #ifdef G_OS_WIN32
111
112 /* This could be interesting to expose in public API */
113 static void
114 _g_test_watcher_add_pid (GPid pid)
115 {
116   static gsize started = 0;
117   HANDLE job;
118
119   if (g_once_init_enter (&started))
120     {
121       JOBOBJECT_EXTENDED_LIMIT_INFORMATION info;
122
123       job = CreateJobObjectW (NULL, NULL);
124       memset (&info, 0, sizeof (info));
125       info.BasicLimitInformation.LimitFlags = 0x2000 /* JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE */;
126
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()));
129
130       g_once_init_leave (&started,(gsize)job);
131     }
132
133   job = (HANDLE)started;
134
135   if (!AssignProcessToJobObject(job, pid))
136     g_warning ("Can't assign process to job: %s", g_win32_error_message (GetLastError()));
137 }
138
139 static void
140 _g_test_watcher_remove_pid (GPid pid)
141 {
142   /* No need to unassign the process from the job object as the process
143      will be killed anyway */
144 }
145
146 #else
147
148 #define ADD_PID_FORMAT "add pid %d\n"
149 #define REMOVE_PID_FORMAT "remove pid %d\n"
150
151 static void
152 watch_parent (gint fd)
153 {
154   GIOChannel *channel;
155   GPollFD fds[1];
156   GArray *pids_to_kill;
157
158   channel = g_io_channel_unix_new (fd);
159
160   fds[0].fd = fd;
161   fds[0].events = G_IO_HUP | G_IO_IN;
162   fds[0].revents = 0;
163
164   pids_to_kill = g_array_new (FALSE, FALSE, sizeof (guint));
165
166   do
167     {
168       gint num_events;
169       gchar *command = NULL;
170       guint pid;
171       guint n;
172       GError *error = NULL;
173
174       num_events = g_poll (fds, 1, -1);
175       if (num_events == 0)
176         continue;
177
178       if (fds[0].revents == G_IO_HUP)
179         {
180           /* Parent quit, cleanup the mess and exit */
181           for (n = 0; n < pids_to_kill->len; n++)
182             {
183               pid = g_array_index (pids_to_kill, guint, n);
184               g_print ("cleaning up pid %d\n", pid);
185               kill (pid, SIGTERM);
186             }
187
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);
192
193           exit (0);
194         }
195
196       /* Read the command from the input */
197       g_io_channel_read_line (channel, &command, NULL, NULL, &error);
198       g_assert_no_error (error);
199
200       /* Check for known commands */
201       if (sscanf (command, ADD_PID_FORMAT, &pid) == 1)
202         {
203           g_array_append_val (pids_to_kill, pid);
204         }
205       else if (sscanf (command, REMOVE_PID_FORMAT, &pid) == 1)
206         {
207           for (n = 0; n < pids_to_kill->len; n++)
208             {
209               if (g_array_index (pids_to_kill, guint, n) == pid)
210                 {
211                   g_array_remove_index (pids_to_kill, n);
212                   pid = 0;
213                   break;
214                 }
215             }
216           if (pid != 0)
217             {
218               g_warning ("unknown pid %d to remove", pid);
219             }
220         }
221       else
222         {
223           g_warning ("unknown command from parent '%s'", command);
224         }
225
226       g_free (command);
227     }
228   while (TRUE);
229 }
230
231 static GIOChannel *
232 watcher_init (void)
233 {
234   static gsize started = 0;
235   static GIOChannel *channel = NULL;
236
237   if (g_once_init_enter (&started))
238     {
239       gint pipe_fds[2];
240
241       /* fork a child to clean up when we are killed */
242       if (pipe (pipe_fds) != 0)
243         {
244           g_warning ("pipe() failed: %m");
245           g_assert_not_reached ();
246         }
247
248       switch (fork ())
249         {
250         case -1:
251           g_warning ("fork() failed: %m");
252           g_assert_not_reached ();
253           break;
254
255         case 0:
256           /* child */
257           close (pipe_fds[1]);
258           watch_parent (pipe_fds[0]);
259           break;
260
261         default:
262           /* parent */
263           close (pipe_fds[0]);
264           channel = g_io_channel_unix_new (pipe_fds[1]);
265         }
266
267       g_once_init_leave (&started, 1);
268     }
269
270   return channel;
271 }
272
273 static void
274 watcher_send_command (const gchar *command)
275 {
276   GIOChannel *channel;
277   GError *error = NULL;
278
279   channel = watcher_init ();
280
281   g_io_channel_write_chars (channel, command, -1, NULL, &error);
282   g_assert_no_error (error);
283
284   g_io_channel_flush (channel, &error);
285   g_assert_no_error (error);
286 }
287
288 /* This could be interesting to expose in public API */
289 static void
290 _g_test_watcher_add_pid (GPid pid)
291 {
292   gchar *command;
293
294   command = g_strdup_printf (ADD_PID_FORMAT, (guint) pid);
295   watcher_send_command (command);
296   g_free (command);
297 }
298
299 static void
300 _g_test_watcher_remove_pid (GPid pid)
301 {
302   gchar *command;
303
304   command = g_strdup_printf (REMOVE_PID_FORMAT, (guint) pid);
305   watcher_send_command (command);
306   g_free (command);
307 }
308
309 #endif
310
311 /* -------------------------------------------------------------------------- */
312 /* GTestDBus object implementation */
313
314 /**
315  * SECTION:gtestdbus
316  * @short_description: D-Bus testing helper
317  * @include: gio/gio.h
318  *
319  * A helper class for testing code which uses D-Bus without touching the user's
320  * session bus.
321  *
322  * <refsect2 id="gio-D-Bus-Test-Scaffolding">
323  *   <title>Creating unit tests using GTestDBus</title>
324  *   <para>
325  *     Testing of D-Bus services can be tricky because normally we only ever run
326  *     D-Bus services over an existing instance of the D-Bus daemon thus we
327  *     usually don't activate D-Bus services that are not yet installed into the
328  *     target system. The #GTestDBus object makes this easier for us by taking care
329  *     of the lower level tasks such as running a private D-Bus daemon and looking
330  *     up uninstalled services in customizable locations, typically in your source code tree.
331  *   </para>
332  *   <para>
333  *     The first thing you will need is a separate service description file for the
334  *     D-Bus daemon. Typically a 'services' subdirectory of your 'tests' directory
335  *     is a good place to put this file.
336  *   </para>
337  *   <para>
338  *     The service file should list your service along with an absolute path to the
339  *     uninstalled service executable in your source tree. Using autotools we would
340  *     achieve this by adding a file such as 'my-server.service.in' in the services
341  *     directory and have it processed by configure.
342  *     <informalexample><programlisting>
343  *     [D-BUS Service]
344  *     Name=org.gtk.GDBus.Examples.ObjectManager
345  *     Exec=@abs_top_builddir@/gio/tests/gdbus-example-objectmanager-server
346  *     </programlisting></informalexample>
347  *     You will also need to indicate this service directory in your test
348  *     fixtures, so you will need to pass the path while compiling your
349  *     test cases. Typically this is done with autotools with an added
350  *     preprocessor flag specified to compile your tests such as:
351  *     <informalexample><programlisting>
352  *     -DTEST_SERVICES=\""$(abs_top_builddir)/tests/services"\"
353  *     </programlisting></informalexample>
354  *   </para>
355  *   <para>
356  *     Once you have a service definition file which is local to your source tree,
357  *     you can proceed to setup a GTest fixture using the GTestDBus scaffolding.
358  *     <example id="gdbus-test-fixture">
359  *       <title>Test Fixture for D-Bus services</title>
360  *       <programlisting>
361  *         <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-test-fixture.c">
362  *           <xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback>
363  *         </xi:include>
364  *       </programlisting>
365  *     </example>
366  *   </para>
367  *   <para>
368  *     Note that these examples only deal with isolating the D-Bus aspect of your
369  *     service. To successfully run isolated unit tests on your service you may need
370  *     some additional modifications to your test case fixture. For example; if your
371  *     service uses GSettings and installs a schema then it is important that your test service
372  *     not load the schema in the ordinary installed location (chances are that your service
373  *     and schema files are not yet installed, or worse; there is an older version of the
374  *     schema file sitting in the install location).
375  *   </para>
376  *   <para>
377  *     Most of the time we can work around these obstacles using the environment. Since the
378  *     environment is inherited by the D-Bus daemon created by GTestDBus and then in turn
379  *     inherited by any services the D-Bus daemon activates, using the setup routine for your
380  *     fixture is a practical place to help sandbox your runtime environment. For the rather
381  *     typical GSettings case we can work around this by setting GSETTINGS_SCHEMA_DIR to the
382  *     in tree directory holding your schemas in the above fixture_setup() routine.
383  *   </para>
384  *   <para>
385  *     The GSettings schemas need to be locally pre-compiled for this to work. This can be achieved
386  *     by compiling the schemas locally as a step before running test cases, an autotools setup might
387  *     do the following in the directory holding schemas:
388  *     <informalexample><programlisting>
389  *     all-am:
390  *             $(GLIB_COMPILE_SCHEMAS) .
391  *
392  *     CLEANFILES += gschemas.compiled
393  *     </programlisting></informalexample>
394  *   </para>
395  * </refsect2>
396  */
397
398 typedef struct _GTestDBusClass   GTestDBusClass;
399 typedef struct _GTestDBusPrivate GTestDBusPrivate;
400
401 /**
402  * GTestDBus:
403  *
404  * The #GTestDBus structure contains only private data and
405  * should only be accessed using the provided API.
406  *
407  * Since: 2.34
408  */
409 struct _GTestDBus {
410   GObject parent;
411
412   GTestDBusPrivate *priv;
413 };
414
415 struct _GTestDBusClass {
416   GObjectClass parent_class;
417 };
418
419 struct _GTestDBusPrivate
420 {
421   GTestDBusFlags flags;
422   GPtrArray *service_dirs;
423   GPid bus_pid;
424   gchar *bus_address;
425   gboolean up;
426 };
427
428 enum
429 {
430   PROP_0,
431   PROP_FLAGS,
432 };
433
434 G_DEFINE_TYPE (GTestDBus, g_test_dbus, G_TYPE_OBJECT)
435
436 static void
437 g_test_dbus_init (GTestDBus *self)
438 {
439   self->priv = G_TYPE_INSTANCE_GET_PRIVATE ((self), G_TYPE_TEST_DBUS,
440       GTestDBusPrivate);
441
442   self->priv->service_dirs = g_ptr_array_new_with_free_func (g_free);
443 }
444
445 static void
446 g_test_dbus_dispose (GObject *object)
447 {
448   GTestDBus *self = (GTestDBus *) object;
449
450   if (self->priv->up)
451     g_test_dbus_down (self);
452
453   G_OBJECT_CLASS (g_test_dbus_parent_class)->dispose (object);
454 }
455
456 static void
457 g_test_dbus_finalize (GObject *object)
458 {
459   GTestDBus *self = (GTestDBus *) object;
460
461   g_ptr_array_unref (self->priv->service_dirs);
462   g_free (self->priv->bus_address);
463
464   G_OBJECT_CLASS (g_test_dbus_parent_class)->finalize (object);
465 }
466
467 static void
468 g_test_dbus_get_property (GObject *object,
469     guint property_id,
470     GValue *value,
471     GParamSpec *pspec)
472 {
473   GTestDBus *self = (GTestDBus *) object;
474
475   switch (property_id)
476     {
477       case PROP_FLAGS:
478         g_value_set_flags (value, g_test_dbus_get_flags (self));
479         break;
480       default:
481         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
482         break;
483     }
484 }
485
486 static void
487 g_test_dbus_set_property (GObject *object,
488     guint property_id,
489     const GValue *value,
490     GParamSpec *pspec)
491 {
492   GTestDBus *self = (GTestDBus *) object;
493
494   switch (property_id)
495     {
496       case PROP_FLAGS:
497         self->priv->flags = g_value_get_flags (value);
498         break;
499       default:
500         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
501         break;
502     }
503 }
504
505 static void
506 g_test_dbus_class_init (GTestDBusClass *klass)
507 {
508   GObjectClass *object_class = G_OBJECT_CLASS (klass);
509
510   object_class->dispose = g_test_dbus_dispose;
511   object_class->finalize = g_test_dbus_finalize;
512   object_class->get_property = g_test_dbus_get_property;
513   object_class->set_property = g_test_dbus_set_property;
514
515   g_type_class_add_private (object_class, sizeof (GTestDBusPrivate));
516
517   /**
518    * GTestDBus:flags:
519    *
520    * #GTestDBusFlags specifying the behaviour of the dbus session
521    *
522    * Since: 2.34
523    */
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));
531
532 }
533
534 static gchar *
535 write_config_file (GTestDBus *self)
536 {
537   GString *contents;
538   gint fd;
539   guint i;
540   GError *error = NULL;
541   gchar *path = NULL;
542
543   fd = g_file_open_tmp ("g-test-dbus-XXXXXX", &path, &error);
544   g_assert_no_error (error);
545
546   contents = g_string_new (NULL);
547   g_string_append (contents,
548       "<busconfig>\n"
549       "  <type>session</type>\n"
550 #ifdef G_OS_WIN32
551       "  <listen>nonce-tcp:</listen>\n"
552 #else
553       "  <listen>unix:tmpdir=/tmp</listen>\n"
554 #endif
555                    );
556
557   for (i = 0; i < self->priv->service_dirs->len; i++)
558     {
559       const gchar *path = g_ptr_array_index (self->priv->service_dirs, i);
560
561       g_string_append_printf (contents,
562           "  <servicedir>%s</servicedir>\n", path);
563     }
564
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"
573       "  </policy>\n"
574       "</busconfig>\n");
575
576   g_file_set_contents (path, contents->str, contents->len, &error);
577   g_assert_no_error (error);
578
579   g_string_free (contents, TRUE);
580
581   close (fd);
582
583   return path;
584 }
585
586 static void
587 start_daemon (GTestDBus *self)
588 {
589   gchar *argv[] = {"dbus-daemon", "--print-address", "--config-file=foo", NULL};
590   gchar *config_path;
591   gchar *config_arg;
592   gint stdout_fd;
593   GIOChannel *channel;
594   gsize termpos;
595   GError *error = NULL;
596
597   if (g_getenv ("G_TEST_DBUS_DAEMON") != NULL)
598     argv[0] = (gchar *)g_getenv ("G_TEST_DBUS_DAEMON");
599
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;
604
605   /* Spawn dbus-daemon */
606   g_spawn_async_with_pipes (NULL,
607                             argv,
608                             NULL,
609 #ifdef G_OS_WIN32
610                             /* We Need this to get the pid returned on win32 */
611                             G_SPAWN_DO_NOT_REAP_CHILD |
612 #endif
613                             G_SPAWN_SEARCH_PATH,
614                             NULL,
615                             NULL,
616                             &self->priv->bus_pid,
617                             NULL,
618                             &stdout_fd,
619                             NULL,
620                             &error);
621   g_assert_no_error (error);
622
623   _g_test_watcher_add_pid (self->priv->bus_pid);
624
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,
628       &termpos, &error);
629   g_assert_no_error (error);
630   self->priv->bus_address[termpos] = '\0';
631
632   /* start dbus-monitor */
633   if (g_getenv ("G_DBUS_MONITOR") != NULL)
634     {
635       gchar *command;
636
637       command = g_strdup_printf ("dbus-monitor --address %s",
638           self->priv->bus_address);
639       g_spawn_command_line_async (command, NULL);
640       g_free (command);
641
642       g_usleep (500 * 1000);
643     }
644
645   /* Cleanup */
646   g_io_channel_shutdown (channel, FALSE, &error);
647   g_assert_no_error (error);
648   g_io_channel_unref (channel);
649
650   /* Don't use g_file_delete since it calls into gvfs */
651   if (g_unlink (config_path) != 0)
652     g_assert_not_reached ();
653
654   g_free (config_path);
655   g_free (config_arg);
656 }
657
658 static void
659 stop_daemon (GTestDBus *self)
660 {
661 #ifdef G_OS_WIN32
662   if (!TerminateProcess (self->priv->bus_pid, 0))
663     g_warning ("Can't terminate process: %s", g_win32_error_message (GetLastError()));
664 #else
665   kill (self->priv->bus_pid, SIGTERM);
666 #endif
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;
670
671   g_free (self->priv->bus_address);
672   self->priv->bus_address = NULL;
673 }
674
675 /**
676  * g_test_dbus_new:
677  * @flags: a #GTestDBusFlags
678  *
679  * Create a new #GTestDBus object.
680  *
681  * Returns: (transfer full): a new #GTestDBus.
682  */
683 GTestDBus *
684 g_test_dbus_new (GTestDBusFlags flags)
685 {
686   return g_object_new (G_TYPE_TEST_DBUS,
687       "flags", flags,
688       NULL);
689 }
690
691 /**
692  * g_test_dbus_get_flags:
693  * @self: a #GTestDBus
694  *
695  * Gets the flags of the #GTestDBus object.
696  *
697  * Returns: the value of #GTestDBus:flags property
698  */
699 GTestDBusFlags
700 g_test_dbus_get_flags (GTestDBus *self)
701 {
702   g_return_val_if_fail (G_IS_TEST_DBUS (self), G_TEST_DBUS_NONE);
703
704   return self->priv->flags;
705 }
706
707 /**
708  * g_test_dbus_get_bus_address:
709  * @self: a #GTestDBus
710  *
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()
714  *
715  * Returns: the address of the bus, or %NULL.
716  */
717 const gchar *
718 g_test_dbus_get_bus_address (GTestDBus *self)
719 {
720   g_return_val_if_fail (G_IS_TEST_DBUS (self), NULL);
721
722   return self->priv->bus_address;
723 }
724
725 /**
726  * g_test_dbus_add_service_dir:
727  * @self: a #GTestDBus
728  * @path: path to a directory containing .service files
729  *
730  * Add a path where dbus-daemon will lookup for .services files. This can't be
731  * called after g_test_dbus_up().
732  */
733 void
734 g_test_dbus_add_service_dir (GTestDBus *self,
735     const gchar *path)
736 {
737   g_return_if_fail (G_IS_TEST_DBUS (self));
738   g_return_if_fail (self->priv->bus_address == NULL);
739
740   g_ptr_array_add (self->priv->service_dirs, g_strdup (path));
741 }
742
743 /**
744  * g_test_dbus_up:
745  * @self: a #GTestDBus
746  *
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.
749  *
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.
752  *
753  * If this function is called from unit test's main(), then g_test_dbus_down()
754  * must be called after g_test_run().
755  */
756 void
757 g_test_dbus_up (GTestDBus *self)
758 {
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);
762
763   start_daemon (self);
764
765   g_setenv ("DBUS_SESSION_BUS_ADDRESS", self->priv->bus_address, TRUE);
766   self->priv->up = TRUE;
767 }
768
769
770 /**
771  * g_test_dbus_stop:
772  * @self: a #GTestDBus
773  *
774  * Stop the session bus started by g_test_dbus_up().
775  *
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.
780  */
781 void
782 g_test_dbus_stop (GTestDBus *self)
783 {
784   g_return_if_fail (G_IS_TEST_DBUS (self));
785   g_return_if_fail (self->priv->bus_address != NULL);
786
787   stop_daemon (self);
788 }
789
790 /**
791  * g_test_dbus_down:
792  * @self: a #GTestDBus
793  *
794  * Stop the session bus started by g_test_dbus_up().
795  *
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.
799  */
800 void
801 g_test_dbus_down (GTestDBus *self)
802 {
803   GDBusConnection *connection;
804
805   g_return_if_fail (G_IS_TEST_DBUS (self));
806   g_return_if_fail (self->priv->up);
807
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);
811
812   if (self->priv->bus_address != NULL)
813     stop_daemon (self);
814
815   if (connection != NULL)
816     _g_object_unref_and_wait_weak_notify (connection);
817
818   g_unsetenv ("DBUS_SESSION_BUS_ADDRESS");
819   self->priv->up = FALSE;
820 }
821
822 /**
823  * g_test_dbus_unset:
824  *
825  * Unset DISPLAY and DBUS_SESSION_BUS_ADDRESS env variables to ensure the test
826  * won't use user's session bus.
827  *
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.
831  */
832 void
833 g_test_dbus_unset (void)
834 {
835   g_unsetenv ("DISPLAY");
836   g_unsetenv ("DBUS_SESSION_BUS_ADDRESS");
837 }