This repository was archived by the owner on Aug 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathdesign_document_tests.py
1858 lines (1756 loc) · 76.3 KB
/
design_document_tests.py
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
#!/usr/bin/env python
# Copyright (C) 2015, 2020 IBM Corp. All rights reserved.
#
# 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.
"""
_design_document_tests_
design_document module - Unit tests for the DesignDocument class
See configuration options for environment variables in unit_t_db_base
module docstring.
"""
import json
import os
import unittest
import mock
import requests
from cloudant._common_util import response_to_json_dict
from cloudant.design_document import DesignDocument
from cloudant.document import Document
from cloudant.error import CloudantArgumentError, CloudantDesignDocumentException
from cloudant.view import View, QueryIndexView
from nose.plugins.attrib import attr
from .unit_t_db_base import UnitTestDbBase, skip_if_iam
class CloudantDesignDocumentExceptionTests(unittest.TestCase):
"""
Ensure CloudantDesignDocumentException functions as expected.
"""
def test_raise_without_code(self):
"""
Ensure that a default exception/code is used if none is provided.
"""
with self.assertRaises(CloudantDesignDocumentException) as cm:
raise CloudantDesignDocumentException()
self.assertEqual(cm.exception.status_code, 100)
def test_raise_using_invalid_code(self):
"""
Ensure that a default exception/code is used if invalid code is provided.
"""
with self.assertRaises(CloudantDesignDocumentException) as cm:
raise CloudantDesignDocumentException('foo')
self.assertEqual(cm.exception.status_code, 100)
def test_raise_without_args(self):
"""
Ensure that a default exception/code is used if the message requested
by the code provided requires an argument list and none is provided.
"""
with self.assertRaises(CloudantDesignDocumentException) as cm:
raise CloudantDesignDocumentException(104)
self.assertEqual(cm.exception.status_code, 100)
def test_raise_with_proper_code_and_args(self):
"""
Ensure that the requested exception is raised.
"""
with self.assertRaises(CloudantDesignDocumentException) as cm:
raise CloudantDesignDocumentException(104, 'foo')
self.assertEqual(cm.exception.status_code, 104)
@attr(db=['cloudant','couch'])
class DesignDocumentTests(UnitTestDbBase):
"""
DesignDocument unit tests
"""
def setUp(self):
"""
Set up test attributes
"""
super(DesignDocumentTests, self).setUp()
self.db_set_up()
def tearDown(self):
"""
Reset test attributes
"""
self.db_tear_down()
super(DesignDocumentTests, self).tearDown()
def test_constructor_with_docid(self):
"""
Test instantiating a DesignDocument providing an id
not prefaced with '_design/'
"""
ddoc = DesignDocument(self.db, 'ddoc001')
self.assertIsInstance(ddoc, DesignDocument)
self.assertEqual(ddoc.get('_id'), '_design/ddoc001')
self.assertEqual(ddoc.get('views'), {})
def test_constructor_with_design_docid(self):
"""
Test instantiating a DesignDocument providing an id
prefaced with '_design/'
"""
ddoc = DesignDocument(self.db, '_design/ddoc001')
self.assertIsInstance(ddoc, DesignDocument)
self.assertEqual(ddoc.get('_id'), '_design/ddoc001')
self.assertEqual(ddoc.get('views'), {})
def test_constructor_without_docid(self):
"""
Test instantiating a DesignDocument without providing an id
"""
ddoc = DesignDocument(self.db)
self.assertIsInstance(ddoc, DesignDocument)
self.assertIsNone(ddoc.get('_id'))
self.assertEqual(ddoc.get('views'), {})
def test_create_design_document_with_docid_encoded_url(self):
"""
Test creating a design document providing an id that has an encoded url
"""
ddoc = DesignDocument(self.db, '_design/http://example.com')
self.assertFalse(ddoc.exists())
self.assertIsNone(ddoc.get('_rev'))
ddoc.create()
self.assertTrue(ddoc.exists())
self.assertTrue(ddoc.get('_rev').startswith('1-'))
def test_fetch_existing_design_document_with_docid_encoded_url(self):
"""
Test fetching design document content from an existing document where
the document id requires an encoded url
"""
ddoc = DesignDocument(self.db, '_design/http://example.com')
ddoc.create()
new_ddoc = DesignDocument(self.db, '_design/http://example.com')
new_ddoc.fetch()
self.assertEqual(new_ddoc, ddoc)
def test_update_design_document_with_encoded_url(self):
"""
Test that updating a design document where the document id requires that
the document url be encoded is successful.
"""
# First create the design document
ddoc = DesignDocument(self.db, '_design/http://example.com')
ddoc.save()
# Now test that the design document gets updated
ddoc.save()
self.assertTrue(ddoc['_rev'].startswith('2-'))
remote_ddoc = DesignDocument(self.db, '_design/http://example.com')
remote_ddoc.fetch()
self.assertEqual(remote_ddoc, ddoc)
def test_delete_design_document_success_with_encoded_url(self):
"""
Test that we can remove a design document from the remote
database successfully when the document id requires an encoded url.
"""
ddoc = DesignDocument(self.db, '_design/http://example.com')
ddoc.create()
self.assertTrue(ddoc.exists())
ddoc.delete()
self.assertFalse(ddoc.exists())
self.assertEqual(ddoc, {'_id': '_design/http://example.com'})
def test_add_a_view(self):
"""
Test that adding a view adds a View object to
the DesignDocument dictionary.
"""
ddoc = DesignDocument(self.db, '_design/ddoc001')
self.assertEqual(ddoc.get('views'), {})
ddoc.add_view(
'view001',
'function (doc) {\n emit(doc._id, 1);\n}'
)
self.assertListEqual(list(ddoc.get('views').keys()), ['view001'])
self.assertIsInstance(ddoc.get('views')['view001'], View)
self.assertEqual(
ddoc.get('views')['view001'],
{'map': 'function (doc) {\n emit(doc._id, 1);\n}'}
)
def test_adding_existing_view(self):
"""
Test that adding an existing view fails as expected.
"""
ddoc = DesignDocument(self.db, '_design/ddoc001')
ddoc.add_view(
'view001',
'function (doc) {\n emit(doc._id, 1);\n}'
)
try:
ddoc.add_view('view001', 'function (doc) {\n emit(doc._id, 2);\n}')
self.fail('Above statement should raise an Exception')
except CloudantArgumentError as err:
self.assertEqual(
str(err),
'View view001 already exists in this design doc.'
)
def test_adding_query_index_view(self):
"""
Test that adding a query index view fails as expected.
"""
ddoc = DesignDocument(self.db, '_design/ddoc001')
ddoc['language'] = 'query'
with self.assertRaises(CloudantDesignDocumentException) as cm:
ddoc.add_view('view001', {'foo': 'bar'})
err = cm.exception
self.assertEqual(
str(err),
'Cannot add a MapReduce view to a '
'design document for query indexes.'
)
def test_update_a_view(self):
"""
Test that updating a view updates the contents of the correct
View object in the DesignDocument dictionary.
"""
ddoc = DesignDocument(self.db, '_design/ddoc001')
ddoc.add_view('view001', 'not-a-valid-map-function')
self.assertEqual(
ddoc.get('views')['view001'],
{'map': 'not-a-valid-map-function'}
)
ddoc.update_view(
'view001',
'function (doc) {\n emit(doc._id, 1);\n}'
)
self.assertEqual(
ddoc.get('views')['view001'],
{'map': 'function (doc) {\n emit(doc._id, 1);\n}'}
)
def test_update_non_existing_view(self):
"""
Test that updating a non-existing view fails as expected.
"""
ddoc = DesignDocument(self.db, '_design/ddoc001')
try:
ddoc.update_view(
'view001',
'function (doc) {\n emit(doc._id, 1);\n}'
)
self.fail('Above statement should raise an Exception')
except CloudantArgumentError as err:
self.assertEqual(
str(err),
'View view001 does not exist in this design doc.'
)
def test_update_query_index_view(self):
"""
Test that updating a query index view fails as expected.
"""
# This is not the preferred way of dealing with query index
# views but it works best for this test.
data = {
'_id': '_design/ddoc001',
'language': 'query',
'views': {
'view001': {'map': {'fields': {'name': 'asc', 'age': 'asc'}},
'reduce': '_count',
'options': {'def': {'fields': ['name', 'age']},
'w': 2}
}
}
}
self.db.create_document(data)
ddoc = DesignDocument(self.db, '_design/ddoc001')
ddoc.fetch()
with self.assertRaises(CloudantDesignDocumentException) as cm:
ddoc.update_view(
'view001',
'function (doc) {\n emit(doc._id, 1);\n}'
)
err = cm.exception
self.assertEqual(
str(err),
'Cannot update a query index view using this method.'
)
def test_delete_a_view(self):
"""
Test deleting a view from the DesignDocument dictionary.
"""
ddoc = DesignDocument(self.db, '_design/ddoc001')
ddoc.add_view('view001', 'function (doc) {\n emit(doc._id, 1);\n}')
self.assertEqual(
ddoc.get('views')['view001'],
{'map': 'function (doc) {\n emit(doc._id, 1);\n}'}
)
ddoc.delete_view('view001')
self.assertEqual(ddoc.get('views'), {})
def test_delete_a_query_index_view(self):
"""
Test deleting a query index view fails as expected.
"""
# This is not the preferred way of dealing with query index
# views but it works best for this test.
data = {
'_id': '_design/ddoc001',
'language': 'query',
'views': {
'view001': {'map': {'fields': {'name': 'asc', 'age': 'asc'}},
'reduce': '_count',
'options': {'def': {'fields': ['name', 'age']},
'w': 2}
}
}
}
self.db.create_document(data)
ddoc = DesignDocument(self.db, '_design/ddoc001')
ddoc.fetch()
with self.assertRaises(CloudantDesignDocumentException) as cm:
ddoc.delete_view('view001')
err = cm.exception
self.assertEqual(
str(err),
'Cannot delete a query index view using this method.'
)
def test_fetch_map_reduce(self):
"""
Ensure that the document fetch from the database returns the
DesignDocument format as expected when retrieving a design document
containing MapReduce views.
"""
ddoc = DesignDocument(self.db, '_design/ddoc001')
view_map = 'function (doc) {\n emit(doc._id, 1);\n}'
view_reduce = '_count'
ddoc.add_view('view001', view_map, view_reduce)
ddoc.add_view('view003', view_map)
ddoc.save()
ddoc_remote = DesignDocument(self.db, '_design/ddoc001')
self.assertNotEqual(ddoc_remote, ddoc)
ddoc_remote.fetch()
self.assertEqual(ddoc_remote, ddoc)
self.assertTrue(ddoc_remote['_rev'].startswith('1-'))
self.assertEqual(ddoc_remote, {
'_id': '_design/ddoc001',
'_rev': ddoc['_rev'],
'options': {'partitioned': False},
'lists': {},
'shows': {},
'indexes': {},
'views': {
'view001': {'map': view_map, 'reduce': view_reduce},
'view003': {'map': view_map}
}
})
self.assertIsInstance(ddoc_remote['views']['view001'], View)
self.assertIsInstance(ddoc_remote['views']['view003'], View)
@attr(db='cloudant')
def test_fetch_dbcopy(self):
"""
Ensure that the document fetch from the database returns the
DesignDocument format as expected when retrieving a view
that has dbcopy.
Note: this asserts the expected dbcopy location from Cloudant
versions based on CouchDB >= 2.0
"""
ddoc = DesignDocument(self.db, '_design/ddoc001')
view_map = 'function (doc) {\n emit(doc._id, 1);\n}'
view_reduce = '_count'
db_copy = '{0}-copy'.format(self.db.database_name)
ddoc.add_view('view002', view_map, view_reduce, dbcopy=db_copy)
ddoc.save()
ddoc_remote = DesignDocument(self.db, '_design/ddoc001')
self.assertNotEqual(ddoc_remote, ddoc)
ddoc_remote.fetch()
# The local ddoc will not contain the server plugin options
# so we need to manipulate the equalities by removing
# the options from remote. The remote ddoc won't contain
# the dbcopy entry in the view dict so that needs to be removed
# before comparison also. Compare the removed values with
# the expected content in each case.
self.assertEqual(db_copy, ddoc['views']['view002'].pop('dbcopy'))
self.assertEqual({'epi': {'dbcopy': {'view002': db_copy}}, 'partitioned': False}, ddoc_remote.pop('options'))
self.assertEqual({'partitioned': False}, ddoc.pop('options'))
self.assertEqual(ddoc_remote, ddoc)
self.assertTrue(ddoc_remote['_rev'].startswith('1-'))
self.assertEqual(ddoc_remote, {
'_id': '_design/ddoc001',
'_rev': ddoc['_rev'],
'lists': {},
'shows': {},
'indexes': {},
'views': {
'view002': {'map': view_map, 'reduce': view_reduce}
}
})
self.assertIsInstance(ddoc_remote['views']['view002'], View)
def test_fetch_no_views(self):
"""
Ensure that the document fetched from the database returns the
DesignDocument format as expected when retrieving a design document
containing no views.
"""
ddoc = DesignDocument(self.db, '_design/ddoc001')
ddoc.save()
ddoc_remote = DesignDocument(self.db, '_design/ddoc001')
ddoc_remote.fetch()
self.assertEqual(set(ddoc_remote.keys()),
{'_id', '_rev', 'indexes', 'views', 'options', 'lists', 'shows'})
self.assertEqual(ddoc_remote['_id'], '_design/ddoc001')
self.assertTrue(ddoc_remote['_rev'].startswith('1-'))
self.assertEqual(ddoc_remote['_rev'], ddoc['_rev'])
self.assertEqual(ddoc_remote.views, {})
def test_fetch_query_views(self):
"""
Ensure that the document fetch from the database returns the
DesignDocument format as expected when retrieving a design document
containing query index views.
"""
# This is not the preferred way of dealing with query index
# views but it works best for this test.
data = {
'_id': '_design/ddoc001',
'indexes': {},
'options': {'partitioned': False},
'lists': {},
'shows': {},
'language': 'query',
'views': {
'view001': {'map': {'fields': {'name': 'asc', 'age': 'asc'}},
'reduce': '_count',
'options': {'def': {'fields': ['name', 'age']},
'w': 2}
}
}
}
doc = self.db.create_document(data)
self.assertIsInstance(doc, Document)
data['_rev'] = doc['_rev']
ddoc = DesignDocument(self.db, '_design/ddoc001')
ddoc.fetch()
self.assertIsInstance(ddoc, DesignDocument)
self.assertEqual(ddoc, data)
self.assertIsInstance(ddoc['views']['view001'], QueryIndexView)
def test_fetch_text_indexes(self):
"""
Ensure that the document fetch from the database returns the
DesignDocument format as expected when retrieving a design document
containing query index views.
"""
# This is not the preferred way of dealing with query index
# views but it works best for this test.
data = {
'_id': '_design/ddoc001',
'language': 'query',
'options': {'partitioned': False},
'lists': {},
'shows': {},
'indexes': {'index001':
{'index': {'index_array_lengths': True,
'fields': [{'name': 'name', 'type': 'string'},
{'name': 'age', 'type': 'number'}],
'default_field': {'enabled': True,
'analyzer': 'german'},
'default_analyzer': 'keyword',
'selector': {}},
'analyzer': {'name': 'perfield',
'default': 'keyword',
'fields': {'$default': 'german'}}}}}
doc = self.db.create_document(data)
self.assertIsInstance(doc, Document)
ddoc = DesignDocument(self.db, '_design/ddoc001')
ddoc.fetch()
self.assertIsInstance(ddoc, DesignDocument)
data['_rev'] = doc['_rev']
data['views'] = dict()
self.assertEqual(ddoc, data)
self.assertIsInstance(ddoc['indexes']['index001'], dict)
def test_fetch_text_indexes_and_query_views(self):
"""
Ensure that the document fetch from the database returns the
DesignDocument format as expected when retrieving a design document
containing query index views and text index definitions.
"""
# This is not the preferred way of dealing with query index
# views but it works best for this test.
data = {
'_id': '_design/ddoc001',
'language': 'query',
'lists': {},
'shows': {},
'options': {'partitioned': False},
'views': {
'view001': {'map': {'fields': {'name': 'asc', 'age': 'asc'}},
'reduce': '_count',
'options': {'def': {'fields': ['name', 'age']},
'w': 2}
}
},
'indexes': {'index001': {
'index': {'index_array_lengths': True,
'fields': [{'name': 'name', 'type': 'string'},
{'name': 'age', 'type': 'number'}],
'default_field': {'enabled': True,
'analyzer': 'german'},
'default_analyzer': 'keyword',
'selector': {}},
'analyzer': {'name': 'perfield',
'default': 'keyword',
'fields': {'$default': 'german'}}}}}
doc = self.db.create_document(data)
self.assertIsInstance(doc, Document)
data['_rev'] = doc['_rev']
ddoc = DesignDocument(self.db, '_design/ddoc001')
ddoc.fetch()
self.assertIsInstance(ddoc, DesignDocument)
self.assertEqual(ddoc, data)
self.assertIsInstance(ddoc['indexes']['index001'], dict)
self.assertIsInstance(ddoc['views']['view001'], QueryIndexView)
def test_text_index_save_fails_when_lang_is_not_query(self):
"""
Tests that save fails when language is not query and a search index
string function is expected.
"""
ddoc = DesignDocument(self.db, '_design/ddoc001')
ddoc['indexes']['index001'] = {
'index': {'index_array_lengths': True,
'fields': [{'name': 'name', 'type': 'string'},
{'name': 'age', 'type': 'number'}],
'default_field': {'enabled': True, 'analyzer': 'german'},
'default_analyzer': 'keyword',
'selector': {}},
'analyzer': {'name': 'perfield','default': 'keyword',
'fields': {'$default': 'german'}}}
self.assertIsInstance(ddoc['indexes']['index001']['index'], dict)
with self.assertRaises(CloudantDesignDocumentException) as cm:
ddoc.save()
err = cm.exception
self.assertEqual(
str(err),
'Function for search index index001 must be of type string.'
)
def test_text_index_save_fails_with_existing_search_index(self):
"""
Tests that save fails when language is not query and both a query text
index and a search index exist in the design document.
"""
ddoc = DesignDocument(self.db, '_design/ddoc001')
search_index = ('function (doc) {\n index("default", doc._id); '
'if (doc._id) {index("name", doc.name, '
'{"store": true}); }\n}')
ddoc.add_search_index('search001', search_index)
self.assertIsInstance(
ddoc['indexes']['search001']['index'], str
)
ddoc.save()
self.assertTrue(ddoc['_rev'].startswith('1-'))
ddoc_remote = DesignDocument(self.db, '_design/ddoc001')
ddoc_remote.fetch()
ddoc_remote['indexes']['index001'] = {
'index': {'index_array_lengths': True,
'fields': [{'name': 'name', 'type': 'string'},
{'name': 'age', 'type': 'number'}],
'default_field': {'enabled': True, 'analyzer': 'german'},
'default_analyzer': 'keyword',
'selector': {}},
'analyzer': {'name': 'perfield','default': 'keyword',
'fields': {'$default': 'german'}}}
self.assertIsInstance(ddoc_remote['indexes']['index001']['index'], dict)
with self.assertRaises(CloudantDesignDocumentException) as cm:
ddoc_remote.save()
err = cm.exception
self.assertEqual(
str(err),
'Function for search index index001 must be of type string.'
)
def test_mr_view_save_fails_when_lang_is_query(self):
"""
Tests that save fails when language is query but views are map reduce
views.
"""
ddoc = DesignDocument(self.db, '_design/ddoc001')
view_map = 'function (doc) {\n emit(doc._id, 1);\n}'
view_reduce = '_count'
db_copy = '{0}-copy'.format(self.db.database_name)
ddoc.add_view('view001', view_map, view_reduce)
ddoc['language'] = 'query'
with self.assertRaises(CloudantDesignDocumentException) as cm:
ddoc.save()
err = cm.exception
self.assertEqual(
str(err),
'View view001 must be of type QueryIndexView.'
)
def test_mr_view_save_succeeds(self):
"""
Tests that save succeeds when no language is specified and views are map
reduce views.
"""
ddoc = DesignDocument(self.db, '_design/ddoc001')
view_map = 'function (doc) {\n emit(doc._id, 1);\n}'
view_reduce = '_count'
db_copy = '{0}-copy'.format(self.db.database_name)
ddoc.add_view('view001', view_map, view_reduce)
ddoc.save()
self.assertTrue(ddoc['_rev'].startswith('1-'))
def test_query_view_save_fails_when_lang_is_not_query(self):
"""
Tests that save fails when language is not query but views are query
index views.
"""
# This is not the preferred way of dealing with query index
# views but it works best for this test.
data = {
'_id': '_design/ddoc001',
'language': 'query',
'views': {
'view001': {'map': {'fields': {'name': 'asc', 'age': 'asc'}},
'reduce': '_count',
'options': {'def': {'fields': ['name', 'age']},
'w': 2}
}
}
}
self.db.create_document(data)
ddoc = DesignDocument(self.db, '_design/ddoc001')
ddoc.fetch()
with self.assertRaises(CloudantDesignDocumentException) as cm:
ddoc['language'] = 'not-query'
ddoc.save()
err = cm.exception
self.assertEqual(str(err), 'View view001 must be of type View.')
with self.assertRaises(CloudantDesignDocumentException) as cm:
del ddoc['language']
ddoc.save()
err = cm.exception
self.assertEqual(str(err), 'View view001 must be of type View.')
def test_query_view_save_succeeds(self):
"""
Tests that save succeeds when language is query and views are query
index views.
"""
# This is not the preferred way of dealing with query index
# views but it works best for this test.
data = {
'_id': '_design/ddoc001',
'language': 'query',
'views': {
'view001': {'map': {'fields': {'name': 'asc', 'age': 'asc'}},
'reduce': '_count',
'options': {'def': {'fields': ['name', 'age']},
'w': 2}
}
}
}
self.db.create_document(data)
ddoc = DesignDocument(self.db, '_design/ddoc001')
ddoc.fetch()
self.assertTrue(ddoc['_rev'].startswith('1-'))
ddoc.save()
self.assertTrue(ddoc['_rev'].startswith('2-'))
def test_save_with_no_views(self):
"""
Tests the functionality when saving a design document without a view.
The locally cached DesignDocument should contain an empty views dict
while the design document saved remotely should not include the empty
views sub-document.
"""
ddoc = DesignDocument(self.db, '_design/ddoc001')
ddoc.save()
# Ensure that locally cached DesignDocument contains an
# empty views dict.
self.assertEqual(set(ddoc.keys()), {'_id', '_rev', 'indexes', 'options', 'views', 'lists', 'shows'})
self.assertEqual(ddoc['_id'], '_design/ddoc001')
self.assertTrue(ddoc['_rev'].startswith('1-'))
self.assertEqual(ddoc.views, {})
# Ensure that remotely saved design document does not
# include a views sub-document.
resp = self.client.r_session.get(ddoc.document_url)
raw_ddoc = response_to_json_dict(resp)
self.assertEqual(set(raw_ddoc.keys()), {'_id', '_rev','options'})
self.assertEqual(raw_ddoc['_id'], ddoc['_id'])
self.assertEqual(raw_ddoc['_rev'], ddoc['_rev'])
def test_setting_id(self):
"""
Ensure when setting the design document id that it is
prefaced by '_design/'
"""
ddoc = DesignDocument(self.db)
ddoc['_id'] = 'ddoc001'
self.assertEqual(ddoc['_id'], '_design/ddoc001')
del ddoc['_id']
self.assertIsNone(ddoc.get('_id'))
ddoc['_id'] = '_design/ddoc002'
self.assertEqual(ddoc['_id'], '_design/ddoc002')
def test_iterating_over_views(self):
"""
Test iterating over views within the DesignDocument
"""
ddoc = DesignDocument(self.db, '_design/ddoc001')
view_map = 'function (doc) {\n emit(doc._id, 1);\n}'
ddoc.add_view('view001', view_map)
ddoc.add_view('view002', view_map)
ddoc.add_view('view003', view_map)
view_names = []
for view_name, view in ddoc.iterviews():
self.assertIsInstance(view, View)
view_names.append(view_name)
self.assertTrue(
all(x in view_names for x in ['view001', 'view002', 'view003'])
)
def test_list_views(self):
"""
Test the retrieval of view name list from DesignDocument
"""
ddoc = DesignDocument(self.db, '_design/ddoc001')
view_map = 'function (doc) {\n emit(doc._id, 1);\n}'
ddoc.add_view('view001', view_map)
ddoc.add_view('view002', view_map)
ddoc.add_view('view003', view_map)
self.assertTrue(
all(x in ddoc.list_views() for x in [
'view001',
'view002',
'view003'
])
)
def test_get_view(self):
"""
Test retrieval of a view from the DesignDocument
"""
ddoc = DesignDocument(self.db, '_design/ddoc001')
view_map = 'function (doc) {\n emit(doc._id, 1);\n}'
view_reduce = '_count'
ddoc.add_view('view001', view_map)
ddoc.add_view('view002', view_map, view_reduce)
ddoc.add_view('view003', view_map)
self.assertIsInstance(ddoc.get_view('view002'), View)
self.assertEqual(
ddoc.get_view('view002'),
{
'map': 'function (doc) {\n emit(doc._id, 1);\n}',
'reduce': '_count'
}
)
def test_get_info(self):
"""
Test retrieval of info endpoint from the DesignDocument.
"""
ddoc = DesignDocument(self.db, '_design/ddoc001')
ddoc.save()
ddoc_remote = DesignDocument(self.db, '_design/ddoc001')
ddoc_remote.fetch()
info = ddoc_remote.info()
# Remove variable fields to make equality easier to check
info['view_index'].pop('signature')
if 'disk_size' in info['view_index']:
info['view_index'].pop('disk_size')
if 'data_size' in info['view_index']:
info['view_index'].pop('data_size')
# Remove Cloudant/Couch 2 fields if present to allow test to pass on Couch 1.6
if 'sizes' in info['view_index']:
info['view_index'].pop('sizes')
if 'updates_pending' in info['view_index']:
info['view_index'].pop('updates_pending')
name = 'ddoc001'
self.assertEqual(
info,
{'view_index': {'update_seq': 0, 'waiting_clients': 0,
'language': 'javascript',
'purge_seq': 0, 'compact_running': False,
'waiting_commit': False, 'updater_running': False
},
'name': name
})
def test_get_info_raises_httperror(self):
"""
Test get_info raises an HTTPError.
"""
# Mock HTTPError when running against CouchDB and Cloudant
resp = requests.Response()
resp.status_code = 400
self.client.r_session.get = mock.Mock(return_value=resp)
ddoc = DesignDocument(self.db, '_design/ddoc001')
with self.assertRaises(requests.HTTPError) as cm:
ddoc.info()
err = cm.exception
self.assertEqual(err.response.status_code, 400)
self.client.r_session.get.assert_called_with(
'/'.join([ddoc.document_url, '_info']))
@attr(db='cloudant')
def test_get_search_info(self):
"""
Test retrieval of search_info endpoint from the DesignDocument.
"""
self.populate_db_with_documents(100)
ddoc = DesignDocument(self.db, '_design/ddoc001')
ddoc.add_search_index(
'search001',
'function (doc) {\n index("default", doc._id); '
'if (doc._id) {index("name", doc.name, {"store": true}); }\n}'
)
ddoc.save()
ddoc_remote = DesignDocument(self.db, '_design/ddoc001')
ddoc_remote.fetch()
# Make a request to the search index to ensure it is built
self.db.get_search_result('_design/ddoc001', 'search001', query='name:julia*')
search_info = ddoc_remote.search_info('search001')
# Check the search index name
self.assertEqual(search_info['name'], '_design/ddoc001/search001', 'The search index name should be correct.')
# Validate the metadata
search_index_metadata = search_info['search_index']
self.assertIsNotNone(search_index_metadata)
self.assertEqual(search_index_metadata['doc_del_count'], 0, 'There should be no deleted docs.')
self.assertTrue(search_index_metadata['doc_count'] <= 100, 'There should be 100 or fewer docs.')
self.assertEqual(search_index_metadata['committed_seq'], 0, 'The committed_seq should be 0.')
self.assertTrue(search_index_metadata['pending_seq'] <= 101, 'The pending_seq should be 101 or fewer.')
self.assertTrue(search_index_metadata['disk_size'] >0, 'The disk_size should be greater than 0.')
@attr(db='cloudant')
def test_get_search_disk_size(self):
"""
Test retrieval of search_disk_size endpoint from the DesignDocument.
"""
self.populate_db_with_documents(100)
ddoc = DesignDocument(self.db, '_design/ddoc001')
ddoc.add_search_index(
'search001',
'function (doc) {\n index("default", doc._id); '
'if (doc._id) {index("name", doc.name, {"store": true}); }\n}'
)
ddoc.save()
ddoc_remote = DesignDocument(self.db, '_design/ddoc001')
ddoc_remote.fetch()
# Make a request to the search index to ensure it is built
self.db.get_search_result('_design/ddoc001', 'search001', query='name:julia*')
search_disk_size = ddoc_remote.search_disk_size('search001')
self.assertEqual(
sorted(search_disk_size.keys()), ['name', 'search_index'],
'The search disk size should contain only keys "name" and "search_index"')
self.assertEqual(
search_disk_size['name'], '_design/ddoc001/search001',
'The search index "name" should be correct.')
self.assertEqual(
sorted(search_disk_size['search_index'].keys()), ['disk_size'],
'The search index should contain only key "disk_size"')
self.assertTrue(
isinstance(search_disk_size['search_index']['disk_size'], int),
'The "disk_size" value should be an integer.')
self.assertTrue(
search_disk_size['search_index']['disk_size'] > 0,
'The "disk_size" should be greater than 0.')
@attr(db='cloudant')
def test_get_search_info_raises_httperror(self):
"""
Test get_search_info raises an HTTPError.
"""
# Mock HTTPError when running against Cloudant
search_index = 'search001'
resp = requests.Response()
resp.status_code = 400
self.client.r_session.get = mock.Mock(return_value=resp)
ddoc = DesignDocument(self.db, '_design/ddoc001')
with self.assertRaises(requests.HTTPError) as cm:
ddoc.search_info(search_index)
err = cm.exception
self.assertEqual(err.response.status_code, 400)
self.client.r_session.get.assert_called_with(
'/'.join([ddoc.document_url, '_search_info', search_index]))
def test_add_a_search_index(self):
"""
Test that adding a search index adds a search index object to
the DesignDocument dictionary.
"""
ddoc = DesignDocument(self.db, '_design/ddoc001')
self.assertEqual(ddoc.get('indexes'), {})
ddoc.add_search_index(
'search001',
'function (doc) {\n index("default", doc._id); '
'if (doc._id) {index("name", doc.name, {"store": true}); }\n}'
)
self.assertListEqual(list(ddoc.get('indexes').keys()), ['search001'])
self.assertEqual(
ddoc.get('indexes')['search001'],
{'index': 'function (doc) {\n index("default", doc._id); '
'if (doc._id) {index("name", doc.name, {"store": true}); }\n}'}
)
def test_add_a_search_index_with_analyzer(self):
"""
Test that adding a search index with an analyzer adds a search index
object to the DesignDocument dictionary.
"""
ddoc = DesignDocument(self.db, '_design/ddoc001')
self.assertEqual(ddoc.get('indexes'), {})
ddoc.add_search_index(
'search001',
'function (doc) {\n index("default", doc._id); '
'if (doc._id) {index("name", doc.name, {"store": true}); }\n}',
{'name': 'perfield', 'default': 'english', 'fields': {
'spanish': 'spanish'}}
)
self.assertListEqual(list(ddoc.get('indexes').keys()), ['search001'])
self.assertEqual(
ddoc.get('indexes')['search001'],
{'index': 'function (doc) {\n index("default", doc._id); '
'if (doc._id) {index("name", doc.name, {"store": true}); }\n}',
'analyzer': {"name": "perfield", "default": "english", "fields":
{"spanish": "spanish"}}}
)
def test_adding_existing_search_index(self):
"""
Test that adding an existing search index fails as expected.
"""
ddoc = DesignDocument(self.db, '_design/ddoc001')
ddoc.add_search_index(
'search001',
'function (doc) {\n index("default", doc._id); '
'if (doc._id) {index("name", doc.name, {"store": true}); }\n}',
)
with self.assertRaises(CloudantArgumentError) as cm:
ddoc.add_search_index(
'search001',
'function (doc) {\n index("default", doc._id); '
'if (doc._id) {index("name", doc.name, '
'{"store": true}); }\n}'
)
err = cm.exception
self.assertEqual(
str(err),
'An index with name search001 already exists in this design doc.'
)
def test_update_a_search_index(self):
"""
Test that updating a search index updates the contents of the correct
search index object in the DesignDocument dictionary.
"""
ddoc = DesignDocument(self.db, '_design/ddoc001')
ddoc.add_search_index('search001', 'not-a-valid-search-index')
self.assertEqual(
ddoc.get('indexes')['search001'],
{'index': 'not-a-valid-search-index'}
)
ddoc.update_search_index(
'search001',
'function (doc) {\n index("default", doc._id); '
'if (doc._id) {index("name", doc.name, {"store": true}); }\n}',
)
self.assertEqual(
ddoc.get('indexes')['search001'],
{'index': 'function (doc) {\n index("default", doc._id); '
'if (doc._id) {index("name", doc.name, '
'{"store": true}); }\n}'}
)
def test_update_a_search_index_with_analyzer(self):
"""
Test that updating a search analyzer updates the contents of the correct
search index object in the DesignDocument dictionary.
"""