-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathcollection_to_string_test.dart
437 lines (399 loc) · 12.7 KB
/
collection_to_string_test.dart
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
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/**
* Tests for the toString methods on collections and maps.
*/
library collection_to_string;
import "package:expect/expect.dart";
import 'dart:collection' show Queue, LinkedHashMap;
import 'dart:math' as Math;
// TODO(jjb): seed random number generator when API allows it
const int NUM_TESTS = 300;
const int MAX_COLLECTION_SIZE = 7;
final rand = Math.Random();
main() {
smokeTest();
exactTest();
inexactTest();
}
/**
* Test a few simple examples.
*/
void smokeTest() {
// Non-const lists
Expect.equals([].toString(), '[]');
Expect.equals([1].toString(), '[1]');
Expect.equals(['Elvis'].toString(), '[Elvis]');
Expect.equals([null].toString(), '[null]');
Expect.equals([1, 2].toString(), '[1, 2]');
Expect.equals(['I', 'II'].toString(), '[I, II]');
Expect.equals(
[
[1, 2],
[3, 4],
[5, 6],
].toString(),
'[[1, 2], [3, 4], [5, 6]]',
);
// Const lists
Expect.equals((const []).toString(), '[]');
Expect.equals((const [1]).toString(), '[1]');
Expect.equals((const ['Elvis']).toString(), '[Elvis]');
Expect.equals((const [null]).toString(), '[null]');
Expect.equals((const [1, 2]).toString(), '[1, 2]');
Expect.equals((const ['I', 'II']).toString(), '[I, II]');
Expect.equals(
(const [
const [1, 2],
const [3, 4],
const [5, 6],
]).toString(),
'[[1, 2], [3, 4], [5, 6]]',
);
// Non-const maps - Note that all keys are strings; the spec currently demands this
Expect.equals({}.toString(), '{}');
Expect.equals({'Elvis': 'King'}.toString(), '{Elvis: King}');
Expect.equals({'Elvis': null}.toString(), '{Elvis: null}');
Expect.equals({'I': 1, 'II': 2}.toString(), '{I: 1, II: 2}');
Expect.equals(
{
'X': {'I': 1, 'II': 2},
'Y': {'III': 3, 'IV': 4},
'Z': {'V': 5, 'VI': 6},
}.toString(),
'{X: {I: 1, II: 2}, Y: {III: 3, IV: 4}, Z: {V: 5, VI: 6}}',
);
// Const maps
Expect.equals(const {}.toString(), '{}');
Expect.equals(const {'Elvis': 'King'}.toString(), '{Elvis: King}');
Expect.equals({'Elvis': null}.toString(), '{Elvis: null}');
Expect.equals(const {'I': 1, 'II': 2}.toString(), '{I: 1, II: 2}');
Expect.equals(
const {
'X': const {'I': 1, 'II': 2},
'Y': const {'III': 3, 'IV': 4},
'Z': const {'V': 5, 'VI': 6},
}.toString(),
'{X: {I: 1, II: 2}, Y: {III: 3, IV: 4}, Z: {V: 5, VI: 6}}',
);
}
// SERIOUS "BASHER" TESTS
/**
* Generate a bunch of random collections (including Maps), and test that
* there string form is as expected. The collections include collections
* as elements, keys, and values, and include recursive references.
*
* This test restricts itself to collections with well-defined iteration
* orders (i.e., no HashSet, HashMap).
*/
void exactTest() {
for (int i = 0; i < NUM_TESTS; i++) {
// Choose a size from 0 to MAX_COLLECTION_SIZE, favoring larger sizes
int size =
Math.sqrt(random(MAX_COLLECTION_SIZE * MAX_COLLECTION_SIZE)).toInt();
StringBuffer stringRep = new StringBuffer();
Object o = randomCollection(size, stringRep, exact: true);
print(stringRep);
print(o);
Expect.equals(o.toString(), stringRep.toString());
}
}
/**
* Generate a bunch of random collections (including Maps), and test that
* there string form is as expected. The collections include collections
* as elements, keys, and values, and include recursive references.
*
* This test includes collections with ill-defined iteration orders (i.e.,
* HashSet, HashMap). As a consequence, it can't use equality tests on the
* string form. Instead, it performs equality tests on their "alphagrams."
* This might allow false positives, but it does give a fair amount of
* confidence.
*/
void inexactTest() {
for (int i = 0; i < NUM_TESTS; i++) {
// Choose a size from 0 to MAX_COLLECTION_SIZE, favoring larger sizes
int size =
Math.sqrt(random(MAX_COLLECTION_SIZE * MAX_COLLECTION_SIZE)).toInt();
StringBuffer stringRep = new StringBuffer();
Object o = randomCollection(size, stringRep, exact: false);
print(stringRep);
print(o);
Expect.equals(alphagram(o.toString()), alphagram(stringRep.toString()));
}
}
/**
* Return a random collection (or Map) of the specified size, placing its
* string representation into the given string buffer.
*
* If exact is true, the returned collections will not be, and will not contain
* a collection with ill-defined iteration order (i.e., a HashSet or HashMap).
*/
Object randomCollection(
int size,
StringBuffer stringRep, {
bool exact = false,
}) {
return randomCollectionHelper(size, exact, stringRep, []);
}
/**
* Return a random collection (or map) of the specified size, placing its
* string representation into the given string buffer. The beingMade
* parameter is a list of collections currently under construction, i.e.,
* candidates for recursive references.
*
* If exact is true, the returned collections will not be, and will not contain
* a collection with ill-defined iteration order (i.e., a HashSet or HashMap).
*/
Object randomCollectionHelper(
int size,
bool exact,
StringBuffer stringRep,
List beingMade,
) {
double interfaceFrac = rand.nextDouble();
if (exact) {
if (interfaceFrac < 1 / 3) {
return randomList(size, exact, stringRep, beingMade);
} else if (interfaceFrac < 2 / 3) {
return randomQueue(size, exact, stringRep, beingMade);
} else {
return randomMap(size, exact, stringRep, beingMade);
}
} else {
if (interfaceFrac < 1 / 4) {
return randomList(size, exact, stringRep, beingMade);
} else if (interfaceFrac < 2 / 4) {
return randomQueue(size, exact, stringRep, beingMade);
} else if (interfaceFrac < 3 / 4) {
return randomSet(size, exact, stringRep, beingMade);
} else {
return randomMap(size, exact, stringRep, beingMade);
}
}
}
/**
* Return a random List of the specified size, placing its string
* representation into the given string buffer. The beingMade
* parameter is a list of collections currently under construction, i.e.,
* candidates for recursive references.
*
* If exact is true, the returned collections will not be, and will not contain
* a collection with ill-defined iteration order (i.e., a HashSet or HashMap).
*/
List randomList(int size, bool exact, StringBuffer stringRep, List beingMade) {
return populateRandomCollection(size, exact, stringRep, beingMade, [], "[]");
}
/**
* Like randomList, but returns a queue.
*/
Queue randomQueue(
int size,
bool exact,
StringBuffer stringRep,
List beingMade,
) {
return populateRandomCollection(
size,
exact,
stringRep,
beingMade,
new Queue(),
"{}",
);
}
/**
* Like randomList, but returns a Set.
*/
Set randomSet(int size, bool exact, StringBuffer stringRep, List beingMade) {
// Until we have LinkedHashSet, method will only be called with exact==true
return populateRandomSet(size, exact, stringRep, beingMade, new Set());
}
/**
* Like randomList, but returns a map.
*/
Map randomMap(int size, bool exact, StringBuffer stringRep, List beingMade) {
if (exact) {
return populateRandomMap(
size,
exact,
stringRep,
beingMade,
new LinkedHashMap(),
);
} else {
return populateRandomMap(
size,
exact,
stringRep,
beingMade,
randomBool() ? new Map() : new LinkedHashMap(),
);
}
}
/**
* Populates the given empty collection with elements, emitting the string
* representation of the collection to stringRep. The beingMade parameter is
* a list of collections currently under construction, i.e., candidates for
* recursive references.
*
* If exact is true, the elements of the returned collections will not be,
* and will not contain a collection with ill-defined iteration order
* (i.e., a HashSet or HashMap).
*/
populateRandomCollection(
int size,
bool exact,
StringBuffer stringRep,
List beingMade,
var coll,
String delimiters,
) {
beingMade.add(coll);
int start = stringRep.length;
stringRep.write(delimiters[0]);
List<int> indices = [];
for (int i = 0; i < size; i++) {
indices.add(stringRep.length);
if (i != 0) stringRep.write(', ');
coll.add(randomElement(random(size), exact, stringRep, beingMade));
}
if (size > 5 && delimiters == "()") {
const int MAX_LENGTH = 80;
const int MIN_COUNT = 3;
const int MAX_COUNT = 100;
// It's an iterable, it may omit some elements.
int end = stringRep.length;
if (size > MAX_COUNT) {
// Last two elements are also omitted, just find the first three or
// first 60 characters.
for (int i = MIN_COUNT; i < size; i++) {
int startIndex = indices[i];
if (startIndex - start > MAX_LENGTH - 6) {
// Limit - ", ...)".length.
String prefix = stringRep.toString().substring(0, startIndex);
stringRep.clear();
stringRep.write(prefix);
stringRep.write(", ...");
}
}
} else if (stringRep.length - start > MAX_LENGTH - 1) {
// 80 - ")".length.
// Last two elements are always included. Middle ones may be omitted.
int lastTwoLength = end - indices[indices.length - 2];
// Try to find first element to omit.
for (int i = 3; i <= size - 3; i++) {
int elementEnd = indices[i + 1];
int lengthAfter = elementEnd - start;
int ellipsisSize = 5; // ", ...".length
if (i == size - 3) ellipsisSize = 0; // No ellipsis if we hit the end.
if (lengthAfter + ellipsisSize + lastTwoLength > MAX_LENGTH - 1) {
// Omit this element and everything up to the last two.
int elementStart = indices[i];
// Rewrite string buffer by copying it out, clearing, and putting
// the parts back in.
String buffer = stringRep.toString();
String prefix = buffer.substring(0, elementStart);
String suffix = buffer.substring(end - lastTwoLength, end);
stringRep.clear();
stringRep.write(prefix);
stringRep.write(", ...");
stringRep.write(suffix);
break;
}
}
}
}
stringRep.write(delimiters[1]);
beingMade.removeLast();
return coll;
}
/** Like populateRandomCollection, but for sets (elements must be hashable) */
Set populateRandomSet(
int size,
bool exact,
StringBuffer stringRep,
List beingMade,
Set set,
) {
stringRep.write('{');
for (int i = 0; i < size; i++) {
if (i != 0) stringRep.write(', ');
set.add(i);
stringRep.write(i);
}
stringRep.write('}');
return set;
}
/** Like populateRandomCollection, but for maps. */
Map populateRandomMap(
int size,
bool exact,
StringBuffer stringRep,
List beingMade,
Map map,
) {
beingMade.add(map);
stringRep.write('{');
for (int i = 0; i < size; i++) {
if (i != 0) stringRep.write(', ');
int key = i; // Ensures no duplicates
stringRep.write(key);
stringRep.write(': ');
Object val = randomElement(random(size), exact, stringRep, beingMade);
map[key] = val;
}
stringRep.write('}');
beingMade.removeLast();
return map;
}
/**
* Generates a random element which can be an int, a collection, or a map,
* and emits it to StringRep. The beingMade parameter is a list of collections
* currently under construction, i.e., candidates for recursive references.
*
* If exact is true, the returned element will not be, and will not contain
* a collection with ill-defined iteration order (i.e., a HashSet or HashMap).
*/
Object randomElement(
int size,
bool exact,
StringBuffer stringRep,
List beingMade,
) {
Object result;
double elementTypeFrac = rand.nextDouble();
if (elementTypeFrac < 1 / 3) {
result = random(1000);
stringRep.write(result);
} else if (elementTypeFrac < 2 / 3) {
// Element is a random (new) collection
result = randomCollectionHelper(size, exact, stringRep, beingMade);
} else {
// Element is a random recursive ref
result = beingMade[random(beingMade.length)];
if (result is List) {
stringRep.write('[...]');
} else if (result is Set || result is Map || result is Queue) {
stringRep.write('{...}');
} else {
stringRep.write('(...)');
}
}
return result;
}
/** Returns a random int on [0, max) */
int random(int max) {
return rand.nextInt(max);
}
/** Returns a random boolean value. */
bool randomBool() {
return rand.nextBool();
}
/** Returns the alphabetized characters in a string. */
String alphagram(String s) {
// Calling [toList] to convert unmodifiable list to normal list.
List<int> chars = s.codeUnits.toList();
chars.sort((int a, int b) => a - b);
return new String.fromCharCodes(chars);
}