-
Notifications
You must be signed in to change notification settings - Fork 1
/
main_test.py
executable file
·4359 lines (3771 loc) · 174 KB
/
main_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
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 2009 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 main module."""
import datetime
import logging
logging.basicConfig(format='%(levelname)-8s %(filename)s] %(message)s')
import os
import shutil
import sys
import time
import tempfile
import unittest
import urllib
import xml.sax
import testutil
testutil.fix_path()
from google.appengine import runtime
from google.appengine.api import memcache
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.runtime import apiproxy_errors
import async_apiproxy
import dos
import feed_diff
import main
import urlfetch_test_stub
import mapreduce.control
import mapreduce.model
################################################################################
# For convenience
sha1_hash = main.sha1_hash
get_hash_key_name = main.get_hash_key_name
OTHER_STRING = '/~one:two/&='
FUNNY = '/CaSeSeNsItIvE'
FUNNY_UNICODE = u'/blah/\u30d6\u30ed\u30b0\u8846'
FUNNY_UTF8 = '/blah/\xe3\x83\x96\xe3\x83\xad\xe3\x82\xb0\xe8\xa1\x86'
FUNNY_IRI = '/blah/%E3%83%96%E3%83%AD%E3%82%B0%E8%A1%86'
################################################################################
class UtilityFunctionTest(unittest.TestCase):
"""Tests for utility functions."""
def setUp(self):
"""Sets up the test harness."""
testutil.setup_for_testing()
def testSha1Hash(self):
self.assertEquals('09f2c66851e75a7800748808ae7d855869b0c9d7',
main.sha1_hash('this is my test data'))
def testGetHashKeyName(self):
self.assertEquals('hash_54f6638eb67ad389b66bbc3fa65f7392b0c2d270',
get_hash_key_name('and now testing a key'))
def testSha1Hmac(self):
self.assertEquals('d95abcea4b2a8b0219da7cb04c261639a7bd8c94',
main.sha1_hmac('secrat', 'mydatahere'))
def testIsValidUrl(self):
self.assertTrue(main.is_valid_url(
'https://example.com:443/path/to?handler=1&b=2'))
self.assertTrue(main.is_valid_url('http://example.com:8080'))
self.assertFalse(main.is_valid_url('httpm://example.com'))
self.assertFalse(main.is_valid_url('http://example.com:9999'))
self.assertFalse(main.is_valid_url('http://example.com/blah#bad'))
def testNormalizeIri(self):
uri_with_port = u'http://foo.com:9120/url/with/a/port'
self.assertEquals(uri_with_port, main.normalize_iri(uri_with_port))
uri_with_query = u'http://foo.com:9120/url?doh=this&port=1'
self.assertEquals(uri_with_query, main.normalize_iri(uri_with_query))
uri_with_funny = u'http://foo.com/~myuser/@url!with#nice;delimiter:chars'
self.assertEquals(uri_with_funny, main.normalize_iri(uri_with_funny))
not_unicode = 'http://foo.com:9120/url/with/a/port'
self.assertEquals(not_unicode, main.normalize_iri(not_unicode))
uri_with_port = u'http://foo.com:9120/url/with/a/port'
self.assertEquals(uri_with_port, main.normalize_iri(uri_with_port))
good_iri = (
'http://www.google.com/reader/public/atom/user'
'/07256788297315478906/label/%E3%83%96%E3%83%AD%E3%82%B0%E8%A1%86')
iri = (u'http://www.google.com/reader/public/atom/user'
u'/07256788297315478906/label/\u30d6\u30ed\u30b0\u8846')
self.assertEquals(good_iri, main.normalize_iri(iri))
################################################################################
class TestWorkQueueHandler(webapp.RequestHandler):
@main.work_queue_only
def get(self):
self.response.out.write('Pass')
class WorkQueueOnlyTest(testutil.HandlerTestBase):
"""Tests the @work_queue_only decorator."""
handler_class = TestWorkQueueHandler
def testNotLoggedIn(self):
os.environ['SERVER_SOFTWARE'] = 'Production'
self.handle('get')
self.assertEquals(302, self.response_code())
def testCronHeader(self):
os.environ['SERVER_SOFTWARE'] = 'Production'
os.environ['HTTP_X_APPENGINE_CRON'] = 'True'
try:
self.handle('get')
self.assertEquals('Pass', self.response_body())
finally:
del os.environ['HTTP_X_APPENGINE_CRON']
def testDevelopmentEnvironment(self):
os.environ['SERVER_SOFTWARE'] = 'Development/1.0'
self.handle('get')
self.assertEquals('Pass', self.response_body())
def testAdminUser(self):
os.environ['SERVER_SOFTWARE'] = 'Production'
os.environ['USER_EMAIL'] = 'foo@example.com'
os.environ['USER_IS_ADMIN'] = '1'
try:
self.handle('get')
self.assertEquals('Pass', self.response_body())
finally:
del os.environ['USER_IS_ADMIN']
def testNonAdminUser(self):
os.environ['SERVER_SOFTWARE'] = 'Production'
os.environ['USER_EMAIL'] = 'foo@example.com'
os.environ['USER_IS_ADMIN'] = '0'
try:
self.handle('get')
self.assertEquals(401, self.response_code())
finally:
del os.environ['USER_IS_ADMIN']
def testTaskQueueHeader(self):
os.environ['SERVER_SOFTWARE'] = 'Production'
os.environ['HTTP_X_APPENGINE_TASKNAME'] = 'Foobar'
try:
self.handle('get')
self.assertEquals('Pass', self.response_body())
finally:
del os.environ['HTTP_X_APPENGINE_TASKNAME']
################################################################################
KnownFeed = main.KnownFeed
class KnownFeedTest(unittest.TestCase):
"""Tests for the KnownFeed model class."""
def setUp(self):
"""Sets up the test harness."""
testutil.setup_for_testing()
self.topic = 'http://example.com/my-topic'
self.topic2 = 'http://example.com/my-topic2'
self.topic3 = 'http://example.com/my-topic3'
def testCreateAndDelete(self):
known_feed = KnownFeed.create(self.topic)
self.assertEquals(self.topic, known_feed.topic)
db.put(known_feed)
found_feed = db.get(KnownFeed.create_key(self.topic))
self.assertEquals(found_feed.key(), known_feed.key())
self.assertEquals(found_feed.topic, known_feed.topic)
db.delete(KnownFeed.create_key(self.topic))
self.assertTrue(db.get(KnownFeed.create_key(self.topic)) is None)
def testCheckExistsMissing(self):
self.assertEquals([], KnownFeed.check_exists([]))
self.assertEquals([], KnownFeed.check_exists([self.topic]))
self.assertEquals([], KnownFeed.check_exists(
[self.topic, self.topic2, self.topic3]))
self.assertEquals([], KnownFeed.check_exists(
[self.topic, self.topic, self.topic, self.topic2, self.topic2]))
def testCheckExists(self):
KnownFeed.create(self.topic).put()
KnownFeed.create(self.topic2).put()
KnownFeed.create(self.topic3).put()
self.assertEquals([self.topic], KnownFeed.check_exists([self.topic]))
self.assertEquals([self.topic2], KnownFeed.check_exists([self.topic2]))
self.assertEquals([self.topic3], KnownFeed.check_exists([self.topic3]))
self.assertEquals(
sorted([self.topic, self.topic2, self.topic3]),
sorted(KnownFeed.check_exists([self.topic, self.topic2, self.topic3])))
self.assertEquals(
sorted([self.topic, self.topic2]),
sorted(KnownFeed.check_exists(
[self.topic, self.topic, self.topic, self.topic2, self.topic2])))
def testCheckExistsSubset(self):
KnownFeed.create(self.topic).put()
KnownFeed.create(self.topic3).put()
self.assertEquals(
sorted([self.topic, self.topic3]),
sorted(KnownFeed.check_exists([self.topic, self.topic2, self.topic3])))
self.assertEquals(
sorted([self.topic, self.topic3]),
sorted(KnownFeed.check_exists(
[self.topic, self.topic, self.topic,
self.topic2, self.topic2,
self.topic3, self.topic3])))
def testRecord(self):
"""Tests the method for recording a feed's identity."""
KnownFeed.record(self.topic)
task = testutil.get_tasks(main.MAPPINGS_QUEUE, index=0, expected_count=1)
self.assertEquals(self.topic, task['params']['topic'])
################################################################################
KnownFeedIdentity = main.KnownFeedIdentity
class KnownFeedIdentityTest(unittest.TestCase):
"""Tests for the KnownFeedIdentity class."""
def setUp(self):
testutil.setup_for_testing()
self.feed_id = 'my;feed;id'
self.feed_id2 = 'my;feed;id;2'
self.topic = 'http://example.com/foobar1'
self.topic2 = 'http://example.com/meep2'
self.topic3 = 'http://example.com/stuff3'
self.topic4 = 'http://example.com/blah4'
self.topic5 = 'http://example.com/woot5'
self.topic6 = 'http://example.com/neehaw6'
def testUpdate(self):
"""Tests the update method."""
feed = KnownFeedIdentity.update(self.feed_id, self.topic)
feed_key = KnownFeedIdentity.create_key(self.feed_id)
self.assertEquals(feed_key, feed.key())
self.assertEquals(self.feed_id, feed.feed_id)
self.assertEquals([self.topic], feed.topics)
feed = KnownFeedIdentity.update(self.feed_id, self.topic2)
self.assertEquals(self.feed_id, feed.feed_id)
self.assertEquals([self.topic, self.topic2], feed.topics)
def testRemove(self):
"""Tests the remove method."""
# Removing a mapping from an unknown ID does nothing.
self.assertTrue(KnownFeedIdentity.remove(self.feed_id, self.topic) is None)
KnownFeedIdentity.update(self.feed_id, self.topic)
KnownFeedIdentity.update(self.feed_id, self.topic2)
# Removing an unknown mapping for a known ID does nothing.
self.assertTrue(KnownFeedIdentity.remove(self.feed_id, self.topic3) is None)
# Removing from a known ID returns the updated copy.
feed = KnownFeedIdentity.remove(self.feed_id, self.topic2)
self.assertEquals([self.topic], feed.topics)
# Removing a second time does nothing.
self.assertTrue(KnownFeedIdentity.remove(self.feed_id, self.topic2) is None)
feed = KnownFeedIdentity.get(KnownFeedIdentity.create_key(self.feed_id))
self.assertEquals([self.topic], feed.topics)
# Removing the last one will delete the mapping completely.
self.assertTrue(KnownFeedIdentity.remove(self.feed_id, self.topic) is None)
feed = KnownFeedIdentity.get(KnownFeedIdentity.create_key(self.feed_id))
self.assertTrue(feed is None)
def testDeriveAdditionalTopics(self):
"""Tests the derive_additional_topics method."""
# topic, topic2 -> feed_id
for topic in (self.topic, self.topic2):
feed = KnownFeed.create(topic)
feed.feed_id = self.feed_id
feed.put()
KnownFeedIdentity.update(self.feed_id, self.topic)
KnownFeedIdentity.update(self.feed_id, self.topic2)
# topic3, topic4 -> feed_id2
for topic in (self.topic3, self.topic4):
feed = KnownFeed.create(topic)
feed.feed_id = self.feed_id2
feed.put()
KnownFeedIdentity.update(self.feed_id2, self.topic3)
KnownFeedIdentity.update(self.feed_id2, self.topic4)
# topic5 -> KnownFeed missing; should not be expanded at all
# topic6 -> KnownFeed where feed_id = None; default to simple mapping
KnownFeed.create(self.topic6).put()
# Put missing topics first to provoke potential ordering errors in the
# iteration order of the retrieval loop.
result = KnownFeedIdentity.derive_additional_topics([
self.topic5, self.topic6, self.topic,
self.topic2, self.topic3, self.topic4])
expected = {
'http://example.com/foobar1':
set(['http://example.com/foobar1', 'http://example.com/meep2']),
'http://example.com/meep2':
set(['http://example.com/foobar1', 'http://example.com/meep2']),
'http://example.com/blah4':
set(['http://example.com/blah4', 'http://example.com/stuff3']),
'http://example.com/neehaw6':
set(['http://example.com/neehaw6']),
'http://example.com/stuff3':
set(['http://example.com/blah4', 'http://example.com/stuff3'])
}
self.assertEquals(expected, result)
def testDeriveAdditionalTopicsWhitespace(self):
"""Tests when the feed ID contains whitespace it is handled correctly.
This test is only required because the 'feed_identifier' module did not
properly strip whitespace in its initial version.
"""
# topic -> feed_id with whitespace
feed = KnownFeed.create(self.topic)
feed.feed_id = self.feed_id
feed.put()
KnownFeedIdentity.update(self.feed_id, self.topic)
# topic2 -> feed_id without whitespace
feed = KnownFeed.create(self.topic2)
feed.feed_id = '\n %s \n \n' % self.feed_id
feed.put()
KnownFeedIdentity.update(self.feed_id, self.topic2)
# topic3 -> KnownFeed where feed_id = all whitespace
feed = KnownFeed.create(self.topic3)
feed.feed_id = '\n \n \n'
feed.put()
result = KnownFeedIdentity.derive_additional_topics([
self.topic, self.topic2, self.topic3])
expected = {
'http://example.com/foobar1':
set(['http://example.com/foobar1', 'http://example.com/meep2']),
'http://example.com/stuff3':
set(['http://example.com/stuff3']),
}
self.assertEquals(expected, result)
def testKnownFeedIdentityTooLarge(self):
"""Tests when the fan-out expansion of the KnownFeedIdentity is too big."""
feed = KnownFeedIdentity.update(self.feed_id, self.topic)
KnownFeedIdentity.update(
self.feed_id,
'http://super-extra-long-topic/' + ('a' * 10000000))
# Doesn't explode and the update time stays the same.
new_feed = db.get(feed.key())
self.assertEquals(feed.last_update, new_feed.last_update)
################################################################################
Subscription = main.Subscription
class SubscriptionTest(unittest.TestCase):
"""Tests for the Subscription model class."""
def setUp(self):
"""Sets up the test harness."""
testutil.setup_for_testing()
self.callback = 'http://example.com/my-callback-url'
self.callback2 = 'http://example.com/second-callback-url'
self.callback3 = 'http://example.com/third-callback-url'
self.topic = 'http://example.com/my-topic-url'
self.topic2 = 'http://example.com/second-topic-url'
self.token = 'token'
self.secret = 'my secrat'
self.callback_key_map = dict(
(Subscription.create_key_name(cb, self.topic), cb)
for cb in (self.callback, self.callback2, self.callback3))
def get_subscription(self):
"""Returns the subscription for the test callback and topic."""
return Subscription.get_by_key_name(
Subscription.create_key_name(self.callback, self.topic))
def verify_tasks(self, next_state, verify_token, secret, **kwargs):
"""Verifies the required tasks have been submitted.
Args:
next_state: The next state the Subscription should have.
verify_token: The token that should be used to confirm the
subscription action.
**kwargs: Passed to testutil.get_tasks().
"""
task = testutil.get_tasks(main.SUBSCRIPTION_QUEUE, **kwargs)
self.assertEquals(next_state, task['params']['next_state'])
self.assertEquals(verify_token, task['params']['verify_token'])
self.assertEquals(secret, task['params']['secret'])
def testRequestInsert_defaults(self):
now_datetime = datetime.datetime.now()
now = lambda: now_datetime
lease_seconds = 1234
self.assertTrue(Subscription.request_insert(
self.callback, self.topic, self.token,
self.secret, lease_seconds=lease_seconds, now=now))
self.verify_tasks(Subscription.STATE_VERIFIED, self.token, self.secret,
expected_count=1, index=0)
self.assertFalse(Subscription.request_insert(
self.callback, self.topic, self.token,
self.secret, lease_seconds=lease_seconds, now=now))
self.verify_tasks(Subscription.STATE_VERIFIED, self.token, self.secret,
expected_count=2, index=1)
sub = self.get_subscription()
self.assertEquals(Subscription.STATE_NOT_VERIFIED, sub.subscription_state)
self.assertEquals(self.callback, sub.callback)
self.assertEquals(sha1_hash(self.callback), sub.callback_hash)
self.assertEquals(self.topic, sub.topic)
self.assertEquals(sha1_hash(self.topic), sub.topic_hash)
self.assertEquals(self.token, sub.verify_token)
self.assertEquals(self.secret, sub.secret)
self.assertEquals(0, sub.confirm_failures)
self.assertEquals(now_datetime + datetime.timedelta(seconds=lease_seconds),
sub.expiration_time)
self.assertEquals(lease_seconds, sub.lease_seconds)
def testInsert_defaults(self):
now_datetime = datetime.datetime.now()
now = lambda: now_datetime
lease_seconds = 1234
self.assertTrue(Subscription.insert(
self.callback, self.topic, self.token, self.secret,
lease_seconds=lease_seconds, now=now))
self.assertFalse(Subscription.insert(
self.callback, self.topic, self.token, self.secret,
lease_seconds=lease_seconds, now=now))
testutil.get_tasks(main.SUBSCRIPTION_QUEUE, expected_count=0)
sub = self.get_subscription()
self.assertEquals(Subscription.STATE_VERIFIED, sub.subscription_state)
self.assertEquals(self.callback, sub.callback)
self.assertEquals(sha1_hash(self.callback), sub.callback_hash)
self.assertEquals(self.topic, sub.topic)
self.assertEquals(sha1_hash(self.topic), sub.topic_hash)
self.assertEquals(self.token, sub.verify_token)
self.assertEquals(self.secret, sub.secret)
self.assertEquals(0, sub.confirm_failures)
self.assertEquals(now_datetime + datetime.timedelta(seconds=lease_seconds),
sub.expiration_time)
self.assertEquals(lease_seconds, sub.lease_seconds)
def testInsertOverride(self):
"""Tests that insert will override the existing Subscription fields."""
self.assertTrue(Subscription.request_insert(
self.callback, self.topic, self.token, self.secret))
self.assertEquals(Subscription.STATE_NOT_VERIFIED,
self.get_subscription().subscription_state)
second_token = 'second token'
second_secret = 'second secret'
sub = self.get_subscription()
sub.confirm_failures = 123
sub.put()
self.assertFalse(Subscription.insert(
self.callback, self.topic, second_token, second_secret))
sub = self.get_subscription()
self.assertEquals(Subscription.STATE_VERIFIED, sub.subscription_state)
self.assertEquals(0, sub.confirm_failures)
self.assertEquals(second_token, sub.verify_token)
self.assertEquals(second_secret, sub.secret)
self.verify_tasks(Subscription.STATE_VERIFIED, self.token, self.secret,
expected_count=1, index=0)
def testInsert_expiration(self):
"""Tests that the expiration time is updated on repeated insert() calls."""
self.assertTrue(Subscription.insert(
self.callback, self.topic, self.token, self.secret))
sub = Subscription.all().get()
expiration1 = sub.expiration_time
time.sleep(0.5)
self.assertFalse(Subscription.insert(
self.callback, self.topic, self.token, self.secret))
sub = db.get(sub.key())
expiration2 = sub.expiration_time
self.assertTrue(expiration2 > expiration1)
def testRemove(self):
self.assertFalse(Subscription.remove(self.callback, self.topic))
self.assertTrue(Subscription.request_insert(
self.callback, self.topic, self.token, self.secret))
self.assertTrue(Subscription.remove(self.callback, self.topic))
self.assertFalse(Subscription.remove(self.callback, self.topic))
# Only task should be the initial insertion request.
self.verify_tasks(Subscription.STATE_VERIFIED, self.token, self.secret,
expected_count=1, index=0)
def testRequestRemove(self):
"""Tests the request remove method."""
self.assertFalse(Subscription.request_remove(
self.callback, self.topic, self.token))
# No tasks should be enqueued and this request should do nothing because
# no subscription currently exists.
testutil.get_tasks(main.SUBSCRIPTION_QUEUE, expected_count=0)
self.assertTrue(Subscription.request_insert(
self.callback, self.topic, self.token, self.secret))
second_token = 'this is the second token'
self.assertTrue(Subscription.request_remove(
self.callback, self.topic, second_token))
sub = self.get_subscription()
self.assertEquals(self.token, sub.verify_token)
self.assertEquals(Subscription.STATE_NOT_VERIFIED, sub.subscription_state)
self.verify_tasks(Subscription.STATE_VERIFIED, self.token, self.secret,
expected_count=2, index=0)
self.verify_tasks(Subscription.STATE_TO_DELETE, second_token, '',
expected_count=2, index=1)
def testRequestInsertOverride(self):
"""Tests that requesting insertion does not override the verify_token."""
self.assertTrue(Subscription.insert(
self.callback, self.topic, self.token, self.secret))
second_token = 'this is the second token'
second_secret = 'another secret here'
self.assertFalse(Subscription.request_insert(
self.callback, self.topic, second_token, second_secret))
sub = self.get_subscription()
self.assertEquals(self.token, sub.verify_token)
self.assertEquals(Subscription.STATE_VERIFIED, sub.subscription_state)
self.verify_tasks(Subscription.STATE_VERIFIED, second_token, second_secret,
expected_count=1, index=0)
def testHasSubscribers_unverified(self):
"""Tests that unverified subscribers do not make the subscription active."""
self.assertFalse(Subscription.has_subscribers(self.topic))
self.assertTrue(Subscription.request_insert(
self.callback, self.topic, self.token, self.secret))
self.assertFalse(Subscription.has_subscribers(self.topic))
def testHasSubscribers_verified(self):
self.assertTrue(Subscription.insert(
self.callback, self.topic, self.token, self.secret))
self.assertTrue(Subscription.has_subscribers(self.topic))
self.assertTrue(Subscription.remove(self.callback, self.topic))
self.assertFalse(Subscription.has_subscribers(self.topic))
def testGetSubscribers_unverified(self):
"""Tests that unverified subscribers will not be retrieved."""
self.assertEquals([], Subscription.get_subscribers(self.topic, 10))
self.assertTrue(Subscription.request_insert(
self.callback, self.topic, self.token, self.secret))
self.assertTrue(Subscription.request_insert(
self.callback2, self.topic, self.token, self.secret))
self.assertTrue(Subscription.request_insert(
self.callback3, self.topic, self.token, self.secret))
self.assertEquals([], Subscription.get_subscribers(self.topic, 10))
def testGetSubscribers_verified(self):
self.assertEquals([], Subscription.get_subscribers(self.topic, 10))
self.assertTrue(Subscription.insert(
self.callback, self.topic, self.token, self.secret))
self.assertTrue(Subscription.insert(
self.callback2, self.topic, self.token, self.secret))
self.assertTrue(Subscription.insert(
self.callback3, self.topic, self.token, self.secret))
sub_list = Subscription.get_subscribers(self.topic, 10)
found_keys = set(s.key().name() for s in sub_list)
self.assertEquals(set(self.callback_key_map.keys()), found_keys)
def testGetSubscribers_count(self):
self.assertTrue(Subscription.insert(
self.callback, self.topic, self.token, self.secret))
self.assertTrue(Subscription.insert(
self.callback2, self.topic, self.token, self.secret))
self.assertTrue(Subscription.insert(
self.callback3, self.topic, self.token, self.secret))
sub_list = Subscription.get_subscribers(self.topic, 1)
self.assertEquals(1, len(sub_list))
def testGetSubscribers_withOffset(self):
"""Tests the behavior of the starting_at_callback offset parameter."""
# In the order the query will sort them.
all_hashes = [
u'87a74994e48399251782eb401e9a61bd1d55aeee',
u'01518f29da9db10888a92e9f0211ac0c98ec7ecb',
u'f745d00a9806a5cdd39f16cd9eff80e8f064cfee',
]
all_keys = ['hash_' + h for h in all_hashes]
all_callbacks = [self.callback_key_map[k] for k in all_keys]
self.assertTrue(Subscription.insert(
self.callback, self.topic, self.token, self.secret))
self.assertTrue(Subscription.insert(
self.callback2, self.topic, self.token, self.secret))
self.assertTrue(Subscription.insert(
self.callback3, self.topic, self.token, self.secret))
def key_list(starting_at_callback):
sub_list = Subscription.get_subscribers(
self.topic, 10, starting_at_callback=starting_at_callback)
return [s.key().name() for s in sub_list]
self.assertEquals(all_keys, key_list(None))
self.assertEquals(all_keys, key_list(all_callbacks[0]))
self.assertEquals(all_keys[1:], key_list(all_callbacks[1]))
self.assertEquals(all_keys[2:], key_list(all_callbacks[2]))
def testGetSubscribers_multipleTopics(self):
"""Tests that separate topics do not overlap in subscriber queries."""
self.assertEquals([], Subscription.get_subscribers(self.topic2, 10))
self.assertTrue(Subscription.insert(
self.callback, self.topic, self.token, self.secret))
self.assertTrue(Subscription.insert(
self.callback2, self.topic, self.token, self.secret))
self.assertTrue(Subscription.insert(
self.callback3, self.topic, self.token, self.secret))
self.assertEquals([], Subscription.get_subscribers(self.topic2, 10))
self.assertTrue(Subscription.insert(
self.callback2, self.topic2, self.token, self.secret))
self.assertTrue(Subscription.insert(
self.callback3, self.topic2, self.token, self.secret))
sub_list = Subscription.get_subscribers(self.topic2, 10)
found_keys = set(s.key().name() for s in sub_list)
self.assertEquals(
set(Subscription.create_key_name(cb, self.topic2)
for cb in (self.callback2, self.callback3)),
found_keys)
self.assertEquals(3, len(Subscription.get_subscribers(self.topic, 10)))
def testConfirmFailed(self):
"""Tests retry delay periods when a subscription confirmation fails."""
start = datetime.datetime.utcnow()
def now():
return start
sub_key = Subscription.create_key_name(self.callback, self.topic)
self.assertTrue(Subscription.request_insert(
self.callback, self.topic, self.token, self.secret))
sub_key = Subscription.create_key_name(self.callback, self.topic)
sub = Subscription.get_by_key_name(sub_key)
self.assertEquals(0, sub.confirm_failures)
for i, delay in enumerate((5, 10, 20, 40, 80)):
self.assertTrue(
sub.confirm_failed(Subscription.STATE_VERIFIED, self.token, False,
max_failures=5, retry_period=5, now=now))
self.assertEquals(sub.eta, start + datetime.timedelta(seconds=delay))
self.assertEquals(i+1, sub.confirm_failures)
# It will give up on the last try.
self.assertFalse(
sub.confirm_failed(Subscription.STATE_VERIFIED, self.token, False,
max_failures=5, retry_period=5))
sub = Subscription.get_by_key_name(sub_key)
self.assertEquals(Subscription.STATE_NOT_VERIFIED, sub.subscription_state)
testutil.get_tasks(main.SUBSCRIPTION_QUEUE, index=0, expected_count=6)
def testQueueSelected(self):
"""Tests that auto_reconfirm will put the task on the polling queue."""
self.assertTrue(Subscription.request_insert(
self.callback, self.topic, self.token, self.secret,
auto_reconfirm=True))
testutil.get_tasks(main.SUBSCRIPTION_QUEUE, expected_count=0)
testutil.get_tasks(main.POLLING_QUEUE, expected_count=1)
self.assertFalse(Subscription.request_insert(
self.callback, self.topic, self.token, self.secret,
auto_reconfirm=False))
testutil.get_tasks(main.SUBSCRIPTION_QUEUE, expected_count=1)
testutil.get_tasks(main.POLLING_QUEUE, expected_count=1)
def testArchiveExists(self):
"""Tests the archive method when the subscription exists."""
Subscription.insert(self.callback, self.topic, self.token, self.secret)
sub_key = Subscription.create_key_name(self.callback, self.topic)
sub = Subscription.get_by_key_name(sub_key)
self.assertEquals(Subscription.STATE_VERIFIED, sub.subscription_state)
Subscription.archive(self.callback, self.topic)
sub = Subscription.get_by_key_name(sub_key)
self.assertEquals(Subscription.STATE_TO_DELETE, sub.subscription_state)
def testArchiveMissing(self):
"""Tests the archive method when the subscription does not exist."""
sub_key = Subscription.create_key_name(self.callback, self.topic)
self.assertTrue(Subscription.get_by_key_name(sub_key) is None)
Subscription.archive(self.callback, self.topic)
self.assertTrue(Subscription.get_by_key_name(sub_key) is None)
################################################################################
FeedToFetch = main.FeedToFetch
class FeedToFetchTest(unittest.TestCase):
def setUp(self):
"""Sets up the test harness."""
testutil.setup_for_testing()
self.topic = 'http://example.com/topic-one'
self.topic2 = 'http://example.com/topic-two'
self.topic3 = 'http://example.com/topic-three'
def testInsertAndGet(self):
"""Tests inserting and getting work."""
all_topics = [self.topic, self.topic2, self.topic3]
found_feeds = FeedToFetch.insert(all_topics)
task = testutil.get_tasks(main.FEED_QUEUE, index=0, expected_count=1)
self.assertTrue(task['name'].endswith('%d-0' % found_feeds[0].work_index))
for topic, feed_to_fetch in zip(all_topics, found_feeds):
self.assertEquals(topic, feed_to_fetch.topic)
self.assertEquals([], feed_to_fetch.source_keys)
self.assertEquals([], feed_to_fetch.source_values)
self.assertEquals(found_feeds[0].work_index, feed_to_fetch.work_index)
def testEmpty(self):
"""Tests when the list of urls is empty."""
FeedToFetch.insert([])
self.assertEquals([], testutil.get_tasks(main.FEED_QUEUE))
def testDuplicates(self):
"""Tests duplicate urls."""
all_topics = [self.topic, self.topic, self.topic2, self.topic2]
found_feeds = FeedToFetch.insert(all_topics)
found_topics = set(t.topic for t in found_feeds)
self.assertEquals(set(all_topics), found_topics)
task = testutil.get_tasks(main.FEED_QUEUE, index=0, expected_count=1)
self.assertTrue(task['name'].endswith('%d-0' % found_feeds[0].work_index))
def testDone(self):
"""Tests marking the feed as completed."""
(feed,) = FeedToFetch.insert([self.topic])
self.assertFalse(feed.done())
self.assertTrue(FeedToFetch.get_by_topic(self.topic) is None)
def testDoneAfterFailure(self):
"""Tests done() after a fetch_failed() writes the FeedToFetch to disk."""
(feed,) = FeedToFetch.insert([self.topic])
feed.fetch_failed()
self.assertTrue(feed.done())
self.assertTrue(FeedToFetch.get_by_topic(self.topic) is None)
def testDoneConflict(self):
"""Tests when another entity was written over the top of this one."""
(feed1,) = FeedToFetch.insert([self.topic])
feed1.put()
(feed2,) = FeedToFetch.insert([self.topic])
feed2.put()
self.assertFalse(feed1.done())
self.assertTrue(FeedToFetch.get_by_topic(self.topic) is not None)
def testFetchFailed(self):
"""Tests when the fetch fails and should be retried."""
start = datetime.datetime.utcnow()
now = lambda: start
(feed,) = FeedToFetch.insert([self.topic])
etas = []
for i, delay in enumerate((5, 10, 20, 40, 80)):
feed = FeedToFetch.get_by_topic(self.topic) or feed
feed.fetch_failed(max_failures=5, retry_period=5, now=now)
expected_eta = start + datetime.timedelta(seconds=delay)
self.assertEquals(expected_eta, feed.eta)
etas.append(testutil.task_eta(feed.eta))
self.assertEquals(i+1, feed.fetching_failures)
self.assertEquals(False, feed.totally_failed)
feed.fetch_failed(max_failures=5, retry_period=5, now=now)
self.assertEquals(True, feed.totally_failed)
tasks = testutil.get_tasks(main.FEED_QUEUE, expected_count=1)
tasks.extend(testutil.get_tasks(main.FEED_RETRIES_QUEUE, expected_count=5))
found_etas = [t['eta'] for t in tasks[1:]] # First task is from insert()
self.assertEquals(etas, found_etas)
def testQueuePreserved(self):
"""Tests the request's polling queue is preserved for new FeedToFetch."""
FeedToFetch.insert([self.topic])
testutil.get_tasks(main.FEED_QUEUE, expected_count=1)
os.environ['HTTP_X_APPENGINE_QUEUENAME'] = main.POLLING_QUEUE
try:
(feed,) = FeedToFetch.insert([self.topic])
testutil.get_tasks(main.FEED_QUEUE, expected_count=1)
testutil.get_tasks(main.POLLING_QUEUE, expected_count=1)
finally:
del os.environ['HTTP_X_APPENGINE_QUEUENAME']
def testSources(self):
"""Tests when sources are supplied."""
source_dict = {'foo': 'bar', 'meepa': 'stuff'}
all_topics = [self.topic, self.topic2, self.topic3]
feed_list = FeedToFetch.insert(all_topics, source_dict=source_dict)
for feed_to_fetch in feed_list:
found_source_dict = dict(zip(feed_to_fetch.source_keys,
feed_to_fetch.source_values))
self.assertEquals(source_dict, found_source_dict)
################################################################################
FeedEntryRecord = main.FeedEntryRecord
EventToDeliver = main.EventToDeliver
class EventToDeliverTest(unittest.TestCase):
def setUp(self):
"""Sets up the test harness."""
testutil.setup_for_testing()
self.topic = 'http://example.com/my-topic'
# Order out of the datastore will be done by callback hash, not alphabetical
self.callback = 'http://example.com/my-callback'
self.callback2 = 'http://example.com/second-callback'
self.callback3 = 'http://example.com/third-callback-123'
self.callback4 = 'http://example.com/fourth-callback-1205'
self.header_footer = '<feed>\n<stuff>blah</stuff>\n<xmldata/></feed>'
self.token = 'verify token'
self.secret = 'some secret'
self.test_payloads = [
'<entry>article1</entry>',
'<entry>article2</entry>',
'<entry>article3</entry>',
]
def insert_subscriptions(self):
"""Inserts Subscription instances and an EventToDeliver for testing.
Returns:
Tuple (event, work_key, sub_list, sub_keys) where:
event: The EventToDeliver that was inserted.
work_key: Key for the 'event'
sub_list: List of Subscription instances that were created in order
of their callback hashes.
sub_keys: Key instances corresponding to the entries in 'sub_list'.
"""
event = EventToDeliver.create_event_for_topic(
self.topic, main.ATOM, 'application/atom+xml',
self.header_footer, self.test_payloads)
event.put()
work_key = event.key()
Subscription.insert(
self.callback, self.topic, self.token, self.secret)
Subscription.insert(
self.callback2, self.topic, self.token, self.secret)
Subscription.insert(
self.callback3, self.topic, self.token, self.secret)
Subscription.insert(
self.callback4, self.topic, self.token, self.secret)
sub_list = Subscription.get_subscribers(self.topic, 10)
sub_keys = [s.key() for s in sub_list]
self.assertEquals(4, len(sub_list))
return (event, work_key, sub_list, sub_keys)
def testCreateEventForTopic(self):
"""Tests that the payload of an event is properly formed."""
event = EventToDeliver.create_event_for_topic(
self.topic, main.ATOM, 'application/atom+xml',
self.header_footer, self.test_payloads)
expected_data = \
u"""<?xml version="1.0" encoding="utf-8"?>
<feed>
<stuff>blah</stuff>
<xmldata/>
<entry>article1</entry>
<entry>article2</entry>
<entry>article3</entry>
</feed>"""
self.assertEquals(expected_data, event.payload)
self.assertEquals('application/atom+xml', event.content_type)
def testCreateEventForTopic_Rss(self):
"""Tests that the RSS payload is properly formed."""
self.test_payloads = [
'<item>article1</item>',
'<item>article2</item>',
'<item>article3</item>',
]
self.header_footer = (
'<rss>\n<channel>\n<stuff>blah</stuff>\n<xmldata/></channel>\n</rss>')
event = EventToDeliver.create_event_for_topic(
self.topic, main.RSS, 'application/rss+xml',
self.header_footer, self.test_payloads)
expected_data = \
u"""<?xml version="1.0" encoding="utf-8"?>
<rss>
<channel>
<stuff>blah</stuff>
<xmldata/>
<item>article1</item>
<item>article2</item>
<item>article3</item>
</channel>
</rss>"""
self.assertEquals(expected_data, event.payload)
self.assertEquals('application/rss+xml', event.content_type)
def testCreateEventForTopic_Abitrary(self):
"""Tests that an arbitrary payload is properly formed."""
self.test_payloads = []
self.header_footer = 'this is my data here'
event = EventToDeliver.create_event_for_topic(
self.topic, main.ARBITRARY, 'my crazy content type',
self.header_footer, self.test_payloads)
expected_data = 'this is my data here'
self.assertEquals(expected_data, event.payload)
self.assertEquals('my crazy content type', event.content_type)
def testCreateEvent_badHeaderFooter(self):
"""Tests when the header/footer data in an event is invalid."""
self.assertRaises(AssertionError, EventToDeliver.create_event_for_topic,
self.topic, main.ATOM, 'content type unused',
'<feed>has no end tag', self.test_payloads)
def testNormal_noFailures(self):
"""Tests that event delivery with no failures will delete the event."""
event, work_key, sub_list, sub_keys = self.insert_subscriptions()
more, subs = event.get_next_subscribers()
event.update(more, [])
event = EventToDeliver.get(work_key)
self.assertTrue(event is None)
def testUpdate_failWithNoSubscribersLeft(self):
"""Tests that failures are written correctly by EventToDeliver.update.
This tests the common case of completing the failed callbacks list extending
when there are new Subscriptions that have been found in the latest work
queue query.
"""
event, work_key, sub_list, sub_keys = self.insert_subscriptions()
# Assert that the callback offset is updated and any failed callbacks
# are recorded.
more, subs = event.get_next_subscribers(chunk_size=1)
event.update(more, [sub_list[0]])
event = EventToDeliver.get(event.key())
self.assertEquals(EventToDeliver.NORMAL, event.delivery_mode)
self.assertEquals([sub_list[0].key()], event.failed_callbacks)
self.assertEquals(self.callback2, event.last_callback)
more, subs = event.get_next_subscribers(chunk_size=3)
event.update(more, sub_list[1:])
event = EventToDeliver.get(event.key())
self.assertTrue(event is not None)
self.assertEquals(EventToDeliver.RETRY, event.delivery_mode)
self.assertEquals('', event.last_callback)
self.assertEquals([s.key() for s in sub_list], event.failed_callbacks)
tasks = testutil.get_tasks(main.EVENT_QUEUE, expected_count=1)
tasks.extend(testutil.get_tasks(main.EVENT_RETRIES_QUEUE, expected_count=1))
self.assertEquals([str(work_key)] * 2,
[t['params']['event_key'] for t in tasks])
def testUpdate_actuallyNoMoreCallbacks(self):
"""Tests when the normal update delivery has no Subscriptions left.
This tests the case where update is called with no Subscribers in the
list of Subscriptions. This can happen if a Subscription is deleted
between when an update happens and when the work queue is invoked again.
"""
event, work_key, sub_list, sub_keys = self.insert_subscriptions()
more, subs = event.get_next_subscribers(chunk_size=3)
event.update(more, subs)