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