test_submission.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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. import six
  17. if six.PY2: # this hack only work in Python 2
  18. import sys
  19. reload(sys)
  20. sys.setdefaultencoding('utf-8')
  21. import os
  22. import pytest
  23. import six.moves.urllib.parse as urlparse
  24. # this gst initialization stuff is really required here
  25. import gi
  26. gi.require_version('Gst', '1.0')
  27. from gi.repository import Gst
  28. Gst.init(None)
  29. from mediagoblin.tests.tools import fixture_add_user
  30. from .media_tools import create_av
  31. from mediagoblin import mg_globals
  32. from mediagoblin.db.models import MediaEntry, User
  33. from mediagoblin.db.base import Session
  34. from mediagoblin.tools import template
  35. from mediagoblin.media_types.image import ImageMediaManager
  36. from mediagoblin.media_types.pdf.processing import check_prerequisites as pdf_check_prerequisites
  37. from .resources import GOOD_JPG, GOOD_PNG, EVIL_FILE, EVIL_JPG, EVIL_PNG, \
  38. BIG_BLUE, GOOD_PDF, GPS_JPG, MED_PNG, BIG_PNG
  39. GOOD_TAG_STRING = u'yin,yang'
  40. BAD_TAG_STRING = six.text_type('rage,' + 'f' * 26 + 'u' * 26)
  41. FORM_CONTEXT = ['mediagoblin/submit/start.html', 'submit_form']
  42. REQUEST_CONTEXT = ['mediagoblin/user_pages/user.html', 'request']
  43. class TestSubmission:
  44. @pytest.fixture(autouse=True)
  45. def setup(self, test_app):
  46. self.test_app = test_app
  47. # TODO: Possibly abstract into a decorator like:
  48. # @as_authenticated_user('chris')
  49. fixture_add_user(privileges=[u'active',u'uploader', u'commenter'])
  50. self.login()
  51. def our_user(self):
  52. """
  53. Fetch the user we're submitting with. Every .get() or .post()
  54. invalidates the session; this is a hacky workaround.
  55. """
  56. #### FIXME: Pytest collects this as a test and runs this.
  57. #### ... it shouldn't. At least it passes, but that's
  58. #### totally stupid.
  59. #### Also if we found a way to make this run it should be a
  60. #### property.
  61. return User.query.filter(User.username==u'chris').first()
  62. def login(self):
  63. self.test_app.post(
  64. '/auth/login/', {
  65. 'username': u'chris',
  66. 'password': 'toast'})
  67. def logout(self):
  68. self.test_app.get('/auth/logout/')
  69. def do_post(self, data, *context_keys, **kwargs):
  70. url = kwargs.pop('url', '/submit/')
  71. do_follow = kwargs.pop('do_follow', False)
  72. template.clear_test_template_context()
  73. response = self.test_app.post(url, data, **kwargs)
  74. if do_follow:
  75. response.follow()
  76. context_data = template.TEMPLATE_TEST_CONTEXT
  77. for key in context_keys:
  78. context_data = context_data[key]
  79. return response, context_data
  80. def upload_data(self, filename):
  81. return {'upload_files': [('file', filename)]}
  82. def check_comments(self, request, media_id, count):
  83. comments = request.db.MediaComment.query.filter_by(media_entry=media_id)
  84. assert count == len(list(comments))
  85. def test_missing_fields(self):
  86. # Test blank form
  87. # ---------------
  88. response, form = self.do_post({}, *FORM_CONTEXT)
  89. assert form.file.errors == [u'You must provide a file.']
  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. def check_url(self, response, path):
  95. assert urlparse.urlsplit(response.location)[2] == path
  96. def check_normal_upload(self, title, filename):
  97. response, context = self.do_post({'title': title}, do_follow=True,
  98. **self.upload_data(filename))
  99. self.check_url(response, '/u/{0}/'.format(self.our_user().username))
  100. assert 'mediagoblin/user_pages/user.html' in context
  101. # Make sure the media view is at least reachable, logged in...
  102. url = '/u/{0}/m/{1}/'.format(self.our_user().username,
  103. title.lower().replace(' ', '-'))
  104. self.test_app.get(url)
  105. # ... and logged out too.
  106. self.logout()
  107. self.test_app.get(url)
  108. def user_upload_limits(self, uploaded=None, upload_limit=None):
  109. our_user = self.our_user()
  110. if uploaded:
  111. our_user.uploaded = uploaded
  112. if upload_limit:
  113. our_user.upload_limit = upload_limit
  114. our_user.save()
  115. Session.expunge(our_user)
  116. def test_normal_jpg(self):
  117. # User uploaded should be 0
  118. assert self.our_user().uploaded == 0
  119. self.check_normal_upload(u'Normal upload 1', GOOD_JPG)
  120. # User uploaded should be the same as GOOD_JPG size in Mb
  121. file_size = os.stat(GOOD_JPG).st_size / (1024.0 * 1024)
  122. file_size = float('{0:.2f}'.format(file_size))
  123. # Reload user
  124. assert self.our_user().uploaded == file_size
  125. def test_normal_png(self):
  126. self.check_normal_upload(u'Normal upload 2', GOOD_PNG)
  127. @pytest.mark.skipif("not os.path.exists(GOOD_PDF) or not pdf_check_prerequisites()")
  128. def test_normal_pdf(self):
  129. response, context = self.do_post({'title': u'Normal upload 3 (pdf)'},
  130. do_follow=True,
  131. **self.upload_data(GOOD_PDF))
  132. self.check_url(response, '/u/{0}/'.format(self.our_user().username))
  133. assert 'mediagoblin/user_pages/user.html' in context
  134. def test_default_upload_limits(self):
  135. self.user_upload_limits(uploaded=500)
  136. # User uploaded should be 500
  137. assert self.our_user().uploaded == 500
  138. response, context = self.do_post({'title': u'Normal upload 4'},
  139. do_follow=True,
  140. **self.upload_data(GOOD_JPG))
  141. self.check_url(response, '/u/{0}/'.format(self.our_user().username))
  142. assert 'mediagoblin/user_pages/user.html' in context
  143. # Shouldn't have uploaded
  144. assert self.our_user().uploaded == 500
  145. def test_user_upload_limit(self):
  146. self.user_upload_limits(uploaded=25, upload_limit=25)
  147. # User uploaded should be 25
  148. assert self.our_user().uploaded == 25
  149. response, context = self.do_post({'title': u'Normal upload 5'},
  150. do_follow=True,
  151. **self.upload_data(GOOD_JPG))
  152. self.check_url(response, '/u/{0}/'.format(self.our_user().username))
  153. assert 'mediagoblin/user_pages/user.html' in context
  154. # Shouldn't have uploaded
  155. assert self.our_user().uploaded == 25
  156. def test_user_under_limit(self):
  157. self.user_upload_limits(uploaded=499)
  158. # User uploaded should be 499
  159. assert self.our_user().uploaded == 499
  160. response, context = self.do_post({'title': u'Normal upload 6'},
  161. do_follow=False,
  162. **self.upload_data(MED_PNG))
  163. form = context['mediagoblin/submit/start.html']['submit_form']
  164. assert form.file.errors == [u'Sorry, uploading this file will put you'
  165. ' over your upload limit.']
  166. # Shouldn't have uploaded
  167. assert self.our_user().uploaded == 499
  168. def test_big_file(self):
  169. response, context = self.do_post({'title': u'Normal upload 7'},
  170. do_follow=False,
  171. **self.upload_data(BIG_PNG))
  172. form = context['mediagoblin/submit/start.html']['submit_form']
  173. assert form.file.errors == [u'Sorry, the file size is too big.']
  174. def check_media(self, request, find_data, count=None):
  175. media = MediaEntry.query.filter_by(**find_data)
  176. if count is not None:
  177. assert media.count() == count
  178. if count == 0:
  179. return
  180. return media[0]
  181. def test_tags(self):
  182. # Good tag string
  183. # --------
  184. response, request = self.do_post({'title': u'Balanced Goblin 2',
  185. 'tags': GOOD_TAG_STRING},
  186. *REQUEST_CONTEXT, do_follow=True,
  187. **self.upload_data(GOOD_JPG))
  188. media = self.check_media(request, {'title': u'Balanced Goblin 2'}, 1)
  189. assert media.tags[0]['name'] == u'yin'
  190. assert media.tags[0]['slug'] == u'yin'
  191. assert media.tags[1]['name'] == u'yang'
  192. assert media.tags[1]['slug'] == u'yang'
  193. # Test tags that are too long
  194. # ---------------
  195. response, form = self.do_post({'title': u'Balanced Goblin 2',
  196. 'tags': BAD_TAG_STRING},
  197. *FORM_CONTEXT,
  198. **self.upload_data(GOOD_JPG))
  199. assert form.tags.errors == [
  200. u'Tags must be shorter than 50 characters. ' \
  201. 'Tags that are too long: ' \
  202. 'ffffffffffffffffffffffffffuuuuuuuuuuuuuuuuuuuuuuuuuu']
  203. def test_delete(self):
  204. self.user_upload_limits(uploaded=50)
  205. response, request = self.do_post({'title': u'Balanced Goblin'},
  206. *REQUEST_CONTEXT, do_follow=True,
  207. **self.upload_data(GOOD_JPG))
  208. media = self.check_media(request, {'title': u'Balanced Goblin'}, 1)
  209. media_id = media.id
  210. # render and post to the edit page.
  211. edit_url = request.urlgen(
  212. 'mediagoblin.edit.edit_media',
  213. user=self.our_user().username, media_id=media_id)
  214. self.test_app.get(edit_url)
  215. self.test_app.post(edit_url,
  216. {'title': u'Balanced Goblin',
  217. 'slug': u"Balanced=Goblin",
  218. 'tags': u''})
  219. media = self.check_media(request, {'title': u'Balanced Goblin'}, 1)
  220. assert media.slug == u"balanced-goblin"
  221. # Add a comment, so we can test for its deletion later.
  222. self.check_comments(request, media_id, 0)
  223. comment_url = request.urlgen(
  224. 'mediagoblin.user_pages.media_post_comment',
  225. user=self.our_user().username, media_id=media_id)
  226. response = self.do_post({'comment_content': 'i love this test'},
  227. url=comment_url, do_follow=True)[0]
  228. self.check_comments(request, media_id, 1)
  229. # Do not confirm deletion
  230. # ---------------------------------------------------
  231. delete_url = request.urlgen(
  232. 'mediagoblin.user_pages.media_confirm_delete',
  233. user=self.our_user().username, media_id=media_id)
  234. # Empty data means don't confirm
  235. response = self.do_post({}, do_follow=True, url=delete_url)[0]
  236. media = self.check_media(request, {'title': u'Balanced Goblin'}, 1)
  237. media_id = media.id
  238. # Confirm deletion
  239. # ---------------------------------------------------
  240. response, request = self.do_post({'confirm': 'y'}, *REQUEST_CONTEXT,
  241. do_follow=True, url=delete_url)
  242. self.check_media(request, {'id': media_id}, 0)
  243. self.check_comments(request, media_id, 0)
  244. # Check that user.uploaded is the same as before the upload
  245. assert self.our_user().uploaded == 50
  246. def test_evil_file(self):
  247. # Test non-suppoerted file with non-supported extension
  248. # -----------------------------------------------------
  249. response, form = self.do_post({'title': u'Malicious Upload 1'},
  250. *FORM_CONTEXT,
  251. **self.upload_data(EVIL_FILE))
  252. assert len(form.file.errors) == 1
  253. assert 'Sorry, I don\'t support that file type :(' == \
  254. str(form.file.errors[0])
  255. def test_get_media_manager(self):
  256. """Test if the get_media_manger function returns sensible things
  257. """
  258. response, request = self.do_post({'title': u'Balanced Goblin'},
  259. *REQUEST_CONTEXT, do_follow=True,
  260. **self.upload_data(GOOD_JPG))
  261. media = self.check_media(request, {'title': u'Balanced Goblin'}, 1)
  262. assert media.media_type == u'mediagoblin.media_types.image'
  263. assert isinstance(media.media_manager, ImageMediaManager)
  264. assert media.media_manager.entry == media
  265. def test_sniffing(self):
  266. '''
  267. Test sniffing mechanism to assert that regular uploads work as intended
  268. '''
  269. template.clear_test_template_context()
  270. response = self.test_app.post(
  271. '/submit/', {
  272. 'title': u'UNIQUE_TITLE_PLS_DONT_CREATE_OTHER_MEDIA_WITH_THIS_TITLE'
  273. }, upload_files=[(
  274. 'file', GOOD_JPG)])
  275. response.follow()
  276. context = template.TEMPLATE_TEST_CONTEXT['mediagoblin/user_pages/user.html']
  277. request = context['request']
  278. media = request.db.MediaEntry.query.filter_by(
  279. title=u'UNIQUE_TITLE_PLS_DONT_CREATE_OTHER_MEDIA_WITH_THIS_TITLE').first()
  280. assert media.media_type == 'mediagoblin.media_types.image'
  281. def check_false_image(self, title, filename):
  282. # NOTE: The following 2 tests will ultimately fail, but they
  283. # *will* pass the initial form submission step. Instead,
  284. # they'll be caught as failures during the processing step.
  285. response, context = self.do_post({'title': title}, do_follow=True,
  286. **self.upload_data(filename))
  287. self.check_url(response, '/u/{0}/'.format(self.our_user().username))
  288. entry = mg_globals.database.MediaEntry.query.filter_by(title=title).first()
  289. assert entry.state == 'failed'
  290. assert entry.fail_error == u'mediagoblin.processing:BadMediaFail'
  291. def test_evil_jpg(self):
  292. # Test non-supported file with .jpg extension
  293. # -------------------------------------------
  294. self.check_false_image(u'Malicious Upload 2', EVIL_JPG)
  295. def test_evil_png(self):
  296. # Test non-supported file with .png extension
  297. # -------------------------------------------
  298. self.check_false_image(u'Malicious Upload 3', EVIL_PNG)
  299. def test_media_data(self):
  300. self.check_normal_upload(u"With GPS data", GPS_JPG)
  301. media = self.check_media(None, {"title": u"With GPS data"}, 1)
  302. assert media.get_location.position["latitude"] == 59.336666666666666
  303. def test_audio(self):
  304. with create_av(make_audio=True) as path:
  305. self.check_normal_upload('Audio', path)
  306. def test_video(self):
  307. with create_av(make_video=True) as path:
  308. self.check_normal_upload('Video', path)
  309. def test_audio_and_video(self):
  310. with create_av(make_audio=True, make_video=True) as path:
  311. self.check_normal_upload('Audio and Video', path)
  312. def test_processing(self):
  313. public_store_dir = mg_globals.global_config[
  314. 'storage:publicstore']['base_dir']
  315. data = {'title': u'Big Blue'}
  316. response, request = self.do_post(data, *REQUEST_CONTEXT, do_follow=True,
  317. **self.upload_data(BIG_BLUE))
  318. media = self.check_media(request, data, 1)
  319. last_size = 1024 ** 3 # Needs to be larger than bigblue.png
  320. for key, basename in (('original', 'bigblue.png'),
  321. ('medium', 'bigblue.medium.png'),
  322. ('thumb', 'bigblue.thumbnail.png')):
  323. # Does the processed image have a good filename?
  324. filename = os.path.join(
  325. public_store_dir,
  326. *media.media_files[key])
  327. assert filename.endswith('_' + basename)
  328. # Is it smaller than the last processed image we looked at?
  329. size = os.stat(filename).st_size
  330. assert last_size > size
  331. last_size = size