This repository has been archived by the owner on Jan 30, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tasks_test.py
197 lines (158 loc) · 6.31 KB
/
tasks_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
#!/usr/bin/python
"""Unit tests for tasks.py.
"""
__author__ = ['Ryan Barrett <salmon@ryanb.org>']
import datetime
import json
import mox
import urlparse
from webob import exc
from fakes import FakeSource
from models import Source
from salmon import Salmon
import tasks
from tasks import Poll, Propagate
from webutil import testutil
from webutil import webapp2
from google.appengine.ext import db
class TaskQueueTest(testutil.HandlerTest):
"""Base class for testing task handlers.
Attributes:
task_params: the query parameters passed in the task POST request
post_url: the URL for post_task() to post to
now: the datetime to be returned by datetime.now()
salmon: a test data Salmon
"""
task_params = None
post_url = None
now = datetime.datetime.now()
def setUp(self):
super(TaskQueueTest, self).setUp()
tasks.NOW_FN = lambda: self.now
self.salmon_vars = {'id': 'tag:foo'}
self.salmon = Salmon(key_name='tag:foo', vars=json.dumps(self.salmon_vars))
def post_task(self, expected_status=200):
"""Runs post() and checks the response status code."""
resp = tasks.application.get_response(self.post_url, method='POST',
POST=self.task_params)
self.assertEqual(expected_status, resp.status_int, resp.body)
class PollTest(TaskQueueTest):
post_url = '/_ah/queue/poll'
def setUp(self):
super(PollTest, self).setUp()
self.source = FakeSource.new(self.handler)
self.source.save()
self.source.set_salmon([self.salmon_vars])
self.task_params = {'source_key': self.source.key(),
'last_polled': '1970-01-01-00-00-00'}
def test_poll(self):
"""A normal poll task."""
self.assertFalse(db.get(self.salmon.key()))
self.assertEqual([], self.taskqueue_stub.GetTasks('poll'))
self.post_task()
self.assertTrue(db.get(self.salmon.key()))
source = db.get(self.source.key())
self.assertEqual(self.now, source.last_polled)
tasks = self.taskqueue_stub.GetTasks('poll')
self.assertEqual(1, len(tasks))
self.assertEqual('/_ah/queue/poll', tasks[0]['url'])
params = testutil.get_task_params(tasks[0])
self.assertEqual(str(source.key()),
params['source_key'])
self.assertEqual(self.now.strftime(Source.POLL_TASK_DATETIME_FORMAT),
params['last_polled'])
def test_existing_salmon(self):
"""Poll should be idempotent and not touch existing salmon entities.
"""
self.salmon.status = 'complete'
self.salmon.save()
self.post_task()
self.assertTrue(db.get(self.salmon.key()))
self.assertEqual('complete', db.get(self.salmon.key()).status)
def test_wrong_last_polled(self):
"""If the source doesn't have our last polled value, we should quit.
"""
self.source.last_polled = datetime.datetime.utcfromtimestamp(3)
self.source.save()
self.post_task()
self.assert_(db.get(self.salmon.key()) is None)
def test_no_source(self):
"""If the source doesn't exist, do nothing and let the task die.
"""
self.source.delete()
self.post_task()
self.assertEqual([], self.taskqueue_stub.GetTasks('poll'))
class PropagateTest(TaskQueueTest):
post_url = '/_ah/queue/propagate'
def setUp(self):
super(PropagateTest, self).setUp()
self.salmon.save()
self.task_params = {'salmon_key': self.salmon.key()}
# can't use StubOutWithMock because i want to check the value of self, not
# args, which evidently mox can't do. :/ i get this error when I try to do
# it with self.mox.StubOutWithMock(Salmon, 'send_slap'):
#
# UnexpectedMethodCallError: Unexpected method call: __call__() -> None.
# Expecting: __call__(<function <lambda> at 0x363b758>) -> None
self.slaps = []
self.orig_send_slap = Salmon.send_slap
Salmon.send_slap = lambda salmon: self.slaps.append(salmon)
def tearDown(self):
Salmon.send_slap = self.orig_send_slap
super(PropagateTest, self).tearDown()
def assert_salmon_is(self, status, leased_until=False):
"""Asserts that self.salmon has the given values in the datastore.
"""
salmon = db.get(self.salmon.key())
self.assertEqual(status, salmon.status)
if leased_until is not False:
self.assertEqual(leased_until, salmon.leased_until)
def test_propagate(self):
"""A normal propagate task."""
self.assertEqual('new', self.salmon.status)
self.post_task()
self.assert_salmon_is('complete', self.now + Propagate.LEASE_LENGTH)
self.assert_entities_equal(self.slaps, self.salmon, keys_only=True)
def test_already_complete(self):
"""If the salmon has already been propagated, do nothing."""
self.salmon.status = 'complete'
self.salmon.save()
self.post_task()
self.assert_salmon_is('complete')
self.assertEqual([], self.slaps)
def test_leased(self):
"""If the salmon is processing and the lease hasn't expired, do nothing."""
self.salmon.status = 'processing'
leased_until = self.now + datetime.timedelta(minutes=1)
self.salmon.leased_until = leased_until
self.salmon.save()
self.post_task(expected_status=exc.HTTPConflict.code)
self.assert_salmon_is('processing', leased_until)
self.assertEqual([], self.slaps)
def test_lease_expired(self):
"""If the salmon is processing but the lease has expired, process it."""
self.salmon.status = 'processing'
self.salmon.leased_until = self.now - datetime.timedelta(minutes=1)
self.salmon.save()
self.post_task()
self.assert_salmon_is('complete', self.now + Propagate.LEASE_LENGTH)
self.assert_entities_equal(self.slaps, self.salmon, keys_only=True)
def test_no_salmon(self):
"""If the salmon doesn't exist, the request should fail."""
self.salmon.delete()
self.post_task(expected_status=exc.HTTPExpectationFailed.code)
self.assertEqual([], self.slaps)
def test_exceptions(self):
"""If any part raises an exception, the lease should be released."""
methods = [(Propagate, 'lease_salmon'),
(Propagate, 'complete_salmon'),
(Salmon, 'send_slap'),
]
for cls, method in methods:
self.mox.UnsetStubs()
self.mox.StubOutWithMock(cls, method)
getattr(cls, method)().AndRaise(Exception('foo'))
self.mox.ReplayAll()
self.post_task(expected_status=500)
self.assert_salmon_is('new', None)
self.mox.VerifyAll()