-
Notifications
You must be signed in to change notification settings - Fork 1
/
offline_jobs_test.py
executable file
·361 lines (322 loc) · 12.3 KB
/
offline_jobs_test.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
#!/usr/bin/env python
#
# Copyright 2010 Google Inc.
#
# 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.
#
"""Tests for the offline_jobs module."""
import datetime
import logging
logging.basicConfig(format='%(levelname)-8s %(filename)s] %(message)s')
import re
import time
import unittest
import testutil
testutil.fix_path()
from google.appengine.ext import db
from mapreduce import context
from mapreduce.lib import key_range
import main
import offline_jobs
################################################################################
class HashKeyDatastoreInputReaderTest(unittest.TestCase):
"""Tests for the HashKeyDatastoreInputReader."""
def setUp(self):
"""Sets up the test harness."""
testutil.setup_for_testing()
self.app = 'my-app-id'
self.entity_kind = 'main.Subscription'
self.namespace = 'my-namespace'
def testOneShard(self):
"""Tests just one shard."""
result = (
offline_jobs.HashKeyDatastoreInputReader._split_input_from_namespace(
self.app, self.namespace, self.entity_kind, 1))
expected = [
key_range.KeyRange(
key_start=db.Key.from_path(
'Subscription',
u'hash_0000000000000000000000000000000000000000',
_app=u'my-app-id'),
key_end=db.Key.from_path(
'Subscription',
u'hash_ffffffffffffffffffffffffffffffffffffffff',
_app=u'my-app-id'),
direction='ASC',
include_start=True,
include_end=True,
namespace='my-namespace',
_app='my-app-id')
]
self.assertEquals(expected, result)
def testTwoShards(self):
"""Tests two shares: one for number prefixes, one for letter prefixes."""
result = (
offline_jobs.HashKeyDatastoreInputReader._split_input_from_namespace(
self.app, self.namespace, self.entity_kind, 2))
expected = [
key_range.KeyRange(
key_start=db.Key.from_path(
'Subscription',
u'hash_0000000000000000000000000000000000000000',
_app=u'my-app-id'),
key_end=db.Key.from_path(
'Subscription',
u'hash_7fffffffffffffffffffffffffffffffffffffff',
_app=u'my-app-id'),
direction='DESC',
include_start=True,
include_end=True,
namespace='my-namespace',
_app='my-app-id'),
key_range.KeyRange(
key_start=db.Key.from_path(
'Subscription',
u'hash_7fffffffffffffffffffffffffffffffffffffff',
_app=u'my-app-id'),
key_end=db.Key.from_path(
'Subscription',
u'hash_ffffffffffffffffffffffffffffffffffffffff',
_app=u'my-app-id'),
direction='ASC',
include_start=False,
include_end=True,
namespace='my-namespace',
_app='my-app-id'),
]
self.assertEquals(expected, result)
def testManyShards(self):
"""Tests having many shards with multiple levels of splits."""
result = (
offline_jobs.HashKeyDatastoreInputReader._split_input_from_namespace(
self.app, self.namespace, self.entity_kind, 4))
expected = [
key_range.KeyRange(
key_start=db.Key.from_path(
'Subscription',
u'hash_0000000000000000000000000000000000000000',
_app=u'my-app-id'),
key_end=db.Key.from_path(
'Subscription',
u'hash_3fffffffffffffffffffffffffffffffffffffff',
_app=u'my-app-id'),
direction='DESC',
include_start=True,
include_end=True,
namespace='my-namespace',
_app='my-app-id'),
key_range.KeyRange(
key_start=db.Key.from_path(
'Subscription',
u'hash_3fffffffffffffffffffffffffffffffffffffff',
_app=u'my-app-id'),
key_end=db.Key.from_path(
'Subscription',
u'hash_7fffffffffffffffffffffffffffffffffffffff',
_app=u'my-app-id'),
direction='ASC',
include_start=False,
include_end=True,
namespace='my-namespace',
_app='my-app-id'),
key_range.KeyRange(
key_start=db.Key.from_path(
'Subscription',
u'hash_7fffffffffffffffffffffffffffffffffffffff',
_app=u'my-app-id'),
key_end=db.Key.from_path(
'Subscription',
u'hash_bfffffffffffffffffffffffffffffffffffffff',
_app=u'my-app-id'),
direction='DESC',
include_start=False,
include_end=True,
namespace='my-namespace',
_app='my-app-id'),
key_range.KeyRange(
key_start=db.Key.from_path(
'Subscription',
u'hash_bfffffffffffffffffffffffffffffffffffffff',
_app=u'my-app-id'),
key_end=db.Key.from_path(
'Subscription',
u'hash_ffffffffffffffffffffffffffffffffffffffff',
_app=u'my-app-id'),
direction='ASC',
include_start=False,
include_end=True,
namespace='my-namespace',
_app='my-app-id'),
]
self.assertEquals(expected, result)
Subscription = main.Subscription
class SubscriptionReconfirmMapperTest(unittest.TestCase):
"""Tests for the SubscriptionReconfirmMapper."""
def setUp(self):
"""Sets up the test harness."""
testutil.setup_for_testing()
self.mapper = offline_jobs.SubscriptionReconfirmMapper()
self.callback = 'http://example.com/my-callback-url'
self.topic = 'http://example.com/my-topic-url'
self.token = 'token'
self.secret = 'my secrat'
self.now = datetime.datetime.utcnow()
self.threshold_seconds = 1000
self.threshold_timestamp = (
time.mktime(self.now.utctimetuple()) + self.threshold_seconds)
self.getnow = lambda: self.now
class FakeMapper(object):
params = {'threshold_timestamp': str(self.threshold_timestamp)}
class FakeSpec(object):
mapreduce_id = '1234'
mapper = FakeMapper()
self.context = context.Context(FakeSpec(), None)
context.Context._set(self.context)
def get_subscription(self):
"""Returns the Subscription used for testing."""
return Subscription.get_by_key_name(
Subscription.create_key_name(self.callback, self.topic))
def testValidateParams(self):
"""Tests the validate_params static method."""
self.assertRaises(
AssertionError,
offline_jobs.SubscriptionReconfirmMapper.validate_params,
{})
offline_jobs.SubscriptionReconfirmMapper.validate_params(
{'threshold_timestamp': 123})
def testIgnoreUnverified(self):
"""Tests that unverified subscriptions are skipped."""
self.assertTrue(Subscription.request_insert(
self.callback, self.topic, self.token, self.secret,
now=self.getnow))
sub = self.get_subscription()
self.mapper.run(sub)
testutil.get_tasks(main.POLLING_QUEUE, expected_count=0)
def testAfterThreshold(self):
"""Tests when a subscription is not yet ready for reconfirmation."""
self.assertTrue(Subscription.insert(
self.callback, self.topic, self.token, self.secret,
now=self.getnow, lease_seconds=self.threshold_seconds))
sub = self.get_subscription()
self.mapper.run(sub)
testutil.get_tasks(main.POLLING_QUEUE, expected_count=0)
def testBeforeThreshold(self):
"""Tests when a subscription is ready for reconfirmation."""
self.assertTrue(Subscription.insert(
self.callback, self.topic, self.token, self.secret,
now=self.getnow, lease_seconds=self.threshold_seconds-1))
sub = self.get_subscription()
self.mapper.run(sub)
task = testutil.get_tasks(main.POLLING_QUEUE, index=0, expected_count=1)
self.assertEquals('polling', task['headers']['X-AppEngine-QueueName'])
################################################################################
class CountSubscribersTest(unittest.TestCase):
"""Tests for the CountSubscribers job."""
def setUp(self):
"""Sets up the test harness."""
testutil.setup_for_testing()
self.mapper = offline_jobs.CountSubscribers()
self.callback = 'http://foo.callback-example.com/my-callback-url'
self.topic = 'http://example.com/my-topic-url'
self.token = 'token'
self.secret = 'my secrat'
# Do not make these raw strings on purpose, since they will get
# passed through escaped in the mapreduce.yaml.
self.topic_pattern = '^http://example\\.com/.*$'
self.callback_pattern = (
'http(?:s)?://(?:[^\\.]+\\.)*([^\\./]+\.[^\\./]+)(?:/.*)?')
class FakeMapper(object):
params = {
'topic_pattern': self.topic_pattern,
'callback_pattern': self.callback_pattern,
}
class FakeSpec(object):
mapreduce_id = '1234'
mapper = FakeMapper()
self.context = context.Context(FakeSpec(), None)
context.Context._set(self.context)
def get_subscription(self):
"""Returns the Subscription used for testing."""
self.assertTrue(Subscription.insert(
self.callback, self.topic, self.token, self.secret))
return Subscription.get_by_key_name(
Subscription.create_key_name(self.callback, self.topic))
def testExpressions(self):
"""Tests the default expressions we're going to use for callbacks."""
callback_re = re.compile(self.callback_pattern)
self.assertEquals(
'blah.com',
callback_re.match('http://foo.blah.com/stuff').group(1))
self.assertEquals(
'blah.com',
callback_re.match('http://blah.com/stuff').group(1))
self.assertEquals(
'blah.com',
callback_re.match('http://one.two.three.blah.com/stuff').group(1))
self.assertEquals(
'blah.com',
callback_re.match('http://no-ending.blah.com').group(1))
self.assertEquals(
'example.com',
callback_re.match('https://fun.with.https.example.com/').group(1))
def testValidateParams(self):
"""Tests the validate_params function."""
self.assertRaises(
KeyError,
offline_jobs.CountSubscribers.validate_params,
{})
self.assertRaises(
AssertionError,
offline_jobs.CountSubscribers.validate_params,
{'topic_pattern': ''})
self.assertRaises(
re.error,
offline_jobs.CountSubscribers.validate_params,
{'topic_pattern': 'this is bad('})
self.assertRaises(
KeyError,
offline_jobs.CountSubscribers.validate_params,
{'topic_pattern': 'okay'})
self.assertRaises(
AssertionError,
offline_jobs.CountSubscribers.validate_params,
{'topic_pattern': 'okay', 'callback_pattern': ''})
self.assertRaises(
re.error,
offline_jobs.CountSubscribers.validate_params,
{'topic_pattern': 'okay', 'callback_pattern': 'this is bad('})
offline_jobs.CountSubscribers.validate_params(
{'topic_pattern': 'okay', 'callback_pattern': 'and okay'})
def testTopicMatch_CallbackMatch(self):
"""Tests when the topic and callbacks match."""
sub = self.get_subscription()
gen = self.mapper.run(sub)
counter = gen.next()
self.assertEquals('callback-example.com', counter.counter_name)
self.assertEquals(1, counter.delta)
self.assertRaises(StopIteration, gen.next)
def testTopicMatch_CallbackNoMatch(self):
"""Tests when the topic matches but the callback does not."""
self.callback = 'some garbage'
sub = self.get_subscription()
gen = self.mapper.run(sub)
self.assertRaises(StopIteration, gen.next)
def testTopicNoMatch(self):
"""Tests when the topic does not match."""
self.topic = 'http://does-not-match.com'
sub = self.get_subscription()
gen = self.mapper.run(sub)
self.assertRaises(StopIteration, gen.next)
################################################################################
if __name__ == '__main__':
unittest.main()