Add GTestDBus object
[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 <unistd.h>
30
31 #include <glib.h>
32
33 #include "gdbus-tests.h"
34 #include "gdbusconnection.h"
35 #include "gdbusprivate.h"
36 #include "gfile.h"
37 #include "gioenumtypes.h"
38 #include "gtestdbus.h"
39
40 #include "glibintl.h"
41
42 /* -------------------------------------------------------------------------- */
43 /* Utilities to cleanup the mess in the case unit test process crash */
44
45 #define ADD_PID_FORMAT "add pid %d\n"
46 #define REMOVE_PID_FORMAT "remove pid %d\n"
47
48 static void
49 watch_parent (gint fd)
50 {
51   GIOChannel *channel;
52   GPollFD fds[1];
53   GArray *pids_to_kill;
54
55   channel = g_io_channel_unix_new (fd);
56
57   fds[0].fd = fd;
58   fds[0].events = G_IO_HUP | G_IO_IN;
59   fds[0].revents = 0;
60
61   pids_to_kill = g_array_new (FALSE, FALSE, sizeof (guint));
62
63   do
64     {
65       gint num_events;
66       gchar *command = NULL;
67       guint pid;
68       guint n;
69       GError *error = NULL;
70
71       num_events = g_poll (fds, 1, -1);
72       if (num_events == 0)
73         continue;
74
75       if (fds[0].revents == G_IO_HUP)
76         {
77           /* Parent quit, cleanup the mess and exit */
78           for (n = 0; n < pids_to_kill->len; n++)
79             {
80               pid = g_array_index (pids_to_kill, guint, n);
81               g_print ("cleaning up pid %d\n", pid);
82               kill (pid, SIGTERM);
83             }
84
85           g_array_unref (pids_to_kill);
86           g_io_channel_shutdown (channel, FALSE, &error);
87           g_assert_no_error (error);
88           g_io_channel_unref (channel);
89
90           exit (0);
91         }
92
93       /* Read the command from the input */
94       g_io_channel_read_line (channel, &command, NULL, NULL, &error);
95       g_assert_no_error (error);
96
97       /* Check for known commands */
98       if (sscanf (command, ADD_PID_FORMAT, &pid) == 1)
99         {
100           g_array_append_val (pids_to_kill, pid);
101         }
102       else if (sscanf (command, REMOVE_PID_FORMAT, &pid) == 1)
103         {
104           for (n = 0; n < pids_to_kill->len; n++)
105             {
106               if (g_array_index (pids_to_kill, guint, n) == pid)
107                 {
108                   g_array_remove_index (pids_to_kill, n);
109                   pid = 0;
110                   break;
111                 }
112             }
113           if (pid != 0)
114             {
115               g_warning ("unknown pid %d to remove", pid);
116             }
117         }
118       else
119         {
120           g_warning ("unknown command from parent '%s'", command);
121         }
122
123       g_free (command);
124     }
125   while (TRUE);
126 }
127
128 static GIOChannel *
129 watcher_init (void)
130 {
131   static gsize started = 0;
132   static GIOChannel *channel = NULL;
133
134   if (g_once_init_enter (&started))
135     {
136       gint pipe_fds[2];
137
138       /* fork a child to clean up when we are killed */
139       if (pipe (pipe_fds) != 0)
140         {
141           g_warning ("pipe() failed: %m");
142           g_assert_not_reached ();
143         }
144
145       switch (fork ())
146         {
147         case -1:
148           g_warning ("fork() failed: %m");
149           g_assert_not_reached ();
150           break;
151
152         case 0:
153           /* child */
154           close (pipe_fds[1]);
155           watch_parent (pipe_fds[0]);
156           break;
157
158         default:
159           /* parent */
160           close (pipe_fds[0]);
161           channel = g_io_channel_unix_new (pipe_fds[1]);
162         }
163
164       g_once_init_leave (&started, 1);
165     }
166
167   return channel;
168 }
169
170 static void
171 watcher_send_command (const gchar *command)
172 {
173   GIOChannel *channel;
174   GError *error = NULL;
175
176   channel = watcher_init ();
177
178   g_io_channel_write_chars (channel, command, -1, NULL, &error);
179   g_assert_no_error (error);
180
181   g_io_channel_flush (channel, &error);
182   g_assert_no_error (error);
183 }
184
185 /* This could be interesting to expose in public API */
186 static void
187 _g_test_watcher_add_pid (GPid pid)
188 {
189   gchar *command;
190
191   command = g_strdup_printf (ADD_PID_FORMAT, (guint) pid);
192   watcher_send_command (command);
193   g_free (command);
194 }
195
196 static void
197 _g_test_watcher_remove_pid (GPid pid)
198 {
199   gchar *command;
200
201   command = g_strdup_printf (REMOVE_PID_FORMAT, (guint) pid);
202   watcher_send_command (command);
203   g_free (command);
204 }
205
206 /* -------------------------------------------------------------------------- */
207 /* GTestDBus object implementation */
208
209 /**
210  * SECTION:gtestdbus
211  * @short_description: D-Bus testing helper
212  * @include: gio/gio.h
213  *
214  * Helper to test D-Bus code wihtout messing up with user' session bus.
215  *
216  * Since: 2.34
217  */
218
219 typedef struct _GTestDBusClass   GTestDBusClass;
220 typedef struct _GTestDBusPrivate GTestDBusPrivate;
221
222 /**
223  * GTestDBus:
224  *
225  * The #GTestDBus structure contains only private data and
226  * should only be accessed using the provided API.
227  *
228  * Since: 2.34
229  */
230 struct _GTestDBus {
231   GObject parent;
232
233   GTestDBusPrivate *priv;
234 };
235
236 /**
237  * GTestDBusClass:
238  *
239  * Class structure for #GTestDBus.
240  *
241  * Since: 2.34
242  */
243 struct _GTestDBusClass {
244   GObjectClass parent_class;
245 };
246
247 struct _GTestDBusPrivate
248 {
249   GTestDBusFlags flags;
250   GPtrArray *service_dirs;
251   GPid bus_pid;
252   gchar *bus_address;
253   gboolean up;
254 };
255
256 enum
257 {
258   PROP_0,
259   PROP_FLAGS,
260 };
261
262 G_DEFINE_TYPE (GTestDBus, g_test_dbus, G_TYPE_OBJECT)
263
264 static void
265 g_test_dbus_init (GTestDBus *self)
266 {
267   self->priv = G_TYPE_INSTANCE_GET_PRIVATE ((self), G_TYPE_TEST_DBUS,
268       GTestDBusPrivate);
269
270   self->priv->service_dirs = g_ptr_array_new_with_free_func (g_free);
271 }
272
273 static void
274 g_test_dbus_dispose (GObject *object)
275 {
276   GTestDBus *self = (GTestDBus *) object;
277
278   if (self->priv->up)
279     g_test_dbus_down (self);
280
281   G_OBJECT_CLASS (g_test_dbus_parent_class)->dispose (object);
282 }
283
284 static void
285 g_test_dbus_finalize (GObject *object)
286 {
287   GTestDBus *self = (GTestDBus *) object;
288
289   g_ptr_array_unref (self->priv->service_dirs);
290   g_free (self->priv->bus_address);
291
292   G_OBJECT_CLASS (g_test_dbus_parent_class)->finalize (object);
293 }
294
295 static void
296 g_test_dbus_get_property (GObject *object,
297     guint property_id,
298     GValue *value,
299     GParamSpec *pspec)
300 {
301   GTestDBus *self = (GTestDBus *) object;
302
303   switch (property_id)
304     {
305       case PROP_FLAGS:
306         g_value_set_flags (value, g_test_dbus_get_flags (self));
307         break;
308       default:
309         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
310         break;
311     }
312 }
313
314 static void
315 g_test_dbus_set_property (GObject *object,
316     guint property_id,
317     const GValue *value,
318     GParamSpec *pspec)
319 {
320   GTestDBus *self = (GTestDBus *) object;
321
322   switch (property_id)
323     {
324       case PROP_FLAGS:
325         self->priv->flags = g_value_get_flags (value);
326         break;
327       default:
328         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
329         break;
330     }
331 }
332
333 static void
334 g_test_dbus_class_init (GTestDBusClass *klass)
335 {
336   GObjectClass *object_class = G_OBJECT_CLASS (klass);
337
338   object_class->dispose = g_test_dbus_dispose;
339   object_class->finalize = g_test_dbus_finalize;
340   object_class->get_property = g_test_dbus_get_property;
341   object_class->set_property = g_test_dbus_set_property;
342
343   g_type_class_add_private (object_class, sizeof (GTestDBusPrivate));
344
345   /**
346    * GTestDBus:flags:
347    *
348    * #GTestDBusFlags specifying the behaviour of the dbus session
349    *
350    * Since: 2.34
351    */
352   g_object_class_install_property (object_class, PROP_FLAGS,
353     g_param_spec_flags ("flags",
354                         P_("dbus session flags"),
355                         P_("Flags specifying the behaviour of the dbus session"),
356                         G_TYPE_TEST_DBUS_FLAGS, G_TEST_DBUS_NONE,
357                         G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
358                         G_PARAM_STATIC_STRINGS));
359
360 }
361
362 static GFile *
363 write_config_file (GTestDBus *self)
364 {
365   GString *contents;
366   GFile *file;
367   GFileIOStream *iostream;
368   guint i;
369   GError *error = NULL;
370
371   file = g_file_new_tmp ("g-test-dbus-XXXXXX", &iostream, &error);
372   g_assert_no_error (error);
373   g_object_unref (iostream);
374
375   contents = g_string_new (NULL);
376   g_string_append (contents,
377       "<busconfig>\n"
378       "  <type>session</type>\n"
379       "  <listen>unix:tmpdir=/tmp</listen>\n");
380
381   for (i = 0; i < self->priv->service_dirs->len; i++)
382     {
383       const gchar *path = g_ptr_array_index (self->priv->service_dirs, i);
384
385       g_string_append_printf (contents,
386           "  <servicedir>%s</servicedir>\n", path);
387     }
388
389   g_string_append (contents,
390       "  <policy context=\"default\">\n"
391       "    <!-- Allow everything to be sent -->\n"
392       "    <allow send_destination=\"*\" eavesdrop=\"true\"/>\n"
393       "    <!-- Allow everything to be received -->\n"
394       "    <allow eavesdrop=\"true\"/>\n"
395       "    <!-- Allow anyone to own anything -->\n"
396       "    <allow own=\"*\"/>\n"
397       "  </policy>\n"
398       "</busconfig>\n");
399
400   g_file_replace_contents (file, contents->str, contents->len,
401       NULL, FALSE, G_FILE_CREATE_NONE, NULL, NULL, &error);
402   g_assert_no_error (error);
403
404   g_string_free (contents, TRUE);
405
406   return file;
407 }
408
409 static void
410 start_daemon (GTestDBus *self)
411 {
412   gchar *argv[] = {"dbus-daemon", "--print-address", "--config-file=foo", NULL};
413   GFile *file;
414   gchar *config_path;
415   gchar *config_arg;
416   gint stdout_fd;
417   GIOChannel *channel;
418   gsize termpos;
419   GError *error = NULL;
420
421   /* Write config file and set its path in argv */
422   file = write_config_file (self);
423   config_path = g_file_get_path (file);
424   config_arg = g_strdup_printf ("--config-file=%s", config_path);
425   argv[2] = config_arg;
426
427   /* Spawn dbus-daemon */
428   g_spawn_async_with_pipes (NULL,
429                             argv,
430                             NULL,
431                             G_SPAWN_SEARCH_PATH,
432                             NULL,
433                             NULL,
434                             &self->priv->bus_pid,
435                             NULL,
436                             &stdout_fd,
437                             NULL,
438                             &error);
439   g_assert_no_error (error);
440
441   _g_test_watcher_add_pid (self->priv->bus_pid);
442
443   /* Read bus address from daemon' stdout */
444   channel = g_io_channel_unix_new (stdout_fd);
445   g_io_channel_read_line (channel, &self->priv->bus_address, NULL,
446       &termpos, &error);
447   g_assert_no_error (error);
448   self->priv->bus_address[termpos] = '\0';
449
450   /* start dbus-monitor */
451   if (g_getenv ("G_DBUS_MONITOR") != NULL)
452     {
453       gchar *command;
454
455       command = g_strdup_printf ("dbus-monitor --address %s",
456           self->priv->bus_address);
457       g_spawn_command_line_async (command, NULL);
458       g_free (command);
459
460       usleep (500 * 1000);
461     }
462
463   /* Cleanup */
464   g_io_channel_shutdown (channel, FALSE, &error);
465   g_assert_no_error (error);
466   g_io_channel_unref (channel);
467
468   g_file_delete (file, NULL, &error);
469   g_assert_no_error (error);
470   g_object_unref (file);
471
472   g_free (config_path);
473   g_free (config_arg);
474 }
475
476 static void
477 stop_daemon (GTestDBus *self)
478 {
479   kill (self->priv->bus_pid, SIGTERM);
480   _g_test_watcher_remove_pid (self->priv->bus_pid);
481   self->priv->bus_pid = 0;
482
483   g_free (self->priv->bus_address);
484   self->priv->bus_address = NULL;
485 }
486
487 /**
488  * g_test_dbus_new:
489  * @flags: a #GTestDBusFlags
490  *
491  * Create a new #GTestDBus object.
492  *
493  * Returns: (transfer full): a new #GTestDBus.
494  */
495 GTestDBus *
496 g_test_dbus_new (GTestDBusFlags flags)
497 {
498   return g_object_new (G_TYPE_TEST_DBUS,
499       "flags", flags,
500       NULL);
501 }
502
503 /**
504  * g_test_dbus_get_flags:
505  * @self: a #GTestDBus
506  *
507  * Returns: the value of #GTestDBus:flags property
508  */
509 GTestDBusFlags
510 g_test_dbus_get_flags (GTestDBus *self)
511 {
512   g_return_val_if_fail (G_IS_TEST_DBUS (self), G_TEST_DBUS_NONE);
513
514   return self->priv->flags;
515 }
516
517 /**
518  * g_test_dbus_get_bus_address:
519  * @self: a #GTestDBus
520  *
521  * Get the address on which dbus-daemon is running. if g_test_dbus_up() has not
522  * been called yet, %NULL is returned. This can be used with
523  * g_dbus_connection_new_for_address()
524  *
525  * Returns: the address of the bus, or %NULL.
526  */
527 const gchar *
528 g_test_dbus_get_bus_address (GTestDBus *self)
529 {
530   g_return_val_if_fail (G_IS_TEST_DBUS (self), NULL);
531
532   return self->priv->bus_address;
533 }
534
535 /**
536  * g_test_dbus_add_service_dir:
537  * @self: a #GTestDBus
538  * @path: path to a directory containing .service files
539  *
540  * Add a path where dbus-daemon will lookup for .services files. This can't be
541  * called after g_test_dbus_up().
542  */
543 void
544 g_test_dbus_add_service_dir (GTestDBus *self,
545     const gchar *path)
546 {
547   g_return_if_fail (G_IS_TEST_DBUS (self));
548   g_return_if_fail (self->priv->bus_address == NULL);
549
550   g_ptr_array_add (self->priv->service_dirs, g_strdup (path));
551 }
552
553 /**
554  * g_test_dbus_up:
555  * @self: a #GTestDBus
556  *
557  * Start a dbus-daemon instance and set DBUS_SESSION_BUS_ADDRESS. After this
558  * call, it is safe for unit tests to start sending messages on the session bug.
559  *
560  * If this function is called from setup callback of g_test_add(),
561  * g_test_dbus_down() must be called in its teardown callback.
562  *
563  * If this function is called from unit test's main(), then g_test_dbus_down()
564  * must be called after g_test_run().
565  */
566 void
567 g_test_dbus_up (GTestDBus *self)
568 {
569   g_return_if_fail (G_IS_TEST_DBUS (self));
570   g_return_if_fail (self->priv->bus_address == NULL);
571   g_return_if_fail (!self->priv->up);
572
573   start_daemon (self);
574
575   g_setenv ("DBUS_SESSION_BUS_ADDRESS", self->priv->bus_address, TRUE);
576   self->priv->up = TRUE;
577 }
578
579
580 /**
581  * g_test_dbus_stop:
582  * @self: a #GTestDBus
583  *
584  * Stop the session bus started by g_test_dbus_up().
585  *
586  * Unlike g_test_dbus_down(), this won't verify the #GDBusConnection
587  * singleton returned by g_bus_get() or g_bus_get_sync() is destroyed. Unit
588  * tests wanting to verify behaviour after the session bus has been stopped
589  * can use this function but should still call g_test_dbus_down() when done.
590  */
591 void
592 g_test_dbus_stop (GTestDBus *self)
593 {
594   g_return_if_fail (G_IS_TEST_DBUS (self));
595   g_return_if_fail (self->priv->bus_address != NULL);
596
597   stop_daemon (self);
598 }
599
600 /**
601  * g_test_dbus_down:
602  * @self: a #GTestDBus
603  *
604  * Stop the session bus started by g_test_dbus_up().
605  *
606  * This will wait for the singleton returned by g_bus_get() or g_bus_get_sync()
607  * is destroyed. This is done to ensure that the next unit test won't get a
608  * leaked singleton from this test.
609  */
610 void
611 g_test_dbus_down (GTestDBus *self)
612 {
613   GDBusConnection *connection;
614
615   g_return_if_fail (G_IS_TEST_DBUS (self));
616   g_return_if_fail (self->priv->up);
617
618   connection = _g_bus_get_singleton_if_exists (G_BUS_TYPE_SESSION);
619   if (connection != NULL)
620     g_dbus_connection_set_exit_on_close (connection, FALSE);
621
622   if (self->priv->bus_address != NULL)
623     stop_daemon (self);
624
625   if (connection != NULL)
626     {
627       _g_object_wait_for_single_ref (connection);
628       g_object_unref (connection);
629     }
630
631   g_unsetenv ("DBUS_SESSION_BUS_ADDRESS");
632   self->priv->up = FALSE;
633 }
634
635 /**
636  * g_test_dbus_unset:
637  *
638  * Unset DISPLAY and DBUS_SESSION_BUS_ADDRESS env variables to ensure the test
639  * won't use user's session bus.
640  *
641  * This is useful for unit tests that want to verify behaviour when no session
642  * bus is running. It is not necessary to call this if unit test already calls
643  * g_test_dbus_up() before acquiring the session bus.
644  */
645 void
646 g_test_dbus_unset (void)
647 {
648   g_unsetenv ("DISPLAY");
649   g_unsetenv ("DBUS_SESSION_BUS_ADDRESS");
650 }