-
Notifications
You must be signed in to change notification settings - Fork 3
/
minimongo-tests.js
10162 lines (10162 loc) · 255 KB
/
minimongo-tests.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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
!function(exports, global) {
global.MinimongoTests = exports;
var Future, __meteor_runtime_config__ = {};
Meteor.isServer && (Future = Npm.require("fibers/future")), /******************************************************************************/
/* TestCaseResults */
/******************************************************************************/
TestCaseResults = function(test_case, onEvent, onException, stop_at_offset) {
var self = this;
self.test_case = test_case, self.onEvent = onEvent, self.expecting_failure = !1,
self.current_fail_count = 0, self.stop_at_offset = stop_at_offset, self.onException = onException,
self.id = Random.id(), self.extraDetails = {};
}, _.extend(TestCaseResults.prototype, {
ok: function(doc) {
var self = this, ok = {
type: "ok"
};
doc && (ok.details = doc), self.expecting_failure && (ok.details = ok.details || {},
ok.details.was_expecting_failure = !0, self.expecting_failure = !1), self.onEvent(ok);
},
expect_fail: function() {
var self = this;
self.expecting_failure = !0;
},
fail: function(doc) {
var self = this;
if ("string" == typeof doc && (// Some very old code still tries to call fail() with a
// string. Don't do this!
doc = {
type: "fail",
message: doc
}), doc = _.extend({}, doc, self.extraDetails), 0 === self.stop_at_offset) {
if (Meteor.isClient) {
// Only supported on the browser for now..
var now = +new Date();
+new Date() - now < 100 && alert("To use this feature, first enable your browser's debugger.");
}
self.stop_at_offset = null;
}
// Get filename and line number of failure if we're using v8 (Chrome or
// Node).
if (self.stop_at_offset && self.stop_at_offset--, Error.captureStackTrace) {
var savedPrepareStackTrace = Error.prepareStackTrace;
Error.prepareStackTrace = function(_, stack) {
return stack;
};
var err = new Error();
Error.captureStackTrace(err);
var stack = err.stack;
Error.prepareStackTrace = savedPrepareStackTrace;
for (var i = stack.length - 1; i >= 0; --i) {
var frame = stack[i];
// Heuristic: use the OUTERMOST line which is in a :tests.js
// file (this is less likely to be a test helper function).
if (frame.getFileName().match(/:tests\.js/)) {
doc.filename = frame.getFileName(), doc.line = frame.getLineNumber();
break;
}
}
}
self.onEvent({
type: self.expecting_failure ? "expected_fail" : "fail",
details: doc,
cookie: {
name: self.test_case.name,
offset: self.current_fail_count,
groupPath: self.test_case.groupPath,
shortName: self.test_case.shortName
}
}), self.expecting_failure = !1, self.current_fail_count++;
},
// Call this to fail the test with an exception. Use this to record
// exceptions that occur inside asynchronous callbacks in tests.
//
// It should only be used with asynchronous tests, and if you call
// this function, you should make sure that (1) the test doesn't
// call its callback (onComplete function); (2) the test function
// doesn't directly raise an exception.
exception: function(exception) {
this.onException(exception);
},
// returns a unique ID for this test run, for convenience use by
// your tests
runId: function() {
return this.id;
},
// === Following patterned after http://vowsjs.org/#reference ===
// XXX eliminate 'message' and 'not' arguments
equal: function(actual, expected, message, not) {
if (!not && "string" == typeof actual && "string" == typeof expected) return void this._stringEqual(actual, expected, message);
/* If expected is a DOM node, do a literal '===' comparison with
* actual. Otherwise do a deep comparison, as implemented by _.isEqual.
*/
var matched;
// XXX remove cruft specific to liverange
if ("object" == typeof expected && expected && expected.nodeType) matched = expected === actual,
expected = "[Node]", actual = "[Unknown]"; else if ("undefined" != typeof Uint8Array && expected instanceof Uint8Array) {
// I have no idea why but _.isEqual on Chrome horks completely on Uint8Arrays.
// and the symptom is the chrome renderer taking up an entire CPU and freezing
// your web page, but not pausing anywhere in _.isEqual. I don't understand it
// but we fall back to a manual comparison
actual instanceof Uint8Array || this.fail({
type: "assert_equal",
message: "found object is not a typed array",
expected: "A typed array",
actual: actual.constructor.toString()
}), expected.length !== actual.length && this.fail({
type: "assert_equal",
message: "lengths of typed arrays do not match",
expected: expected.length,
actual: actual.length
});
for (var i = 0; i < expected.length; i++) this.equal(actual[i], expected[i]);
} else matched = EJSON.equals(expected, actual);
matched === !!not ? this.fail({
type: "assert_equal",
message: message,
expected: JSON.stringify(expected),
actual: JSON.stringify(actual),
not: !!not
}) : this.ok();
},
notEqual: function(actual, expected, message) {
this.equal(actual, expected, message, !0);
},
instanceOf: function(obj, klass, message) {
obj instanceof klass ? this.ok() : this.fail({
type: "instanceOf",
message: message,
not: !1
});
},
notInstanceOf: function(obj, klass, message) {
obj instanceof klass ? this.fail({
type: "instanceOf",
message: message,
not: !0
}) : this.ok();
},
matches: function(actual, regexp, message) {
regexp.test(actual) ? this.ok() : this.fail({
type: "matches",
message: message,
actual: actual,
regexp: regexp.toString(),
not: !1
});
},
notMatches: function(actual, regexp, message) {
regexp.test(actual) ? this.fail({
type: "matches",
message: message,
actual: actual,
regexp: regexp.toString(),
not: !0
}) : this.ok();
},
// expected can be:
// undefined: accept any exception.
// string: pass if the string is a substring of the exception message.
// regexp: pass if the exception message passes the regexp.
// function: call the function as a predicate with the exception.
//
// Note: Node's assert.throws also accepts a constructor to test
// whether the error is of the expected class. But since
// JavaScript can't distinguish between constructors and plain
// functions and Node's assert.throws also accepts a predicate
// function, if the error fails the instanceof test with the
// constructor then the constructor is then treated as a predicate
// and called (!)
//
// The upshot is, if you want to test whether an error is of a
// particular class, use a predicate function.
//
"throws": function(f, expected) {
var actual, predicate;
if (void 0 === expected) predicate = function(actual) {
return !0;
}; else if (_.isString(expected)) predicate = function(actual) {
return _.isString(actual.message) && -1 !== actual.message.indexOf(expected);
}; else if (expected instanceof RegExp) predicate = function(actual) {
return expected.test(actual.message);
}; else {
if ("function" != typeof expected) throw new Error("expected should be a string, regexp, or predicate function");
predicate = expected;
}
try {
f();
} catch (exception) {
actual = exception;
}
actual && predicate(actual) ? this.ok() : this.fail({
type: "throws",
message: actual ? "wrong error thrown: " + actual.message : "did not throw an error as expected"
});
},
isTrue: function(v, msg) {
v ? this.ok() : this.fail({
type: "true",
message: msg,
not: !1
});
},
isFalse: function(v, msg) {
v ? this.fail({
type: "true",
message: msg,
not: !0
}) : this.ok();
},
isNull: function(v, msg) {
null === v ? this.ok() : this.fail({
type: "null",
message: msg,
not: !1
});
},
isNotNull: function(v, msg) {
null === v ? this.fail({
type: "null",
message: msg,
not: !0
}) : this.ok();
},
isUndefined: function(v, msg) {
void 0 === v ? this.ok() : this.fail({
type: "undefined",
message: msg,
not: !1
});
},
isNotUndefined: function(v, msg) {
void 0 === v ? this.fail({
type: "undefined",
message: msg,
not: !0
}) : this.ok();
},
isNaN: function(v, msg) {
isNaN(v) ? this.ok() : this.fail({
type: "NaN",
message: msg,
not: !1
});
},
isNotNaN: function(v, msg) {
isNaN(v) ? this.fail({
type: "NaN",
message: msg,
not: !0
}) : this.ok();
},
include: function(s, v, message, not) {
var pass = !1;
s instanceof Array ? pass = _.any(s, function(it) {
return _.isEqual(v, it);
}) : "object" == typeof s ? pass = v in s : "string" == typeof s && s.indexOf(v) > -1 && (pass = !0),
pass === !not ? this.ok() : this.fail({
type: "include",
message: message,
sequence: s,
should_contain_value: v,
not: !!not
});
},
notInclude: function(s, v, message) {
this.include(s, v, message, !0);
},
// XXX should change to lengthOf to match vowsjs
length: function(obj, expected_length, msg) {
obj.length === expected_length ? this.ok() : this.fail({
type: "length",
expected: expected_length,
actual: obj.length,
message: msg
});
},
// EXPERIMENTAL way to compare two strings that results in
// a nicer display in the test runner, e.g. for multiline
// strings
_stringEqual: function(actual, expected, message) {
actual !== expected ? this.fail({
type: "string_equal",
message: message,
expected: expected,
actual: actual
}) : this.ok();
}
}), /******************************************************************************/
/* TestCase */
/******************************************************************************/
TestCase = function(name, func) {
var self = this;
self.name = name, self.func = func;
var nameParts = _.map(name.split(" - "), function(s) {
return s.replace(/^\s*|\s*$/g, "");
});
self.shortName = nameParts.pop(), nameParts.unshift("tinytest"), self.groupPath = nameParts;
}, _.extend(TestCase.prototype, {
// Run the test asynchronously, delivering results via onEvent;
// then call onComplete() on success, or else onException(e) if the
// test raised (or voluntarily reported) an exception.
run: function(onEvent, onComplete, onException, stop_at_offset) {
var self = this, completed = !1, markComplete = function() {
return completed ? (Meteor._debug("*** Test error -- test '" + self.name + "' returned multiple times."),
!1) : (completed = !0, !0);
}, wrappedOnEvent = function(e) {
// If this trace prints, it means you ran some test.* function after the
// test finished! Another symptom will be that the test will display as
// "waiting" even when it counts as passed or failed.
return completed && console.trace("event after complete!"), onEvent(e);
}, results = new TestCaseResults(self, wrappedOnEvent, function(e) {
markComplete() && onException(e);
}, stop_at_offset);
Meteor.defer(function() {
try {
self.func(results, function() {
markComplete() && onComplete();
});
} catch (e) {
markComplete() && onException(e);
}
});
}
}), /******************************************************************************/
/* TestManager */
/******************************************************************************/
TestManager = function() {
var self = this;
self.tests = {}, self.ordered_tests = [], self.testQueue = Meteor.isServer && new Meteor._SynchronousQueue();
}, Meteor.isServer && process.env.TINYTEST_FILTER && (__meteor_runtime_config__.tinytestFilter = process.env.TINYTEST_FILTER),
_.extend(TestManager.prototype, {
addCase: function(test) {
var self = this;
if (test.name in self.tests) throw new Error("Every test needs a unique name, but there are two tests named '" + test.name + "'");
__meteor_runtime_config__.tinytestFilter && -1 === test.name.indexOf(__meteor_runtime_config__.tinytestFilter) || (self.tests[test.name] = test,
self.ordered_tests.push(test));
},
createRun: function(onReport, pathPrefix) {
var self = this;
return new TestRun(self, onReport, pathPrefix);
}
}), // singleton
TestManager = new TestManager(), /******************************************************************************/
/* TestRun */
/******************************************************************************/
TestRun = function(manager, onReport, pathPrefix) {
var self = this;
self.manager = manager, self.onReport = onReport, self.next_sequence_number = 0,
self._pathPrefix = pathPrefix || [], _.each(self.manager.ordered_tests, function(test) {
self._prefixMatch(test.groupPath) && self._report(test);
});
}, _.extend(TestRun.prototype, {
_prefixMatch: function(testPath) {
for (var self = this, i = 0; i < self._pathPrefix.length; i++) if (!testPath[i] || self._pathPrefix[i] !== testPath[i]) return !1;
return !0;
},
_runTest: function(test, onComplete, stop_at_offset) {
var self = this, startTime = +new Date();
test.run(function(event) {
/* onEvent */
// Ignore result callbacks if the test has already been reported
// as timed out.
test.timedOut || self._report(test, event);
}, function() {
/* onComplete */
if (!test.timedOut) {
var totalTime = +new Date() - startTime;
self._report(test, {
type: "finish",
timeMs: totalTime
}), onComplete();
}
}, function(exception) {
/* onException */
test.timedOut || (// XXX you want the "name" and "message" fields on the
// exception, to start with..
self._report(test, {
type: "exception",
details: {
message: exception.message,
// XXX empty???
stack: exception.stack
}
}), onComplete());
}, stop_at_offset);
},
// Run a single test. On the server, ensure that only one test runs
// at a time, even with multiple clients submitting tests. However,
// time out the test after three minutes to avoid locking up the
// server if a test fails to complete.
//
_runOne: function(test, onComplete, stop_at_offset) {
var self = this;
// On the server, ensure that only one test runs at a time, even
// with multiple clients.
// client
return self._prefixMatch(test.groupPath) ? void (Meteor.isServer ? self.manager.testQueue.queueTask(function() {
// The future resolves when the test completes or times out.
var future = new Future();
Meteor.setTimeout(function() {
future.isResolved() || (test.timedOut = !0, self._report(test, {
type: "exception",
details: {
message: "test timed out"
}
}), future["return"]());
}, 18e4), self._runTest(test, function() {
// The test can complete after it has timed out (it might
// just be slow), so only resolve the future if the test
// hasn't timed out.
future.isResolved() || future["return"]();
}, stop_at_offset), // Wait for the test to complete or time out.
future.wait(), onComplete && onComplete();
}) : self._runTest(test, function() {
onComplete && onComplete();
}, stop_at_offset)) : void (onComplete && onComplete());
},
run: function(onComplete) {
var self = this, tests = _.clone(self.manager.ordered_tests), reportCurrent = function(name) {
Meteor.isClient && Tinytest._onCurrentClientTest(name);
}, runNext = function() {
if (tests.length) {
var t = tests.shift();
reportCurrent(t.name), self._runOne(t, runNext);
} else reportCurrent(null), onComplete && onComplete();
};
runNext();
},
// An alternative to run(). Given the 'cookie' attribute of a
// failure record, try to rerun that particular test up to that
// failure, and then open the debugger.
debug: function(cookie, onComplete) {
var self = this, test = self.manager.tests[cookie.name];
if (!test) throw new Error("No such test '" + cookie.name + "'");
self._runOne(test, onComplete, cookie.offset);
},
_report: function(test, event) {
var self = this;
if (event) var events = [ _.extend({
sequence: self.next_sequence_number++
}, event) ]; else var events = [];
self.onReport({
groupPath: test.groupPath,
test: test.shortName,
events: events
});
}
}), /******************************************************************************/
/* Public API */
/******************************************************************************/
Tinytest = {}, Tinytest.addAsync = function(name, func) {
TestManager.addCase(new TestCase(name, func));
}, Tinytest.add = function(name, func) {
Tinytest.addAsync(name, function(test, onComplete) {
func(test), onComplete();
});
}, // Run every test, asynchronously. Runs the test in the current
// process only (if called on the server, runs the tests on the
// server, and likewise for the client.) Report results via
// onReport. Call onComplete when it's done.
//
Tinytest._runTests = function(onReport, onComplete, pathPrefix) {
var testRun = TestManager.createRun(onReport, pathPrefix);
testRun.run(onComplete);
}, // Run just one test case, and stop the debugger at a particular
// error, all as indicated by 'cookie', which will have come from a
// failure event output by _runTests.
//
Tinytest._debugTest = function(cookie, onReport, onComplete) {
var testRun = TestManager.createRun(onReport);
testRun.debug(cookie, onComplete);
}, // Replace this callback to get called when we run a client test,
// and then called with `null` when the client tests are
// done. This is used to provide a live display of the current
// running client test on the test results page.
Tinytest._onCurrentClientTest = function(name) {}, // Like Tinytest._runTests, but runs the tests on both the client and
// the server. Sets a 'server' flag on test results that came from the
// server.
//
// Options:
// serial if true, will not run tests in parallel. Currently this means
// running the server tests before running the client tests.
// Default is currently true (serial operation), but we will likely
// change this to false in future.
Tinytest._runTestsEverywhere = function(onReport, onComplete, pathPrefix, options) {
var runId = Random.id(), localComplete = !1, localStarted = !1, remoteComplete = !1, done = !1;
options = _.extend({
serial: !0
}, options);
var handle, serial = !!options.serial, maybeDone = function() {
!done && localComplete && remoteComplete && (done = !0, onComplete && onComplete()),
serial && remoteComplete && !localStarted && startLocalTests();
}, startLocalTests = function() {
localStarted = !0, Tinytest._runTests(onReport, function() {
localComplete = !0, maybeDone();
}, pathPrefix);
};
Meteor.connection.registerStore(Meteor._ServerTestResultsCollection, {
update: function(msg) {
// We only should call _runTestsEverywhere once per client-page-load, so
// we really only should see one runId here.
msg.id === runId && (// This will only work for added & changed messages.
// hope that is all you get.
_.each(msg.fields, function(report, key) {
// Skip the 'complete' report (deal with it last)
"complete" !== key && (_.each(report.events, function(event) {
delete event.cookie;
}), report.server = !0, onReport(report));
}), // Now that we've processed all the other messages,
// check if we have the 'complete' message
msg.fields && _.has(msg.fields, "complete") && (remoteComplete = !0, handle.stop(),
Meteor.call("tinytest/clearResults", runId), maybeDone()));
}
}), handle = Meteor.subscribe(Meteor._ServerTestResultsSubscription, runId), Meteor.call("tinytest/run", runId, pathPrefix, function(error, result) {
if (error) // XXX better report error
throw new Error("Test server returned an error");
}), serial || startLocalTests();
}, // Hack to make LocalCollection generate ObjectIDs by default.
LocalCollection._useOID = !0;
// assert that f is a strcmp-style comparison function that puts
// 'values' in the provided order
var assert_ordering = function(test, f, values) {
for (var i = 0; i < values.length; i++) {
var x = f(values[i], values[i]);
if (0 !== x && // XXX super janky
test.fail({
type: "minimongo-ordering",
message: "value doesn't order as equal to itself",
value: JSON.stringify(values[i]),
should_be_zero_but_got: JSON.stringify(x)
}), i + 1 < values.length) {
var less = values[i], more = values[i + 1], x = f(less, more);
0 > x || // XXX super janky
test.fail({
type: "minimongo-ordering",
message: "ordering test failed",
first: JSON.stringify(less),
second: JSON.stringify(more),
should_be_negative_but_got: JSON.stringify(x)
}), x = f(more, less), x > 0 || // XXX super janky
test.fail({
type: "minimongo-ordering",
message: "ordering test failed",
first: JSON.stringify(less),
second: JSON.stringify(more),
should_be_positive_but_got: JSON.stringify(x)
});
}
}
}, log_callbacks = function(operations) {
return {
addedAt: function(obj, idx, before) {
delete obj._id, operations.push(EJSON.clone([ "added", obj, idx, before ]));
},
changedAt: function(obj, old_obj, at) {
delete obj._id, delete old_obj._id, operations.push(EJSON.clone([ "changed", obj, at, old_obj ]));
},
movedTo: function(obj, old_at, new_at, before) {
delete obj._id, operations.push(EJSON.clone([ "moved", obj, old_at, new_at, before ]));
},
removedAt: function(old_obj, at) {
var id = old_obj._id;
delete old_obj._id, operations.push(EJSON.clone([ "removed", id, at, old_obj ]));
}
};
};
// XXX test shared structure in all MM entrypoints
Tinytest.add("minimongo - basics", function(test) {
var fluffyKitten_id, count, c = new LocalCollection();
fluffyKitten_id = c.insert({
type: "kitten",
name: "fluffy"
}), c.insert({
type: "kitten",
name: "snookums"
}), c.insert({
type: "cryptographer",
name: "alice"
}), c.insert({
type: "cryptographer",
name: "bob"
}), c.insert({
type: "cryptographer",
name: "cara"
}), test.equal(c.find().count(), 5), test.equal(c.find({
type: "kitten"
}).count(), 2), test.equal(c.find({
type: "cryptographer"
}).count(), 3), test.length(c.find({
type: "kitten"
}).fetch(), 2), test.length(c.find({
type: "cryptographer"
}).fetch(), 3), test.equal(fluffyKitten_id, c.findOne({
type: "kitten",
name: "fluffy"
})._id), c.remove({
name: "cara"
}), test.equal(c.find().count(), 4), test.equal(c.find({
type: "kitten"
}).count(), 2), test.equal(c.find({
type: "cryptographer"
}).count(), 2), test.length(c.find({
type: "kitten"
}).fetch(), 2), test.length(c.find({
type: "cryptographer"
}).fetch(), 2), count = c.update({
name: "snookums"
}, {
$set: {
type: "cryptographer"
}
}), test.equal(count, 1), test.equal(c.find().count(), 4), test.equal(c.find({
type: "kitten"
}).count(), 1), test.equal(c.find({
type: "cryptographer"
}).count(), 3), test.length(c.find({
type: "kitten"
}).fetch(), 1), test.length(c.find({
type: "cryptographer"
}).fetch(), 3), c.remove(null), c.remove(!1), c.remove(void 0), test.equal(c.find().count(), 4),
c.remove({
_id: null
}), c.remove({
_id: !1
}), c.remove({
_id: void 0
}), count = c.remove(), test.equal(count, 0), test.equal(c.find().count(), 4), count = c.remove({}),
test.equal(count, 4), test.equal(c.find().count(), 0), c.insert({
_id: 1,
name: "strawberry",
tags: [ "fruit", "red", "squishy" ]
}), c.insert({
_id: 2,
name: "apple",
tags: [ "fruit", "red", "hard" ]
}), c.insert({
_id: 3,
name: "rose",
tags: [ "flower", "red", "squishy" ]
}), test.equal(c.find({
tags: "flower"
}).count(), 1), test.equal(c.find({
tags: "fruit"
}).count(), 2), test.equal(c.find({
tags: "red"
}).count(), 3), test.length(c.find({
tags: "flower"
}).fetch(), 1), test.length(c.find({
tags: "fruit"
}).fetch(), 2), test.length(c.find({
tags: "red"
}).fetch(), 3), test.equal(c.findOne(1).name, "strawberry"), test.equal(c.findOne(2).name, "apple"),
test.equal(c.findOne(3).name, "rose"), test.equal(c.findOne(4), void 0), test.equal(c.findOne("abc"), void 0),
test.equal(c.findOne(void 0), void 0), test.equal(c.find(1).count(), 1), test.equal(c.find(4).count(), 0),
test.equal(c.find("abc").count(), 0), test.equal(c.find(void 0).count(), 0), test.equal(c.find().count(), 3),
test.equal(c.find(1, {
skip: 1
}).count(), 0), test.equal(c.find({
_id: 1
}, {
skip: 1
}).count(), 0), test.equal(c.find({}, {
skip: 1
}).count(), 2), test.equal(c.find({}, {
skip: 2
}).count(), 1), test.equal(c.find({}, {
limit: 2
}).count(), 2), test.equal(c.find({}, {
limit: 1
}).count(), 1), test.equal(c.find({}, {
skip: 1,
limit: 1
}).count(), 1), test.equal(c.find({
tags: "fruit"
}, {
skip: 1
}).count(), 1), test.equal(c.find({
tags: "fruit"
}, {
limit: 1
}).count(), 1), test.equal(c.find({
tags: "fruit"
}, {
skip: 1,
limit: 1
}).count(), 1), test.equal(c.find(1, {
sort: [ "_id", "desc" ],
skip: 1
}).count(), 0), test.equal(c.find({
_id: 1
}, {
sort: [ "_id", "desc" ],
skip: 1
}).count(), 0), test.equal(c.find({}, {
sort: [ "_id", "desc" ],
skip: 1
}).count(), 2), test.equal(c.find({}, {
sort: [ "_id", "desc" ],
skip: 2
}).count(), 1), test.equal(c.find({}, {
sort: [ "_id", "desc" ],
limit: 2
}).count(), 2), test.equal(c.find({}, {
sort: [ "_id", "desc" ],
limit: 1
}).count(), 1), test.equal(c.find({}, {
sort: [ "_id", "desc" ],
skip: 1,
limit: 1
}).count(), 1), test.equal(c.find({
tags: "fruit"
}, {
sort: [ "_id", "desc" ],
skip: 1
}).count(), 1), test.equal(c.find({
tags: "fruit"
}, {
sort: [ "_id", "desc" ],
limit: 1
}).count(), 1), test.equal(c.find({
tags: "fruit"
}, {
sort: [ "_id", "desc" ],
skip: 1,
limit: 1
}).count(), 1), // Regression test for #455.
c.insert({
foo: {
bar: "baz"
}
}), test.equal(c.find({
foo: {
bam: "baz"
}
}).count(), 0), test.equal(c.find({
foo: {
bar: "baz"
}
}).count(), 1);
}), Tinytest.add("minimongo - cursors", function(test) {
for (var res, c = new LocalCollection(), i = 0; 20 > i; i++) c.insert({
i: i
});
var q = c.find();
test.equal(q.count(), 20), // fetch
res = q.fetch(), test.length(res, 20);
for (var i = 0; 20 > i; i++) test.equal(res[i].i, i);
// call it again, it still works
test.length(q.fetch(), 20);
// forEach
var count = 0, context = {};
q.forEach(function(obj, i, cursor) {
test.equal(obj.i, count++), test.equal(obj.i, i), test.isTrue(context === this),
test.isTrue(cursor === q);
}, context), test.equal(count, 20), // call it again, it still works
test.length(q.fetch(), 20), // map
res = q.map(function(obj, i, cursor) {
return test.equal(obj.i, i), test.isTrue(context === this), test.isTrue(cursor === q),
2 * obj.i;
}, context), test.length(res, 20);
for (var i = 0; 20 > i; i++) test.equal(res[i], 2 * i);
// call it again, it still works
test.length(q.fetch(), 20), // findOne (and no rewind first)
test.equal(c.findOne({
i: 0
}).i, 0), test.equal(c.findOne({
i: 1
}).i, 1);
var id = c.findOne({
i: 2
})._id;
test.equal(c.findOne(id).i, 2);
}), Tinytest.add("minimongo - transform", function(test) {
var c = new LocalCollection();
c.insert({});
// transform functions must return objects
var invalidTransform = function(doc) {
return doc._id;
};
test["throws"](function() {
c.findOne({}, {
transform: invalidTransform
});
});
// transformed documents get _id field transplanted if not present
var transformWithoutId = function(doc) {
return _.omit(doc, "_id");
};
test.equal(c.findOne({}, {
transform: transformWithoutId
})._id, c.findOne()._id);
}), Tinytest.add("minimongo - misc", function(test) {
// deepcopy
var a = {
a: [ 1, 2, 3 ],
b: "x",
c: !0,
d: {
x: 12,
y: [ 12 ]
},
f: null,
g: new Date()
}, b = EJSON.clone(a);
test.equal(a, b), test.isTrue(LocalCollection._f._equal(a, b)), a.a.push(4), test.length(b.a, 3),
a.c = !1, test.isTrue(b.c), b.d.z = 15, a.d.z = 14, test.equal(b.d.z, 15), a.d.y.push(88),
test.length(b.d.y, 1), test.equal(a.g, b.g), b.g.setDate(b.g.getDate() + 1), test.notEqual(a.g, b.g),
a = {
x: function() {}
}, b = EJSON.clone(a), a.x.a = 14, test.equal(b.x.a, 14);
}), Tinytest.add("minimongo - lookup", function(test) {
var lookupA = MinimongoTest.makeLookupFunction("a");
test.equal(lookupA({}), [ {
value: void 0
} ]), test.equal(lookupA({
a: 1
}), [ {
value: 1
} ]), test.equal(lookupA({
a: [ 1 ]
}), [ {
value: [ 1 ]
} ]);
var lookupAX = MinimongoTest.makeLookupFunction("a.x");
test.equal(lookupAX({
a: {
x: 1
}
}), [ {
value: 1
} ]), test.equal(lookupAX({
a: {
x: [ 1 ]
}
}), [ {
value: [ 1 ]
} ]), test.equal(lookupAX({
a: 5
}), [ {
value: void 0
} ]), test.equal(lookupAX({
a: [ {
x: 1
}, {
x: [ 2 ]
}, {
y: 3
} ]
}), [ {
value: 1,
arrayIndices: [ 0 ]
}, {
value: [ 2 ],
arrayIndices: [ 1 ]
}, {
value: void 0,
arrayIndices: [ 2 ]
} ]);
var lookupA0X = MinimongoTest.makeLookupFunction("a.0.x");
test.equal(lookupA0X({
a: [ {
x: 1
} ]
}), [ // From interpreting '0' as "0th array element".
{
value: 1,
arrayIndices: [ 0, "x" ]
}, // From interpreting '0' as "after branching in the array, look in the
// object {x:1} for a field named 0".
{
value: void 0,
arrayIndices: [ 0 ]
} ]), test.equal(lookupA0X({
a: [ {
x: [ 1 ]
} ]
}), [ {
value: [ 1 ],
arrayIndices: [ 0, "x" ]
}, {
value: void 0,
arrayIndices: [ 0 ]
} ]), test.equal(lookupA0X({
a: 5
}), [ {
value: void 0
} ]), test.equal(lookupA0X({
a: [ {
x: 1
}, {
x: [ 2 ]
}, {
y: 3
} ]
}), [ // From interpreting '0' as "0th array element".
{
value: 1,
arrayIndices: [ 0, "x" ]
}, // From interpreting '0' as "after branching in the array, look in the
// object {x:1} for a field named 0".
{
value: void 0,
arrayIndices: [ 0 ]
}, {
value: void 0,
arrayIndices: [ 1 ]
}, {
value: void 0,
arrayIndices: [ 2 ]
} ]), test.equal(MinimongoTest.makeLookupFunction("w.x.0.z")({
w: [ {
x: [ {
z: 5
} ]
} ]
}), [ // From interpreting '0' as "0th array element".
{
value: 5,
arrayIndices: [ 0, 0, "x" ]
}, // From interpreting '0' as "after branching in the array, look in the
// object {z:5} for a field named "0".
{
value: void 0,
arrayIndices: [ 0, 0 ]
} ]);
}), Tinytest.add("minimongo - selector_compiler", function(test) {
var matches = function(shouldMatch, selector, doc) {
var doesMatch = new Minimongo.Matcher(selector).documentMatches(doc).result;
doesMatch != shouldMatch && // XXX super janky
test.fail({
message: "minimongo match failure: document " + (shouldMatch ? "should match, but doesn't" : "shouldn't match, but does"),
selector: JSON.stringify(selector),
document: JSON.stringify(doc)
});
}, match = _.bind(matches, null, !0), nomatch = _.bind(matches, null, !1);
// XXX blog post about what I learned while writing these tests (weird
// mongo edge cases)
// empty selectors
match({}, {}), match({}, {
a: 12
}), // scalars
match(1, {
_id: 1,
a: "foo"
}), nomatch(1, {
_id: 2,
a: "foo"
}), match("a", {
_id: "a",
a: "foo"
}), nomatch("a", {
_id: "b",
a: "foo"
}), // safety
nomatch(void 0, {}), nomatch(void 0, {
_id: "foo"
}), nomatch(!1, {
_id: "foo"
}), nomatch(null, {
_id: "foo"
}), nomatch({
_id: void 0
}, {
_id: "foo"
}), nomatch({
_id: !1
}, {
_id: "foo"
}), nomatch({
_id: null
}, {
_id: "foo"
}), // matching one or more keys
nomatch({
a: 12
}, {}), match({
a: 12
}, {
a: 12
}), match({
a: 12
}, {
a: 12,
b: 13
}), match({
a: 12,
b: 13
}, {
a: 12,
b: 13
}), match({
a: 12,
b: 13
}, {
a: 12,
b: 13,
c: 14
}), nomatch({
a: 12,
b: 13,