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