collection: Have gobject-introspection and glib-mkenums recognize flags
[platform/upstream/libsecret.git] / libsecret / tests / mock-service.c
1 /* libsecret - GLib wrapper for Secret Service
2  *
3  * Copyright 2011 Red Hat Inc.
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU Lesser General Public License as published
7  * by the Free Software Foundation; either version 2 of the licence or (at
8  * your option) any later version.
9  *
10  * See the included COPYING file for more information.
11  *
12  * Author: Stef Walter <stefw@gnome.org>
13  */
14
15
16 #include "config.h"
17
18 #include "mock-service.h"
19
20 #include "secret-private.h"
21
22 #include <errno.h>
23 #include <stdio.h>
24
25 static GPid pid = 0;
26
27 gboolean
28 mock_service_start (const gchar *mock_script,
29                     GError **error)
30 {
31         gchar ready[8] = { 0, };
32         GSpawnFlags flags;
33         int wait_pipe[2];
34         GPollFD poll_fd;
35         gboolean ret;
36         gint polled;
37
38         gchar *argv[] = {
39                 "python", (gchar *)mock_script,
40                 "--name", MOCK_SERVICE_NAME,
41                 "--ready", ready,
42                 NULL
43         };
44
45         g_return_val_if_fail (mock_script != NULL, FALSE);
46         g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
47
48         g_setenv ("SECRET_SERVICE_BUS_NAME", MOCK_SERVICE_NAME, TRUE);
49
50         if (pipe (wait_pipe) < 0) {
51                 g_set_error_literal (error, G_IO_ERROR, g_io_error_from_errno (errno),
52                                      "Couldn't create pipe for mock service");
53                 return FALSE;
54         }
55
56         snprintf (ready, sizeof (ready), "%d", wait_pipe[1]);
57
58         flags = G_SPAWN_SEARCH_PATH | G_SPAWN_LEAVE_DESCRIPTORS_OPEN;
59         ret = g_spawn_async (SRCDIR, argv, NULL, flags, NULL, NULL, &pid, error);
60
61         close (wait_pipe[1]);
62
63         if (ret) {
64                 poll_fd.events = G_IO_IN | G_IO_HUP | G_IO_ERR;
65                 poll_fd.fd = wait_pipe[0];
66                 poll_fd.revents = 0;
67
68                 polled = g_poll (&poll_fd, 1, 2000);
69                 if (polled < -1)
70                         g_warning ("couldn't poll file descirptor: %s", g_strerror (errno));
71                 if (polled != 1)
72                         g_warning ("couldn't wait for mock service");
73         }
74
75         close (wait_pipe[0]);
76         return ret;
77 }
78
79 void
80 mock_service_stop (void)
81 {
82         if (!pid)
83                 return;
84
85         if (kill (pid, SIGTERM) < 0) {
86                 if (errno != ESRCH)
87                         g_warning ("kill() failed: %s", g_strerror (errno));
88         }
89
90         g_spawn_close_pid (pid);
91         pid = 0;
92 }