/
combinators.js
504 lines (484 loc) · 12.3 KB
/
combinators.js
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
/**
* @module
*/
import _ from 'lodash';
import assert from 'assert';
import Random from 'random-js';
import RandExp from 'randexp';
import {smallerRange,
ulog2} from './utils';
import {fromGenMaker,
isArbitrary,
Arbitrary} from './arbitrary';
import {TestData} from './testdata';
import {any, bool} from './types/primitive';
/**
* Generates a contant value.
*
* @param {*} value
* @returns {Arbitrary}
*
* @example
* // returns 1.
* ke.constant(1).generate();
*/
export function constant(value) {
return new Arbitrary({
name: 'Constant',
gen: () => () => value
});
}
/**
* Generates one of the given values. The input list must be non-empty.
*
* @param {Array} pool
* @return {Arbitrary}
*
* @example
* // returns 1 or 'a';
* ke.elements([1, 'a']).generates();
*/
export function elements(pool) {
assert(_.isArray(pool) && pool.length > 0,
'pool must be a non-empty array.');
return new Arbitrary({
name: 'Elements',
gen: function() {
return function (engine) {
const e = Random.picker(pool)(engine);
return constant(e).makeGen()(engine);
};
}
});
}
/**
* Generates a value of the given regular expression.
*
* @param {string} pattern regualr expression string.
* @return {Arbitrary}
* @example
* ke.regex('hello+ (world|to you)').random
*/
export function regex(pattern) {
return new Arbitrary({
gen: function(s) {
return function(engine) {
const regexp = new RegExp(s);
const randexp = new RandExp(regexp);
randexp.randInt = (from, to) => {
return Random.integer(from, to)(engine);
};
return randexp.gen();
}
},
genOpts: [pattern]
});
};
/**
* Choose one of the given arbitraries, with a weighted random distribution.
* The input list must be non-empty.
*
* @param {Array<Array<*>>} pool
* @return {*}
* @example
* ke.frequency([ [4, ke.int], [6, ke.bool] ]).generate();
*/
export function frequency(pool) {
assert(_.isArray(pool) && pool.length > 0,
'pool must be an non-empty array.');
return new Arbitrary({
name: 'Frequency',
gen: function(pool) {
return function(engine, locale) {
function pick(n, [[k,x], ...xs]) {
return (n <= k) ? x : pick(n -k, xs);
}
const total = _.sum(pool.map(e => e[0]));
const head = Random.integer(1, total)(engine);
const result = pick(head, pool);
if (isArbitrary(result)) {
return result.makeGen()(engine, locale);
}
else {
return result;
};
};
},
genOpts: [pool]
});
}
/**
* Produce a smaller version of a arbitrary.
*
* @param {Arbitrary} arb
* @return {Arbitrary}
*/
export function small(arb) {
return arb.small;
}
/**
* Produce a nested values.
*
* @param {function} combinator a function to return an arbitrary.
* @param {Arbitrary} arb the base arbitrary.
* @param {number} depth the depth of recursively stacks. default is 4.
* @return {*}
* @example
* ke.recursive(ke.array, ke.any);
*/
export function recursive(combinator, arb, depth = 4) {
return new Arbitrary({
name: 'Recursive',
gen: function(combinator, arb, depth) {
return function(engine, locale) {
function rec(n) {
const chance = Random.integer(0, 3)(engine);
if (n <= 0 || chance === 0 ) {
return n == depth ? combinator(arb) : arb;
}
else {
return combinator(rec(n - 1));
}
}
return rec(depth).makeGen()(engine, locale);
};
},
genOpts: [combinator, arb, depth],
smaller: function([combinator, arb, depth]) {
return [combinator, arb, ulog2(depth)];
}
});
}
/**
* Generates a value that satisfies a predicate.
*
* @param {!function} predicate - a predicate function.
* @param {!Arbitrary} arb - an arbitrary.
* @returns {Arbitrary}
*
* @example
* // returns even number.
* ke.suchThat(ke.int, (n) => n / 2 === 0).generate();
*/
export function suchThat(predicate, arb) {
const oriGen = arb.makeGen();
const clone = arb.clone();
const newGenerator = function (...genOpts) {
return function (engine, locale) {
let x;
let j = 0;
for (let i=0;;i++) {
j++;
if (i > 5) {
i = 0;
}
x = oriGen(engine, locale);
if (j > 5000) {
throw new Error('can not find value in this range.');
}
if (predicate(x)) {
break;
}
}
return x;
};
};
clone.gen(newGenerator);
return clone;
}
/**
* Randomly uses one of the given generators. The input list must be non-empty.
*
* @param {!Arbitrary[]} arbs
* @returns {Arbitrary}
*
* @example
* // Produces a boolean or an integer.
* ke.oneOf(ke.bool, ke.int).generate();
*/
export function oneOf(arbs) {
assert(_.every(arbs, isArbitrary), 'arbs must be an array of Arbitrary.');
return new Arbitrary({
name: 'OneOf',
gen: function (pool) {
return function (engine, locale) {
const arb = Random.picker(pool)(engine);
return arb.makeGen()(engine, locale);
};
},
genOpts: [arbs]
});
}
/**
* An arbitrary returns a value or null.
*
* @param {!Arbitrary} arb
* @return {Arbitrary}
*/
export function maybe(arb) {
return oneOf([arb, constant(null)]).name('Maybe');
}
/**
* Generate a orderd array.
*
* @param {...Arbitrary}
* @return {Arbitrary}
* @example
* // returns [1, true, 143.321]
* ke.sequence(ke.int, ke.bool, ke.number).generate();
*/
export function sequence(...arbs) {
assert(_.every(arbs, isArbitrary), 'arguments must be array of Arbitrary');
return fromGenMaker(function(...pool) {
return function(engine, locale) {
return pool.map(arb => arb.makeGen()(engine, locale));
};
}, arbs).name('Sequence');
}
/**
* Generates a pair of two arbitraries.
*
* @param {!Arbitrary} arb1 first arbitrary.
* @param {!Arbitrary} arb2 second arbitrary.
* @return {Arbitrary}
*
* @example
* ke.pair(ke.int, ke.int).generate();
*
* @example
* // choose different arbitraries.
* ke.pair(ke.int, ke.int).choose(ke.bool, ke.bool).generate();
*/
export function pair(arb1, arb2) {
assert(isArbitrary(arb1), 'arb1 must be an arbitrary.');
assert(isArbitrary(arb2), 'arb2 must be an arbitrary.');
return sequence(arb1, arb2).name('Pair');
}
/**
* Generates an array of random length.
*
* @param {Arbitrary} arb a arbitrary.
* @return {Arbitrary}
*
* @example
* // Produces an array of integer that the length between 1 and 3.
* ke.array(ke.int).choose(1, 3).generate();
*
* // more complicate case.
* ke.array(ke.oneOf([ke.int, ke.falsy, ke.array(ke.int)]));
*
* // Produces an nested array with random values.
* ke.array().generate();
*/
export function array(arb) {
return new Arbitrary({
name: 'Array',
gen: function (min, max) {
assert(min >= 0 || max >= 0, 'min or max must be larger than 0.');
assert(max >= min, 'max must be larger than min.');
return function(engine, locale) {
return _.range(0, Random.integer(min, max)(engine)).map(() => {
if (arb !== undefined) {
assert(isArbitrary(arb), 'arb must be a Arbitrary.');
return arb.makeGen()(engine, locale);
}
else {
return recursive(array, any, 2).makeGen()(engine, locale);
}
});
};
},
genOpts: [0, 30],
smaller: smallerRange
});
}
/**
*
* Generates an non-empty array.
*
* @param {Arbitrary}
* @return {Arbitrary}
*/
export function nearray(arb) {
return array(arb).choose(1, 30).name('Non-Empty Array');
};
/**
* Generate a object.
*
* Takes an object as a template and will go through the enumerable own
* properties of object and expanding.
*
* @param {Object} spec an object
* @return {Arbitrary}
*
* @example
* // return {k: 1234};
* ke.object({k: ke.int}).generate();
*/
export function object(spec) {
assert(_.isObject(spec), 'spec must be an object');
return new Arbitrary({
name: 'Object',
gen: function(opts) {
const _spec = _.defaults(opts, spec);
return function(engine, locale) {
const o = {};
Object.keys(_spec).forEach((k) => {
const arbOrValue = _spec[k];
if (arbOrValue instanceof Arbitrary) {
o[k] = arbOrValue.makeGen()(engine, locale);
}
else {
o[k] = arbOrValue;
}
});
return o;
};
},
genOpts: [spec]
});
}
/**
* transform a class to an Arbitrary.
*
* @param {function} cls a class.
* @return {Arbitrary}
*
* @exmaple
* function() {}
*
* ke.objectOf(Person, ke.person.name).generate();
* ke.objectOf(Person).choose(ke.person.name).generate();
*/
export function objectOf(...args) {
const cls = args[0];
const clsarbargs1 = args.slice(1, args.length);
return fromGenMaker(function(...clsarbargs2) {
return function(engine, locale) {
const clsarbargs = clsarbargs2.length > 0 ? clsarbargs2 : clsarbargs1;
const impl = Object.create(cls.prototype);
const clsargs = clsarbargs.map(arb => arb.makeGen()(engine, locale));
const v = cls.apply(impl, clsargs);
return v ? v : impl;
};
});
}
/**
* Produce a function.
*
* @param {?outputArb} a arbitrary to produce the return value of
* this function.
* @return {Arbitary}
* @example
* // return 1
* ke.func(ke.int).random()
*/
export function func(outputArb) {
return new Arbitrary({
name: 'Function',
gen: function(outputArb = oneOf([any, array()])) {
return function(engine, locale) {
return function() {
return outputArb.makeGen()(engine, locale);
};
};
},
genOpts: [outputArb]
});
}
/**
* Produce a generator function.
*
* @param {?outputArb} a arbitrary to produce the return value of
* this function.
* @return {Arbitary}
* @example
* // return 1
* ke.genfunc(ke.int).random()
*/
export function genfunc(genOpts) {
return new Arbitrary({
name: 'Generator Function',
gen: function(outputArb = oneOf([any, array()])) {
return function (engine, locale) {
return function * () {
yield outputArb.makeGen()(engine, locale);
};
};
},
genOpts: [genOpts]
});
}
/**
* Produce a promise.
*
* @param {Object} opts
* @property {Number} failrate 0 - 100.
* @prpperty {Arbitary} dataArb
* @property {Arbitrary} errorArb
* @return {Arbitary}
* @example
* p = ke.promise.random
* p.then(console.log).catch(console.error);
*/
export function promise(opts) {
const _defaults = {
dataArb: any,
errorArb: constant('promiseFail'),
failrate: 50
};
function promiseGenMaker({dataArb, errorArb, failrate}) {
return function(engine, locale) {
return new Promise(function(resolve, reject){
const fail = bool.choose(failrate).makeGen()(engine, locale);
const data = dataArb.makeGen()(engine, locale);
const error = errorArb.makeGen()(engine, locale);
return fail ? reject(error) : resolve(data);
});
}
}
return new Arbitrary({
name: 'Promise',
gen: promiseGenMaker,
genOpts: [_.defaults(opts, _defaults)]
});
}
/**
* An arbitrary to produce either valid or invalid values.
*
* @param {!Arbitrary} valid an arbitrary to produce valid value.
* @param {?Arbitrary} invalid an arbitrary to produce invalid value,
* default is constant(undefined).
* @return {Arbitrary}
* @example
* // returns a integer or a boolean.
* ke.vairant(ke.int, ke.bool).random
*/
export function variant(valid, invalid = constant(undefined)) {
assert(isArbitrary(valid), 'valid must be an arbitrary.');
return oneOf([valid, invalid]).name('Variant');
}
/**
* An arbitrary to produce a data set consists of variants.
*
* @param {Object} variants
* @return {TestData}
* @example
* const variants = {
* userName: ke.variant(ke.internet.userName, ke.falsy),
* birthday: ke.variant(ke.date, ke.falsy)
* };
*
* // returns valid username and valid birthday.
* ke.data(variants).allValid().random;
*
* // returns invalid username and invalid birthday.
* ke.data(variants).allInvalid().random;
*
* // returns valid username and invalid birthday.
* ke.data(variants).invalid('birthday').random;
*
*/
export function data(variants) {
return new TestData({variants: variants});
}