Files
SanctuaryCommander/test/upload_photo_test.py
T

147 lines
6.8 KiB
Python

from contextlib import closing
from io import BytesIO
import base64
import json
import os
from pathlib import Path
import runpy
import sqlite3
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
from blueprints.upload_photo.upload_photo import MAX_IMAGE_SIZE
ROOT = Path(__file__).resolve().parents[1]
PNG = base64.b64decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aK1cAAAAASUVORK5CYII=')
class UploadPhotoTest(unittest.TestCase):
def setUp(self):
self.directory = tempfile.TemporaryDirectory()
self.addCleanup(self.directory.cleanup)
self.workdir = Path(self.directory.name)
self.database = self.workdir / 'test.db'
self.storage = self.workdir / 'Images'
(self.workdir / 'config.json').write_text(json.dumps({
'database': {'type': 'SQLite', 'name': str(self.database)},
'upload_location': str(self.workdir / 'uploads')
}))
subprocess.run([sys.executable, str(ROOT / 'sc_database_generator.py')],
cwd=self.workdir, check=True, capture_output=True)
original = Path.cwd()
try:
os.chdir(self.workdir)
self.app = runpy.run_path(str(ROOT / 'sc_webserver.py'))['app']
finally:
os.chdir(original)
self.app.config['TESTING'] = True
self.client = self.app.test_client()
def post_image(self, content=PNG, name='Image', filename='photo.png'):
return self.client.post('/upload/photo', data={
'name': name, 'files[]': (BytesIO(content), filename)
})
def assert_no_files_or_records(self):
self.assertEqual(list(self.storage.glob('*')), [])
with closing(sqlite3.connect(self.database)) as db:
self.assertEqual(db.execute('SELECT COUNT(*) FROM media').fetchone(), (0,))
def test_page_and_navigation(self):
self.assertIn(b'/upload/photo', self.client.get('/').data)
response = self.client.get('/upload/photo')
self.assertEqual(response.status_code, 200)
self.assertEqual(MAX_IMAGE_SIZE, 100 * 1024 ** 2)
for text in (str(MAX_IMAGE_SIZE).encode(), b'Do not leave this page',
b'role="progressbar"', b'upload_media.js', b'data-media-kind="image"',
b'data-limit-label="100MB"'):
self.assertIn(text, response.data)
def test_upload_saves_image_and_display_name(self):
response = self.post_image(name=' Welcome image ', filename='PHOTO.PNG')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json['status'], 'SUCCESS')
with closing(sqlite3.connect(self.database)) as db:
name, uri = db.execute('SELECT media_name, media_uri FROM media').fetchone()
self.assertEqual(name, 'Welcome image')
self.assertEqual(Path(uri).parent, self.storage)
self.assertEqual(Path(uri).read_bytes(), PNG)
self.assertEqual(Path(uri).suffix, '.png')
self.assertEqual(len(list(self.storage.iterdir())), 1)
self.assertFalse((self.workdir / 'Videos').exists())
def test_configurable_folder(self):
self.app.config['config']['image_upload_location'] = 'CustomImages'
self.assertEqual(self.post_image().status_code, 200)
self.assertEqual(len(list((self.workdir / 'CustomImages').iterdir())), 1)
self.assertFalse(self.storage.exists())
def test_invalid_submissions(self):
cases = [({}, 400), ({'name': 'Image'}, 400),
({'name': ' ', 'files[]': (BytesIO(PNG), 'photo.png')}, 400),
({'name': 'Image', 'files[]': (BytesIO(b''), 'photo.png')}, 400),
({'name': 'Image', 'files[]': (BytesIO(b'code'), 'script.svg')}, 400),
({'name': 'Image', 'files[]': (BytesIO(b'video'), 'clip.mp4')}, 400),
({'name': 'Image', 'files[]': [(BytesIO(PNG), 'a.png'), (BytesIO(PNG), 'b.png')]}, 400)]
for data, status in cases:
with self.subTest(data=data):
response = self.client.post('/upload/photo', data=data)
self.assertEqual(response.status_code, status)
self.assertEqual(response.json['status'], 'FAILED')
self.assert_no_files_or_records()
def test_file_limit_exact_boundary_and_one_byte_over(self):
with patch('blueprints.upload_photo.upload_photo.MAX_IMAGE_SIZE', len(PNG)):
self.assertEqual(self.post_image(content=PNG + b'x').status_code, 413)
self.assert_no_files_or_records()
self.assertEqual(self.post_image().status_code, 200)
def test_request_limit_rejects_oversized_body_with_json(self):
with patch('blueprints.upload_photo.upload_photo.MAX_IMAGE_SIZE', 16):
with patch('blueprints.upload_photo.upload_photo.MULTIPART_OVERHEAD', 1024):
response = self.post_image(content=b'x' * 2048)
self.assertEqual(response.status_code, 413)
self.assertEqual(response.json['status'], 'FAILED')
self.assertIn('100MB', response.json['error'])
self.assert_no_files_or_records()
def test_filenames_and_names_cannot_escape_or_overwrite_storage(self):
for index in range(2):
self.assertEqual(self.post_image(name=f'../../Display name {index}', filename='../../photo.png').status_code, 200)
paths = list(self.storage.iterdir())
self.assertEqual(len(paths), 2)
self.assertTrue(all(path.name.startswith('upload-') for path in paths))
self.assertFalse((self.workdir / 'photo.png').exists())
def test_database_failure_removes_saved_file(self):
with patch('utilities.database.database.Database.insert', side_effect=sqlite3.OperationalError('Test failure')):
with self.assertLogs(self.app.logger, level='ERROR'):
response = self.post_image()
self.assertEqual(response.status_code, 500)
self.assert_no_files_or_records()
def test_storage_failure_returns_useful_error(self):
self.storage.write_text('Not a directory')
with self.assertLogs(self.app.logger, level='ERROR'):
response = self.post_image()
self.assertEqual(response.status_code, 500)
self.assertEqual(response.json['status'], 'FAILED')
def test_old_media_records_remain_unchanged(self):
with closing(sqlite3.connect(self.database)) as db:
db.execute('INSERT INTO media (media_name, media_uri) VALUES (?, ?)',
['Old image', 'uploads/Old image/photo.png'])
db.commit()
self.assertEqual(self.post_image().status_code, 200)
with closing(sqlite3.connect(self.database)) as db:
self.assertEqual(db.execute('SELECT media_name, media_uri FROM media WHERE media_id = 1').fetchone(),
('Old image', 'uploads/Old image/photo.png'))
if __name__ == '__main__':
unittest.main()