|
| 1 | +import 'dart:math'; |
| 2 | + |
| 3 | +import 'package:dartoos/src/text/rand.dart'; |
| 4 | +import 'package:test/test.dart'; |
| 5 | + |
| 6 | +Future<void> main() async { |
| 7 | + group('Rand.dig', () { |
| 8 | + test('length', () async { |
| 9 | + final four = await Rand.dig(4, Random.secure()); |
| 10 | + expect(four.length, 4); |
| 11 | + }); |
| 12 | + test('digits only', () async { |
| 13 | + final digits = await Rand.dig(10, SeqIndexRandom()); |
| 14 | + // Regexp '\D' means non-digit characters |
| 15 | + // the generated value cannot contain any non-digit character |
| 16 | + expect(digits.contains(RegExp(r'\D')), false); |
| 17 | + }); |
| 18 | + test('decimal digits [0–9]', () async { |
| 19 | + final decimalDigits = await Rand.dig(10, SeqIndexRandom()); |
| 20 | + expect(decimalDigits, '0123456789'); |
| 21 | + }); |
| 22 | + }); |
| 23 | + group('Rand.hex', () { |
| 24 | + test('length', () async { |
| 25 | + expect((await Rand.hex(1)).length, 1); |
| 26 | + expect((await Rand.hex(5)).length, 5); |
| 27 | + }); |
| 28 | + test('hex digits only', () async { |
| 29 | + final hex = await Rand.hex(10, SeqIndexRandom()); |
| 30 | + // the generated value cannot contain any non-hex character |
| 31 | + expect(hex.contains(RegExp('[^0-9a-f]')), false); |
| 32 | + }); |
| 33 | + test('hexadecimal digits [0–9a–f]', () async { |
| 34 | + final hexDigits = await Rand.hex(16, SeqIndexRandom()); |
| 35 | + expect(hexDigits, '0123456789abcdef'); |
| 36 | + }); |
| 37 | + }); |
| 38 | + group('Rand.str', () { |
| 39 | + test('length', () async { |
| 40 | + final one = await Rand.str(1, 'abc'); |
| 41 | + expect(one.length, 1); |
| 42 | + }); |
| 43 | + test('custom characters source', () async { |
| 44 | + final custom = await Rand.str(100, 'a', SeqIndexRandom()); |
| 45 | + expect(custom.length, 100); |
| 46 | + |
| 47 | + /// Must not contain any character other than 'a' |
| 48 | + expect(custom.contains(RegExp('[^a]')), false); |
| 49 | + }); |
| 50 | + }); |
| 51 | +} |
| 52 | + |
| 53 | +/// Sequentially generated integer values; quite the opposite of |
| 54 | +/// random!!! |
| 55 | +class SeqIndexRandom implements Random { |
| 56 | + int _counter = 1; |
| 57 | + int _currBound = 1; |
| 58 | + |
| 59 | + @override |
| 60 | + bool nextBool() => throw UnsupportedError('nextBool not implemented'); |
| 61 | + @override |
| 62 | + double nextDouble() => throw UnsupportedError('nextDouble not implemented'); |
| 63 | + |
| 64 | + /// Generates sequential integers from 0 up to bound - 1. |
| 65 | + /// If [bound] changes, the counter is reset so that the first |
| 66 | + /// value for the new max is 0. |
| 67 | + @override |
| 68 | + int nextInt(int bound) { |
| 69 | + if (_currBound != bound) { |
| 70 | + _currBound = bound; |
| 71 | + _counter = bound; |
| 72 | + } |
| 73 | + final value = _counter % _currBound; |
| 74 | + ++_counter; |
| 75 | + return value; |
| 76 | + } |
| 77 | +} |
0 commit comments