-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathdatastore.py
357 lines (283 loc) · 12.7 KB
/
datastore.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
# Copyright 2014 Google Inc. 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.
import datetime
import os
import pytz
import unittest2
from gcloud import datastore
from gcloud.datastore.entity import Entity
from gcloud.datastore.key import Key
from gcloud.datastore.query import Query
from gcloud.datastore.transaction import Transaction
# This assumes the command is being run via tox hence the
# repository root is the current directory.
from regression import populate_datastore
DATASET_ID = os.getenv('GCLOUD_TESTS_DATASET_ID')
datastore.set_default_dataset(dataset_id=DATASET_ID)
datastore.set_default_connection()
class TestDatastore(unittest2.TestCase):
def setUp(self):
self.case_entities_to_delete = []
def tearDown(self):
with Transaction():
for entity in self.case_entities_to_delete:
entity.key.delete()
class TestDatastoreAllocateIDs(TestDatastore):
def test_allocate_ids(self):
num_ids = 10
allocated_keys = datastore.allocate_ids(Key('Kind'), num_ids)
self.assertEqual(len(allocated_keys), num_ids)
unique_ids = set()
for key in allocated_keys:
unique_ids.add(key.id)
self.assertEqual(key.name, None)
self.assertNotEqual(key.id, None)
self.assertEqual(len(unique_ids), num_ids)
class TestDatastoreSave(TestDatastore):
def _get_post(self, id_or_name=None, post_content=None):
post_content = post_content or {
'title': u'How to make the perfect pizza in your grill',
'tags': [u'pizza', u'grill'],
'publishedAt': datetime.datetime(2001, 1, 1, tzinfo=pytz.utc),
'author': u'Silvano',
'isDraft': False,
'wordCount': 400,
'rating': 5.0,
}
# Create an entity with the given content.
entity = Entity(key=Key('Post'))
entity.update(post_content)
# Update the entity key.
if id_or_name is not None:
entity.key = entity.key.completed_key(id_or_name)
return entity
def _generic_test_post(self, name=None, key_id=None):
entity = self._get_post(id_or_name=(name or key_id))
entity.save()
# Register entity to be deleted.
self.case_entities_to_delete.append(entity)
if name is not None:
self.assertEqual(entity.key.name, name)
if key_id is not None:
self.assertEqual(entity.key.id, key_id)
retrieved_entity = entity.key.get()
# Check the keys are the same.
self.assertTrue(retrieved_entity.key is entity.key)
# Check the data is the same.
retrieved_dict = dict(retrieved_entity.items())
entity_dict = dict(entity.items())
self.assertEqual(retrieved_dict, entity_dict)
def test_post_with_name(self):
self._generic_test_post(name='post1')
def test_post_with_id(self):
self._generic_test_post(key_id=123456789)
def test_post_with_generated_id(self):
self._generic_test_post()
def test_save_multiple(self):
with Transaction():
entity1 = self._get_post()
entity1.save()
# Register entity to be deleted.
self.case_entities_to_delete.append(entity1)
second_post_content = {
'title': u'How to make the perfect homemade pasta',
'tags': [u'pasta', u'homemade'],
'publishedAt': datetime.datetime(2001, 1, 1),
'author': u'Silvano',
'isDraft': False,
'wordCount': 450,
'rating': 4.5,
}
entity2 = self._get_post(post_content=second_post_content)
entity2.save()
# Register entity to be deleted.
self.case_entities_to_delete.append(entity2)
keys = [entity1.key, entity2.key]
matches = datastore.get_entities(keys)
self.assertEqual(len(matches), 2)
def test_empty_kind(self):
query = Query(kind='Post')
posts = list(query.fetch(limit=2))
self.assertEqual(posts, [])
class TestDatastoreSaveKeys(TestDatastore):
def test_save_key_self_reference(self):
key = Key('Person', 'name')
entity = Entity(key=key)
entity['fullName'] = u'Full name'
entity['linkedTo'] = key # Self reference.
entity.save()
self.case_entities_to_delete.append(entity)
query = Query(kind='Person')
query.add_filter('linkedTo', '=', key)
stored_persons = list(query.fetch(limit=2))
self.assertEqual(len(stored_persons), 1)
stored_person = stored_persons[0]
self.assertEqual(stored_person['fullName'], entity['fullName'])
self.assertEqual(stored_person.key.path, key.path)
self.assertEqual(stored_person.key.namespace, key.namespace)
class TestDatastoreQuery(TestDatastore):
@classmethod
def setUpClass(cls):
super(TestDatastoreQuery, cls).setUpClass()
cls.CHARACTERS = populate_datastore.CHARACTERS
cls.ANCESTOR_KEY = Key(*populate_datastore.ANCESTOR)
def _base_query(self):
return Query(kind='Character', ancestor=self.ANCESTOR_KEY)
def test_limit_queries(self):
limit = 5
query = self._base_query()
# Fetch characters.
iterator = query.fetch(limit=limit)
character_entities, _, cursor = iterator.next_page()
self.assertEqual(len(character_entities), limit)
# Check cursor after fetch.
self.assertTrue(cursor is not None)
# Fetch remaining of characters.
new_character_entities = list(iterator)
characters_remaining = len(self.CHARACTERS) - limit
self.assertEqual(len(new_character_entities), characters_remaining)
def test_query_simple_filter(self):
query = self._base_query()
query.add_filter('appearances', '>=', 20)
expected_matches = 6
# We expect 6, but allow the query to get 1 extra.
entities = list(query.fetch(limit=expected_matches + 1))
self.assertEqual(len(entities), expected_matches)
def test_query_multiple_filters(self):
query = self._base_query()
query.add_filter('appearances', '>=', 26)
query.add_filter('family', '=', 'Stark')
expected_matches = 4
# We expect 4, but allow the query to get 1 extra.
entities = list(query.fetch(limit=expected_matches + 1))
self.assertEqual(len(entities), expected_matches)
def test_ancestor_query(self):
filtered_query = self._base_query()
expected_matches = 8
# We expect 8, but allow the query to get 1 extra.
entities = list(filtered_query.fetch(limit=expected_matches + 1))
self.assertEqual(len(entities), expected_matches)
def test_query___key___filter(self):
rickard_key = Key(*populate_datastore.RICKARD)
query = self._base_query()
query.add_filter('__key__', '=', rickard_key)
expected_matches = 1
# We expect 1, but allow the query to get 1 extra.
entities = list(query.fetch(limit=expected_matches + 1))
self.assertEqual(len(entities), expected_matches)
def test_ordered_query(self):
query = self._base_query()
query.order = 'appearances'
expected_matches = 8
# We expect 8, but allow the query to get 1 extra.
entities = list(query.fetch(limit=expected_matches + 1))
self.assertEqual(len(entities), expected_matches)
# Actually check the ordered data returned.
self.assertEqual(entities[0]['name'], self.CHARACTERS[0]['name'])
self.assertEqual(entities[7]['name'], self.CHARACTERS[3]['name'])
def test_projection_query(self):
filtered_query = self._base_query()
filtered_query.projection = ['name', 'family']
# NOTE: There are 9 responses because of Catelyn. She has both
# Stark and Tully as her families, hence occurs twice in
# the results.
expected_matches = 9
# We expect 9, but allow the query to get 1 extra.
entities = list(filtered_query.fetch(limit=expected_matches + 1))
self.assertEqual(len(entities), expected_matches)
arya_entity = entities[0]
arya_dict = dict(arya_entity.items())
self.assertEqual(arya_dict, {'name': 'Arya', 'family': 'Stark'})
catelyn_stark_entity = entities[2]
catelyn_stark_dict = dict(catelyn_stark_entity.items())
self.assertEqual(catelyn_stark_dict,
{'name': 'Catelyn', 'family': 'Stark'})
catelyn_tully_entity = entities[3]
catelyn_tully_dict = dict(catelyn_tully_entity.items())
self.assertEqual(catelyn_tully_dict,
{'name': 'Catelyn', 'family': 'Tully'})
# Check both Catelyn keys are the same.
catelyn_stark_key = catelyn_stark_entity.key
catelyn_tully_key = catelyn_tully_entity.key
self.assertEqual(catelyn_stark_key.path, catelyn_tully_key.path)
self.assertEqual(catelyn_stark_key.namespace,
catelyn_tully_key.namespace)
# Also check the dataset_id since both retrieved from datastore.
self.assertEqual(catelyn_stark_key.dataset_id,
catelyn_tully_key.dataset_id)
sansa_entity = entities[8]
sansa_dict = dict(sansa_entity.items())
self.assertEqual(sansa_dict, {'name': 'Sansa', 'family': 'Stark'})
def test_query_paginate_with_offset(self):
page_query = self._base_query()
page_query.order = 'appearances'
offset = 2
limit = 3
iterator = page_query.fetch(limit=limit, offset=offset)
# Fetch characters.
entities, _, cursor = iterator.next_page()
self.assertEqual(len(entities), limit)
self.assertEqual(entities[0]['name'], 'Robb')
self.assertEqual(entities[1]['name'], 'Bran')
self.assertEqual(entities[2]['name'], 'Catelyn')
# Fetch next set of characters.
new_iterator = page_query.fetch(limit=limit, offset=0,
start_cursor=cursor)
entities = list(new_iterator)
self.assertEqual(len(entities), limit)
self.assertEqual(entities[0]['name'], 'Sansa')
self.assertEqual(entities[1]['name'], 'Jon Snow')
self.assertEqual(entities[2]['name'], 'Arya')
def test_query_paginate_with_start_cursor(self):
page_query = self._base_query()
page_query.order = 'appearances'
limit = 3
offset = 2
iterator = page_query.fetch(limit=limit, offset=offset)
# Fetch characters.
entities, _, cursor = iterator.next_page()
self.assertEqual(len(entities), limit)
# Use cursor to create a fresh query.
fresh_query = self._base_query()
fresh_query.order = 'appearances'
new_entities = list(fresh_query.fetch(start_cursor=cursor,
limit=limit))
characters_remaining = len(self.CHARACTERS) - limit - offset
self.assertEqual(len(new_entities), characters_remaining)
self.assertEqual(new_entities[0]['name'], 'Sansa')
self.assertEqual(new_entities[2]['name'], 'Arya')
def test_query_group_by(self):
query = self._base_query()
query.group_by = ['alive']
expected_matches = 2
# We expect 2, but allow the query to get 1 extra.
entities = list(query.fetch(limit=expected_matches + 1))
self.assertEqual(len(entities), expected_matches)
self.assertEqual(entities[0]['name'], 'Catelyn')
self.assertEqual(entities[1]['name'], 'Arya')
class TestDatastoreTransaction(TestDatastore):
def test_transaction(self):
entity = Entity(key=Key('Company', 'Google'))
entity['url'] = u'www.google.com'
with Transaction():
retrieved_entity = entity.key.get()
if retrieved_entity is None:
entity.save()
self.case_entities_to_delete.append(entity)
# This will always return after the transaction.
retrieved_entity = entity.key.get()
self.case_entities_to_delete.append(retrieved_entity)
retrieved_dict = dict(retrieved_entity.items())
entity_dict = dict(entity.items())
self.assertEqual(retrieved_dict, entity_dict)