Removing the assertion that this site is run by StatusNet (major oops) and adding...
[mediagoblin.git] / mediagoblin / tests / test_submission.py
1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU Affero General Public License for more details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 import sys
18 reload(sys)
19 sys.setdefaultencoding('utf-8')
20
21 import urlparse
22 import os
23 import pytest
24
25 from mediagoblin.tests.tools import fixture_add_user
26 from mediagoblin import mg_globals
27 from mediagoblin.db.models import MediaEntry, User
28 from mediagoblin.db.base import Session
29 from mediagoblin.tools import template
30 from mediagoblin.media_types.image import ImageMediaManager
31 from mediagoblin.media_types.pdf.processing import check_prerequisites as pdf_check_prerequisites
32
33 from .resources import GOOD_JPG, GOOD_PNG, EVIL_FILE, EVIL_JPG, EVIL_PNG, \
34 BIG_BLUE, GOOD_PDF, GPS_JPG, MED_PNG, BIG_PNG
35
36 GOOD_TAG_STRING = u'yin,yang'
37 BAD_TAG_STRING = unicode('rage,' + 'f' * 26 + 'u' * 26)
38
39 FORM_CONTEXT = ['mediagoblin/submit/start.html', 'submit_form']
40 REQUEST_CONTEXT = ['mediagoblin/user_pages/user.html', 'request']
41
42
43 class TestSubmission:
44 @pytest.fixture(autouse=True)
45 def setup(self, test_app):
46 self.test_app = test_app
47
48 # TODO: Possibly abstract into a decorator like:
49 # @as_authenticated_user('chris')
50 fixture_add_user(privileges=[u'active',u'uploader', u'commenter'])
51
52 self.login()
53
54 def our_user(self):
55 """
56 Fetch the user we're submitting with. Every .get() or .post()
57 invalidates the session; this is a hacky workaround.
58 """
59 #### FIXME: Pytest collects this as a test and runs this.
60 #### ... it shouldn't. At least it passes, but that's
61 #### totally stupid.
62 #### Also if we found a way to make this run it should be a
63 #### property.
64 return User.query.filter(User.username==u'chris').first()
65
66 def login(self):
67 self.test_app.post(
68 '/auth/login/', {
69 'username': u'chris',
70 'password': 'toast'})
71
72 def logout(self):
73 self.test_app.get('/auth/logout/')
74
75 def do_post(self, data, *context_keys, **kwargs):
76 url = kwargs.pop('url', '/submit/')
77 do_follow = kwargs.pop('do_follow', False)
78 template.clear_test_template_context()
79 response = self.test_app.post(url, data, **kwargs)
80 if do_follow:
81 response.follow()
82 context_data = template.TEMPLATE_TEST_CONTEXT
83 for key in context_keys:
84 context_data = context_data[key]
85 return response, context_data
86
87 def upload_data(self, filename):
88 return {'upload_files': [('file', filename)]}
89
90 def check_comments(self, request, media_id, count):
91 comments = request.db.MediaComment.query.filter_by(media_entry=media_id)
92 assert count == len(list(comments))
93
94 def test_missing_fields(self):
95 # Test blank form
96 # ---------------
97 response, form = self.do_post({}, *FORM_CONTEXT)
98 assert form.file.errors == [u'You must provide a file.']
99
100 # Test blank file
101 # ---------------
102 response, form = self.do_post({'title': u'test title'}, *FORM_CONTEXT)
103 assert form.file.errors == [u'You must provide a file.']
104
105 def check_url(self, response, path):
106 assert urlparse.urlsplit(response.location)[2] == path
107
108 def check_normal_upload(self, title, filename):
109 response, context = self.do_post({'title': title}, do_follow=True,
110 **self.upload_data(filename))
111 self.check_url(response, '/u/{0}/'.format(self.our_user().username))
112 assert 'mediagoblin/user_pages/user.html' in context
113 # Make sure the media view is at least reachable, logged in...
114 url = '/u/{0}/m/{1}/'.format(self.our_user().username,
115 title.lower().replace(' ', '-'))
116 self.test_app.get(url)
117 # ... and logged out too.
118 self.logout()
119 self.test_app.get(url)
120
121 def user_upload_limits(self, uploaded=None, upload_limit=None):
122 our_user = self.our_user()
123
124 if uploaded:
125 our_user.uploaded = uploaded
126 if upload_limit:
127 our_user.upload_limit = upload_limit
128
129 our_user.save()
130 Session.expunge(our_user)
131
132 def test_normal_jpg(self):
133 # User uploaded should be 0
134 assert self.our_user().uploaded == 0
135
136 self.check_normal_upload(u'Normal upload 1', GOOD_JPG)
137
138 # User uploaded should be the same as GOOD_JPG size in Mb
139 file_size = os.stat(GOOD_JPG).st_size / (1024.0 * 1024)
140 file_size = float('{0:.2f}'.format(file_size))
141
142 # Reload user
143 assert self.our_user().uploaded == file_size
144
145 def test_normal_png(self):
146 self.check_normal_upload(u'Normal upload 2', GOOD_PNG)
147
148 @pytest.mark.skipif("not pdf_check_prerequisites()")
149 def test_normal_pdf(self):
150 response, context = self.do_post({'title': u'Normal upload 3 (pdf)'},
151 do_follow=True,
152 **self.upload_data(GOOD_PDF))
153 self.check_url(response, '/u/{0}/'.format(self.our_user().username))
154 assert 'mediagoblin/user_pages/user.html' in context
155
156 def test_default_upload_limits(self):
157 self.user_upload_limits(uploaded=500)
158
159 # User uploaded should be 500
160 assert self.our_user().uploaded == 500
161
162 response, context = self.do_post({'title': u'Normal upload 4'},
163 do_follow=True,
164 **self.upload_data(GOOD_JPG))
165 self.check_url(response, '/u/{0}/'.format(self.our_user().username))
166 assert 'mediagoblin/user_pages/user.html' in context
167
168 # Shouldn't have uploaded
169 assert self.our_user().uploaded == 500
170
171 def test_user_upload_limit(self):
172 self.user_upload_limits(uploaded=25, upload_limit=25)
173
174 # User uploaded should be 25
175 assert self.our_user().uploaded == 25
176
177 response, context = self.do_post({'title': u'Normal upload 5'},
178 do_follow=True,
179 **self.upload_data(GOOD_JPG))
180 self.check_url(response, '/u/{0}/'.format(self.our_user().username))
181 assert 'mediagoblin/user_pages/user.html' in context
182
183 # Shouldn't have uploaded
184 assert self.our_user().uploaded == 25
185
186 def test_user_under_limit(self):
187 self.user_upload_limits(uploaded=499)
188
189 # User uploaded should be 499
190 assert self.our_user().uploaded == 499
191
192 response, context = self.do_post({'title': u'Normal upload 6'},
193 do_follow=False,
194 **self.upload_data(MED_PNG))
195 form = context['mediagoblin/submit/start.html']['submit_form']
196 assert form.file.errors == [u'Sorry, uploading this file will put you'
197 ' over your upload limit.']
198
199 # Shouldn't have uploaded
200 assert self.our_user().uploaded == 499
201
202 def test_big_file(self):
203 response, context = self.do_post({'title': u'Normal upload 7'},
204 do_follow=False,
205 **self.upload_data(BIG_PNG))
206
207 form = context['mediagoblin/submit/start.html']['submit_form']
208 assert form.file.errors == [u'Sorry, the file size is too big.']
209
210 def check_media(self, request, find_data, count=None):
211 media = MediaEntry.query.filter_by(**find_data)
212 if count is not None:
213 assert media.count() == count
214 if count == 0:
215 return
216 return media[0]
217
218 def test_tags(self):
219 # Good tag string
220 # --------
221 response, request = self.do_post({'title': u'Balanced Goblin 2',
222 'tags': GOOD_TAG_STRING},
223 *REQUEST_CONTEXT, do_follow=True,
224 **self.upload_data(GOOD_JPG))
225 media = self.check_media(request, {'title': u'Balanced Goblin 2'}, 1)
226 assert media.tags[0]['name'] == u'yin'
227 assert media.tags[0]['slug'] == u'yin'
228
229 assert media.tags[1]['name'] == u'yang'
230 assert media.tags[1]['slug'] == u'yang'
231
232 # Test tags that are too long
233 # ---------------
234 response, form = self.do_post({'title': u'Balanced Goblin 2',
235 'tags': BAD_TAG_STRING},
236 *FORM_CONTEXT,
237 **self.upload_data(GOOD_JPG))
238 assert form.tags.errors == [
239 u'Tags must be shorter than 50 characters. ' \
240 'Tags that are too long: ' \
241 'ffffffffffffffffffffffffffuuuuuuuuuuuuuuuuuuuuuuuuuu']
242
243 def test_delete(self):
244 self.user_upload_limits(uploaded=50)
245 response, request = self.do_post({'title': u'Balanced Goblin'},
246 *REQUEST_CONTEXT, do_follow=True,
247 **self.upload_data(GOOD_JPG))
248 media = self.check_media(request, {'title': u'Balanced Goblin'}, 1)
249 media_id = media.id
250
251 # render and post to the edit page.
252 edit_url = request.urlgen(
253 'mediagoblin.edit.edit_media',
254 user=self.our_user().username, media_id=media_id)
255 self.test_app.get(edit_url)
256 self.test_app.post(edit_url,
257 {'title': u'Balanced Goblin',
258 'slug': u"Balanced=Goblin",
259 'tags': u''})
260 media = self.check_media(request, {'title': u'Balanced Goblin'}, 1)
261 assert media.slug == u"balanced-goblin"
262
263 # Add a comment, so we can test for its deletion later.
264 self.check_comments(request, media_id, 0)
265 comment_url = request.urlgen(
266 'mediagoblin.user_pages.media_post_comment',
267 user=self.our_user().username, media_id=media_id)
268 response = self.do_post({'comment_content': 'i love this test'},
269 url=comment_url, do_follow=True)[0]
270 self.check_comments(request, media_id, 1)
271
272 # Do not confirm deletion
273 # ---------------------------------------------------
274 delete_url = request.urlgen(
275 'mediagoblin.user_pages.media_confirm_delete',
276 user=self.our_user().username, media_id=media_id)
277 # Empty data means don't confirm
278 response = self.do_post({}, do_follow=True, url=delete_url)[0]
279 media = self.check_media(request, {'title': u'Balanced Goblin'}, 1)
280 media_id = media.id
281
282 # Confirm deletion
283 # ---------------------------------------------------
284 response, request = self.do_post({'confirm': 'y'}, *REQUEST_CONTEXT,
285 do_follow=True, url=delete_url)
286 self.check_media(request, {'id': media_id}, 0)
287 self.check_comments(request, media_id, 0)
288
289 # Check that user.uploaded is the same as before the upload
290 assert self.our_user().uploaded == 50
291
292 def test_evil_file(self):
293 # Test non-suppoerted file with non-supported extension
294 # -----------------------------------------------------
295 response, form = self.do_post({'title': u'Malicious Upload 1'},
296 *FORM_CONTEXT,
297 **self.upload_data(EVIL_FILE))
298 assert len(form.file.errors) == 1
299 assert 'Sorry, I don\'t support that file type :(' == \
300 str(form.file.errors[0])
301
302
303 def test_get_media_manager(self):
304 """Test if the get_media_manger function returns sensible things
305 """
306 response, request = self.do_post({'title': u'Balanced Goblin'},
307 *REQUEST_CONTEXT, do_follow=True,
308 **self.upload_data(GOOD_JPG))
309 media = self.check_media(request, {'title': u'Balanced Goblin'}, 1)
310
311 assert media.media_type == u'mediagoblin.media_types.image'
312 assert isinstance(media.media_manager, ImageMediaManager)
313 assert media.media_manager.entry == media
314
315
316 def test_sniffing(self):
317 '''
318 Test sniffing mechanism to assert that regular uploads work as intended
319 '''
320 template.clear_test_template_context()
321 response = self.test_app.post(
322 '/submit/', {
323 'title': u'UNIQUE_TITLE_PLS_DONT_CREATE_OTHER_MEDIA_WITH_THIS_TITLE'
324 }, upload_files=[(
325 'file', GOOD_JPG)])
326
327 response.follow()
328
329 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/user_pages/user.html']
330
331 request = context['request']
332
333 media = request.db.MediaEntry.query.filter_by(
334 title=u'UNIQUE_TITLE_PLS_DONT_CREATE_OTHER_MEDIA_WITH_THIS_TITLE').first()
335
336 assert media.media_type == 'mediagoblin.media_types.image'
337
338 def check_false_image(self, title, filename):
339 # NOTE: The following 2 tests will ultimately fail, but they
340 # *will* pass the initial form submission step. Instead,
341 # they'll be caught as failures during the processing step.
342 response, context = self.do_post({'title': title}, do_follow=True,
343 **self.upload_data(filename))
344 self.check_url(response, '/u/{0}/'.format(self.our_user().username))
345 entry = mg_globals.database.MediaEntry.query.filter_by(title=title).first()
346 assert entry.state == 'failed'
347 assert entry.fail_error == u'mediagoblin.processing:BadMediaFail'
348
349 def test_evil_jpg(self):
350 # Test non-supported file with .jpg extension
351 # -------------------------------------------
352 self.check_false_image(u'Malicious Upload 2', EVIL_JPG)
353
354 def test_evil_png(self):
355 # Test non-supported file with .png extension
356 # -------------------------------------------
357 self.check_false_image(u'Malicious Upload 3', EVIL_PNG)
358
359 def test_media_data(self):
360 self.check_normal_upload(u"With GPS data", GPS_JPG)
361 media = self.check_media(None, {"title": u"With GPS data"}, 1)
362 assert media.media_data.gps_latitude == 59.336666666666666
363
364 def test_processing(self):
365 public_store_dir = mg_globals.global_config[
366 'storage:publicstore']['base_dir']
367
368 data = {'title': u'Big Blue'}
369 response, request = self.do_post(data, *REQUEST_CONTEXT, do_follow=True,
370 **self.upload_data(BIG_BLUE))
371 media = self.check_media(request, data, 1)
372 last_size = 1024 ** 3 # Needs to be larger than bigblue.png
373 for key, basename in (('original', 'bigblue.png'),
374 ('medium', 'bigblue.medium.png'),
375 ('thumb', 'bigblue.thumbnail.png')):
376 # Does the processed image have a good filename?
377 filename = os.path.join(
378 public_store_dir,
379 *media.media_files[key])
380 assert filename.endswith('_' + basename)
381 # Is it smaller than the last processed image we looked at?
382 size = os.stat(filename).st_size
383 assert last_size > size
384 last_size = size