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