File: asynchelpers.vala

package info (click to toggle)
libfsoframework 0.12.0-5
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 5,640 kB
  • ctags: 8,717
  • sloc: ansic: 52,981; sh: 11,367; makefile: 819
file content (237 lines) | stat: -rw-r--r-- 9,250 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
/*
 * Valadate - Unit testing library for GObject-based libraries.
 * Copyright (C) 2009-2012  Jan Hudec <bulb@ucw.cz>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

using GLib;

namespace FsoFramework.Test
{
    public delegate bool Predicate();
    public delegate void Block();
    public delegate void AsyncBegin(AsyncReadyCallback callback);
    public delegate void CancelableAsyncBegin(Cancellable cancel, AsyncReadyCallback callback);
    public delegate void AsyncFinish(AsyncResult result) throws GLib.Error;

    private class SignalWaiter
    {
        public MainLoop loop = new MainLoop(MainContext.default(), true);
        public bool succeeded = false;
        public Predicate predicate;

        public SignalWaiter(owned Predicate predicate)
        {
            this.predicate = predicate;
        }

        public int callback()
        {
            if(predicate())
            {
                succeeded = true;
                loop.quit();
            }

            return 0;
        }

        public bool abort()
        {
            loop.quit();
            return false;
        }
    }

    /**
     * Wait until a condition becomes true.
     *
     * Waits until a condition becomes true. The condition is checked
     * at the begining and than each time emitter emits signal signame.
     * This can be used to check asynchronous functionality that uses
     * signals to signal completion when the first emission does not
     * necessarily imply the desired state was reached.
     *
     * @param timeout Maximum timeout to wait for the emission, in
     * milliseconds.
     * @param emitter The object that will emit signal.
     * @param signame Name of the signal to wait for. May include detail
     * (in the format used by g_signal_connect).
     * @param predicate Function that will be called to test whether the
     * waited-for condition occured. The wait will continue until this
     * function returns true.
     * @param block Function that will start the asynchronous operation.
     * The function will register the signal if it's emitted
     * synchronously from block, while obviously it cannot notice if it
     * is emitted before.
     * @return true if the condition became true, false otherwise.
     */
    public bool wait_for_condition(int timeout, Object emitter, string signame, owned Predicate predicate, Block block)
    {
        // FIXME: The fixture should push a new context in set_up and
        // pop it back on clean-up! (But it's GLib 2.21.0+ and
        // I still have 2.20.4)
        var waiter = new SignalWaiter(predicate);
        // Connect to the signal
        var sh = Signal.connect_swapped(emitter, signame, (Callback)SignalWaiter.callback, waiter);
        // Run the block to trigger the signal
        block();
        // Check whether the condition is not true already
        waiter.callback();
        // Plan timeout
        var t1 = Timeout.add(timeout, waiter.abort);
        // Run the loop if it was not quit yet.
        if(waiter.loop.is_running())
            waiter.loop.run();
        // Disconnect from singnal
        SignalHandler.disconnect(emitter, sh);
        // Cancel timer
        Source.remove(t1);
        // Return whether the callback succeeded.
        return waiter.succeeded;
    }

    /**
     * Wait for signal to be emited.
     *
     * Waits at most timeout for given signal to be emited and return
     * whether the signal was emited. Runs main loop while waiting. This
     * can be used to test asynchronous functionality using signals to
     * signal completion.
     *
     * @param timeout Maximum timeout to wait for the emission, in
     * milliseconds.
     * @param emitter The object that will emit signal.
     * @param signame Name of the signal to wait for. May include detail
     * (in the format used by g_signal_connect).
     * @param block Function that will start the asynchronous operation.
     * The function will register the signal if it's emitted
     * synchronously from block, while obviously it cannot notice if it
     * is emitted before.
     * @return true if the signal was emited, false otherwise.
     */
    public bool wait_for_signal(int timeout, Object emitter, string signame, Block block)
    {
        bool condition = false;
        return wait_for_condition(timeout, emitter, signame, () => {
            if(condition)
                return true;
            condition = true;
            return false;
        }, block);
    }

    /**
     * Wait for an async operation to complete.
     *
     * Waits until a async function completes.
     * @param timeout Maximum timeout to wait for completion, in
     * milliseconds.
     * @param async_function The async function to call. The signature
     * corresponds to function declared as
     * {{{
     *     async void async_function()
     * }}}
     * in Vala.
     * @param async_finish The finsih part of the async function. It is
     * assumed it will either assert any problems, or stash the result
     * somewhere.
     * @return ture if the function completed and passed the check, false
     * otherwise.
     * [[warning:
     * If it times out, the async function may run to completion when
     * main loop is entered again later. By that time, the callback data
     * will be destroyed and the callback will crash.
     *
     * This should be avoided by setting new GLib.MainContext for each
     * test case, but that is only available in development 2.21 GLib.
     * ]]
     */
    public bool wait_for_async(int timeout, AsyncBegin async_function, AsyncFinish async_finish) throws GLib.Error
    {
        var loop = new MainLoop(MainContext.default(), true);
        AsyncResult? result = null;
        // Plan the async function
        async_function((o, r) => { result = r; loop.quit(); });
        // Plan timeout
        var t1 = Timeout.add(timeout, () => { loop.quit(); return false; });
        // Run the loop if it was not quit yet.
        if(loop.is_running())
            loop.run();
        // Cancel timer
        Source.remove(t1);
        // Check the outcome
        if(result == null)
            return false;
        async_finish(result);
        return true;
    }

    /**
     * Wait for cancellable async operation to complete.
     *
     * Calls an async function and waits until it completes, at most
     * specified time. If it does not complete in time, it cancels the
     * operation and waits once more the same timeout for the
     * cancellation (it still fails if the cancellation succeeds).
     *
     * @param timeout Maximum timeout to wait for completion, in
     * milliseconds.
     * @param async_function The async function to call. The signature
     * corresponds to function declared as
     * {{{
     *     async void async_function(GLib.Cancellable cancel)
     * }}}
     * in Vala.
     * @param async_finish The finsih part of the async function. It is
     * assumed it will either assert any problems, or stash the result
     * somewhere.
     * @return ture if the function completed (without being cancelled)
     * and passed the check, false otherwise.
     * [[warning:
     * If the cancel fails and it times out second time, the async
     * function may run to completion when main loop is entered again
     * later. By that time, the callback data will be destroyed and the
     * callback will crash.
     *
     * This should be avoided by setting new GLib.MainContext for each
     * test case, but that is only available in development 2.21 GLib.
     * ]]
     */
    public bool wait_for_cancellable_async(int timeout, CancelableAsyncBegin async_function, AsyncFinish async_finish) throws GLib.Error
    {
        var loop = new MainLoop(MainContext.default(), true);
        AsyncResult? result = null;
        var cancel = new Cancellable();
        // Plan the async function
        async_function(cancel, (o, r) => { result = r; loop.quit(); });
        // Plan timeouts
        var t1 = Timeout.add(timeout, () => { cancel.cancel(); return false; });
        var t2 = Timeout.add(2 * timeout, () => { loop.quit(); return false; });
        // Run the loop if it was not quit yet.
        if(loop.is_running())
            loop.run();
        // Cancel timers
        Source.remove(t1);
        Source.remove(t2);
        // Check the outcome
        if(result == null)
            return false; // The async wasn't called at all.
        if(cancel.is_cancelled()) // Only succeed if not cancelled
            return false;
        async_finish(result);
        return true;
    }
}