mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-29 19:36:20 -05:00
Creating AutoAwaitTestClient for tests which automatically runs background tasks and expires db objects.
This commit is contained in:
parent
d5aa781397
commit
2a27d354a5
15 changed files with 97 additions and 150 deletions
|
|
@ -25,6 +25,7 @@ async def check_results(async_client, data, ids):
|
|||
async def test_archives_search_order(test_session, archive_directory, archive_factory, async_client):
|
||||
"""Search using all orders."""
|
||||
archive_factory('example.com', 'https://example.com/one', 'my archive', 'foo bar qux')
|
||||
test_session.commit()
|
||||
for order_by in lib.ARCHIVE_ORDERS:
|
||||
data = {'search_str': 'foo', 'order_by': order_by}
|
||||
request, response = await async_client.post('/api/archive/search', content=json.dumps(data))
|
||||
|
|
@ -196,8 +197,6 @@ async def test_archive_upload(test_session, async_client, singlefile_contents_fa
|
|||
request, response = await async_client.post('/api/archive/upload', content=body, headers=headers)
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
|
||||
await await_switches()
|
||||
|
||||
archive, = test_session.query(Archive).all()
|
||||
assert archive.singlefile_path.is_file(), 'Singlefile should have been saved.'
|
||||
assert archive.readability_path.is_file(), 'Readability should be extracted.'
|
||||
|
|
@ -253,11 +252,7 @@ async def test_archive_upload_file_tracking(test_session, async_client, archive_
|
|||
request, response = await async_client.post('/api/files/upload', content=body, headers=headers)
|
||||
assert response.status_code == HTTPStatus.CREATED, f'Upload failed with status {response.status_code}: {response.json}'
|
||||
|
||||
await await_switches()
|
||||
|
||||
# Step 4: Verify info.json is tracked
|
||||
# Refresh the session to get updated data
|
||||
test_session.expire_all()
|
||||
archive = test_session.query(Archive).filter_by(id=archive.id).one()
|
||||
|
||||
# Assert info.json properties exist
|
||||
|
|
@ -293,10 +288,6 @@ async def test_archive_upload_file_tracking(test_session, async_client, archive_
|
|||
request, response = await async_client.post('/api/files/upload', content=body, headers=headers)
|
||||
assert response.status_code == HTTPStatus.CREATED, f'Image upload failed with status {response.status_code}: {response.json}'
|
||||
|
||||
await await_switches()
|
||||
|
||||
# Refresh session to get updated data
|
||||
test_session.expire_all()
|
||||
archive = test_session.query(Archive).filter_by(id=archive.id).one()
|
||||
|
||||
# Assert screenshot properties exist
|
||||
|
|
@ -336,11 +327,7 @@ async def test_archive_generate_screenshot(test_session, async_client, archive_f
|
|||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['message'] == 'Screenshot generation queued'
|
||||
|
||||
# Wait for background processing
|
||||
await await_switches()
|
||||
|
||||
# Verify screenshot was generated
|
||||
test_session.expire_all()
|
||||
archive = test_session.query(Archive).filter_by(id=archive.id).one()
|
||||
assert archive.screenshot_path is not None, 'Screenshot should have been generated'
|
||||
assert archive.screenshot_path.is_file(), 'Screenshot file should exist'
|
||||
|
|
@ -373,11 +360,7 @@ async def test_archive_generate_screenshot(test_session, async_client, archive_f
|
|||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['message'] == 'Screenshot generation queued'
|
||||
|
||||
# Wait for background processing
|
||||
await await_switches()
|
||||
|
||||
# Verify screenshot is still there and properly tracked
|
||||
test_session.expire_all()
|
||||
archive = test_session.query(Archive).filter_by(id=archive.id).one()
|
||||
assert archive.screenshot_path == original_screenshot_path, 'Screenshot path should be unchanged'
|
||||
assert archive.screenshot_path.is_file(), 'Screenshot file should still exist'
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ from wrolpi import flags
|
|||
from wrolpi.api_utils import json_response
|
||||
from wrolpi.common import wrol_mode_check, get_media_directory, background_task
|
||||
from wrolpi.errors import ValidationError
|
||||
from wrolpi.vars import PYTEST, DOCKERIZED
|
||||
from wrolpi.vars import DOCKERIZED
|
||||
|
||||
map_bp = Blueprint('Map', '/api/map')
|
||||
|
||||
|
|
@ -30,11 +30,7 @@ async def import_pbfs(_: Request, body: schema.ImportPost):
|
|||
if not paths:
|
||||
raise ValidationError('No PBF or dump files were provided')
|
||||
|
||||
coro = lib.import_files(paths)
|
||||
if PYTEST:
|
||||
await coro
|
||||
else:
|
||||
background_task(coro)
|
||||
background_task(lib.import_files(paths))
|
||||
return response.empty()
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -467,7 +467,7 @@ async def test_channel_download_id(async_client, test_session, tag_factory, simp
|
|||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tag_channel(async_client, test_session, test_directory, channel_factory, tag_factory, video_factory,
|
||||
test_channels_config, test_download_manager, test_downloader, await_background_tasks):
|
||||
test_channels_config, test_download_manager, test_downloader):
|
||||
"""A single Tag can be applied to a Channel."""
|
||||
# Create channel directory in the usual videos directory.
|
||||
videos_directory = get_videos_directory()
|
||||
|
|
@ -498,7 +498,6 @@ async def test_tag_channel(async_client, test_session, test_directory, channel_f
|
|||
body = dict(tag_name=tag.name, directory='videos/Tag Name/Channel Name')
|
||||
request, response = await async_client.post(f'/api/videos/channels/{channel.id}/tag', json=body)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT
|
||||
await await_background_tasks() # Wait for move to complete and expire session objects
|
||||
|
||||
channel = test_session.query(Channel).one()
|
||||
assert channel.tag_name == tag.name
|
||||
|
|
@ -530,7 +529,6 @@ async def test_tag_channel(async_client, test_session, test_directory, channel_f
|
|||
body = dict(tag_name=None, directory='videos/Channel Name')
|
||||
request, response = await async_client.post(f'/api/videos/channels/{channel.id}/tag', json=body)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, response.content.decode()
|
||||
await await_background_tasks() # Wait for move to complete and expire session objects
|
||||
|
||||
channel = test_session.query(Channel).one()
|
||||
assert channel.tag_name is None
|
||||
|
|
|
|||
|
|
@ -84,8 +84,6 @@ async def test_refresh_videos(async_client, test_session, test_directory, simple
|
|||
|
||||
await async_client.post('/api/files/refresh')
|
||||
|
||||
test_session.expire_all()
|
||||
|
||||
# Posters were found during refresh.
|
||||
assert video1.file_group.my_poster_files()
|
||||
assert 'subdir' in str(video1.file_group.my_poster_files()[0])
|
||||
|
|
@ -383,8 +381,7 @@ async def test_video_file_format_with_upload_year(async_client, test_session, fa
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_video_upload_file_tracking(test_session, async_client, video_factory, await_switches,
|
||||
make_multipart_form,
|
||||
async def test_video_upload_file_tracking(test_session, async_client, video_factory, make_multipart_form,
|
||||
image_bytes_factory):
|
||||
"""Test that uploading info.json, poster, and caption files via /api/files/upload properly tracks them in Video and FileGroup."""
|
||||
from wrolpi.common import get_relative_to_media_directory
|
||||
|
|
@ -432,11 +429,7 @@ async def test_video_upload_file_tracking(test_session, async_client, video_fact
|
|||
request, response = await async_client.post('/api/files/upload', content=body, headers=headers)
|
||||
assert response.status_code == HTTPStatus.CREATED, f'Upload failed with status {response.status_code}: {response.json}'
|
||||
|
||||
await await_switches()
|
||||
|
||||
# Step 4: Verify info.json is tracked
|
||||
# Refresh the session to get updated data
|
||||
test_session.expire_all()
|
||||
video = test_session.query(Video).filter_by(id=video.id).one()
|
||||
|
||||
# Assert info.json properties exist
|
||||
|
|
@ -471,10 +464,6 @@ async def test_video_upload_file_tracking(test_session, async_client, video_fact
|
|||
request, response = await async_client.post('/api/files/upload', content=body, headers=headers)
|
||||
assert response.status_code == HTTPStatus.CREATED, f'Poster upload failed with status {response.status_code}: {response.json}'
|
||||
|
||||
await await_switches()
|
||||
|
||||
# Refresh session to get updated data
|
||||
test_session.expire_all()
|
||||
video = test_session.query(Video).filter_by(id=video.id).one()
|
||||
|
||||
# Assert poster properties exist
|
||||
|
|
@ -521,10 +510,6 @@ Another line of captions.
|
|||
request, response = await async_client.post('/api/files/upload', content=body, headers=headers)
|
||||
assert response.status_code == HTTPStatus.CREATED, f'Caption upload failed with status {response.status_code}: {response.json}'
|
||||
|
||||
await await_switches()
|
||||
|
||||
# Refresh session to get updated data
|
||||
test_session.expire_all()
|
||||
video = test_session.query(Video).filter_by(id=video.id).one()
|
||||
|
||||
# Assert caption properties exist
|
||||
|
|
|
|||
|
|
@ -550,10 +550,8 @@ async def remove_outdated_zim_files(path: pathlib.Path = None) -> int:
|
|||
file.unlink()
|
||||
deleted_count += 1
|
||||
|
||||
if PYTEST:
|
||||
await refresh_files(outdated)
|
||||
else:
|
||||
background_task(refresh_files(outdated))
|
||||
# Must refresh synchronously to clean up DB before returning.
|
||||
await refresh_files(outdated)
|
||||
|
||||
await restart_kiwix()
|
||||
|
||||
|
|
|
|||
|
|
@ -366,9 +366,6 @@ class TestCollectionDeletion:
|
|||
# Check response
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT
|
||||
|
||||
# Expire all cached objects to see changes made by the API's separate session
|
||||
test_session.expire_all()
|
||||
|
||||
# Verify collection is deleted
|
||||
assert test_session.query(Collection).filter_by(id=collection_id).count() == 0
|
||||
|
||||
|
|
@ -427,7 +424,6 @@ class TestCollectionDeletion:
|
|||
|
||||
collection_id = channel.collection.id
|
||||
channel_id = channel.id
|
||||
video_id = video.id
|
||||
video_path = video.video_path
|
||||
|
||||
# Delete the collection
|
||||
|
|
@ -436,9 +432,6 @@ class TestCollectionDeletion:
|
|||
# Check response
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT
|
||||
|
||||
# Expire all cached objects to see changes made by the API's separate session
|
||||
test_session.expire_all()
|
||||
|
||||
# Verify collection is deleted
|
||||
assert test_session.query(Collection).filter_by(id=collection_id).count() == 0
|
||||
|
||||
|
|
@ -446,7 +439,6 @@ class TestCollectionDeletion:
|
|||
assert test_session.query(Channel).filter_by(id=channel_id).count() == 0
|
||||
|
||||
# Video should still exist but be orphaned (channel_id = NULL)
|
||||
video = test_session.query(Video).filter_by(id=video_id).one()
|
||||
assert video.channel_id is None, 'Video should be orphaned when Channel is deleted'
|
||||
assert video.video_path == video_path, 'Video path should not change'
|
||||
assert video.video_path.is_file(), 'Video file should still exist'
|
||||
|
|
@ -487,9 +479,6 @@ class TestCollectionTagging:
|
|||
# Check response
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
|
||||
# Refresh the collection from database
|
||||
test_session.refresh(collection)
|
||||
|
||||
# Verify the tag has been removed
|
||||
assert collection.tag_id is None
|
||||
assert collection.tag_name is None
|
||||
|
|
@ -524,9 +513,6 @@ class TestCollectionTagging:
|
|||
# Check response - should succeed
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
|
||||
# Refresh the collection from database
|
||||
test_session.refresh(collection)
|
||||
|
||||
# Verify the tag was set
|
||||
assert collection.tag_id == tag.id
|
||||
assert collection.tag_name == 'TestTag'
|
||||
|
|
|
|||
|
|
@ -20,7 +20,6 @@ async def test_tag_domain_collection_moves_archives(
|
|||
archive_factory,
|
||||
async_client,
|
||||
tag_factory,
|
||||
await_switches,
|
||||
):
|
||||
"""
|
||||
When a domain collection with a directory is tagged via the API with a new directory,
|
||||
|
|
@ -61,17 +60,11 @@ async def test_tag_domain_collection_moves_archives(
|
|||
body = {'tag_name': 'News', 'directory': 'archive/News/example.com'}
|
||||
request, response = await async_client.post(f'/api/collections/{collection.id}/tag', json=body)
|
||||
assert response.status_code == HTTPStatus.OK, response.content.decode()
|
||||
await await_switches()
|
||||
|
||||
# Refresh objects from DB
|
||||
test_session.expire_all()
|
||||
|
||||
# Verify collection directory was updated
|
||||
assert collection.directory == dest_dir
|
||||
|
||||
# Verify archives were moved
|
||||
test_session.refresh(archive1)
|
||||
test_session.refresh(archive2)
|
||||
assert str(dest_dir) in str(archive1.file_group.primary_path), \
|
||||
f'Archive 1 should be in {dest_dir}, but is at {archive1.file_group.primary_path}'
|
||||
assert str(dest_dir) in str(archive2.file_group.primary_path), \
|
||||
|
|
@ -89,7 +82,6 @@ async def test_tag_domain_collection_moves_archives(
|
|||
|
||||
# Verify FileGroup paths were updated correctly
|
||||
for archive in [archive1, archive2]:
|
||||
test_session.refresh(archive)
|
||||
data = archive.file_group.data
|
||||
assert data is not None, f"Archive {archive.id} should have FileGroup.data"
|
||||
# FileGroup.directory should point to new location
|
||||
|
|
@ -111,7 +103,6 @@ async def test_tag_domain_collection_moves_extra_files(
|
|||
archive_factory,
|
||||
async_client,
|
||||
tag_factory,
|
||||
await_switches,
|
||||
):
|
||||
"""
|
||||
Extra files (not associated with Archives) in the domain directory should also be moved.
|
||||
|
|
@ -147,7 +138,6 @@ async def test_tag_domain_collection_moves_extra_files(
|
|||
body = {'tag_name': 'News', 'directory': 'archive/News/example.com'}
|
||||
request, response = await async_client.post(f'/api/collections/{collection.id}/tag', json=body)
|
||||
assert response.status_code == HTTPStatus.OK, response.content.decode()
|
||||
await await_switches()
|
||||
|
||||
# Verify extra file was moved
|
||||
assert (dest_dir / 'notes.txt').exists(), 'Extra file should be moved to new directory'
|
||||
|
|
@ -162,7 +152,6 @@ async def test_tag_domain_collection_old_directory_removed(
|
|||
archive_factory,
|
||||
async_client,
|
||||
tag_factory,
|
||||
await_switches,
|
||||
):
|
||||
"""
|
||||
After moving, the old directory should be removed if empty.
|
||||
|
|
@ -194,7 +183,6 @@ async def test_tag_domain_collection_old_directory_removed(
|
|||
body = {'tag_name': 'News', 'directory': 'archive/News/example.com'}
|
||||
request, response = await async_client.post(f'/api/collections/{collection.id}/tag', json=body)
|
||||
assert response.status_code == HTTPStatus.OK, response.content.decode()
|
||||
await await_switches()
|
||||
|
||||
# Verify old directory was removed
|
||||
assert not src_dir.exists(), f'Old directory {src_dir} should be removed after move'
|
||||
|
|
@ -207,7 +195,6 @@ async def test_untag_domain_collection_moves_back(
|
|||
make_files_structure,
|
||||
async_client,
|
||||
tag_factory,
|
||||
await_switches,
|
||||
):
|
||||
"""
|
||||
When removing a tag from a domain collection with a new directory,
|
||||
|
|
@ -244,18 +231,15 @@ async def test_untag_domain_collection_moves_back(
|
|||
untagged_dir = test_directory / 'archive' / 'example.com'
|
||||
untagged_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Store collection ID for lookup after API call
|
||||
# Store collection ID for lookup after API call (collection may be deleted)
|
||||
collection_id = collection.id
|
||||
file_group_id = file_group.id
|
||||
|
||||
# Remove the tag and move to untagged directory
|
||||
body = {'tag_name': None, 'directory': 'archive/example.com'}
|
||||
request, response = await async_client.post(f'/api/collections/{collection_id}/tag', json=body)
|
||||
assert response.status_code == HTTPStatus.OK, response.content.decode()
|
||||
await await_switches()
|
||||
|
||||
# Refresh objects from DB - query fresh from database
|
||||
test_session.expire_all()
|
||||
# Query fresh from database - collection may be deleted during cleanup
|
||||
collection = test_session.query(Collection).filter_by(id=collection_id).one_or_none()
|
||||
|
||||
# Note: The collection may be deleted if it becomes empty during refresh cleanup
|
||||
|
|
@ -266,8 +250,6 @@ async def test_untag_domain_collection_moves_back(
|
|||
assert collection.directory == untagged_dir
|
||||
|
||||
# Verify file was moved - the key test here is that files moved, not the collection state
|
||||
from wrolpi.files.models import FileGroup
|
||||
file_group = test_session.query(FileGroup).filter_by(id=file_group_id).one()
|
||||
assert str(untagged_dir) in str(file_group.primary_path), \
|
||||
f'File should be in {untagged_dir}, but is at {file_group.primary_path}'
|
||||
|
||||
|
|
@ -279,7 +261,6 @@ async def test_tag_domain_collection_without_directory_no_move(
|
|||
archive_factory,
|
||||
async_client,
|
||||
tag_factory,
|
||||
await_switches,
|
||||
):
|
||||
"""
|
||||
When tagging a domain collection without providing a directory,
|
||||
|
|
@ -312,11 +293,6 @@ async def test_tag_domain_collection_without_directory_no_move(
|
|||
body = {'tag_name': 'News'}
|
||||
request, response = await async_client.post(f'/api/collections/{collection.id}/tag', json=body)
|
||||
assert response.status_code == HTTPStatus.OK, response.content.decode()
|
||||
await await_switches()
|
||||
|
||||
# Refresh objects from DB
|
||||
test_session.expire_all()
|
||||
test_session.refresh(collection)
|
||||
|
||||
# Verify tag was set
|
||||
assert collection.tag_name == 'News'
|
||||
|
|
@ -325,7 +301,6 @@ async def test_tag_domain_collection_without_directory_no_move(
|
|||
assert collection.directory == src_dir
|
||||
|
||||
# Verify archive was NOT moved
|
||||
test_session.refresh(archive)
|
||||
assert archive.file_group.primary_path == original_path, \
|
||||
f'Archive should NOT be moved when directory is not provided'
|
||||
|
||||
|
|
@ -429,11 +404,6 @@ async def test_tag_domain_comprehensive(
|
|||
body = {'tag_name': tag.name, 'directory': 'archive/News/example.com'}
|
||||
request, response = await async_client.post(f'/api/collections/{collection.id}/tag', json=body)
|
||||
assert response.status_code == HTTPStatus.OK, response.content.decode()
|
||||
await await_switches()
|
||||
|
||||
# Refresh objects from DB
|
||||
test_session.expire_all()
|
||||
collection = test_session.query(Collection).one()
|
||||
|
||||
assert collection.tag_name == tag.name
|
||||
# Domain was moved to Tag's directory, old directory was removed
|
||||
|
|
@ -443,12 +413,9 @@ async def test_tag_domain_comprehensive(
|
|||
assert not domain_directory.exists(), 'Old domain directory should have been deleted.'
|
||||
|
||||
# Domain download goes into the domain's directory
|
||||
download = test_session.query(Download).one()
|
||||
assert download.destination == new_domain_directory, f'{download} was not moved'
|
||||
|
||||
# Archives were moved
|
||||
test_session.refresh(archive1)
|
||||
test_session.refresh(archive2)
|
||||
assert str(new_domain_directory) in str(archive1.file_group.primary_path), \
|
||||
f'Archive 1 should be in new directory'
|
||||
assert str(new_domain_directory) in str(archive2.file_group.primary_path), \
|
||||
|
|
@ -474,10 +441,8 @@ async def test_tag_domain_comprehensive(
|
|||
body = {'tag_name': None, 'directory': 'archive/example.com'}
|
||||
request, response = await async_client.post(f'/api/collections/{collection.id}/tag', json=body)
|
||||
assert response.status_code == HTTPStatus.OK, response.content.decode()
|
||||
await await_switches()
|
||||
|
||||
# Refresh objects from DB
|
||||
test_session.expire_all()
|
||||
# Query collection from DB
|
||||
collection = test_session.query(Collection).filter_by(name='example.com').one_or_none()
|
||||
|
||||
# Collection may be deleted during cleanup if empty, but we can still verify downloads
|
||||
|
|
@ -486,15 +451,12 @@ async def test_tag_domain_comprehensive(
|
|||
assert collection.directory == original_directory
|
||||
|
||||
# Archives were moved back
|
||||
test_session.refresh(archive1)
|
||||
test_session.refresh(archive2)
|
||||
assert str(original_directory) in str(archive1.file_group.primary_path), \
|
||||
f'Archive 1 should be moved back'
|
||||
assert str(original_directory) in str(archive2.file_group.primary_path), \
|
||||
f'Archive 2 should be moved back'
|
||||
|
||||
# Download was moved back
|
||||
download = test_session.query(Download).one()
|
||||
assert download.destination == original_directory, f'{download} was not moved back'
|
||||
|
||||
assert not (test_directory / 'archive/News/example.com').exists(), \
|
||||
|
|
@ -514,21 +476,13 @@ async def test_tag_domain_comprehensive(
|
|||
body = {'tag_name': tag.name}
|
||||
request, response = await async_client.post(f'/api/collections/{collection.id}/tag', json=body)
|
||||
assert response.status_code == HTTPStatus.OK, response.content.decode()
|
||||
await await_switches()
|
||||
|
||||
# Refresh objects from DB
|
||||
test_session.expire_all()
|
||||
collection = test_session.query(Collection).filter_by(name='example.com').one()
|
||||
|
||||
assert collection.tag_name == 'News'
|
||||
assert collection.directory == original_directory, 'Directory should not change without explicit directory'
|
||||
|
||||
# Archives were not moved
|
||||
test_session.refresh(archive1)
|
||||
test_session.refresh(archive2)
|
||||
assert str(original_directory) in str(archive1.file_group.primary_path)
|
||||
assert str(original_directory) in str(archive2.file_group.primary_path)
|
||||
|
||||
# Download was not changed
|
||||
download = test_session.query(Download).one()
|
||||
assert download.destination == original_directory, f'{download} should not have moved'
|
||||
|
|
|
|||
|
|
@ -143,20 +143,89 @@ async def background_task_listener(request, response):
|
|||
await await_switches_()
|
||||
|
||||
|
||||
class AutoAwaitTestClient:
|
||||
"""
|
||||
A wrapper around SanicASGITestClient that automatically awaits background
|
||||
tasks and switches after modifying HTTP requests (POST, PUT, PATCH, DELETE).
|
||||
|
||||
This eliminates the need to manually call await_switches() and
|
||||
await_background_tasks() after each modifying request in tests.
|
||||
"""
|
||||
|
||||
def __init__(self, client: SanicASGITestClient, session: Session):
|
||||
self._client = client
|
||||
self._session = session
|
||||
|
||||
async def _await_and_expire(self):
|
||||
"""Await all background tasks and switches, then expire session objects."""
|
||||
await await_switches_()
|
||||
await await_background_tasks_()
|
||||
self._session.expire_all()
|
||||
|
||||
async def post(self, *args, **kwargs):
|
||||
"""POST request with auto-await."""
|
||||
result = await self._client.post(*args, **kwargs)
|
||||
await self._await_and_expire()
|
||||
return result
|
||||
|
||||
async def put(self, *args, **kwargs):
|
||||
"""PUT request with auto-await."""
|
||||
result = await self._client.put(*args, **kwargs)
|
||||
await self._await_and_expire()
|
||||
return result
|
||||
|
||||
async def patch(self, *args, **kwargs):
|
||||
"""PATCH request with auto-await."""
|
||||
result = await self._client.patch(*args, **kwargs)
|
||||
await self._await_and_expire()
|
||||
return result
|
||||
|
||||
async def delete(self, *args, **kwargs):
|
||||
"""DELETE request with auto-await."""
|
||||
result = await self._client.delete(*args, **kwargs)
|
||||
await self._await_and_expire()
|
||||
return result
|
||||
|
||||
async def get(self, *args, **kwargs):
|
||||
"""GET request (no auto-await)."""
|
||||
return await self._client.get(*args, **kwargs)
|
||||
|
||||
async def head(self, *args, **kwargs):
|
||||
"""HEAD request (no auto-await)."""
|
||||
return await self._client.head(*args, **kwargs)
|
||||
|
||||
async def options(self, *args, **kwargs):
|
||||
"""OPTIONS request (no auto-await)."""
|
||||
return await self._client.options(*args, **kwargs)
|
||||
|
||||
async def websocket(self, *args, **kwargs):
|
||||
"""WebSocket connection (pass-through)."""
|
||||
return await self._client.websocket(*args, **kwargs)
|
||||
|
||||
@property
|
||||
def sanic_app(self):
|
||||
"""Access to the underlying Sanic app."""
|
||||
return self._client.sanic_app
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def async_client(test_directory, test_session) -> SanicASGITestClient:
|
||||
async def async_client(test_directory, test_session) -> AutoAwaitTestClient:
|
||||
"""Get an Async Sanic Test Client with all default routes attached.
|
||||
|
||||
Depends on test_session to ensure the database mock is in place for session middleware.
|
||||
|
||||
This client automatically awaits switches and background tasks after
|
||||
POST, PUT, PATCH, and DELETE requests, and expires session objects.
|
||||
"""
|
||||
api_app.signalize()
|
||||
attach_shared_contexts(api_app)
|
||||
initialize_configs_contexts(api_app)
|
||||
|
||||
client = SanicASGITestClient(api_app)
|
||||
wrapped_client = AutoAwaitTestClient(client, test_session)
|
||||
|
||||
try:
|
||||
yield client
|
||||
yield wrapped_client
|
||||
finally:
|
||||
api_app.stop()
|
||||
logger.debug('Destroying async_client')
|
||||
|
|
|
|||
|
|
@ -136,16 +136,14 @@ def get_db_curs(commit: bool = False, isolation_level=psycopg2.extensions.ISOLAT
|
|||
curs = connection.cursor(cursor_factory=psycopg2.extras.DictCursor)
|
||||
try:
|
||||
yield curs
|
||||
if commit and not PYTEST:
|
||||
# Don't commit during tests - test_session manages the transaction
|
||||
if commit:
|
||||
connection.commit()
|
||||
except sqlalchemy.exc.DatabaseError:
|
||||
session.rollback()
|
||||
raise
|
||||
finally:
|
||||
# Rollback only if a transaction hasn't been committed.
|
||||
# Don't rollback during tests - test_session manages the transaction
|
||||
if not PYTEST and session.transaction.is_active:
|
||||
if session.transaction.is_active:
|
||||
connection.rollback()
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -17,7 +17,6 @@ from ..api_utils import json_response, api_app
|
|||
from ..events import Events
|
||||
from ..schema import JSONErrorResponse
|
||||
from ..tags import Tag
|
||||
from ..vars import PYTEST
|
||||
|
||||
files_bp = Blueprint('Files', '/api/files')
|
||||
|
||||
|
|
@ -240,10 +239,7 @@ async def post_create_directory(_: Request, body: schema.Directory):
|
|||
except FileExistsError:
|
||||
raise FileConflict(f'{path} already exists')
|
||||
|
||||
if PYTEST:
|
||||
await lib.refresh_files([path, ])
|
||||
else:
|
||||
background_task(lib.refresh_files([path, ]))
|
||||
background_task(lib.refresh_files([path, ]))
|
||||
|
||||
return response.empty(HTTPStatus.CREATED)
|
||||
|
||||
|
|
@ -300,10 +296,7 @@ async def post_rename(request: Request, body: schema.Rename):
|
|||
# Refreshing individual files causes the FileGroup's files list to be overwritten
|
||||
# with only the specified file, losing track of associated files.
|
||||
parent_dir = new_path.parent
|
||||
if PYTEST:
|
||||
await lib.refresh_files([parent_dir])
|
||||
else:
|
||||
background_task(lib.refresh_files([parent_dir]))
|
||||
background_task(lib.refresh_files([parent_dir]))
|
||||
|
||||
return response.empty(HTTPStatus.NO_CONTENT)
|
||||
|
||||
|
|
@ -462,11 +455,7 @@ async def post_upload(request: Request):
|
|||
logger.info(f'Got final chunk of uploaded file: {output_str}')
|
||||
del api_app.shared_ctx.uploaded_files[output_str]
|
||||
# Upsert this new file (and any related files) into the DB.
|
||||
coro = lib.upsert_file(output, tag_names=tag_names)
|
||||
if PYTEST:
|
||||
await coro
|
||||
else:
|
||||
background_task(coro)
|
||||
background_task(lib.upsert_file(output, tag_names=tag_names))
|
||||
return response.empty(HTTPStatus.CREATED)
|
||||
|
||||
# Request the next chunk.
|
||||
|
|
|
|||
|
|
@ -255,11 +255,10 @@ async def delete(*paths: Union[str, pathlib.Path]):
|
|||
else:
|
||||
path.unlink()
|
||||
|
||||
coro = refresh_files(paths)
|
||||
if PYTEST:
|
||||
await coro
|
||||
else:
|
||||
background_task(coro)
|
||||
# Must refresh synchronously to clean up DB before returning.
|
||||
# This ensures deleted FileGroups are removed before the caller continues
|
||||
# (e.g., upload API recreating the file).
|
||||
await refresh_files(paths)
|
||||
|
||||
|
||||
def _mimetype_suffix_map(path: Path, mimetype: str):
|
||||
|
|
|
|||
|
|
@ -902,7 +902,6 @@ async def test_rename_file_with_associated_files_via_api(test_session, test_dire
|
|||
assert not srt.exists(), "Old SRT should not exist"
|
||||
|
||||
# Verify FileGroup is updated
|
||||
test_session.expire_all()
|
||||
fg = test_session.query(FileGroup).one()
|
||||
assert fg.primary_path == new_video_1
|
||||
file_names = [f['path'] for f in fg.files]
|
||||
|
|
@ -924,7 +923,6 @@ async def test_rename_file_with_associated_files_via_api(test_session, test_dire
|
|||
assert not new_srt_1.exists(), "'example 2.srt' should not exist"
|
||||
|
||||
# Verify FileGroup is updated
|
||||
test_session.expire_all()
|
||||
fg = test_session.query(FileGroup).one()
|
||||
assert fg.primary_path == final_video
|
||||
file_names = [f['path'] for f in fg.files]
|
||||
|
|
@ -975,7 +973,6 @@ async def test_rename_collection_directory(test_session, test_directory, make_fi
|
|||
assert response.status_code == HTTPStatus.NO_CONTENT
|
||||
|
||||
# Verify Collection.directory was updated
|
||||
test_session.expire_all()
|
||||
collection = test_session.query(Collection).filter_by(id=collection_id).one()
|
||||
assert collection.directory == test_directory / 'renamed_collection'
|
||||
assert not (test_directory / 'my_collection').exists()
|
||||
|
|
@ -1020,7 +1017,6 @@ async def test_rename_directory_with_nested_collections(test_session, test_direc
|
|||
assert response.status_code == HTTPStatus.NO_CONTENT
|
||||
|
||||
# Verify nested Collection directories were updated
|
||||
test_session.expire_all()
|
||||
coll_a = test_session.query(Collection).filter_by(id=coll_a_id).one()
|
||||
coll_b = test_session.query(Collection).filter_by(id=coll_b_id).one()
|
||||
|
||||
|
|
@ -1054,8 +1050,7 @@ async def test_delete_directory_recursive(test_session, test_directory, make_fil
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_file(test_session, async_client, test_directory, make_files_structure, await_background_tasks,
|
||||
await_switches):
|
||||
async def test_get_file(test_session, async_client, test_directory, make_files_structure):
|
||||
"""Can get info about a single file."""
|
||||
make_files_structure({'foo/bar.txt': 'foo contents'})
|
||||
await lib.refresh_files()
|
||||
|
|
@ -1066,9 +1061,6 @@ async def test_get_file(test_session, async_client, test_directory, make_files_s
|
|||
assert response.json['file']
|
||||
assert response.json['file']['path'] == 'foo/bar.txt'
|
||||
|
||||
# Wait for `viewed` to be set in background task.
|
||||
await await_background_tasks()
|
||||
|
||||
fg, = test_session.query(FileGroup).all()
|
||||
assert fg.primary_path == test_directory / 'foo/bar.txt'
|
||||
assert isinstance(fg.viewed, datetime)
|
||||
|
|
|
|||
|
|
@ -222,10 +222,7 @@ class Tag(ModelHelper, Base):
|
|||
f" {channel} {possible_directory} {self}"
|
||||
logger.warning(msg)
|
||||
|
||||
if PYTEST:
|
||||
await _()
|
||||
else:
|
||||
background_task(_())
|
||||
background_task(_())
|
||||
|
||||
def delete(self):
|
||||
"""Deletes this Tag, if it is unused.
|
||||
|
|
|
|||
|
|
@ -87,7 +87,8 @@ async def test_recreate_download(test_session, test_download_manager, test_downl
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_rename_tag(async_client, test_session, test_download_manager, test_downloader, tag_factory):
|
||||
async def test_download_rename_tag(async_client, test_session, test_download_manager, test_downloader, tag_factory,
|
||||
await_background_tasks):
|
||||
"""Renaming a Tag renames any Downloads that reference that Tag."""
|
||||
tag = await tag_factory()
|
||||
|
||||
|
|
@ -99,6 +100,7 @@ async def test_download_rename_tag(async_client, test_session, test_download_man
|
|||
assert download.tag_names == ['one', ]
|
||||
|
||||
await tag.update_tag(test_session, 'new name', tag.color)
|
||||
await await_background_tasks() # Wait for tag rename background task
|
||||
|
||||
download = test_session.query(Download).one()
|
||||
assert download.tag_names == ['new name', ]
|
||||
|
|
|
|||
|
|
@ -485,7 +485,7 @@ async def test_update_tag(test_session, test_directory, video_factory, tag_facto
|
|||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tag_rename_with_channel(test_session, test_directory, video_factory, tag_factory,
|
||||
channel_factory, await_switches):
|
||||
channel_factory, await_switches, await_background_tasks):
|
||||
tag = await tag_factory()
|
||||
channel = channel_factory(name='Channel Name', tag_name=tag.name)
|
||||
video_factory(title='video', channel_id=channel.id)
|
||||
|
|
@ -497,6 +497,7 @@ async def test_tag_rename_with_channel(test_session, test_directory, video_facto
|
|||
assert (test_directory / 'videos/one/Channel Name/video.mp4').is_file()
|
||||
|
||||
await tag.update_tag(test_session, 'New Tag Name', None)
|
||||
await await_background_tasks() # Wait for channel move background task to complete
|
||||
|
||||
assert (test_directory / 'tags').is_dir()
|
||||
assert (test_directory / 'videos/New Tag Name/Channel Name').is_dir()
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue