1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
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.
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.
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/>.
19 sys
.setdefaultencoding('utf-8')
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
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
36 GOOD_TAG_STRING
= u
'yin,yang'
37 BAD_TAG_STRING
= unicode('rage,' + 'f' * 26 + 'u' * 26)
39 FORM_CONTEXT
= ['mediagoblin/submit/start.html', 'submit_form']
40 REQUEST_CONTEXT
= ['mediagoblin/user_pages/user.html', 'request']
44 @pytest.fixture(autouse
=True)
45 def setup(self
, test_app
):
46 self
.test_app
= test_app
48 # TODO: Possibly abstract into a decorator like:
49 # @as_authenticated_user('chris')
50 fixture_add_user(privileges
=[u
'active',u
'uploader', u
'commenter'])
56 Fetch the user we're submitting with. Every .get() or .post()
57 invalidates the session; this is a hacky workaround.
59 #### FIXME: Pytest collects this as a test and runs this.
60 #### ... it shouldn't. At least it passes, but that's
62 #### Also if we found a way to make this run it should be a
64 return User
.query
.filter(User
.username
==u
'chris').first()
73 self
.test_app
.get('/auth/logout/')
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
)
82 context_data
= template
.TEMPLATE_TEST_CONTEXT
83 for key
in context_keys
:
84 context_data
= context_data
[key
]
85 return response
, context_data
87 def upload_data(self
, filename
):
88 return {'upload_files': [('file', filename
)]}
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
))
94 def test_missing_fields(self
):
97 response
, form
= self
.do_post({}, *FORM_CONTEXT
)
98 assert form
.file.errors
== [u
'You must provide a file.']
102 response
, form
= self
.do_post({'title': u
'test title'}, *FORM_CONTEXT
)
103 assert form
.file.errors
== [u
'You must provide a file.']
105 def check_url(self
, response
, path
):
106 assert urlparse
.urlsplit(response
.location
)[2] == path
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.
119 self
.test_app
.get(url
)
121 def user_upload_limits(self
, uploaded
=None, upload_limit
=None):
122 our_user
= self
.our_user()
125 our_user
.uploaded
= uploaded
127 our_user
.upload_limit
= upload_limit
130 Session
.expunge(our_user
)
132 def test_normal_jpg(self
):
133 # User uploaded should be 0
134 assert self
.our_user().uploaded
== 0
136 self
.check_normal_upload(u
'Normal upload 1', GOOD_JPG
)
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
))
143 assert self
.our_user().uploaded
== file_size
145 def test_normal_png(self
):
146 self
.check_normal_upload(u
'Normal upload 2', GOOD_PNG
)
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)'},
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
156 def test_default_upload_limits(self
):
157 self
.user_upload_limits(uploaded
=500)
159 # User uploaded should be 500
160 assert self
.our_user().uploaded
== 500
162 response
, context
= self
.do_post({'title': u
'Normal upload 4'},
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
168 # Shouldn't have uploaded
169 assert self
.our_user().uploaded
== 500
171 def test_user_upload_limit(self
):
172 self
.user_upload_limits(uploaded
=25, upload_limit
=25)
174 # User uploaded should be 25
175 assert self
.our_user().uploaded
== 25
177 response
, context
= self
.do_post({'title': u
'Normal upload 5'},
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
183 # Shouldn't have uploaded
184 assert self
.our_user().uploaded
== 25
186 def test_user_under_limit(self
):
187 self
.user_upload_limits(uploaded
=499)
189 # User uploaded should be 499
190 assert self
.our_user().uploaded
== 499
192 response
, context
= self
.do_post({'title': u
'Normal upload 6'},
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.']
199 # Shouldn't have uploaded
200 assert self
.our_user().uploaded
== 499
202 def test_big_file(self
):
203 response
, context
= self
.do_post({'title': u
'Normal upload 7'},
205 **self
.upload_data(BIG_PNG
))
207 form
= context
['mediagoblin/submit/start.html']['submit_form']
208 assert form
.file.errors
== [u
'Sorry, the file size is too big.']
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
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'
229 assert media
.tags
[1]['name'] == u
'yang'
230 assert media
.tags
[1]['slug'] == u
'yang'
232 # Test tags that are too long
234 response
, form
= self
.do_post({'title': u
'Balanced Goblin 2',
235 'tags': BAD_TAG_STRING
},
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']
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)
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",
260 media
= self
.check_media(request
, {'title': u
'Balanced Goblin'}, 1)
261 assert media
.slug
== u
"balanced-goblin"
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)
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)
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)
289 # Check that user.uploaded is the same as before the upload
290 assert self
.our_user().uploaded
== 50
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'},
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])
303 def test_get_media_manager(self
):
304 """Test if the get_media_manger function returns sensible things
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)
311 assert media
.media_type
== u
'mediagoblin.media_types.image'
312 assert isinstance(media
.media_manager
, ImageMediaManager
)
313 assert media
.media_manager
.entry
== media
316 def test_sniffing(self
):
318 Test sniffing mechanism to assert that regular uploads work as intended
320 template
.clear_test_template_context()
321 response
= self
.test_app
.post(
323 'title': u
'UNIQUE_TITLE_PLS_DONT_CREATE_OTHER_MEDIA_WITH_THIS_TITLE'
329 context
= template
.TEMPLATE_TEST_CONTEXT
['mediagoblin/user_pages/user.html']
331 request
= context
['request']
333 media
= request
.db
.MediaEntry
.query
.filter_by(
334 title
=u
'UNIQUE_TITLE_PLS_DONT_CREATE_OTHER_MEDIA_WITH_THIS_TITLE').first()
336 assert media
.media_type
== 'mediagoblin.media_types.image'
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'
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
)
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
)
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
364 def test_processing(self
):
365 public_store_dir
= mg_globals
.global_config
[
366 'storage:publicstore']['base_dir']
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(
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