Files
filecodebox/tests/test_local_browser.py
T

89 lines
4.2 KiB
Python

import unittest
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import patch
from fastapi import FastAPI
import httpx
from apps.admin.services import LocalFileService
from apps.admin.views import admin_api
from apps.admin.dependencies import admin_required
from apps.base.models import FileCodes
from core.settings import settings
from tests.helpers import init_memory_db, close_db
class LocalBrowserTests(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self):
self.original = dict(settings.user_config)
await init_memory_db()
self.tmp = TemporaryDirectory()
self.root = Path(self.tmp.name)
self.patch = patch('core.settings.data_root', self.root)
self.patch.start()
(self.root/'local').mkdir()
async def asyncTearDown(self):
self.patch.stop()
self.tmp.cleanup()
settings.user_config = self.original
await close_db()
async def test_pagination_and_search_reach_beyond_500_entries(self):
root = self.root/'local'
for n in range(505): (root/f'{n:04d}.txt').write_text('data')
(root/'folder').mkdir()
service = LocalFileService()
first = await service.list_files('', page=1, size=20)
self.assertEqual((first['total'], first['page'], first['size']), (506,1,20))
self.assertEqual(first['items'][0]['type'], 'dir')
last = await service.list_files('', page=26, size=20)
self.assertEqual(last['items'][-1]['name'], '0504.txt')
self.assertEqual(len(last['items']), 6)
search = await service.list_files('', page=1, size=20, keyword='0504')
self.assertEqual(search['total'],1)
self.assertEqual(search['items'][0]['path'],'0504.txt')
self.assertEqual(len((await service.list_files('', legacy=True))['items']),505)
empty = await service.list_files('', page=999, size=20, keyword='missing')
self.assertEqual((empty['page'],empty['items']), (1,[]))
async def test_http_pagination_auth_and_share_validation(self):
(self.root/'local'/'safe.txt').write_text('safe')
app = FastAPI(); app.include_router(admin_api)
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app),base_url='http://test') as client:
self.assertIn((await client.get('/admin/local/lists?path=&page=1')).status_code,(401,403))
app.dependency_overrides[admin_required] = lambda: None
response=await client.get('/admin/local/lists?path=&page=1&size=20&keyword=safe')
self.assertEqual(response.status_code,200)
self.assertEqual(response.json()['detail']['total'],1)
for params in [{'page':0},{'size':0},{'size':101}]:
self.assertEqual((await client.get('/admin/local/lists',params={'path':'',**params})).status_code,422)
settings.expireStyle=['day','count']
for style,value in [('wrong',1),('forever',1),('day',0),('day',-1),('count',0)]:
r=await client.post('/admin/local/share',json={'filename':'safe.txt','expire_style':style,'expire_value':value})
self.assertIn(r.status_code,(400,422),r.text)
self.assertEqual(await FileCodes.all().count(),0)
r=await client.post('/admin/local/share',json={'filename':'safe.txt','expire_style':'count','expire_value':2})
self.assertEqual(r.status_code,200,r.text)
self.assertEqual((await FileCodes.get(code=r.json()['detail']['code'])).expired_count,2)
self.assertEqual((self.root/'local'/'safe.txt').read_text(),'safe')
async def test_slow_directory_scan_does_not_block_other_requests(self):
import asyncio
import time
original = Path.iterdir
events = []
def slow_scan(directory):
time.sleep(0.08)
return original(directory)
async def browse():
await LocalFileService().list_files('', page=1)
events.append('listed')
async def other_request():
await asyncio.sleep(0.01)
events.append('other')
with patch.object(Path, 'iterdir', slow_scan):
await asyncio.gather(browse(), other_request())
self.assertEqual(events, ['other', 'listed'])