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