import asyncio import tempfile import unittest from pathlib import Path from unittest.mock import patch import httpx from aiohttp import web from fastapi import FastAPI from starlette.responses import StreamingResponse from apps.admin.views import admin_api from apps.admin.dependencies import admin_required from apps.admin.download_checks import _read_response from apps.base.models import FileCodes, KeyValue, TransferStats from core.settings import settings from tests.helpers import init_memory_db, close_db class DownloadCheckTests(unittest.IsolatedAsyncioTestCase): async def asyncSetUp(self): self.original = dict(settings.user_config) await init_memory_db() self.status = 200 self.data = b'file content' self.requests = 0 upstream = web.Application() upstream.router.add_get('/dav/{path:.*}', self.upstream) self.runner = web.AppRunner(upstream) await self.runner.setup() site = web.TCPSite(self.runner, '127.0.0.1', 0) await site.start() port = site._server.sockets[0].getsockname()[1] settings.user_config = {'file_storage': 'webdav', 'jwt_secret': 'test-secret', 'webdav_url': f'http://127.0.0.1:{port}/dav', 'webdav_username': 'test', 'webdav_password': 'test'} await KeyValue.create(key='settings', value=dict(settings.user_config)) self.file = await FileCodes.create(code='CHECK123', prefix='a', suffix='.txt', file_path='share/test', uuid_file_name='a.txt', size=len(self.data), expired_count=2) app = FastAPI() app.include_router(admin_api) app.dependency_overrides[admin_required] = lambda: True self.app = app self.client = httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://test') async def asyncTearDown(self): await self.client.aclose() await self.runner.cleanup() await close_db() settings.user_config = self.original async def upstream(self, request): self.requests += 1 return web.Response(status=self.status, body=self.data if self.status == 200 else b'failure') async def check(self, ids=None): response = await self.client.post('/admin/file/download-check', json={'ids': ids or [self.file.id]}) self.assertEqual(response.status_code, 200, response.text) return response.json()['detail'] async def test_real_webdav_read_without_usage_or_audit_side_effects(self): rows = await self.check([self.file.id, self.file.id]) self.assertEqual(len(rows), 1) self.assertEqual(rows[0]['status'], 'available', rows) self.assertIsNotNone(rows[0]['checkedAt']) self.assertEqual(self.requests, 1) await self.file.refresh_from_db() self.assertEqual(self.file.expired_count, 2) self.assertEqual(self.file.used_count, 0) self.assertEqual(await TransferStats.all().count(), 0) async def test_404_416_and_size_mismatch_are_unavailable(self): for status in [404, 416, 401]: self.status = status self.assertEqual((await self.check())[0]['status'], 'unavailable') self.status = 200 self.data = b'wrong size' self.assertEqual((await self.check())[0]['status'], 'unavailable') async def test_expired_trashed_missing_and_text_batch(self): self.file.expired_count = 0 await self.file.save() text = await FileCodes.create(code='TEXT1234', text='', size=0) trash = await FileCodes.create(code='TRASH123', is_trashed=True) rows = await self.check([self.file.id, text.id, trash.id, 999]) self.assertEqual([row['status'] for row in rows], ['unavailable', 'available', 'unavailable', 'unavailable']) self.assertEqual(self.requests, 0) async def test_timeout_is_reported_without_failing_the_batch(self): async def slow(_): await asyncio.sleep(1) with patch('apps.admin.download_checks.CHECK_TIMEOUT', 0.01), patch('apps.admin.download_checks._probe', slow): rows = await self.check() self.assertEqual(rows[0]['message'], '检测超时,请重试') async def test_local_file_reads_and_missing_are_detected(self): settings.file_storage = 'local' with tempfile.TemporaryDirectory() as directory, patch('core.storage.data_root', Path(directory)): path = Path(directory) / 'share/test/a.txt' path.parent.mkdir(parents=True) path.write_bytes(self.data) self.assertEqual((await self.check())[0]['status'], 'available') path.unlink() self.assertEqual((await self.check())[0]['status'], 'unavailable') async def test_direct_link_is_read_not_just_head(self): from core.storage import WebDAVFileStorage with patch.object(WebDAVFileStorage, 'get_file_url', return_value=settings.webdav_url + '/direct'): self.file.expired_count = -1 await self.file.save() self.assertEqual((await self.check())[0]['status'], 'available') self.status = 404 self.assertEqual((await self.check())[0]['status'], 'unavailable') async def test_admin_auth_and_batch_validation(self): for ids in [[], [0], ['1'], list(range(1, 22))]: result = await self.client.post('/admin/file/download-check', json={'ids': ids}) self.assertEqual(result.status_code, 422) self.app.dependency_overrides.clear() result = await self.client.post('/admin/file/download-check', json={'ids': [1]}) self.assertEqual(result.status_code, 401) async def test_interval_persistence_and_invalid_config(self): for interval in [0, 30, 300, 86400]: result = await self.client.patch('/admin/config/update', json={'downloadCheckInterval': interval}) self.assertEqual(result.status_code, 200, result.text) result = await self.client.get('/admin/config/get') self.assertEqual(result.json()['detail']['downloadCheckInterval'], interval) for interval in [-1, 1, 29, 86401, True, '30', 30.5]: result = await self.client.patch('/admin/config/update', json={'downloadCheckInterval': interval}) self.assertEqual(result.status_code, 400) async def test_probe_stops_stream_and_closes_on_read_failure(self): closed = [] async def stream(): try: yield b'x' raise AssertionError('must not read the entire file') finally: closed.append(True) await _read_response(StreamingResponse(stream()), 100) self.assertEqual(closed, [True]) async def broken(): try: raise OSError('connection lost') yield b'' finally: closed.append(True) with self.assertRaises(OSError): await _read_response(StreamingResponse(broken()), 100) self.assertEqual(len(closed), 2) async def test_local_reference_uses_nas_file_even_with_webdav_selected(self): self.file.file_path = 'local-ref' self.file.uuid_file_name = 'a.txt' await self.file.save() with tempfile.TemporaryDirectory() as directory, patch('core.settings.data_root', Path(directory)): path = Path(directory) / 'local/a.txt' path.parent.mkdir() path.write_bytes(self.data) self.assertEqual((await self.check())[0]['status'], 'available') path.unlink() self.assertEqual((await self.check())[0]['status'], 'unavailable') self.assertEqual(self.requests, 0) async def test_empty_local_file_and_expired_share(self): import datetime from core.utils import get_now settings.file_storage = 'local' self.file.size = 0 await self.file.save() with tempfile.TemporaryDirectory() as directory, patch('core.storage.data_root', Path(directory)): path = Path(directory) / 'share/test/a.txt' path.parent.mkdir(parents=True) path.write_bytes(b'') self.assertEqual((await self.check())[0]['status'], 'available') self.file.expired_at = await get_now() - datetime.timedelta(seconds=1) self.file.expired_count = -1 await self.file.save() self.assertEqual((await self.check())[0]['status'], 'unavailable') async def test_network_failure_and_empty_body_are_unavailable(self): from unittest.mock import AsyncMock from core.storage import WebDAVFileStorage with patch.object(WebDAVFileStorage, 'get_file_response', side_effect=OSError('connection lost')): self.assertEqual((await self.check())[0]['status'], 'unavailable') async def empty(): if False: yield b'' with patch.object(WebDAVFileStorage, 'get_file_response', new=AsyncMock(return_value=StreamingResponse(empty()))): self.assertEqual((await self.check())[0]['status'], 'unavailable') async def test_full_check_ids_include_other_pages_without_reading_storage(self): from core.settings import DEFAULT_CONFIG self.assertEqual(DEFAULT_CONFIG['downloadCheckInterval'], 0) expired = await FileCodes.create(code='EXPIRED1', expired_count=0) await FileCodes.create(code='TRASHED1', is_trashed=True) response = await self.client.get('/admin/file/download-check-ids') self.assertEqual(response.status_code, 200) self.assertEqual(response.json()['detail'], [self.file.id, expired.id]) self.assertEqual(self.requests, 0) self.assertEqual(await TransferStats.all().count(), 0) self.app.dependency_overrides.clear() response = await self.client.get('/admin/file/download-check-ids') self.assertEqual(response.status_code, 401)