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 pathview_tests.py
448 lines (407 loc) · 15.2 KB
/
view_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
#!/usr/bin/env python
# Copyright (C) 2015, 2018 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.
"""
_view_tests_
view module - Unit tests for the View/QueryIndexView classes
See configuration options for environment variables in unit_t_db_base
module docstring.
"""
import unittest
import mock
import requests
from cloudant._common_util import _Code
from cloudant.design_document import DesignDocument
from cloudant.error import CloudantArgumentError, CloudantViewException
from cloudant.result import Result
from cloudant.view import View, QueryIndexView
from nose.plugins.attrib import attr
from .unit_t_db_base import UnitTestDbBase
class CodeTests(unittest.TestCase):
"""
_Code class unit test
"""
def test_constructor(self):
"""
Ensure that the _Code class constructor returns a _Code object that
wraps a Python str
"""
code = _Code('this is code.')
self.assertIsInstance(code, _Code)
self.assertEqual(code, 'this is code.')
class CloudantViewExceptionTests(unittest.TestCase):
"""
Ensure CloudantReplicatorException functions as expected.
"""
def test_raise_without_code(self):
"""
Ensure that a default exception/code is used if none is provided.
"""
with self.assertRaises(CloudantViewException) as cm:
raise CloudantViewException()
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(CloudantViewException) as cm:
raise CloudantViewException('foo')
self.assertEqual(cm.exception.status_code, 100)
def test_raise_with_proper_code(self):
"""
Ensure that the requested exception is raised.
"""
with self.assertRaises(CloudantViewException) as cm:
raise CloudantViewException(101)
self.assertEqual(cm.exception.status_code, 101)
@attr(db=['cloudant','couch'])
class ViewTests(UnitTestDbBase):
"""
View class unit tests
"""
def setUp(self):
"""
Set up test attributes
"""
super(ViewTests, self).setUp()
self.db_set_up()
def tearDown(self):
"""
Reset test attributes
"""
self.db_tear_down()
super(ViewTests, self).tearDown()
def test_constructor(self):
"""
Test instantiating a View
"""
ddoc = DesignDocument(self.db, 'ddoc001')
view = View(
ddoc,
'view001',
'function (doc) {\n emit(doc._id, 1);\n}',
'_count',
dbcopy='{0}-copy'.format(self.db.database_name)
)
self.assertEqual(view.design_doc, ddoc)
self.assertEqual(view.view_name, 'view001')
self.assertIsInstance(view['map'], _Code)
self.assertEqual(
view['map'],
'function (doc) {\n emit(doc._id, 1);\n}'
)
self.assertIsInstance(view['reduce'], _Code)
self.assertEqual(view['reduce'], '_count')
self.assertEqual(
view['dbcopy'],
'{0}-copy'.format(self.db.database_name)
)
self.assertEqual(view, {
'map': 'function (doc) {\n emit(doc._id, 1);\n}',
'reduce': '_count',
'dbcopy': '{0}-copy'.format(self.db.database_name)
})
def test_map_setter(self):
"""
Test that the map setter works
"""
ddoc = DesignDocument(self.db, 'ddoc001')
view = View(ddoc, 'view001')
self.assertIsNone(view.get('map'))
view.map = 'function (doc) {\n emit(doc._id, 1);\n}'
self.assertEqual(
view.get('map'),
'function (doc) {\n emit(doc._id, 1);\n}'
)
def test_map_getter(self):
"""
Test that the map getter works
"""
ddoc = DesignDocument(self.db, 'ddoc001')
view = View(ddoc, 'view001')
self.assertIsNone(view.map)
view.map = 'function (doc) {\n emit(doc._id, 1);\n}'
self.assertIsInstance(view.map, _Code)
self.assertEqual(view.map, 'function (doc) {\n emit(doc._id, 1);\n}')
def test_reduce_setter(self):
"""
Test that the reduce setter works
"""
ddoc = DesignDocument(self.db, 'ddoc001')
view = View(ddoc, 'view001')
self.assertIsNone(view.get('reduce'))
view.reduce = '_count'
self.assertEqual(view.get('reduce'), '_count')
def test_reduce_getter(self):
"""
Test that the reduce getter works
"""
ddoc = DesignDocument(self.db, 'ddoc001')
view = View(ddoc, 'view001')
self.assertIsNone(view.reduce)
view.reduce = '_count'
self.assertIsInstance(view.reduce, _Code)
self.assertEqual(view.reduce, '_count')
def test_retrieve_view_url(self):
"""
Test the retrieval of the View url
"""
ddoc = DesignDocument(self.db, 'ddoc001')
view = View(ddoc, 'view001')
self.assertEqual(
view.url,
'/'.join((ddoc.document_url, '_view/view001'))
)
def test_get_view_callable_raw_json(self):
"""
Test that the GET request of the View __call__ method that is invoked
when calling the view object returns the appropriate raw JSON response.
"""
self.populate_db_with_documents()
ddoc = DesignDocument(self.db, 'ddoc001')
ddoc.add_view(
'view001',
'function (doc) {\n emit(doc._id, 1);\n}'
)
ddoc.save()
view = ddoc.get_view('view001')
ids = []
# view(limit=3) calls the view object and passes it the limit parameter
# where a HTTP GET request is made.
for row in view(limit=3)['rows']:
ids.append(row['id'])
expected = ['julia000', 'julia001', 'julia002']
self.assertTrue(all(x in ids for x in expected))
def test_post_view_callable_raw_json(self):
"""
Using the "keys" parameter test that the POST request of the View
__call__ method that is invoked when calling the view object returns the
appropriate raw JSON response.
"""
# Create 200 documents with ids julia000, julia001, julia002, ..., julia199
self.populate_db_with_documents(200)
# Generate keys list for every other document created
# with ids julia000, julia002, julia004, ..., julia198
keys_list = ['julia{0:03d}'.format(i) for i in range(0, 200, 2)]
self.assertEqual(len(keys_list), 100)
ddoc = DesignDocument(self.db, 'ddoc001')
ddoc.add_view(
'view001',
'function (doc) {\n emit(doc._id, 1);\n}'
)
ddoc.save()
view = ddoc.get_view('view001')
# view(keys=keys_list) calls the view object and passes keys parameter
ids = [row['id'] for row in view(keys=keys_list)['rows']]
self.assertEqual(len(ids), 100)
self.assertTrue(all(x in ids for x in keys_list))
def test_post_view_callable_raw_json_multiple_params(self):
"""
Using "keys" and other parameters test that the POST request of the View
__call__ method that is invoked when calling the view object returns the
appropriate raw JSON response.
"""
# Create 200 documents with ids julia000, julia001, julia002, ..., julia199
self.populate_db_with_documents(200)
# Generate keys list for every other document created
# with ids julia000, julia002, julia004, ..., julia198
keys_list = ['julia{0:03d}'.format(i) for i in range(0, 200, 2)]
self.assertEqual(len(keys_list), 100)
ddoc = DesignDocument(self.db, 'ddoc001')
ddoc.add_view(
'view001',
'function (doc) {\n emit(doc._id, 1);\n}'
)
ddoc.save()
view = ddoc.get_view('view001')
# view(keys=keys_list, limit=3) calls the view object and passes keys
# and limit parameters
ids = [row['id'] for row in view(keys=keys_list, limit=3)['rows']]
self.assertTrue(all(x in ids for x in ['julia000', 'julia002', 'julia004']))
def test_view_callable_view_result(self):
"""
Test that by referencing the .result attribute the view callable
method is invoked and the data returned is wrapped as a Result.
"""
self.populate_db_with_documents()
ddoc = DesignDocument(self.db, 'ddoc001')
ddoc.add_view(
'view001',
'function (doc) {\n emit(doc._id, 1);\n}'
)
ddoc.save()
view = ddoc.get_view('view001')
rslt = view.result
self.assertIsInstance(rslt, Result)
ids = []
# rslt[:3] limits the Result to the first 3 elements
for row in rslt[:3]:
ids.append(row['id'])
expected = ['julia000', 'julia001', 'julia002']
self.assertTrue(all(x in ids for x in expected))
def test_view_callable_with_non_existing_view(self):
"""
Test error condition when view used does not exist remotely.
"""
self.populate_db_with_documents()
# The view "missing-view" does not exist in the remote database
view = View(
DesignDocument(self.db, 'ddoc001'),
'missing-view',
'function (doc) {\n emit(doc._id, 1);\n}'
)
self.assertIsInstance(view, View)
try:
for row in view.result:
self.fail('Above statement should raise an Exception')
except requests.HTTPError as err:
self.assertEqual(err.response.status_code, 404)
def test_custom_result_context_manager(self):
"""
Test that the context manager for custom results returns
the expected Results
"""
self.populate_db_with_documents()
ddoc = DesignDocument(self.db, 'ddoc001')
ddoc.add_view(
'view001',
'function (doc) {\n emit(doc._id, 1);\n}'
)
ddoc.save()
view = ddoc.get_view('view001')
# Return a custom result by including documents
with view.custom_result(include_docs=True, reduce=False) as rslt:
i = 0
for row in rslt:
self.assertEqual(row['doc']['_id'], 'julia{0:03d}'.format(i))
self.assertTrue(row['doc']['_rev'].startswith('1-'))
self.assertEqual(row['doc']['name'], 'julia')
self.assertEqual(row['doc']['age'], i)
i += 1
self.assertEqual(i, 100)
class QueryIndexViewTests(unittest.TestCase):
"""
QueryIndexView class unit tests. These tests use a mocked DesignDocument
since a QueryIndexView object is not callable so an actual connection
is not necessary.
"""
def setUp(self):
"""
Set up test attributes
"""
self.ddoc = mock.Mock()
self.ddoc.r_session = 'mocked-session'
self.ddoc.document_url = 'http://mock.example.com/my_db/_design/ddoc001'
self.view = QueryIndexView(
self.ddoc,
'view001',
{'fields': {'name': 'asc', 'age': 'asc'}},
'_count',
options = {'def': {'fields': ['name', 'age']}, 'w': 2}
)
def test_constructor(self):
"""
Test constructing a QueryIndexView
"""
self.assertIsInstance(self.view, QueryIndexView)
self.assertEqual(self.view.design_doc, self.ddoc)
self.assertEqual(self.view.view_name, 'view001')
self.assertIsNone(self.view.result)
self.assertEqual(self.view, {
'map': {'fields': {'name': 'asc', 'age': 'asc'}},
'reduce': '_count',
'options': {'def': {'fields': ['name', 'age']}, 'w': 2}
})
def test_map_getter(self):
"""
Test that the map getter works
"""
self.assertEqual(
self.view.map,
{'fields': {'name': 'asc', 'age': 'asc'}}
)
self.assertEqual(self.view.map, self.view['map'])
def test_map_setter(self):
"""
Test that the map setter works
"""
self.view.map = {'fields': {'name': 'desc', 'age': 'desc'}}
self.assertEqual(
self.view.map,
{'fields': {'name': 'desc', 'age': 'desc'}}
)
self.assertEqual(self.view.map, self.view['map'])
def test_map_setter_failure(self):
"""
Test that the map setter fails if a dict is not supplied
"""
try:
self.view.map = 'function (doc) {\n emit(doc._id, 1);\n}'
self.fail('Above statement should raise an Exception')
except CloudantArgumentError as err:
self.assertEqual(
str(err),
'The map property must be a dictionary.'
)
def test_reduce_getter(self):
"""
Test that the reduce getter works
"""
self.assertEqual(self.view.reduce, '_count')
self.assertEqual(self.view.reduce, self.view['reduce'])
def test_reduce_setter(self):
"""
Test that the reduce setter works
"""
self.view.reduce = '_sum'
self.assertEqual(self.view.reduce, '_sum')
self.assertEqual(self.view.reduce, self.view['reduce'])
def test_reduce_setter_failure(self):
"""
Test that the reduce setter fails if a string is not supplied
"""
with self.assertRaises(CloudantArgumentError) as cm:
self.view.reduce = {'_count'}
err = cm.exception
self.assertEqual(str(err), 'The reduce property must be a string.')
def test_callable_disabled(self):
"""
Test that the callable for QueryIndexView does not execute.
"""
with self.assertRaises(CloudantViewException) as cm:
self.view()
err = cm.exception
self.assertEqual(
str(err),
'A QueryIndexView is not callable. '
'If you wish to execute a query '
'use the database \'get_query_result\' convenience method.'
)
def test_custom_result_disabled(self):
"""
Test that the custom_result context manager for QueryIndexView does not
execute.
"""
with self.assertRaises(CloudantViewException) as cm:
with self.view.custom_result() as result:
pass
err = cm.exception
self.assertEqual(
str(err),
'Cannot create a custom result context manager using a '
'QueryIndexView. If you wish to execute a query use the '
'database \'get_query_result\' convenience method instead.'
)
if __name__ == '__main__':
unittest.main()