First step towards a MediaManager class: Compat one.
[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
28 from mediagoblin.tools import template
29 from mediagoblin.media_types.image import MEDIA_MANAGER as img_MEDIA_MANAGER
30 from mediagoblin.media_types.pdf.processing import check_prerequisites as pdf_check_prerequisites
31
32 from .resources import GOOD_JPG, GOOD_PNG, EVIL_FILE, EVIL_JPG, EVIL_PNG, \
33 BIG_BLUE, GOOD_PDF, GPS_JPG
34
35 GOOD_TAG_STRING = u'yin,yang'
36 BAD_TAG_STRING = unicode('rage,' + 'f' * 26 + 'u' * 26)
37
38 FORM_CONTEXT = ['mediagoblin/submit/start.html', 'submit_form']
39 REQUEST_CONTEXT = ['mediagoblin/user_pages/user.html', 'request']
40
41
42 class TestSubmission:
43 def _setup(self, test_app):
44 self.test_app = test_app
45
46 # TODO: Possibly abstract into a decorator like:
47 # @as_authenticated_user('chris')
48 test_user = fixture_add_user()
49
50 self.test_user = test_user
51
52 self.login()
53
54 def login(self):
55 self.test_app.post(
56 '/auth/login/', {
57 'username': u'chris',
58 'password': 'toast'})
59
60 def logout(self):
61 self.test_app.get('/auth/logout/')
62
63 def do_post(self, data, *context_keys, **kwargs):
64 url = kwargs.pop('url', '/submit/')
65 do_follow = kwargs.pop('do_follow', False)
66 template.clear_test_template_context()
67 response = self.test_app.post(url, data, **kwargs)
68 if do_follow:
69 response.follow()
70 context_data = template.TEMPLATE_TEST_CONTEXT
71 for key in context_keys:
72 context_data = context_data[key]
73 return response, context_data
74
75 def upload_data(self, filename):
76 return {'upload_files': [('file', filename)]}
77
78 def check_comments(self, request, media_id, count):
79 comments = request.db.MediaComment.find({'media_entry': media_id})
80 assert count == len(list(comments))
81
82 def test_missing_fields(self, test_app):
83 self._setup(test_app)
84
85 # Test blank form
86 # ---------------
87 response, form = self.do_post({}, *FORM_CONTEXT)
88 assert form.file.errors == [u'You must provide a file.']
89
90 # Test blank file
91 # ---------------
92 response, form = self.do_post({'title': u'test title'}, *FORM_CONTEXT)
93 assert form.file.errors == [u'You must provide a file.']
94
95 def check_url(self, response, path):
96 assert urlparse.urlsplit(response.location)[2] == path
97
98 def check_normal_upload(self, title, filename):
99 response, context = self.do_post({'title': title}, do_follow=True,
100 **self.upload_data(filename))
101 self.check_url(response, '/u/{0}/'.format(self.test_user.username))
102 assert 'mediagoblin/user_pages/user.html' in context
103 # Make sure the media view is at least reachable, logged in...
104 url = '/u/{0}/m/{1}/'.format(self.test_user.username,
105 title.lower().replace(' ', '-'))
106 self.test_app.get(url)
107 # ... and logged out too.
108 self.logout()
109 self.test_app.get(url)
110
111 def test_normal_jpg(self, test_app):
112 self._setup(test_app)
113 self.check_normal_upload(u'Normal upload 1', GOOD_JPG)
114
115 def test_normal_png(self, test_app):
116 self._setup(test_app)
117 self.check_normal_upload(u'Normal upload 2', GOOD_PNG)
118
119 @pytest.mark.skipif("not pdf_check_prerequisites()")
120 def test_normal_pdf(self, test_app):
121 self._setup(test_app)
122 response, context = self.do_post({'title': u'Normal upload 3 (pdf)'},
123 do_follow=True,
124 **self.upload_data(GOOD_PDF))
125 self.check_url(response, '/u/{0}/'.format(self.test_user.username))
126 assert 'mediagoblin/user_pages/user.html' in context
127
128 def check_media(self, request, find_data, count=None):
129 media = MediaEntry.find(find_data)
130 if count is not None:
131 assert media.count() == count
132 if count == 0:
133 return
134 return media[0]
135
136 def test_tags(self, test_app):
137 self._setup(test_app)
138
139 # Good tag string
140 # --------
141 response, request = self.do_post({'title': u'Balanced Goblin 2',
142 'tags': GOOD_TAG_STRING},
143 *REQUEST_CONTEXT, do_follow=True,
144 **self.upload_data(GOOD_JPG))
145 media = self.check_media(request, {'title': u'Balanced Goblin 2'}, 1)
146 assert media.tags[0]['name'] == u'yin'
147 assert media.tags[0]['slug'] == u'yin'
148
149 assert media.tags[1]['name'] == u'yang'
150 assert media.tags[1]['slug'] == u'yang'
151
152 # Test tags that are too long
153 # ---------------
154 response, form = self.do_post({'title': u'Balanced Goblin 2',
155 'tags': BAD_TAG_STRING},
156 *FORM_CONTEXT,
157 **self.upload_data(GOOD_JPG))
158 assert form.tags.errors == [
159 u'Tags must be shorter than 50 characters. ' \
160 'Tags that are too long: ' \
161 'ffffffffffffffffffffffffffuuuuuuuuuuuuuuuuuuuuuuuuuu']
162
163 def test_delete(self, test_app):
164 self._setup(test_app)
165
166 response, request = self.do_post({'title': u'Balanced Goblin'},
167 *REQUEST_CONTEXT, do_follow=True,
168 **self.upload_data(GOOD_JPG))
169 media = self.check_media(request, {'title': u'Balanced Goblin'}, 1)
170 media_id = media.id
171
172 # render and post to the edit page.
173 edit_url = request.urlgen(
174 'mediagoblin.edit.edit_media',
175 user=self.test_user.username, media_id=media_id)
176 self.test_app.get(edit_url)
177 self.test_app.post(edit_url,
178 {'title': u'Balanced Goblin',
179 'slug': u"Balanced=Goblin",
180 'tags': u''})
181 media = self.check_media(request, {'title': u'Balanced Goblin'}, 1)
182 assert media.slug == u"balanced-goblin"
183
184 # Add a comment, so we can test for its deletion later.
185 self.check_comments(request, media_id, 0)
186 comment_url = request.urlgen(
187 'mediagoblin.user_pages.media_post_comment',
188 user=self.test_user.username, media_id=media_id)
189 response = self.do_post({'comment_content': 'i love this test'},
190 url=comment_url, do_follow=True)[0]
191 self.check_comments(request, media_id, 1)
192
193 # Do not confirm deletion
194 # ---------------------------------------------------
195 delete_url = request.urlgen(
196 'mediagoblin.user_pages.media_confirm_delete',
197 user=self.test_user.username, media_id=media_id)
198 # Empty data means don't confirm
199 response = self.do_post({}, do_follow=True, url=delete_url)[0]
200 media = self.check_media(request, {'title': u'Balanced Goblin'}, 1)
201 media_id = media.id
202
203 # Confirm deletion
204 # ---------------------------------------------------
205 response, request = self.do_post({'confirm': 'y'}, *REQUEST_CONTEXT,
206 do_follow=True, url=delete_url)
207 self.check_media(request, {'id': media_id}, 0)
208 self.check_comments(request, media_id, 0)
209
210 def test_evil_file(self, test_app):
211 self._setup(test_app)
212
213 # Test non-suppoerted file with non-supported extension
214 # -----------------------------------------------------
215 response, form = self.do_post({'title': u'Malicious Upload 1'},
216 *FORM_CONTEXT,
217 **self.upload_data(EVIL_FILE))
218 assert len(form.file.errors) == 1
219 assert 'Sorry, I don\'t support that file type :(' == \
220 str(form.file.errors[0])
221
222
223 def test_get_media_manager(self, test_app):
224 """Test if the get_media_manger function returns sensible things
225 """
226 self._setup(test_app)
227
228 response, request = self.do_post({'title': u'Balanced Goblin'},
229 *REQUEST_CONTEXT, do_follow=True,
230 **self.upload_data(GOOD_JPG))
231 media = self.check_media(request, {'title': u'Balanced Goblin'}, 1)
232
233 assert media.media_type == u'mediagoblin.media_types.image'
234 assert media.media_manager.mm_dict == img_MEDIA_MANAGER
235 assert media.media_manager.entry == media
236
237
238 def test_sniffing(self, test_app):
239 '''
240 Test sniffing mechanism to assert that regular uploads work as intended
241 '''
242 self._setup(test_app)
243
244 template.clear_test_template_context()
245 response = self.test_app.post(
246 '/submit/', {
247 'title': u'UNIQUE_TITLE_PLS_DONT_CREATE_OTHER_MEDIA_WITH_THIS_TITLE'
248 }, upload_files=[(
249 'file', GOOD_JPG)])
250
251 response.follow()
252
253 context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/user_pages/user.html']
254
255 request = context['request']
256
257 media = request.db.MediaEntry.find_one({
258 u'title': u'UNIQUE_TITLE_PLS_DONT_CREATE_OTHER_MEDIA_WITH_THIS_TITLE'})
259
260 assert media.media_type == 'mediagoblin.media_types.image'
261
262 def check_false_image(self, title, filename):
263 # NOTE: The following 2 tests will ultimately fail, but they
264 # *will* pass the initial form submission step. Instead,
265 # they'll be caught as failures during the processing step.
266 response, context = self.do_post({'title': title}, do_follow=True,
267 **self.upload_data(filename))
268 self.check_url(response, '/u/{0}/'.format(self.test_user.username))
269 entry = mg_globals.database.MediaEntry.find_one({'title': title})
270 assert entry.state == 'failed'
271 assert entry.fail_error == u'mediagoblin.processing:BadMediaFail'
272
273 def test_evil_jpg(self, test_app):
274 self._setup(test_app)
275
276 # Test non-supported file with .jpg extension
277 # -------------------------------------------
278 self.check_false_image(u'Malicious Upload 2', EVIL_JPG)
279
280 def test_evil_png(self, test_app):
281 self._setup(test_app)
282
283 # Test non-supported file with .png extension
284 # -------------------------------------------
285 self.check_false_image(u'Malicious Upload 3', EVIL_PNG)
286
287 def test_media_data(self, test_app):
288 self._setup(test_app)
289
290 self.check_normal_upload(u"With GPS data", GPS_JPG)
291 media = self.check_media(None, {"title": u"With GPS data"}, 1)
292 assert media.media_data.gps_latitude == 59.336666666666666
293
294 def test_processing(self, test_app):
295 self._setup(test_app)
296
297 public_store_dir = mg_globals.global_config[
298 'storage:publicstore']['base_dir']
299
300 data = {'title': u'Big Blue'}
301 response, request = self.do_post(data, *REQUEST_CONTEXT, do_follow=True,
302 **self.upload_data(BIG_BLUE))
303 media = self.check_media(request, data, 1)
304 last_size = 1024 ** 3 # Needs to be larger than bigblue.png
305 for key, basename in (('original', 'bigblue.png'),
306 ('medium', 'bigblue.medium.png'),
307 ('thumb', 'bigblue.thumbnail.png')):
308 # Does the processed image have a good filename?
309 filename = os.path.join(
310 public_store_dir,
311 *media.media_files.get(key, []))
312 assert filename.endswith('_' + basename)
313 # Is it smaller than the last processed image we looked at?
314 size = os.stat(filename).st_size
315 assert last_size > size
316 last_size = size