-
Notifications
You must be signed in to change notification settings - Fork 920
/
Copy pathvalidation.test.ts
1398 lines (1282 loc) · 43.1 KB
/
validation.test.ts
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
/**
* @license
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { expect } from 'chai';
import { Deferred } from '../../util/promise';
import {
arrayRemove,
arrayUnion,
collectionGroup,
connectFirestoreEmulator,
deleteField,
documentId,
enableIndexedDbPersistence,
endAt,
endBefore,
increment,
limit,
limitToLast,
newTestFirestore,
startAfter,
startAt,
writeBatch,
collection,
disableNetwork,
doc,
DocumentSnapshot,
enableNetwork,
Firestore,
getDoc,
onSnapshot,
orderBy,
query,
runTransaction,
serverTimestamp,
setDoc,
updateDoc,
where,
or,
and,
newTestApp
} from '../util/firebase_export';
import {
apiDescribe,
PersistenceMode,
withAlternateTestDb,
withTestCollection,
withTestDb
} from '../util/helpers';
import {
ALT_PROJECT_ID,
DEFAULT_PROJECT_ID,
TARGET_DB_ID,
USE_EMULATOR,
getEmulatorPort
} from '../util/settings';
// We're using 'as any' to pass invalid values to APIs for testing purposes.
/* eslint-disable @typescript-eslint/no-explicit-any */
interface ValidationIt {
(
persistence: PersistenceMode,
message: string,
testFunction: (db: Firestore) => void | Promise<any>
): void;
skip: (
persistence: PersistenceMode,
message: string,
testFunction: (db: Firestore) => void | Promise<any>
) => void;
only: (
persistence: PersistenceMode,
message: string,
testFunction: (db: Firestore) => void | Promise<any>
) => void;
}
// Since most of our tests are "synchronous" but require a Firestore instance,
// we have a helper wrapper around it() and withTestDb() to optimize for that.
const validationIt: ValidationIt = Object.assign(
(
persistence: PersistenceMode,
message: string,
testFunction: (db: Firestore) => void | Promise<any>
) => {
it(message, () => {
return withTestDb(persistence, async db => {
const maybePromise = testFunction(db);
if (maybePromise) {
return maybePromise;
}
});
});
},
{
skip(
persistence: PersistenceMode,
message: string,
_: (db: Firestore) => void | Promise<any>
): void {
// eslint-disable-next-line no-restricted-properties
it.skip(message, () => {});
},
only(
persistence: PersistenceMode,
message: string,
testFunction: (db: Firestore) => void | Promise<any>
): void {
// eslint-disable-next-line no-restricted-properties
it.only(message, () => {
return withTestDb(persistence, async db => {
const maybePromise = testFunction(db);
if (maybePromise) {
return maybePromise;
}
});
});
}
}
);
/** Class used to verify custom classes can't be used in writes. */
class TestClass {
constructor(readonly property: string) {}
}
apiDescribe('Validation:', persistence => {
describe('FirestoreSettings', () => {
validationIt(
persistence,
'disallows changing settings after use',
async db => {
await setDoc(doc(db, 'foo/bar'), {});
expect(() =>
connectFirestoreEmulator(db, 'something-else.example.com', 8080)
).to.throw(
'Firestore has already been started and its settings can no ' +
'longer be changed. You can only modify settings before calling any other ' +
'methods on a Firestore object.'
);
}
);
validationIt(persistence, 'enforces minimum cache size', () => {
expect(() =>
newTestFirestore(newTestApp('test-project'), { cacheSizeBytes: 1 })
).to.throw('cacheSizeBytes must be at least 1048576');
});
validationIt(persistence, 'garbage collection can be disabled', () => {
// Verify that this doesn't throw.
newTestFirestore(newTestApp('test-project'), {
cacheSizeBytes: /* CACHE_SIZE_UNLIMITED= */ -1
});
});
validationIt(
persistence,
'connectFirestoreEmulator() can set host and port',
() => {
const db = newTestFirestore(newTestApp('test-project'));
// Verify that this doesn't throw.
connectFirestoreEmulator(db, '127.0.0.1', 9000);
}
);
validationIt(
persistence,
'connectFirestoreEmulator() can set mockUserToken object',
() => {
const db = newTestFirestore(newTestApp('test-project'));
// Verify that this doesn't throw.
connectFirestoreEmulator(db, '127.0.0.1', 9000, {
mockUserToken: { sub: 'foo' }
});
}
);
validationIt(
persistence,
'disallows calling connectFirestoreEmulator() for first time after use',
async db => {
const errorMsg =
'Firestore has already been started and its settings can no longer be changed.';
await setDoc(doc(db, 'foo/bar'), {});
expect(() => connectFirestoreEmulator(db, '127.0.0.1', 9000)).to.throw(
errorMsg
);
}
);
validationIt(
persistence,
'allows calling connectFirestoreEmulator() after use with same config',
async db => {
if (USE_EMULATOR) {
const port = getEmulatorPort();
connectFirestoreEmulator(db, '127.0.0.1', port);
await setDoc(doc(db, 'foo/bar'), {});
expect(() =>
connectFirestoreEmulator(db, '127.0.0.1', port)
).to.not.throw();
}
}
);
validationIt(
persistence,
'disallows calling connectFirestoreEmulator() after use with different config',
async db => {
if (USE_EMULATOR) {
const errorMsg =
'Firestore has already been started and its settings can no longer be changed.';
const port = getEmulatorPort();
connectFirestoreEmulator(db, '127.0.0.1', port);
await setDoc(doc(db, 'foo/bar'), {});
expect(() =>
connectFirestoreEmulator(db, '127.0.0.1', port + 1)
).to.throw(errorMsg);
}
}
);
validationIt(
persistence,
'connectFirestoreEmulator() can set mockUserToken string',
() => {
const db = newTestFirestore(newTestApp('test-project'));
// Verify that this doesn't throw.
connectFirestoreEmulator(db, '127.0.0.1', 9000, {
mockUserToken: 'my-mock-user-token'
});
}
);
validationIt(
persistence,
'throws if sub / user_id is missing in mockUserToken',
async db => {
const errorMsg = "mockUserToken must contain 'sub' or 'user_id' field!";
expect(() =>
connectFirestoreEmulator(db, '127.0.0.1', 9000, {
mockUserToken: {} as any
})
).to.throw(errorMsg);
}
);
});
describe('Firestore', () => {
validationIt(
persistence,
'disallows calling enableIndexedDbPersistence() after use',
async db => {
await getDoc(doc(db, 'foo/bar'));
expect(() => enableIndexedDbPersistence(db)).to.throw(
'Firestore has already been started and persistence can no ' +
'longer be enabled. You can only enable persistence before ' +
'calling any other methods on a Firestore object.'
);
}
);
it("fails transaction if function doesn't return a Promise.", () => {
return withTestDb(persistence, db => {
return runTransaction(db, () => 5 as any).then(
() => expect.fail('Transaction should fail'),
err => {
expect(err.message).to.equal(
'Transaction callback must return a Promise'
);
}
);
});
});
});
describe('Collection paths', () => {
validationIt(persistence, 'must be non-empty strings', db => {
expect(() => collection(db, '')).to.throw(
'Function collection() cannot be called with an empty path.'
);
});
validationIt(persistence, 'must be odd-length', db => {
const baseDocRef = doc(db, 'foo/bar');
const badAbsolutePaths = ['foo/bar', 'foo/bar/baz/quu'];
const badRelativePaths = ['/', 'baz/quu'];
const badPathLengths = [2, 4];
for (let i = 0; i < badAbsolutePaths.length; i++) {
const error =
'Invalid collection reference. Collection references ' +
'must have an odd number of segments, but ' +
`${badAbsolutePaths[i]} has ${badPathLengths[i]}`;
expect(() => collection(db, badAbsolutePaths[i])).to.throw(error);
expect(() => collection(baseDocRef, badRelativePaths[i])).to.throw(
error
);
}
});
validationIt(persistence, 'must not have empty segments', db => {
// NOTE: leading / trailing slashes are okay.
collection(db, '/foo/');
collection(db, '/foo');
collection(db, 'foo/');
const badPaths = ['foo//bar//baz', '//foo', 'foo//'];
const collRef = collection(db, 'test-collection');
const docRef = doc(collRef, 'test-document');
for (const path of badPaths) {
const reason = `Invalid segment (${path}). Paths must not contain // in them.`;
expect(() => collection(db, path)).to.throw(reason);
expect(() => doc(db, path)).to.throw(reason);
expect(() => doc(collRef, path)).to.throw(reason);
expect(() => collection(docRef, path)).to.throw(reason);
}
});
});
describe('Document paths', () => {
validationIt(persistence, 'must be strings', db => {
expect(() => doc(db, '')).to.throw(
'Function doc() cannot be called with an empty path.'
);
});
validationIt(persistence, 'must be even-length', db => {
const baseCollectionRef = collection(db, 'foo');
const badAbsolutePaths = ['foo', 'foo/bar/baz'];
const badRelativePaths = ['/', 'bar/baz'];
const badPathLengths = [1, 3];
for (let i = 0; i < badAbsolutePaths.length; i++) {
const error =
'Invalid document reference. Document references ' +
'must have an even number of segments, but ' +
`${badAbsolutePaths[i]} has ${badPathLengths[i]}`;
expect(() => doc(db, badAbsolutePaths[i])).to.throw(error);
expect(() => doc(baseCollectionRef, badRelativePaths[i])).to.throw(
error
);
}
});
});
describe('Writes', () => {
validationIt(persistence, 'must be objects.', db => {
// PORTING NOTE: The error for deleteField() is different for minified
// builds, so omit testing it specifically.
const badData = [
42,
[1],
new Date(),
null,
() => {},
new TestClass('foo'),
undefined
];
const errorDescriptions = [
'42',
'an array',
'a custom Date object',
'null',
'a function',
'a custom TestClass object'
];
const promises: Array<Promise<void>> = [];
for (let i = 0; i < badData.length; i++) {
const error =
'Data must be an object, but it was: ' + errorDescriptions[i];
promises.push(expectWriteToFail(db, badData[i], error));
}
return Promise.all(promises);
});
validationIt(
persistence,
'must not contain custom objects or functions.',
db => {
const badData = [
{ foo: new TestClass('foo') },
{ foo: [new TestClass('foo')] },
{ foo: { bar: new TestClass('foo') } },
{ foo: () => {} },
{ foo: [() => {}] },
{ foo: { bar: () => {} } }
];
const errorDescriptions = [
'Unsupported field value: a custom TestClass object (found in field foo)',
'Unsupported field value: a custom TestClass object',
'Unsupported field value: a custom TestClass object (found in field foo.bar)',
'Unsupported field value: a function (found in field foo)',
'Unsupported field value: a function',
'Unsupported field value: a function (found in field foo.bar)'
];
const promises: Array<Promise<void>> = [];
for (let i = 0; i < badData.length; i++) {
promises.push(
expectWriteToFail(db, badData[i], errorDescriptions[i])
);
}
return Promise.all(promises);
}
);
validationIt(
persistence,
'must not contain field value transforms in arrays',
db => {
return expectWriteToFail(
db,
{ 'array': [serverTimestamp()] },
'serverTimestamp() is not currently supported inside arrays'
);
}
);
validationIt(
persistence,
'must not contain directly nested arrays.',
db => {
return expectWriteToFail(
db,
{ 'nested-array': [1, [2]] },
'Nested arrays are not supported'
);
}
);
validationIt(persistence, 'may contain indirectly nested arrays.', db => {
const data = { 'nested-array': [1, { foo: [2] }] };
const ref = doc(collection(db, 'foo'));
const ref2 = doc(collection(db, 'foo'));
return setDoc(ref, data)
.then(() => writeBatch(db).set(ref, data).commit())
.then(() => updateDoc(ref, data))
.then(() => writeBatch(db).update(ref, data).commit())
.then(() =>
runTransaction(db, async txn => {
// Note ref2 does not exist at this point so set that and update ref.
txn.update(ref, data);
txn.set(ref2, data);
})
);
});
validationIt(persistence, 'must not contain undefined.', db => {
// Note: This test uses the default setting for `ignoreUndefinedProperties`.
return expectWriteToFail(
db,
{ foo: undefined },
'Unsupported field value: undefined (found in field foo)'
);
});
validationIt(
persistence,
'must not contain references to a different database',
db => {
return withAlternateTestDb(persistence, db2 => {
const ref = doc(db2, 'baz/quu');
const data = { foo: ref };
return expectWriteToFail(
db,
data,
`Document reference is for database ` +
`${ALT_PROJECT_ID}/${TARGET_DB_ID} but should be for database ` +
`${DEFAULT_PROJECT_ID}/${TARGET_DB_ID} (found in field ` +
`foo)`
);
});
}
);
validationIt(persistence, 'must not contain reserved field names.', db => {
return Promise.all([
expectWriteToFail(
db,
{ __baz__: 1 },
'Document fields cannot begin and end with "__" (found in field ' +
'__baz__)'
),
expectWriteToFail(
db,
{ foo: { __baz__: 1 } },
'Document fields cannot begin and end with "__" (found in field ' +
'foo.__baz__)'
),
expectWriteToFail(
db,
{ __baz__: { foo: 1 } },
'Document fields cannot begin and end with "__" (found in field ' +
'__baz__)'
),
expectUpdateToFail(
db,
{ 'foo.__baz__': 1 },
'Document fields cannot begin and end with "__" (found in field ' +
'foo.__baz__)'
),
expectUpdateToFail(
db,
{ '__baz__.foo': 1 },
'Document fields cannot begin and end with "__" (found in field ' +
'__baz__.foo)'
)
]);
});
validationIt(persistence, 'must not contain empty field names.', db => {
return expectSetToFail(
db,
{ '': 'foo' },
'Document fields must not be empty (found in field ``)'
);
});
validationIt(
persistence,
'via set() must not contain deleteField()',
db => {
return expectSetToFail(
db,
{ foo: deleteField() },
'deleteField() cannot be used with set() unless you pass ' +
'{merge:true} (found in field foo)'
);
}
);
validationIt(
persistence,
'via update() must not contain nested deleteField()',
db => {
return expectUpdateToFail(
db,
{ foo: { bar: deleteField() } },
'deleteField() can only appear at the top level of your ' +
'update data (found in field foo.bar)'
);
}
);
});
validationIt(
persistence,
'Batch writes require correct Document References',
db => {
return withAlternateTestDb(persistence, async db2 => {
const badRef = doc(db2, 'foo/bar');
const reason =
'Provided document reference is from a different Firestore instance.';
const data = { foo: 1 };
const batch = writeBatch(db);
expect(() => batch.set(badRef, data)).to.throw(reason);
expect(() => batch.update(badRef, data)).to.throw(reason);
expect(() => batch.delete(badRef)).to.throw(reason);
});
}
);
validationIt(
persistence,
'Transaction writes require correct Document References',
db => {
return withAlternateTestDb(persistence, db2 => {
const badRef = doc(db2, 'foo/bar');
const reason =
'Provided document reference is from a different Firestore instance.';
const data = { foo: 1 };
return runTransaction(db, async txn => {
expect(() => txn.get(badRef)).to.throw(reason);
expect(() => txn.set(badRef, data)).to.throw(reason);
expect(() => txn.update(badRef, data)).to.throw(reason);
expect(() => txn.delete(badRef)).to.throw(reason);
});
});
}
);
validationIt(persistence, 'Field paths must not have empty segments', db => {
const docRef = doc(collection(db, 'test'));
return setDoc(docRef, { test: 1 })
.then(() => getDoc(docRef))
.then(snapshot => {
const badFieldPaths = ['', 'foo..baz', '.foo', 'foo.'];
const promises: Array<Promise<void>> = [];
for (const fieldPath of badFieldPaths) {
const reason =
`Invalid field path (${fieldPath}). Paths must not be ` +
`empty, begin with '.', end with '.', or contain '..'`;
promises.push(expectFieldPathToFail(snapshot, fieldPath, reason));
}
return Promise.all(promises);
});
});
validationIt(
persistence,
'Field paths must not have invalid segments',
db => {
const docRef = doc(collection(db, 'test'));
return setDoc(docRef, { test: 1 })
.then(() => getDoc(docRef))
.then(snapshot => {
const badFieldPaths = [
'foo~bar',
'foo*bar',
'foo/bar',
'foo[1',
'foo]1',
'foo[1]'
];
const promises: Array<Promise<void>> = [];
for (const fieldPath of badFieldPaths) {
const reason =
`Invalid field path (${fieldPath}). Paths must not ` +
`contain '~', '*', '/', '[', or ']'`;
promises.push(expectFieldPathToFail(snapshot, fieldPath, reason));
}
return Promise.all(promises);
});
}
);
describe('Array transforms', () => {
validationIt(persistence, 'fail in queries', db => {
const coll = collection(db, 'test');
expect(() =>
query(coll, where('test', '==', { test: arrayUnion(1) }))
).to.throw(
'Function where() called with invalid data. ' +
'arrayUnion() can only be used with update() and set() ' +
'(found in field test)'
);
expect(() =>
query(coll, where('test', '==', { test: arrayRemove(1) }))
).to.throw(
'Function where() called with invalid data. ' +
'arrayRemove() can only be used with update() and set() ' +
'(found in field test)'
);
});
validationIt(persistence, 'reject invalid elements', db => {
const docRef = doc(collection(db, 'test'));
expect(() =>
setDoc(docRef, { x: arrayUnion(1, new TestClass('foo')) })
).to.throw(
'Function arrayUnion() called with invalid data. ' +
'Unsupported field value: a custom TestClass object'
);
expect(() =>
setDoc(docRef, { x: arrayRemove(1, new TestClass('foo')) })
).to.throw(
'Function arrayRemove() called with invalid data. ' +
'Unsupported field value: a custom TestClass object'
);
expect(() => setDoc(docRef, { x: arrayRemove(undefined) })).to.throw(
'Function arrayRemove() called with invalid data. ' +
'Unsupported field value: undefined'
);
});
validationIt(persistence, 'reject arrays', db => {
const docRef = doc(collection(db, 'test'));
// This would result in a directly nested array which is not supported.
expect(() => setDoc(docRef, { x: arrayUnion(1, ['nested']) })).to.throw(
'Function arrayUnion() called with invalid data. ' +
'Nested arrays are not supported'
);
expect(() => setDoc(docRef, { x: arrayRemove(1, ['nested']) })).to.throw(
'Function arrayRemove() called with invalid data. ' +
'Nested arrays are not supported'
);
});
});
describe('Numeric transforms', () => {
validationIt(persistence, 'fail in queries', db => {
const coll = collection(db, 'test');
expect(() =>
query(coll, where('test', '==', { test: increment(1) }))
).to.throw(
'Function where() called with invalid data. ' +
'increment() can only be used with update() and set() ' +
'(found in field test)'
);
});
});
describe('Queries', () => {
validationIt(persistence, 'with non-positive limit fail', db => {
const coll = collection(db, 'test');
expect(() => query(coll, limit(0))).to.throw(
`Function limit() requires a positive number, but it was: 0.`
);
expect(() => query(coll, limitToLast(-1))).to.throw(
`Function limitToLast() requires a positive number, but it was: -1.`
);
});
it('cannot be created from documents missing sort values', () => {
const testDocs = {
f: { k: 'f', nosort: 1 } // should not show up
};
return withTestCollection(persistence, testDocs, coll => {
const query1 = query(coll, orderBy('sort'));
return getDoc(doc(coll, 'f')).then(doc => {
expect(doc.data()).to.deep.equal({ k: 'f', nosort: 1 });
const reason =
`Invalid query. You are trying to start or end a ` +
`query using a document for which the field 'sort' (used as ` +
`the orderBy) does not exist.`;
expect(() => query(query1, startAt(doc))).to.throw(reason);
expect(() => query(query1, startAfter(doc))).to.throw(reason);
expect(() => query(query1, endBefore(doc))).to.throw(reason);
expect(() => query(query1, endAt(doc))).to.throw(reason);
});
});
});
validationIt(
persistence,
'cannot be sorted by an uncommitted server timestamp',
db => {
return withTestCollection(
persistence,
/*docs=*/ {},
async collection => {
await disableNetwork(db);
const offlineDeferred = new Deferred<void>();
const onlineDeferred = new Deferred<void>();
const unsubscribe = onSnapshot(collection, snapshot => {
// Skip the initial empty snapshot.
if (snapshot.empty) {
return;
}
expect(snapshot.docs).to.have.lengthOf(1);
const docSnap: DocumentSnapshot = snapshot.docs[0];
if (snapshot.metadata.hasPendingWrites) {
// Offline snapshot. Since the server timestamp is uncommitted,
// we shouldn't be able to query by it.
expect(() =>
onSnapshot(
query(collection, orderBy('timestamp'), endAt(docSnap)),
() => {}
)
).to.throw('uncommitted server timestamp');
offlineDeferred.resolve();
} else {
// Online snapshot. Since the server timestamp is committed, we
// should be able to query by it.
onSnapshot(
query(collection, orderBy('timestamp'), endAt(docSnap)),
() => {}
);
onlineDeferred.resolve();
}
});
const docRef = doc(collection);
void setDoc(docRef, { timestamp: serverTimestamp() });
await offlineDeferred.promise;
await enableNetwork(db);
await onlineDeferred.promise;
unsubscribe();
}
);
}
);
validationIt(
persistence,
'must not have more components than order by.',
db => {
const coll = collection(db, 'collection');
const query1 = query(coll, orderBy('foo'));
const reason =
'Too many arguments provided to startAt(). The number of ' +
'arguments must be less than or equal to the number of orderBy() ' +
'clauses';
expect(() => query(query1, startAt(1, 2))).to.throw(reason);
expect(() => query(query1, orderBy('bar'), startAt(1, 2, 3))).to.throw(
reason
);
}
);
validationIt(
persistence,
'order-by-key bounds must be strings without slashes.',
db => {
const collQuery = query(
collection(db, 'collection'),
orderBy(documentId())
);
const cgQuery = query(
collectionGroup(db, 'collection'),
orderBy(documentId())
);
expect(() => query(collQuery, startAt(1))).to.throw(
'Invalid query. Expected a string for document ID in ' +
'startAt(), but got a number'
);
expect(() => query(collQuery, startAt('foo/bar'))).to.throw(
'Invalid query. When querying a collection and ordering by ' +
'documentId(), the value passed to startAt() ' +
"must be a plain document ID, but 'foo/bar' contains a slash."
);
expect(() => query(cgQuery, startAt('foo'))).to.throw(
'Invalid query. When querying a collection group and ordering by ' +
'documentId(), the value passed to startAt() ' +
"must result in a valid document path, but 'foo' is not because " +
'it contains an odd number of segments.'
);
}
);
validationIt(persistence, 'with more than one != query fail', db => {
const coll = collection(db, 'test');
expect(() =>
query(coll, where('x', '!=', 32), where('x', '!=', 33))
).to.throw("Invalid query. You cannot use more than one '!=' filter.");
});
validationIt(persistence, 'with != and not-in filters fail', db => {
expect(() =>
query(
collection(db, 'test'),
where('foo', 'not-in', [2, 3]),
where('foo', '!=', 4)
)
).to.throw(
"Invalid query. You cannot use '!=' filters with 'not-in' filters."
);
expect(() =>
query(
collection(db, 'test'),
where('foo', '!=', 4),
where('foo', 'not-in', [2, 3])
)
).to.throw(
"Invalid query. You cannot use 'not-in' filters with '!=' filters."
);
});
validationIt(persistence, 'with multiple disjunctive filters fail', db => {
expect(() =>
query(
collection(db, 'test'),
where('foo', 'not-in', [1, 2]),
where('foo', 'not-in', [2, 3])
)
).to.throw(
"Invalid query. You cannot use more than one 'not-in' filter."
);
expect(() =>
query(
collection(db, 'test'),
where('foo', 'not-in', [2, 3]),
where('foo', 'array-contains-any', [2, 3])
)
).to.throw(
"Invalid query. You cannot use 'array-contains-any' filters with " +
"'not-in' filters."
);
expect(() =>
query(
collection(db, 'test'),
where('foo', 'array-contains-any', [2, 3]),
where('foo', 'not-in', [2, 3])
)
).to.throw(
"Invalid query. You cannot use 'not-in' filters with " +
"'array-contains-any' filters."
);
expect(() =>
query(
collection(db, 'test'),
where('foo', 'not-in', [2, 3]),
where('foo', 'in', [2, 3])
)
).to.throw(
"Invalid query. You cannot use 'in' filters with 'not-in' filters."
);
expect(() =>
query(
collection(db, 'test'),
where('foo', 'in', [2, 3]),
where('foo', 'not-in', [2, 3])
)
).to.throw(
"Invalid query. You cannot use 'not-in' filters with 'in' filters."
);
});
validationIt(
persistence,
'can have an IN filter with an array-contains filter.',
db => {
expect(() =>
query(
collection(db, 'test'),
where('foo', 'array-contains', 1),
where('foo', 'in', [2, 3])
)
).not.to.throw();
expect(() =>
query(
collection(db, 'test'),
where('foo', 'in', [2, 3]),
where('foo', 'array-contains', 1)
)
).not.to.throw();
}
);
validationIt(
persistence,
'enforce array requirements for disjunctive filters',
db => {
expect(() =>
query(collection(db, 'test'), where('foo', 'in', 2))
).to.throw(
"Invalid Query. A non-empty array is required for 'in' filters."
);
expect(() =>
query(collection(db, 'test'), where('foo', 'array-contains-any', 2))
).to.throw(
'Invalid Query. A non-empty array is required for ' +
"'array-contains-any' filters."
);
expect(() =>
query(collection(db, 'test'), where('foo', 'in', []))
).to.throw(
"Invalid Query. A non-empty array is required for 'in' filters."
);
expect(() =>
query(collection(db, 'test'), where('foo', 'array-contains-any', []))
).to.throw(
'Invalid Query. A non-empty array is required for ' +
"'array-contains-any' filters."
);
}
);
validationIt(
persistence,
'must not specify starting or ending point after orderBy',
db => {
const coll = collection(db, 'collection');
const query1 = query(coll, orderBy('foo'));
let reason =
'Invalid query. You must not call startAt() or startAfter() before calling orderBy().';
expect(() => query(query1, startAt(1), orderBy('bar'))).to.throw(
reason
);
expect(() => query(query1, startAfter(1), orderBy('bar'))).to.throw(