|
1 | 1 | import os
|
2 | 2 | import re
|
| 3 | +from contextlib import contextmanager |
| 4 | +from unittest import mock |
| 5 | + |
3 | 6 | from django.test import TestCase
|
4 | 7 | from django.urls import reverse
|
5 | 8 |
|
6 | 9 |
|
7 | 10 | class SimpleTest(TestCase):
|
8 | 11 |
|
9 |
| - def test_upload(self): |
| 12 | + @contextmanager |
| 13 | + def _get_image_fp(self): |
| 14 | + full_path = os.path.join( |
| 15 | + os.path.dirname(__file__), |
| 16 | + 'static', |
| 17 | + 'django-markdownx-preview.png', |
| 18 | + ) |
| 19 | + with open(full_path, 'rb') as fp: |
| 20 | + yield fp |
| 21 | + |
| 22 | + def test_upload_anonymous_fails(self): |
10 | 23 | url = reverse('markdownx_upload')
|
11 |
| - with open('markdownx/tests/static/django-markdownx-preview.png', 'rb') as fp: |
| 24 | + |
| 25 | + # Test that image upload fails for an anonymous user when |
| 26 | + # MARKDOWNX_UPLOAD_ALLOW_ANONYMOUS is the default False. |
| 27 | + with self._get_image_fp() as fp: |
12 | 28 | response = self.client.post(url, {'image': fp}, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
|
13 |
| - json = response.json() |
| 29 | + self.assertEqual(response.status_code, 403) |
| 30 | + |
| 31 | + def test_upload_anonymous_succeeds_with_setting(self): |
| 32 | + """ |
| 33 | + Ensures that uploads succeed when MARKDOWNX_UPLOAD_ALLOW_ANONYMOUS |
| 34 | + is True. This implicitly tests the authenticated case as well. |
| 35 | + """ |
| 36 | + url = reverse('markdownx_upload') |
| 37 | + |
| 38 | + # A patch is required here because the view sets the |
| 39 | + # MARKDOWNX_UPLOAD_ALLOW_ANONYMOUS at first import, reading from |
| 40 | + # django.conf.settings once, which means Django's standard |
| 41 | + # override_settings helper does not work. There's probably a case for |
| 42 | + # re-working the app-local settings. |
| 43 | + with mock.patch('markdownx.settings.MARKDOWNX_UPLOAD_ALLOW_ANONYMOUS', True): |
| 44 | + with self._get_image_fp() as fp: |
| 45 | + response = self.client.post(url, {'image': fp}, HTTP_X_REQUESTED_WITH='XMLHttpRequest') |
14 | 46 |
|
15 | 47 | self.assertEqual(response.status_code, 200)
|
| 48 | + json = response.json() |
16 | 49 | self.assertIn('image_code', json)
|
17 | 50 |
|
18 | 51 | match = re.findall(r'(markdownx/[\w\-]+\.png)', json['image_code'])
|
|
0 commit comments