-
Notifications
You must be signed in to change notification settings - Fork 1
/
test_promise.cpp
525 lines (514 loc) · 12.5 KB
/
test_promise.cpp
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
#include <exception>
#include <stdexcept>
#include <thread>
#include <mutex>
#include <condition_variable>
#include "assertion.h"
#include "promise.h"
using namespace std;
using namespace kaiu;
Assertions assert({
{ nullptr, "Immediates" },
{ "IRPR", "Immediately resolved promise resolves" },
{ "IRCPR", "Immediately resolved chained promise resolves" },
{ nullptr, "Transparent finalizers" },
{ "RVPF", "Resolved value passes through finally() stage unaltered" },
{ "JVPF", "Rejection passes through finally() stage unaltered" },
{ nullptr, "Asynchronous promises" },
{ "ARPR", "Asynchronously resolved promise resolved" },
{ "AJPJ", "Asynchronously rejected promise rejected" },
{ nullptr, "Exception handler behaviour" },
{ "EMPJH", "Exception message passes to rejection handler" },
{ "HJRPDV", "Handled rejection results in resolved promise with default value if none specified by handler" },
{ nullptr, "Finalizer behaviour" },
{ "FC", "Finalizer called" },
{ "EFJP", "Exception in finalizer results in rejected promise" },
{ "FCEF", "Finally handler called even on exception in previous finally handler" },
{ nullptr, "Promise combinator (heterogenous)" },
{ "PCR", "Resolves correctly" },
{ "PCJ", "Rejects correctly" },
{ nullptr, "Promise combinator (homogenous)" },
{ "VCR", "Resolves correctly" },
{ "VCJ", "Rejects correctly" },
{ nullptr, "Efficiency" },
{ "NC", "Copy-free promise chaining" },
{ "NCP", "Copy-free heterogenous combinator" },
{ "NCV", "Copy-free homogenous combinator" },
{ nullptr, "Compiler handles optional arguments correctly (statically checked)" },
{ "OATH", "Then: omit 'handler'" },
{ "OATF", "Then: omit 'finalizer'" },
{ nullptr, "Promise monad" },
{ "MONADB1", "Basic flow test #1 (next)" },
{ "MONADB2", "Basic flow test #2 (handler)" },
{ "MONADB3", "Basic flow test #2 (finalizer)" },
{ "MONAD1", "Chain #1" },
{ "MONAD2", "Chain #2" },
{ "MONADE1", "Exception handling #1" },
{ "MONADE2", "Exception handling #2" },
});
void do_async_nonblock(function<void()> op)
{
auto func = [op] () noexcept {
try {
op();
} catch (...) {
assert.print_error();
}
};
thread(func).detach();
}
void flow_test() {
mutex mx;
condition_variable cv;
volatile bool done = false;
promise::resolved(42)
->then(
[] (auto result) {
assert.expect(result, 42, "IRPR");
return 21.0;
},
[] (auto error) {
assert.fail("IRPR");
return 0;
})
->then(
[] (auto result) {
assert.expect(result, 21.0, "IRCPR");
return 69;
},
[] (auto error) {
assert.fail("IRCPR");
return -1;
})
->finally(
[] {
return;
})
->then(
[] (auto result) {
assert.expect(result, 69, "RVPF");
throw runtime_error("oops");
return -1;
},
[] (auto error) {
assert.fail("RVPF");
throw runtime_error("oops");
return -1;
})
->finally(
[] {
return;
})
->then(
[] (auto result) {
assert.fail("JVPF");
return nullptr;
},
[] (auto error) {
try {
rethrow_exception(error);
} catch (const exception& e) {
assert.expect(string(e.what()), string("oops"), "JVPF");
}
return nullptr;
})
->then(
[] (auto result) {
Promise<string> promise;
do_async_nonblock([promise] { promise->resolve("hi"); });
return promise;
})
->then(
[] (auto result) {
assert.expect(result, "hi", "ARPR");
Promise<int> promise;
do_async_nonblock([promise] { promise->reject("failed"); });
return promise;
},
[] (auto error) {
assert.fail("ARPR");
return promise::resolved<int>(-1);
})
->then(
[] (auto result) {
assert.fail("AJPJ");
return result;
})
->except([] (auto error) {
assert.pass("AJPJ");
try {
rethrow_exception(error);
} catch (const exception& e) {
assert.expect(e.what(), string{"failed"}, "EMPJH");
}
return 0;
})
->then(
[] (auto result) {
assert.expect(result, int(), "HJRPDV");
return true;
},
[] (auto error) {
assert.fail("HJRPDV");
return true;
})
->finally(
[] {
assert.pass("FC");
throw runtime_error("bye");
})
->then(
[] (auto result) {
assert.fail("EFJP");
return 0;
},
[] (auto error) {
assert.pass("EFJP");
return 0;
},
[] {
assert.pass("FCEF");
})
->finally(
[&done, &cv] {
done = true;
cv.notify_one();
})
->finish();
/* Wait for chain to complete */
unique_lock<mutex> lock(mx);
cv.wait(lock, [&done] { return done; });
/* Delay for thread to finalize after CV was set */
this_thread::sleep_for(100ms);
}
void static_combine_test()
{
promise::combine(
promise::resolved(int(2)),
promise::resolved(float(3.1f)),
promise::resolved(string("hello"))
)->then(
[] (const auto result) {
assert.expect(
get<0>(result) == 2 &&
get<1>(result) == 3.1f &&
get<2>(result) == string("hello"),
true,
"PCR");
},
[] (const auto error) {
assert.fail("PCR");
});
promise::combine(
promise::resolved(int(2)),
promise::rejected<float>("Kartuliõis!"),
promise::resolved(string("hello"))
)->then(
[] (const auto result) {
assert.fail("PCJ");
},
[] (const auto error) {
try {
rethrow_exception(error);
} catch (const runtime_error& e) {
assert.expect(e.what(), string("Kartuliõis!"), "PCJ");
}
});
}
void dynamic_combine_test()
{
const size_t count = 10;
function<size_t(const size_t)> func = [] (const size_t i) { return i; };
auto fac = promise::factory(func);
vector<Promise<size_t>> seq;
seq.reserve(count);
for (size_t i = 0; i < count; i++) {
seq.emplace_back(fac(i));
}
promise::combine(seq)
->then(
[] (const auto result) {
bool pass = true;
for (size_t i = 0; i < count; i++) {
pass = pass && result[i] == i;
}
assert.expect(pass, true, "VCR");
},
[] (const auto error) {
assert.fail("VCR");
});
seq.resize(0);
seq.emplace_back(promise::rejected<size_t>("These aren't the droids you're looking for"));
for (size_t i = 1; i < count; i++) {
seq.emplace_back(fac(i));
}
promise::combine(seq)
->then(
[] (const auto result) {
assert.fail("VCJ");
},
[] (const auto error) {
assert.pass("VCJ");
});
}
void efficiency_test()
{
{
promise::resolved(true)
->then([] (bool result) {
return make_unique<int>(42);
})
->except([] (auto e) {
assert.fail("NC");
rethrow_exception(e);
return unique_ptr<int>(nullptr);
})
->finally([] () {
})
->then([] (auto ptr) {
assert.expect(*ptr, 42, "NC");
});
}
{
promise::combine(
promise::resolved(make_unique<int>(1)),
promise::resolved(make_unique<int>(2)))
->then([] (auto result) {
assert.expect(
*get<0>(result) == 1 && *get<1>(result) == 2, true,
"NCP");
});
}
{
vector<Promise<unique_ptr<int>>> v;
v.emplace_back(promise::resolved(make_unique<int>(1)));
v.emplace_back(promise::resolved(make_unique<int>(2)));
promise::combine(v)
->then([] (auto result) {
assert.expect(
result.size() == 2 &&
*result[0] == 1 && *result[1] == 2, true,
"NCV");
});
}
}
void static_checks()
{
promise::resolved(42)
->then(
[] (auto result) {
return 21;
},
nullptr,
[] () {
})
->then(
[] (int result) {
assert.expect(result, 21, "OATH");
},
[] (exception_ptr) {
assert.fail("OATH");
});
promise::resolved(42)
->then(
[] (auto result) {
return 21;
},
[] (exception_ptr) {
return 42;
},
nullptr)
->then(
[] (int result) {
assert.expect(result, 21, "OATF");
},
[] (exception_ptr) {
assert.fail("OATF");
});
}
void monad_basic_test()
{
using promise::Factory;
using promise::callback_pack;
Factory<int, int> f1 {[] (int x) {
return promise::resolved(x + 1);
}};
Factory<int, int> f2 {[] (int x) {
return promise::resolved(x * 2);
}};
Factory<int, int> thrower {[] (int x) {
throw runtime_error("Lol");
return promise::resolved(x);
}};
Factory<int, exception_ptr> h1 {[] (exception_ptr) {
return promise::resolved(100);
}};
auto make_final = [] (int& result) {
return function<void()> {[&result] {
result = 100;
}};
};
{
auto ch = callback_pack<int, int>{f1}.bind(callback_pack<int, int>{f2});
int result = -1;
ch(10)->then([&] (int x) { result = x; }, [&] (auto) { result = -2; });
if (result == -1) {
assert.fail("MONADB1", "callback_pack::call did not work");
} else if (result == -2) {
assert.fail("MONADB1", "callback_pack::call threw");
} else if (result == 21) {
assert.fail("MONADB1", "callback_pack chain fired in wrong order");
} else if (result != 22) {
assert.fail("MONADB1", "callback_pack chain did something strange");
} else {
assert.pass("MONADB1");
}
}
{
auto ch = callback_pack<int, int>{thrower}.bind(callback_pack<int, int>{f2, h1});
int result = -1;
ch(10)->then([&] (int x) { result = x; }, [&] (auto) { result = -2; });
if (result == -1) {
assert.fail("MONADB2", "callback_pack::call did not work");
} else if (result == -2) {
assert.fail("MONADB2", "exception handler failed or was ignored");
} else if (result != 100) {
assert.fail("MONADB2", "callback_pack chain did something strange");
} else {
assert.pass("MONADB2");
}
}
{
int result = -1;
auto ch = callback_pack<int, int>{thrower}.bind(callback_pack<int, int>{f2, h1, make_final(result)});
ch(10);
if (result != 100) {
assert.fail("MONADB3", "callback_pack finalizer was not called");
} else {
assert.pass("MONADB3");
}
}
}
void monad_chain_test()
{
using promise::Factory;
using namespace promise::monads;
struct monad_test {
monad_test(const string name) : complete(false), name(name) { }
monad_test() : monad_test(string{}) { }
void fail(const string msg) const { assert.fail(name, msg); }
void pass() const { assert.try_pass(name); }
void end()
{
if (name.empty()) {
return;
}
if (complete) {
pass();
} else {
fail("Test not completed");
}
name = {};
}
void completed() { complete = true; }
private:
bool complete;
string name;
};
static monad_test this_test;
struct begin_test {
begin_test(const string name) { this_test = monad_test(name); }
void end() { this_test.end(); }
~begin_test() { end(); }
};
/* Basic operations */
Factory<int, int> sqr {[] (int x) {
return promise::resolved(x * x);
}};
auto add = [] (int addend) {
return Factory<int, int> {[=] (int x) {
return promise::resolved(x + addend);
}};
};
auto div{[] (int divisor) {
return Factory<int, int> {[=] (int x) {
if (divisor == 0) {
throw runtime_error("Division by zero");
}
return promise::resolved(x / divisor);
}};
}};
/* Assert current value in chain */
auto test = [] (int expect) -> Factory<int, int> {
return [expect] (int x) {
if (x != expect) {
this_test.fail("Test result was incorrect");
}
this_test.completed();
return promise::resolved(x);
};
};
/* Should never be called */
Factory<int, int> test_fail {[] (int) {
this_test.fail("Catch block not triggered by exception");
return promise::resolved(0);
}};
/* Unexpected exception */
Factory<int, exception_ptr> catcher {[] (exception_ptr) {
this_test.fail("Unexpected exception thrown");
throw logic_error("Promise flow control broken");
return promise::resolved(0);
}};
/* Rethrow, testing (delete this) */
Factory<int, exception_ptr> rethrow {[] (exception_ptr err) {
rethrow_exception(err);
return promise::resolved(0);
}};
/* Consume error, return new value */
auto must_catch = [] (int value) -> Factory<int, exception_ptr> {
return [value] (exception_ptr) {
return promise::resolved(value);
};
};
auto eat_error = [] (exception_ptr) { };
{
auto t = begin_test("MONAD1");
auto chain = sqr >>= test(169)/catcher >>= add(31) >>= div(20) >>= test(10)/catcher;
chain(13)->except(eat_error);
t.end();
}
{
auto t = begin_test("MONAD2");
auto chain = sqr >>= test(3600)/catcher >>= add(496) >>= div(256) >>= test(16)/catcher;
chain(60)->except(eat_error);
t.end();
}
{
auto t = begin_test("MONADE1");
auto chain = add(100) >>= div(0)/catcher >>= test_fail/rethrow >>=
test_fail/must_catch(69) >>= div(3)/catcher >>= test(23)/catcher;
chain(1);
t.end();
}
{
auto t = begin_test("MONADE2");
auto chain = add(100) >>= div(0)/catcher >>= test_fail >>=
nullptr/must_catch(69) >>= div(3)/catcher/nullptr >>=
nullptr/catcher >>= test(23)/catcher;
chain(1);
t.end();
}
}
int main(int argc, char *argv[])
try {
flow_test();
static_combine_test();
dynamic_combine_test();
efficiency_test();
static_checks();
monad_basic_test();
monad_chain_test();
return assert.print(argc, argv);
} catch (...) {
assert.print_error();
}