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