forked from mozilla/zamboni
/
test_views.py
1306 lines (1098 loc) · 52.3 KB
/
test_views.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
# -*- coding: utf-8 -*-
import json
from decimal import Decimal
from textwrap import dedent
from django.conf import settings
from django.test.client import Client
from django.utils import translation
import jingo
from mock import patch
from nose.tools import eq_
from pyquery import PyQuery as pq
import amo
import api
from addons.models import (Addon, AppSupport, CompatOverride,
CompatOverrideRange, Persona, Preview)
from amo import helpers
from amo.helpers import absolutify
from amo.tests import addon_factory, ESTestCase, TestCase
from amo.urlresolvers import reverse
from amo.views import handler500
from api.utils import addon_to_dict
from api.views import addon_filter
from applications.models import Application, AppVersion
from bandwagon.models import Collection, CollectionAddon, FeaturedCollection
from files.models import File, Platform
from files.tests.test_models import UploadTest
from market.models import AddonPremium, Price, PriceCurrency
from tags.models import AddonTag, Tag
def api_url(x, app='firefox', lang='en-US', version=1.2):
return '/%s/%s/api/%.1f/%s' % (lang, app, version, x)
client = Client()
make_call = lambda *args, **kwargs: client.get(api_url(*args, **kwargs))
def test_json_not_implemented():
eq_(api.views.APIView().render_json({}), '{"msg": "Not implemented yet."}')
class UtilsTest(TestCase):
fixtures = ['base/addon_3615']
def setUp(self):
self.a = Addon.objects.get(pk=3615)
def test_dict(self):
"""Verify that we're getting dict."""
d = addon_to_dict(self.a)
assert d, 'Add-on dictionary not found'
assert d['learnmore'].endswith('/addon/a3615/?src=api'), (
'Add-on details URL does not end with "?src=api"')
def test_dict_disco(self):
"""Check for correct add-on detail URL for discovery pane."""
d = addon_to_dict(self.a, disco=True, src='discovery-personalrec')
u = '%s%s?src=discovery-personalrec' % (settings.SERVICES_URL,
reverse('discovery.addons.detail', args=['a3615']))
eq_(d['learnmore'], u)
def test_sanitize(self):
"""Check that tags are stripped for summary and description."""
self.a.summary = self.a.description = 'i <3 <a href="">amo</a>!'
self.a.save()
d = addon_to_dict(self.a)
eq_(d['summary'], 'i <3 amo!')
eq_(d['description'], 'i <3 amo!')
def test_contrib_info(self):
self.a.wants_contributions = True
self.a.suggested_amount = 5
self.a.paypal_id = 'alice@example.com'
self.a.save()
d = addon_to_dict(self.a)
eq_(d['contribution']['suggested_amount'], 5)
def test_no_contrib_info_until_approved(self):
self.a.wants_contributions = True
self.a.suggested_amount = 5
self.a.status = amo.STATUS_LITE
self.a.paypal_id = 'alice@example.com'
self.a.save()
d = addon_to_dict(self.a)
assert 'contribution' not in d
class No500ErrorsTest(TestCase):
"""
A series of unfortunate urls that have caused 500 errors in the past.
"""
def test_search_bad_type(self):
"""
For search/:term/:addon_type <-- addon_type should be an integer.
"""
response = make_call('/search/foo/theme')
# We'll likely get a 503 since Sphinx is off and that
# is good. We just don't want 500 errors.
assert response.status_code != 500, "We received a 500 error, wtf?"
def test_list_bad_type(self):
"""
For list/new/:addon_type <-- addon_type should be an integer.
"""
response = make_call('/list/new/extension')
assert response.status_code != 500, "We received a 500 error, wtf?"
def test_utf_redirect(self):
"""Test that urls with unicode redirect properly."""
response = make_call(u'search/ツールバー', version=1.5)
assert response.status_code != 500, "Unicode failed to redirect."
def test_manual_utf_search(self):
"""If someone searches for non doubly encoded data using an old API we
should not try to decode it."""
response = make_call(u'search/für', version=1.2)
assert response.status_code != 500, "ZOMG Unicode fails."
def test_broken_guid(self):
response = make_call(u'search/guid:+972"e4c6-}', version=1.5)
assert response.status_code != 500, "Failed to cope with guid"
class ControlCharacterTest(TestCase):
"""This test is to assure we aren't showing control characters."""
fixtures = ('base/addon_3615',)
def test(self):
a = Addon.objects.get(pk=3615)
char = chr(12)
a.name = "I %sove You" % char
a.save()
response = make_call('addon/3615')
self.assertNotContains(response, char)
class StripHTMLTest(TestCase):
fixtures = ('base/addon_3615',)
def test(self):
"""For API < 1.5 we remove HTML."""
a = Addon.objects.get(pk=3615)
a.eula = '<i>free</i> stock tips'
a.summary = '<i>xxx video</i>s'
a.description = 'FFFF<b>UUUU</b>'
a.save()
r = make_call('addon/3615', version=1.5)
doc = pq(r.content)
eq_(doc('eula').html(), '<i>free</i> stock tips')
eq_(doc('summary').html(), '<i>xxx video</i>s')
eq_(doc('description').html(), 'FFFF<b>UUUU</b>')
r = make_call('addon/3615')
doc = pq(r.content)
eq_(doc('eula').html(), 'free stock tips')
eq_(doc('summary').html(), 'xxx videos')
eq_(doc('description').html(), 'FFFFUUUU')
class APITest(TestCase):
fixtures = ['base/apps', 'base/addon_3615', 'base/addon_4664_twitterbar',
'base/addon_5299_gcal', 'perf/index']
def test_api_caching(self):
response = self.client.get('/en-US/firefox/api/1.5/addon/3615')
eq_(response.status_code, 200)
self.assertContains(response, '<author id="')
# Make sure we don't cache the 1.5 response for 1.2.
response = self.client.get('/en-US/firefox/api/1.2/addon/3615')
eq_(response.status_code, 200)
self.assertContains(response, '<author>')
def test_redirection(self):
"""
Test that /api/addon is redirected to /api/LATEST_API_VERSION/addon
"""
response = self.client.get('/en-US/firefox/api/addon/12', follow=True)
last_link = response.redirect_chain[-1]
assert last_link[0].endswith('en-US/firefox/api/%.1f/addon/12' %
api.CURRENT_VERSION)
def test_forbidden_api(self):
"""
APIs older than api.MIN_VERSION are deprecated, and we send a 403.
We suggest people to use api.CURRENT_VERSION.
"""
response = self.client.get('/en-US/firefox/api/0.9/addon/12')
self.assertContains(response, 'The API version, %.1f, you are using '
'is not valid. Please upgrade to the current version %.1f '
'API.' % (0.9, api.CURRENT_VERSION), status_code=403)
def test_addon_detail_missing(self):
"""
Check missing addons.
"""
response = self.client.get('/en-US/firefox/api/%.1f/addon/999' %
api.CURRENT_VERSION)
self.assertContains(response, 'Add-on not found!', status_code=404)
def test_handler404(self):
"""
Check separate handler404 response for API.
"""
response = self.client.get('/en-US/firefox/api/nonsense')
doc = pq(response.content)
eq_(response.status_code, 404)
d = doc('error')
self.assertTemplateUsed(response, 'api/message.xml')
eq_(d.length, 1)
eq_(d.text(), 'Not Found')
def test_handler500(self):
"""
Check separate handler500 response for API.
"""
req = self.client.get('/en-US/firefox/api/').context['request']
try:
raise NameError('an error')
except NameError:
r = handler500(req)
eq_(r.status_code, 500)
doc = pq(r.content)
d = doc('error')
eq_(d.length, 1)
eq_(d.text(), 'Server Error')
def test_addon_detail_appid(self):
"""
Make sure we serve an appid. See
https://bugzilla.mozilla.org/show_bug.cgi?id=546542.
"""
response = self.client.get('/en-US/firefox/api/%.1f/addon/3615' %
api.CURRENT_VERSION)
self.assertContains(response,
'<appID>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</appID>')
def test_addon_detail_empty_eula(self):
"""
Empty EULA should show up as '' not None. See
https://bugzilla.mozilla.org/show_bug.cgi?id=546542.
"""
response = self.client.get('/en-US/firefox/api/%.1f/addon/4664' %
api.CURRENT_VERSION)
self.assertContains(response, '<eula></eula>')
def test_addon_detail_rating(self):
a = Addon.objects.get(pk=4664)
response = self.client.get('/en-US/firefox/api/%.1f/addon/4664' %
api.CURRENT_VERSION)
self.assertContains(response, '<rating>%d</rating>' %
int(round(a.average_rating)))
def test_addon_detail_xml(self):
response = self.client.get('/en-US/firefox/api/%.1f/addon/3615' % 1.2)
self.assertContains(response, "<name>Delicious Bookmarks</name>")
self.assertContains(response, """id="1">Extension</type>""")
self.assertContains(response,
"""<guid>{2fa4ed95-0317-4c6a-a74c-5f3e3912c1f9}</guid>""")
self.assertContains(response, "<version>2.1.072</version>")
self.assertContains(response, '<status id="4">Fully Reviewed</status>')
self.assertContains(response,
u'<author>55021 \u0627\u0644\u062a\u0637\u0628</author>')
self.assertContains(response, "<summary>Delicious Bookmarks is the")
self.assertContains(response, "<description>This extension integrates")
icon_url = settings.ADDON_ICON_URL % (3, 3615, 32, '')
self.assertContains(response, '<icon size="32">' + icon_url)
self.assertContains(response, "<application>")
self.assertContains(response, "<name>Firefox</name>")
self.assertContains(response, "<application_id>1</application_id>")
self.assertContains(response, "<min_version>2.0</min_version>")
self.assertContains(response, "<max_version>4.0</max_version>")
self.assertContains(response, "<os>ALL</os>")
self.assertContains(response, "<eula>")
self.assertContains(response, "/icons/no-preview.png</thumbnail>")
self.assertContains(response, "<rating>3</rating>")
self.assertContains(response,
"/en-US/firefox/addon/a3615/?src=api</learnmore>")
self.assertContains(response,
"""hash="sha256:3808b13ef8341378b9c8305ca64820095"""
'4ee7dcd8dce09fef55f2673458bc31f"')
def test_addon_detail_json(self):
addon = Addon.objects.get(id=3615)
response = self.client.get(
'/en-US/firefox/api/%.1f/addon/3615?format=json' % 1.2)
data = json.loads(response.content)
eq_(data['name'], unicode(addon.name))
eq_(data['type'], 'extension')
eq_(data['guid'], addon.guid)
eq_(data['version'], '2.1.072')
eq_(data['status'], 'public')
eq_(data['authors'],
[{'id': 55021, 'name': u'55021 \u0627\u0644\u062a\u0637\u0628',
'link': absolutify(u'/en-US/firefox/user/55021/?src=api')}])
eq_(data['summary'], unicode(addon.summary))
eq_(data['description'],
'This extension integrates your browser with Delicious '
'(http://delicious.com), the leading social bookmarking '
'service on the Web.')
eq_(data['icon'],
settings.ADDON_ICON_URL % (3, 3615, 32, '') + '1275062517')
eq_(data['compatible_apps'],
[{'Firefox': {'max': '4.0', 'min': '2.0'}}])
eq_(data['eula'], unicode(addon.eula))
eq_(data['learnmore'],
absolutify('/en-US/firefox/addon/a3615/?src=api'))
assert 'theme' not in data
def test_app_detail(self):
addon = Addon.objects.get(id=3615)
addon.update(type=amo.ADDON_WEBAPP)
response = self.client.get(
'/en-US/firefox/api/%.1f/addon/3615?format=json' % 1.2)
eq_(json.loads(response.content)['msg'], 'Add-on not found!')
def test_theme_detail(self):
addon = Addon.objects.get(id=3615)
addon.update(type=amo.ADDON_PERSONA)
Persona.objects.create(persona_id=3, addon=addon)
response = self.client.get(
'/en-US/firefox/api/%.1f/addon/3615?format=json' % 1.2)
data = json.loads(response.content)
eq_(data['id'], 3615)
eq_(data['theme']['id'], '3615',
'`id` should be `addon_id`, not `persona_id`')
def test_addon_license(self):
"""Test for license information in response."""
addon = Addon.objects.get(id=3615)
license = addon.current_version.license
license.name = 'My License'
license.url = 'someurl'
license.save()
api_url = '/en-US/firefox/api/%.1f/addon/3615' % api.CURRENT_VERSION
response = self.client.get(api_url)
doc = pq(response.content)
eq_(doc('license').length, 1)
eq_(doc('license name').length, 1)
eq_(doc('license url').length, 1)
eq_(doc('license name').text(), unicode(license.name))
eq_(doc('license url').text(), absolutify(license.url))
license.url = ''
license.save()
addon.save()
response = self.client.get(api_url)
doc = pq(response.content)
license_url = addon.current_version.license_url()
eq_(doc('license url').text(), absolutify(license_url))
license.delete()
response = self.client.get(api_url)
doc = pq(response.content)
eq_(doc('license').length, 0)
def test_whitespace(self):
"""Whitespace is apparently evil for learnmore and install."""
r = make_call('addon/3615')
doc = pq(r.content)
learnmore = doc('learnmore')[0].text
eq_(learnmore, learnmore.strip())
install = doc('install')[0].text
eq_(install, install.strip())
def test_absolute_install_url(self):
response = make_call('addon/4664', version=1.2)
doc = pq(response.content)
url = doc('install').text()
expected = '%s/firefox/downloads/file' % settings.SITE_URL
assert url.startswith(expected), url
def test_15_addon_detail(self):
"""
For an api>1.5 we need to verify we have:
# Contributions information, including a link to contribute, suggested
amount, and Meet the Developers page
# Number of user reviews and link to view them
# Total downloads, weekly downloads, and latest daily user counts
# Add-on creation date
# Link to the developer's profile
# File size
"""
e = jingo.env.filters['e']
def urlparams(x, *args, **kwargs):
return e(helpers.urlparams(x, *args, **kwargs))
needles = (
'<addon id="4664">',
"<contribution_data>",
"%s/en-US/firefox/addon/4664/contribute/?src=api</link>"
% settings.SITE_URL,
"<meet_developers>",
"%s/en-US/firefox/addon/4664/developers?src=api"
% settings.SITE_URL,
"</meet_developers>",
"""<reviews num="131">""",
"%s/en-US/firefox/addon/4664/reviews/?src=api"
% settings.SITE_URL,
"<total_downloads>1352192</total_downloads>",
"<weekly_downloads>13849</weekly_downloads>",
"<daily_users>67075</daily_users>",
'<author id="2519"',
"%s/en-US/firefox/user/cfinke/?src=api</link>"
% settings.SITE_URL,
"<previews>",
"""<preview position="0">""",
"<caption>"
"TwitterBar places an icon in the address bar.</caption>",
"""<full type="image/png">""",
urlparams(settings.PREVIEW_FULL_URL %
('20', 20397, 'png', 1209834208), src='api'),
"""<thumbnail type="image/png">""",
urlparams(settings.PREVIEW_THUMBNAIL_URL %
('20', 20397, 1209834208), src='api'),
"<developer_comments>Embrace hug love hug meow meow"
"</developer_comments>",
'size="100352"',
'<homepage>http://www.chrisfinke.com/addons/twitterbar/'
'</homepage>',
'<support>http://www.chrisfinke.com/addons/twitterbar/'
'</support>',
)
response = make_call('addon/4664', version=1.5)
doc = pq(response.content)
tags = {
'suggested_amount': (
{'currency': 'USD', 'amount': '5.00'}, '$5.00'),
'created': ({'epoch': '1174134235'}, '2007-03-17T12:23:55Z'),
'last_updated': (
{'epoch': '1272326983'}, '2010-04-27T00:09:43Z'),
}
for tag, v in tags.items():
attrs, text = v
el = doc(tag)
for attr, val in attrs.items():
eq_(el.attr(attr), val)
eq_(el.text(), text)
for needle in needles:
self.assertContains(response, needle)
def test_no_contribs_until_approved(self):
Addon.objects.filter(id=4664).update(status=amo.STATUS_LITE)
response = make_call('addon/4664', version=1.5)
self.assertNotContains(response, 'contribution_data')
def test_no_suggested_amount(self):
Addon.objects.filter(id=4664).update(suggested_amount=None)
response = make_call('addon/4664', version=1.5)
assert '<suggested_amount' not in response.content
def setup_premium(self, lang='en-US'):
addon = Addon.objects.get(id=4664)
addon.update(premium_type=amo.ADDON_PREMIUM,
wants_contributions=False)
price = Price.objects.create(price=Decimal('5.12'))
PriceCurrency.objects.create(tier=price, currency='EUR',
price=Decimal('5.12'))
AddonPremium.objects.create(addon=addon, price=price)
return pq(make_call('addon/4664', version=1.5, lang=lang).content)
def test_beta_channel(self):
"""
This tests that addons with files in beta will have those files
displayed.
"""
response = make_call('addon/5299', version=1.5)
needles = (
"""<install hash="sha256:4395f9cf4934ecc8f22d367c2a301fd7""",
"""9613b68937c59e676e92e4f0a89a5b92" """,
'size="24576"',
'status="Beta">',
"/downloads/file/64874/better_gcal-0.4-fx.xpi?src=api",
)
for needle in needles:
self.assertContains(response, needle)
def test_slug(self):
Addon.objects.get(pk=5299).update(type=amo.ADDON_FREE)
self.assertContains(make_call('addon/5299', version=1.5),
'<slug>%s</slug>' %
Addon.objects.get(pk=5299).slug)
def test_is_featured(self):
self.assertContains(make_call('addon/5299', version=1.5),
'<featured>0</featured>')
c = CollectionAddon.objects.create(
addon=Addon.objects.get(id=5299),
collection=Collection.objects.create())
FeaturedCollection.objects.create(locale='ja',
application=Application.objects.get(id=amo.FIREFOX.id),
collection=c.collection)
for lang, app, result in [('ja', 'firefox', 1),
('en-US', 'firefox', 0),
('ja', 'seamonkey', 0)]:
self.assertContains(make_call('addon/5299', version=1.5,
lang=lang, app=app),
'<featured>%s</featured>' % result)
def test_default_icon(self):
addon = Addon.objects.get(pk=5299)
addon.update(icon_type='')
self.assertContains(make_call('addon/5299'), '<icon size="32"></icon>')
def test_thumbnail_size(self):
addon = Addon.objects.get(pk=5299)
preview = Preview.objects.create(addon=addon)
preview.sizes = {'thumbnail': [200, 150]}
preview.save()
result = make_call('addon/5299', version=1.5)
self.assertContains(result, '<full type="">')
self.assertContains(result,
'<thumbnail type="" width="200" height="150">')
def test_performance_data(self):
response = self.client.get('/en-US/firefox/api/%.1f/addon/3615' %
api.CURRENT_VERSION)
doc = pq(response.content)
eq_(doc('performance application').eq(0).attr('name'), 'fx')
eq_(doc('performance application').eq(0).attr('version'), '3.6')
eq_(doc('performance application platform').eq(0).attr('name'), 'mac')
eq_(doc('performance application platform').eq(0).attr('version'),
'10.6')
result = doc('performance application platform result').eq(0)
eq_(result.attr('type'), 'ts')
eq_(result.attr('average'), '5.21')
eq_(result.attr('baseline'), '1.2')
@patch.object(settings, 'PERF_THRESHOLD', 335)
def test_performance_threshold_false(self):
response = self.client.get('/en-US/firefox/api/%.1f/addon/3615' %
api.CURRENT_VERSION)
doc = pq(response.content)
result = doc('performance application platform result').eq(0)
eq_(result.attr('above_threshold'), 'false')
@patch.object(settings, 'PERF_THRESHOLD', 332)
def test_performance_threshold_true(self):
response = self.client.get('/en-US/firefox/api/%.1f/addon/3615' %
api.CURRENT_VERSION)
doc = pq(response.content)
result = doc('performance application platform result').eq(0)
eq_(result.attr('above_threshold'), 'true')
@patch.object(Addon, 'is_disabled', lambda self: True)
def test_disabled_addon(self):
response = self.client.get('/en-US/firefox/api/%.1f/addon/3615' %
api.CURRENT_VERSION)
doc = pq(response.content)
eq_(doc[0].tag, 'error')
eq_(response.status_code, 404)
def test_cross_origin(self):
# Add-on details should allow cross-origin requests.
response = self.client.get('/en-US/firefox/api/%.1f/addon/3615' %
api.CURRENT_VERSION)
eq_(response['Access-Control-Allow-Origin'], '*')
eq_(response['Access-Control-Allow-Methods'], 'GET')
# Even those that are not found.
response = self.client.get('/en-US/firefox/api/%.1f/addon/999' %
api.CURRENT_VERSION)
eq_(response['Access-Control-Allow-Origin'], '*')
eq_(response['Access-Control-Allow-Methods'], 'GET')
class ListTest(TestCase):
"""Tests the list view with various urls."""
fixtures = ['base/apps', 'base/users', 'base/addon_3615', 'base/featured',
'addons/featured', 'bandwagon/featured_collections',
'base/collections']
def test_defaults(self):
"""
This tests the default settings for /list.
i.e. We should get 3 items by default.
"""
response = make_call('list')
self.assertContains(response, '<addon id', 3)
def test_ignore_apps(self):
Addon.objects.update(type=amo.ADDON_WEBAPP)
response = make_call('list')
self.assertNotContains(response, '<addon id')
def test_type_filter(self):
"""
This tests that list filtering works.
E.g. /list/recommended/theme gets only shows themes
"""
response = make_call('list/recommended/9/1')
self.assertContains(response, """<type id="9">Theme</type>""", 1)
def test_persona_search_15(self):
response = make_call('list/recommended/9/1', version=1.5)
self.assertContains(response, """<type id="9">Theme</type>""", 1)
def test_limits(self):
"""
Assert /list/recommended/all/1 gets one item only.
"""
response = make_call('list/recommended/all/1')
self.assertContains(response, "<addon id", 1)
def test_version_filter(self):
"""
Assert that filtering by application version works.
E.g.
/list/new/all/1/mac/4.0 gives us nothing
"""
response = make_call('list/new/1/1/all/4.0')
self.assertNotContains(response, "<addon id")
def test_backfill(self):
"""
The /list/recommended should first populate itself with addons in its
locale. If it doesn't reach the desired limit, it should backfill from
the general population of featured addons.
"""
response = make_call('list', lang='fr')
self.assertContains(response, "<addon id", 3)
response = make_call('list', lang='he')
self.assertContains(response, "<addon id", 3)
def test_browser_featured_list(self):
"""
This is a query that a browser would use to show it's featured list.
c.f.: https://bugzilla.mozilla.org/show_bug.cgi?id=548114
"""
response = make_call('list/featured/all/10/Linux/3.7a2pre',
version=1.3)
self.assertContains(response, "<addons>")
def test_average_daily_users(self):
"""Verify that average daily users returns data in order."""
r = make_call('list/by_adu', version=1.5)
doc = pq(r.content)
vals = [int(a.text) for a in doc("average_daily_users")]
sorted_vals = sorted(vals, reverse=True)
eq_(vals, sorted_vals)
def test_adu_no_personas(self):
"""Verify that average daily users does not return Themes."""
response = make_call('list/by_adu')
self.assertNotContains(response, """<type id="9">Theme</type>""")
def test_featured_no_personas(self):
"""Verify that featured does not return Themes."""
response = make_call('list/featured')
self.assertNotContains(response, """<type id="9">Theme</type>""")
def test_json(self):
"""Verify that we get some json."""
r = make_call('list/by_adu?format=json', version=1.5)
assert json.loads(r.content)
def test_unicode(self):
make_call(u'list/featured/all/10/Linux/3.7a2prexec\xb6\u0153\xec\xb2')
class AddonFilterTest(TestCase):
"""Tests the addon_filter, including the various d2c cases."""
fixtures = ['base/apps', 'base/appversion']
def setUp(self):
# Start with 2 compatible add-ons.
self.addon1 = addon_factory(version_kw=dict(max_app_version='5.0'))
self.addon2 = addon_factory(version_kw=dict(max_app_version='6.0'))
self.addons = [self.addon1, self.addon2]
def _defaults(self, **kwargs):
# Default args for addon_filter.
defaults = {
'addons': self.addons,
'addon_type': 'ALL',
'limit': 0,
'app': amo.FIREFOX,
'platform': 'all',
'version': '5.0',
'compat_mode': 'strict',
'shuffle': False,
}
defaults.update(kwargs)
return defaults
def test_basic(self):
addons = addon_filter(**self._defaults())
eq_(addons, self.addons)
def test_limit(self):
addons = addon_filter(**self._defaults(limit=1))
eq_(addons, [self.addon1])
def test_app_filter(self):
self.addon1.update(type=amo.ADDON_DICT)
addons = addon_filter(
**self._defaults(addon_type=str(amo.ADDON_EXTENSION)))
eq_(addons, [self.addon2])
def test_platform_filter(self):
platform, _ = Platform.objects.get_or_create(pk=amo.PLATFORM_WIN.id)
file = self.addon1.current_version.files.all()[0]
file.update(platform=platform)
# Transformers don't know 'bout my files.
self.addons[0] = Addon.objects.get(pk=self.addons[0].pk)
addons = addon_filter(
**self._defaults(platform=amo.PLATFORM_LINUX.shortname))
eq_(addons, [self.addon2])
def test_version_filter_strict(self):
addons = addon_filter(**self._defaults(version='6.0'))
eq_(addons, [self.addon2])
def test_version_filter_ignore(self):
addons = addon_filter(**self._defaults(version='6.0',
compat_mode='ignore'))
eq_(addons, self.addons)
def test_version_version_less_than_min(self):
# Ensure we filter out addons with a higher min than our app.
addon3 = addon_factory(version_kw=dict(min_app_version='12.0',
max_app_version='14.0'))
addons = self.addons + [addon3]
addons = addon_filter(**self._defaults(addons=addons, version='11.0',
compat_mode='ignore'))
eq_(addons, self.addons)
def test_version_filter_normal_strict_opt_in(self):
# Ensure we filter out strict opt-in addons in normal mode.
addon3 = addon_factory(version_kw=dict(max_app_version='7.0'),
file_kw=dict(strict_compatibility=True))
addons = self.addons + [addon3]
addons = addon_filter(**self._defaults(addons=addons, version='11.0',
compat_mode='normal'))
eq_(addons, self.addons)
def test_version_filter_normal_binary_components(self):
# Ensure we filter out strict opt-in addons in normal mode.
addon3 = addon_factory(version_kw=dict(max_app_version='7.0'),
file_kw=dict(binary_components=True))
addons = self.addons + [addon3]
addons = addon_filter(**self._defaults(addons=addons, version='11.0',
compat_mode='normal'))
eq_(addons, self.addons)
def test_version_filter_normal_compat_override(self):
# Ensure we filter out strict opt-in addons in normal mode.
addon3 = addon_factory()
addons = self.addons + [addon3]
# Add override for this add-on.
compat = CompatOverride.objects.create(guid='three', addon=addon3)
CompatOverrideRange.objects.create(
compat=compat, app=Application.objects.get(pk=1),
min_version=addon3.current_version.version, max_version='*')
addons = addon_filter(**self._defaults(addons=addons, version='11.0',
compat_mode='normal'))
eq_(addons, self.addons)
def test_locale_preferencing(self):
# Add-ons matching the current locale get prioritized.
addon3 = addon_factory()
addon3.description = {'de': 'Unst Unst'}
addon3.save()
addons = self.addons + [addon3]
translation.activate('de')
addons = addon_filter(**self._defaults(addons=addons))
eq_(addons, [addon3] + self.addons)
translation.deactivate()
class SeamonkeyFeaturedTest(TestCase):
fixtures = ['base/seamonkey']
def test_seamonkey_wankery(self):
"""
An add-on used to support seamonkey, but not in its current_version.
This was making our filters crash.
"""
response = make_call('/list/featured/all/10/all/1', app='seamonkey')
eq_(response.context['addons'], [])
class TestGuidSearch(TestCase):
fixtures = ('base/apps', 'base/addon_6113', 'base/addon_3615')
# These are the guids for addon 6113 and 3615.
good = ('search/guid:{22870005-adef-4c9d-ae36-d0e1f2f27e5a},'
'{2fa4ed95-0317-4c6a-a74c-5f3e3912c1f9}')
def setUp(self):
addon = Addon.objects.get(id=3615)
c = CompatOverride.objects.create(guid=addon.guid)
app = addon.compatible_apps.keys()[0]
CompatOverrideRange.objects.create(compat=c, app_id=app.id)
def test_success(self):
r = make_call(self.good)
dom = pq(r.content)
eq_(set(['3615', '6113']),
set([a.attrib['id'] for a in dom('addon')]))
# Make sure the <addon_compatibility> blocks are there.
eq_(['3615'], [a.attrib['id'] for a in dom('addon_compatibility')])
@patch('waffle.switch_is_active', lambda x: True)
def test_api_caching_locale(self):
addon = Addon.objects.get(pk=3615)
addon.summary = {'en-US': 'Delicious', 'fr': 'Francais'}
addon.save()
# This will prime the cache with the en-US version.
response = make_call(self.good)
self.assertContains(response, '<summary>Delicious')
# We should get back the fr version, not the en-US one.
response = make_call(self.good, lang='fr')
self.assertContains(response, '<summary>Francais')
def test_xss(self):
Addon.objects.create(guid='test@xss', type=amo.ADDON_EXTENSION,
status=amo.STATUS_PUBLIC,
name='<script>alert("test");</script>')
r = make_call('search/guid:test@xss')
assert '<script>alert' not in r.content
assert '<script>alert' in r.content
def test_block_inactive(self):
Addon.objects.filter(id=6113).update(disabled_by_user=True)
r = make_call(self.good)
eq_(set(['3615']),
set([a.attrib['id'] for a in pq(r.content)('addon')]))
def test_block_nonpublic(self):
Addon.objects.filter(id=6113).update(status=amo.STATUS_UNREVIEWED)
r = make_call(self.good)
eq_(set(['3615']),
set([a.attrib['id'] for a in pq(r.content)('addon')]))
def test_empty(self):
"""
Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=607044
guid:foo, should search for just 'foo' and not empty guids.
"""
r = make_call('search/guid:koberger,')
doc = pq(r.content)
# No addons should exist with guid koberger and the , should not
# indicate that we are searching for null guid.
eq_(len(doc('addon')), 0)
def test_addon_compatibility(self):
addon = Addon.objects.get(id=3615)
r = make_call('search/guid:%s' % addon.guid)
dom = pq(r.content)
eq_(len(dom('addon_compatibility')), 1)
eq_(dom('addon_compatibility')[0].attrib['id'], '3615')
eq_(dom('addon_compatibility')[0].attrib['hosted'], 'true')
eq_(dom('addon_compatibility guid').text(), addon.guid)
eq_(dom('addon_compatibility > name').text(), '')
eq_(dom('addon_compatibility version_ranges version_range '
'compatible_applications application appID').text(),
amo.FIREFOX.guid)
def test_addon_compatibility_not_hosted(self):
c = CompatOverride.objects.create(guid='yeah', name='ok')
CompatOverrideRange.objects.create(app_id=1, compat=c,
min_version='1', max_version='2',
min_app_version='3',
max_app_version='4')
r = make_call('search/guid:%s' % c.guid)
dom = pq(r.content)
eq_(len(dom('addon_compatibility')), 1)
eq_(dom('addon_compatibility')[0].attrib['hosted'], 'false')
assert 'id' not in dom('addon_compatibility')[0].attrib
eq_(dom('addon_compatibility guid').text(), c.guid)
eq_(dom('addon_compatibility > name').text(), c.name)
cr = c.compat_ranges[0]
eq_(dom('version_range')[0].attrib['type'], cr.override_type())
eq_(dom('version_range > min_version').text(), cr.min_version)
eq_(dom('version_range > max_version').text(), cr.max_version)
eq_(dom('application name').text(), amo.FIREFOX.pretty)
eq_(dom('application application_id').text(), str(amo.FIREFOX.id))
eq_(dom('application appID').text(), amo.FIREFOX.guid)
eq_(dom('application min_version').text(), cr.min_app_version)
eq_(dom('application max_version').text(), cr.max_app_version)
class SearchTest(ESTestCase):
fixtures = ('base/apps', 'base/platforms', 'base/appversion',
'base/addon_6113', 'base/addon_40', 'base/addon_3615',
'base/addon_6704_grapple', 'base/addon_4664_twitterbar',
'base/addon_10423_youtubesearch')
no_results = """<searchresults total_results="0">"""
def setUp(self):
self.addons = Addon.objects.filter(status=amo.STATUS_PUBLIC,
disabled_by_user=False)
t = Tag.objects.create(tag_text='ballin')
a = Addon.objects.get(pk=3615)
AddonTag.objects.create(tag=t, addon=a)
[addon.save() for addon in self.addons]
self.refresh()
self.url = ('/en-US/firefox/api/%(api_version)s/search/%(query)s/'
'%(type)s/%(limit)s/%(platform)s/%(app_version)s/'
'%(compat_mode)s')
self.defaults = {
'api_version': '1.5',
'type': 'all',
'limit': '30',
'platform': 'Linux',
'app_version': '4.0',
'compat_mode': 'strict',
}
def test_double_escaping(self):
"""
For API < 1.5 we use double escaping in search.
"""
resp = make_call('search/%25E6%2596%25B0%25E5%2590%258C%25E6%2596%'
'2587%25E5%25A0%2582/all/10/WINNT/3.6', version=1.2)
self.assertContains(resp, '<addon id="6113">')
def test_zero_results(self):
"""
Tests that the search API correctly gives us zero results found.
"""
# The following URLs should yield zero results.
zeros = (
'yslow category:alerts',
'jsonview version:1.0',
'firebug type:dictionary',
'grapple platform:linux',
'firebug/3',
'grapple/all/10/Linux',
'jsonview/all/10/Darwin/1.0',
)
for url in zeros:
if not url.startswith('/'):
url = '/en-US/firefox/api/1.2/search/' + url
response = self.client.get(url)
self.assertContains(response, self.no_results, msg_prefix=url)
for url in zeros:
if not url.startswith('/'):
url = '/en-US/firefox/api/1.5/search/' + url
response = self.client.get(url)
self.assertContains(response, self.no_results, msg_prefix=url)
def test_search_for_specifics(self):
"""
Tests that the search API correctly returns specific results.
"""
expect = {
'delicious': 'Delicious Bookmarks',
'delicious category:feeds': 'Delicious Bookmarks',
'delicious version:3.6': 'Delicious Bookmarks',
'delicious type:extension': 'Delicious Bookmarks',
'delicious tag:ballin': 'Delicious Bookmarks',
'grapple platform:mac': 'GrApple',
'delicious/1': 'Delicious Bookmarks',
'grapple/all/10/Darwin': 'GrApple',
'delicious/all/10/Darwin/3.5': 'Delicious Bookmarks',
'/en-US/mobile/api/1.2/search/twitter/all/10/Linux/1.0':
'TwitterBar',