-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathattempt.test.js
More file actions
220 lines (184 loc) · 11 KB
/
attempt.test.js
File metadata and controls
220 lines (184 loc) · 11 KB
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
import { describe, test } from 'node:test';
import { ok, strictEqual, doesNotReject, rejects, throws, deepStrictEqual, fail as failTest, doesNotThrow } from 'node:assert';
import {
attemptAsync, attemptSync, createSafeSyncCallback, createSafeAsyncCallback, succeed, fail, succeeded, unwrap,
failed, isAttemptResult, getResultError, getResultValue, handleResultAsync, handleResultSync, throwIfFailed,
getAttemptStatus, SUCCEEDED, FAILED, attemptAll, AttemptSuccess, AttemptFailure, AttemptResult, NONE, isNone,
} from './attempt.js';
describe('Test `attempt` library', async () => {
/**
*
* @param {string} msg
* @throws {Error}
*/
const err = (msg = 'I throw') => {
throw new Error(msg);
};
/**
*
* @param {string} result
* @returns {string}
*/
const returns = (result = 'I return') => result;
const signal = AbortSignal.timeout(1_000);
test('Test that it does not throw', { signal }, async () => {
await doesNotReject(() => attemptAsync(err, 'Should not throw.'), 'Errors should not be thrown.');
});
test('Verify valid results/tuples', { signal }, () => {
const sig = AbortSignal.abort();
const good = succeed(true);
const bad = fail(new Error('forced failure.'));
const invalid = fail(['Invalid', 'error']);
const unaborted = fail(signal);
const aborted = fail(sig);
const abortedStr = fail(AbortSignal.abort('failed'));
strictEqual(good.toString(), '[object AttemptSuccess]', '`AttemptSuccess should stringify as the correct object type.');
strictEqual(bad.toString(), '[object AttemptFailure]', '`AttemptFailure should stringify as the correct object type.');
throws(() => new AttemptResult('true', 'false', false), 'Should not be able to construct `AttemptResult` directly.');
ok(good.ok, 'Successful results should have `ok` set to `true`.');
ok(isNone(good.error), 'Success results should have `NONE` for error.');
ok(isNone(bad.value), 'Failed results should have `NONE` for value.');
ok(! bad.ok, 'Failed results should have `ok` set to `false`.');
ok(good instanceof AttemptSuccess, '`succeed()` should return an `AttemptSuccess` object/tuple.');
ok(bad instanceof AttemptFailure, '`fail()` should return an `AttemptFailure` object/tuple.');
deepStrictEqual(getResultError(invalid), new TypeError('Invalid error type provided.'), 'Should return a TypeError for invalid error types.');
ok(isAttemptResult(good), 'Should return a frozen tuple with a hidden status.');
ok(succeeded(good), 'Should be a valid result with a successful status.');
ok(failed(bad), 'Should be a valid result with a failed status.');
ok(getResultValue(good), 'Should return the value given by a successful attempt.');
ok(getResultError(bad) instanceof Error, 'Should return the error of a failed attempt.');
throws(() => getResultValue(bad), 'Failed attempts throw TypeError when attempting to get value.');
throws(() => getResultError(good), 'Successful attempts throw TypeError when attempting to get error.');
ok(failed(fail(null)), 'Should be a valid result with a failed status when passing `null` to `fail()`.');
strictEqual(succeed(good), good, 'Duplicate `succeed()`/`fail()` on results should return original value.');
strictEqual(fail(bad), bad, 'Duplicate `succeed()`/`fail()` on results should return original value.');
deepStrictEqual(aborted.error, sig.reason, 'Failures from aborted `AbortSignal`s should have an error of the signal\'s reason.');
ok(unaborted.error instanceof TypeError, 'Failing with an unaborted `AbortSignal` should fail with a `TypeError`.');
ok(abortedStr.error instanceof Error, 'Failing with an `AbortSignal` with a string `reason` should fail an `Error` with that message.');
deepStrictEqual(good, succeed(good), 'Creating an AttemptResult from a prior result should just return the original.');
});
test('Test forced succeed/fail returns', { signal }, () => {
// Checks object destructuring
const { value, error } = succeed('This should succeed.');
// Checks tuple destructuring
const [result2, err2] = fail('This should error.');
strictEqual(value, 'This should succeed.', '`succeed()` should have the expected result.');
strictEqual(error, NONE, '`succeed()` should not return an error.');
strictEqual(result2, NONE, '`fail()` should not return a result.');
ok(err2 instanceof Error, '`fail()` should return an error.');
});
test('Test return tuples.', { signal }, () => {
const msg = 'Hello, World!';
const [result1, error1, passed1] = attemptSync(returns, msg);
const [result2, error2, passed2] = attemptSync(err, 'I should throw');
ok(passed1, '3rd element should be a boolean and `true` on successful attempts.');
ok(! passed2, '3rd element should be a boolean and `false` on failed attempts.');
strictEqual(error1, NONE, 'Successful path should not return an error.');
strictEqual(result1, msg, 'Returned result should match expectations.');
strictEqual(result2, NONE, 'Failed attempts should not return a value.');
ok(error2 instanceof Error, 'Failed attempts should return an error.');
});
test('Test unwrapping of results.', { signal }, () => {
const err = new Error('Failed');
const passed = succeed('success');
const failed = fail(err);
throws(() => unwrap(failed), 'Failed results should throw when unwrapped.');
doesNotThrow(() => unwrap(passed), 'Successful results should not throw when unwrapped.');
strictEqual(unwrap(passed), passed.value, 'Unwrapping should return the value.');
});
test('`attemptAsync()` should throw if callback is not a function.', { signal }, async () => {
await rejects(() => attemptAsync('Not a function.'), '`attemptAsync()` should throw if callback is not a function.');
});
test('`attemptSync()` should throw if callback is invalid.', { signal }, () => {
throws(() => attemptSync('Not a function.'), '`attemptSync()` should throw if callback is not a function.');
throws(() => attemptSync(async () => null), '`attemptSync()` should throw if callback is an async function.');
});
test('Test `createCallbackSync()`', { signal }, () => {
const data = {foo: 'bar'};
const parse = createSafeSyncCallback(JSON.parse);
const [parsed, err] = parse(JSON.stringify(data));
const [failed, error] = parse('{Invalid JSON}');
deepStrictEqual(parsed, data, 'Safe callbacks should return expected results.');
strictEqual(err, NONE, 'Successfull callbacks should not return an error.');
strictEqual(failed, NONE, 'Errored callbacks should not return results.');
ok(error instanceof Error, 'Failed callbacks should return an error.');
});
test('Test `createCallbackAsync()`', { signal }, async () => {
const data = {foo: 'bar'};
const parse = createSafeAsyncCallback(JSON.parse);
const [parsed, err] = await parse(JSON.stringify(data));
const [failed, error] = await parse('{Invalid JSON}');
deepStrictEqual(parsed, data, 'Safe callbacks should return expected results.');
strictEqual(err, NONE, 'Successfull callbacks should not return an error.');
strictEqual(failed, NONE, 'Errored callbacks should not return results.');
ok(error instanceof Error, 'Failed callbacks should return an error.');
throws(() => throwIfFailed(handleResultSync(err, {})), 'Default error handle should return an `AttemptFailure`.');
});
test('Test asynchronously handling results', { signal }, async () => {
const result = succeed('Success.');
const err = fail(new Error('Failure.'));
const aborted = await handleResultAsync(result, { signal: AbortSignal.abort('Aborted') });
const notAborted = await handleResultAsync(result, { signal });
ok(failed(aborted), 'Aborted results should be considered failed.');
ok(succeeded(notAborted), 'Not aborted results should be considered successful.');
ok(getResultError(aborted) instanceof Error, 'Aborted results should have an error.');
rejects(() => handleResultAsync(['invlid'], {}));
rejects(() => handleResultAsync(result, { success: null }), 'Invalid success callback should throw a TypeError.');
rejects(() => handleResultAsync(result, { failure: null }), 'Invalid failuer callback should throw a TypeError.');
throws(() => throwIfFailed(err), 'Failed result should throw its error.');
throwIfFailed(handleResultAsync(result, {
failure: failTest,
}));
throwIfFailed(handleResultAsync(result, { signal: AbortSignal.timeout(500) }), 'Should not throw if result is successful and signal is not aborted.');
throwIfFailed(handleResultAsync(err, {
success: () => failTest('Failed test triggered success branch of handler.'),
failure: () => null,
}));
rejects(async () => throwIfFailed(await handleResultAsync(err, {})), 'Default error handle should return an `AttemptFailure`.');
});
test('Test synchronously handling results', { signal }, async () => {
const result = succeed('Successful results should be handled by `success` handler.');
const err = fail(new TypeError('Failed results should be handled by `failure` handler.'));
doesNotThrow(() => handleResultSync(result, {
success: value => strictEqual(value, 'Successful results should be handled by `success` handler.', 'Should handle successful results with `success` handler.'),
failure: () => failTest('Failed test triggered success branch of handler.'),
}), 'Should not throw when handling a successful result.');
throws(() => handleResultSync(['invalid']), 'Invalid results should throw a TypeError.');
throws(() => handleResultSync(result, { success: null }), 'Invalid success callback should throw a TypeError.');
throws(() => handleResultSync(result, { failure: null }), 'Invalid failuer callback should throw a TypeError.');
throwIfFailed(handleResultSync(result, {
failure: failTest,
}));
throwIfFailed(handleResultSync(err, {
success: () => failTest('Failed test triggered success branch of handler.'),
failure: () => null,
}));
});
test('Test result status', { signal }, () => {
const result = succeed('Successful results should be handled by `success` handler.');
const err = fail(new TypeError('Failed results should be handled by `failure` handler.'));
strictEqual(getAttemptStatus(result), SUCCEEDED, 'Result should have a status of `SUCCEEDED`.');
strictEqual(getAttemptStatus(err), FAILED, 'Result should have a status of `FAILED`.');
throws(() => getAttemptStatus('invalid'), 'Invalid results should throw a TypeError.');
});
test('Test `attemptAll()`', { signal }, async () => {
const [val] = await attemptAll(
() => 'Hello, World!',
text => new TextEncoder().encode(text),
encoded => crypto.subtle.digest('SHA-256', encoded),
hash => new Uint8Array(hash),
bytes => bytes.toBase64(),
);
let didFail = false;
const result = await attemptAll(
() => 'Hello, World!',
() => {throw new Error('Forced error.');},
() => didFail = true,
() => 'This should not be reached.',
);
strictEqual(val, '3/1gIbsr1bCvZ2KQgJ7DpTGR3YHH9wpLKGiKNiGCmG8=', 'Should return the expected base64-encoded string.');
rejects(() => attemptAll('Not a function'), 'Should throw if any callback is not a function.');
ok(failed(result), 'Should return a failed result if any callback throws an error.');
ok(! didFail, 'Should not reach the last callback if an error is thrown in a previous callback.');
});
});