GooDrive/backend/drive/test_create_documents.py
Louis Mazin 3fea8a85c8 perfect
2026-10-14 19:17:56 +02:00

64 lines
3.2 KiB
Python

"""Regression tests for New > File and LibreOffice safe previews."""
import tempfile
from pathlib import Path
from zipfile import ZipFile
from django.contrib.auth import get_user_model
from django.test import SimpleTestCase, TestCase, override_settings
from rest_framework.test import APIClient
from .document_formats import ODF_TYPES, blank_file, render_odf_preview
from .models import DriveItem
class DocumentFormatsTests(SimpleTestCase):
def test_valid_blank_office_files_have_expected_structure(self):
for extension in ('docx', 'odt', 'ods', 'odp'):
with self.subTest(ext=extension):
content = blank_file(extension)
with tempfile.TemporaryDirectory() as temp:
p = Path(temp) / f'blank.{extension}'
p.write_bytes(content)
with ZipFile(p) as archive:
self.assertIsNone(archive.testzip())
self.assertIn('word/document.xml' if extension == 'docx' else 'content.xml', archive.namelist())
if extension in ODF_TYPES:
html = render_odf_preview(p)
self.assertIn('<html', html)
self.assertNotIn('<script', html)
def test_disallow_active_xml(self):
with tempfile.TemporaryDirectory() as temp:
p = Path(temp) / 'unsafe.odt'
with ZipFile(p, 'w') as archive:
archive.writestr('content.xml', b'<!DOCTYPE doc [<!ENTITY x SYSTEM "file:///etc/passwd">]><doc>&x;</doc>')
with self.assertRaises(ValueError):
render_odf_preview(p)
class NewFileEndpointTests(TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
override = override_settings(DRIVE_STORAGE_ROOT=self.root, FILE_UPLOAD_TEMP_DIR=str(self.root / '.tmp'))
override.enable()
self.addCleanup(override.disable)
self.user = get_user_model().objects.create_superuser('newfilesadmin', 'new@example.com', 'secret')
self.client = APIClient()
self.client.force_authenticate(user=self.user)
self.space = self.client.get('/api/auth/me/').data['space_id']
def test_create_lo_file_and_reject_duplicate(self):
payload = {'name': 'Feuille.ods', 'type': 'ods', 'space': self.space}
response = self.client.post('/api/drive/files/create/', payload, format='json')
self.assertEqual(response.status_code, 201, response.data)
item = DriveItem.objects.get(pk=response.data['id'])
self.assertEqual(item.size, (self.root / 'Feuille.ods').stat().st_size)
self.assertTrue(item.storage_location.endswith('Feuille.ods'))
self.assertEqual(self.client.post('/api/drive/files/create/', payload, format='json').status_code, 409)
self.assertEqual(DriveItem.objects.filter(name='Feuille.ods').count(), 1)
def test_forbidden_extensions_and_empty_extensions(self):
for payload in [{'name':'x.exe','type':'exe','space':self.space},
{'name':'x.txt','type':'ods','space':self.space}]:
self.assertEqual(self.client.post('/api/drive/files/create/', payload, format='json').status_code, 400)