From 4365e2332706d56db4333da3248814144a056234 Mon Sep 17 00:00:00 2001 From: lrnselfreliance <33263708+lrnselfreliance@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:00:15 -0600 Subject: [PATCH] Remove code that only tests called (#888) Deletes functions nothing in the app calls, along with the tests that only exercised them. Tests that covered live logic through a dead wrapper now call the live functions: the Download-linking tests use `domain_download_links` / `channel_download_links` with `_link_downloads`, the archive tests create Archives with `write_archive_files` + `register_archive`, and the collection lifecycle test removes an item with `Collection.remove_item`. Co-authored-by: Claude Opus 5.5 --- controller/lib/fstab.py | 9 --- controller/test/test_fstab.py | 45 ----------- modules/archive/lib.py | 81 +------------------ modules/archive/test/test_lib.py | 60 +++++--------- modules/videos/lib.py | 50 +----------- modules/videos/models.py | 13 --- modules/videos/test/test_lib.py | 72 ++++------------- modules/videos/test/test_models.py | 4 - modules/zim/lib.py | 8 -- modules/zim/models.py | 48 +---------- modules/zim/test/test_lib.py | 26 +----- wrolpi/collections/models.py | 16 ---- .../test/test_collection_lifecycle.py | 3 +- wrolpi/common.py | 24 ------ wrolpi/dates.py | 15 +--- wrolpi/test/test_common.py | 37 --------- wrolpi/test/test_dates.py | 19 +---- 17 files changed, 49 insertions(+), 481 deletions(-) diff --git a/controller/lib/fstab.py b/controller/lib/fstab.py index 860a62fd..6e7fcb95 100644 --- a/controller/lib/fstab.py +++ b/controller/lib/fstab.py @@ -249,12 +249,3 @@ def remove_fstab_entry(mount_point: str) -> dict: logger.info("Removed fstab entry for %s", mount_point) return {"success": True, "mount_point": mount_point} - - -def get_wrolpi_fstab_entries() -> list[dict]: - """Get all fstab entries for mounts under /media (WROLPi-managed mounts).""" - entries = parse_fstab() - return [ - e for e in entries - if e["type"] == "mount" and e["mount_point"].startswith("/media") - ] diff --git a/controller/test/test_fstab.py b/controller/test/test_fstab.py index ab532f16..155b73c6 100644 --- a/controller/test/test_fstab.py +++ b/controller/test/test_fstab.py @@ -8,7 +8,6 @@ from controller.lib.fstab import ( parse_fstab, add_fstab_entry, remove_fstab_entry, - get_wrolpi_fstab_entries, ) @@ -345,47 +344,3 @@ UUID=5678 /media/test ext4 defaults,nofail 0 2 # User's manual comment should still be there written_str = "".join(written_content) assert "# User added this mount manually" in written_str - - -class TestGetWrolpiFstabEntries: - """Tests for get_wrolpi_fstab_entries function.""" - - def test_returns_all_media_entries(self): - """Should return all entries under /media, not just /media/wrolpi.""" - fstab_content = """\ -UUID=1234 / ext4 defaults 0 1 -UUID=5678 /media/wrolpi ext4 defaults 0 2 -UUID=9abc /media/wrolpi/data ext4 defaults 0 2 -UUID=defg /media/usb vfat defaults 0 0 -UUID=hijk /media/roland/64GB exfat defaults 0 0 -""" - with mock.patch("builtins.open", mock.mock_open(read_data=fstab_content)): - result = get_wrolpi_fstab_entries() - # Should include all /media/* entries - assert len(result) == 4 - mount_points = [e["mount_point"] for e in result] - assert "/media/wrolpi" in mount_points - assert "/media/wrolpi/data" in mount_points - assert "/media/usb" in mount_points - assert "/media/roland/64GB" in mount_points - # Root should NOT be included - assert "/" not in mount_points - - def test_excludes_non_media_mounts(self): - """Should exclude mounts outside /media.""" - fstab_content = """\ -UUID=1234 / ext4 defaults 0 1 -UUID=5678 /home ext4 defaults 0 2 -UUID=9abc /media/wrolpi ext4 defaults 0 2 -""" - with mock.patch("builtins.open", mock.mock_open(read_data=fstab_content)): - result = get_wrolpi_fstab_entries() - assert len(result) == 1 - assert result[0]["mount_point"] == "/media/wrolpi" - - def test_returns_empty_if_no_media_entries(self): - """Should return empty list if no entries under /media.""" - fstab_content = "UUID=1234 / ext4 defaults 0 1\n" - with mock.patch("builtins.open", mock.mock_open(read_data=fstab_content)): - result = get_wrolpi_fstab_entries() - assert result == [] diff --git a/modules/archive/lib.py b/modules/archive/lib.py index 500b5075..76640fa4 100644 --- a/modules/archive/lib.py +++ b/modules/archive/lib.py @@ -16,7 +16,7 @@ from typing import Optional, Tuple, List, Union, Dict, Set from urllib.parse import urlparse import pytz -from sqlalchemy import asc, func, BigInteger +from sqlalchemy import asc from sqlalchemy.orm import Session from modules.archive.models import Archive, MATCH_DATE, parse_singlefile_saved_date, read_singlefile_header @@ -58,7 +58,7 @@ def _domain_row(description, directory, tag_name, file_format) -> dict: class DomainsSection(ConfigSection): """domains.yaml's domain Collections, keyed by name. (Their Downloads are linked after the import, see - `link_domain_and_downloads`.)""" + `domain_download_links`.)""" name = 'domains' def file_rows(self, config: dict) -> Tuple[Dict[str, dict], Set[str]]: @@ -860,28 +860,6 @@ def register_archive(session: Session, written: WrittenArchiveFiles) -> Archive: return archive -async def model_archive_result(url: str, singlefile: str, readability: dict, screenshot: bytes, - destination: pathlib.Path = None) -> Archive: - """ - Convert results from ArchiveDownloader into real files. Create Archive record. - - Thin wrapper around write_archive_files + register_archive that opens its own - transaction. New code (notably the phase-split ArchiveDownloader) should call - the helpers directly so the caller controls the session. - - Args: - url: The URL that was archived - singlefile: The HTML content from SingleFile - readability: The readability extraction results - screenshot: The screenshot bytes - destination: Optional directory to save files to. If provided, files go here instead of archive/ - """ - written = write_archive_files(url, singlefile, readability, screenshot, destination=destination) - with get_db_session(commit=True) as session: - archive = register_archive(session, written) - return archive - - def detect_domain_directory(collection: Collection) -> Optional[pathlib.Path]: """ Detect directory for domain collection using format_destination template. @@ -1043,13 +1021,6 @@ def _link_downloads(session: Session, links: Dict[int, int]): session.flush() -def link_domain_and_downloads(session: Session): - """Associate any Download related to a Domain Collection (see `domain_download_links`).""" - if links := domain_download_links(session): - _link_downloads(session, links) - session.commit() - - SINGLEFILE_URL_EXTRACTOR = re.compile(r'Page saved with SingleFile \s+url: (http.+?)\n') COMPRESSED_SINGLEFILE_INDEX = 'index.html' @@ -1278,17 +1249,6 @@ def get_archive_by_file_group_id(session: Session, file_group_id: int, skip_view return archive -def delete_archives_by_file_group_ids(*file_group_ids: int, force: bool = False) -> None: - """Delete Archives by their FileGroup IDs and all of their files. Pass force=True to delete - even tagged FileGroups (raises FileGroupIsTagged otherwise via FileGroup.delete).""" - with get_db_session(commit=True) as session: - archives: List[Archive] = list(session.query(Archive).filter(Archive.file_group_id.in_(file_group_ids))) - if not archives: - raise UnknownArchive(f'Unknown Archives with FileGroup IDs: {", ".join(map(str, file_group_ids))}') - for archive in archives: - archive.delete(force=force) - - def archive_strftime(dt: datetime) -> str: return dt.strftime('%Y-%m-%d-%H-%M-%S') @@ -1320,43 +1280,6 @@ def is_singlefile_file(path: pathlib.Path) -> bool: return False -def get_domains(): - """ - Get all domain collections with their archive statistics. - - This is a thin wrapper around Collection queries that adds archive-specific statistics. - Returns a list of dicts with collection id, domain name, url_count, and total size. - """ - with get_db_session() as session: - # Query all domain collections with archive statistics in a single query - # This uses ORM for better maintainability while keeping performance - query = ( - session.query( - Collection.id, - Collection.name.label('domain'), - func.count(Archive.id).label('url_count'), - func.sum(FileGroup.size).cast(BigInteger).label('size') - ) - .outerjoin(Archive, Collection.id == Archive.collection_id) - .outerjoin(FileGroup, FileGroup.id == Archive.file_group_id) - .filter(Collection.kind == 'domain') - .group_by(Collection.id, Collection.name) - .order_by(Collection.name) - ) - - domains = [ - { - 'id': row.id, - 'domain': row.domain, - 'url_count': row.url_count or 0, - 'size': row.size or 0, - } - for row in query.all() - ] - - return domains - - ARCHIVE_ORDERS = { # Sometimes we don't have a published_datetime. This is equivalent to COALESCE(fg.published_datetime, fg.download_datetime) 'published_datetime': (date := 'fg.effective_datetime ASC NULLS LAST'), diff --git a/modules/archive/test/test_lib.py b/modules/archive/test/test_lib.py index 2d6379e7..ab0b7609 100644 --- a/modules/archive/test/test_lib.py +++ b/modules/archive/test/test_lib.py @@ -17,7 +17,7 @@ from modules.archive.lib import ArchiveDownloaderConfigValidator from modules.archive.lib import format_archive_filename from modules.archive.lib import get_archive_downloader_config from modules.archive.lib import get_or_create_domain_collection, get_new_archive_files, \ - delete_archives_by_file_group_ids, model_archive_result, get_domains + write_archive_files, register_archive, domain_download_links, _link_downloads from modules.archive.models import Archive from wrolpi.api_utils import CustomJSONEncoder from wrolpi.cmd import CommandResult @@ -29,6 +29,15 @@ from wrolpi.files.models import FileGroup from wrolpi.test.common import skip_ci +async def model_archive_result(url: str, singlefile: str, readability: dict, screenshot: bytes, + destination: pathlib.Path = None) -> Archive: + """Write the ArchiveDownloader results to files and register the Archive, like the downloader does.""" + written = write_archive_files(url, singlefile, readability, screenshot, destination=destination) + with get_db_session(commit=True) as session: + archive = register_archive(session, written) + return archive + + def make_fake_archive_result(readability=True, screenshot=True, title=True): with tempfile.NamedTemporaryFile(suffix='.png') as fh: Image.new('RGB', (1, 1), color='grey').save(fh) @@ -246,7 +255,9 @@ async def test_delete_archive(async_client, test_session, archive_factory): archive3_paths = list(archive3.my_paths()) # Delete the oldest. - delete_archives_by_file_group_ids(archive1.file_group_id, archive3.file_group_id) + archive1.delete() + archive3.delete() + test_session.commit() assert test_session.query(Archive).count() == 1 assert test_session.query(FileGroup).count() == 1 # Files were deleted. @@ -256,7 +267,8 @@ async def test_delete_archive(async_client, test_session, archive_factory): assert archive2_paths and all(i.is_file() for i in archive2_paths) # Delete the last archive. The domain collection should also be deleted. - delete_archives_by_file_group_ids(archive2.file_group_id) + archive2.delete() + test_session.commit() assert test_session.query(Archive).count() == 0 domain = test_session.query(Collection).filter_by(kind='domain').one_or_none() assert domain is None @@ -266,34 +278,6 @@ async def test_delete_archive(async_client, test_session, archive_factory): assert archive2_paths and not any(i.is_file() for i in archive2_paths) -def test_get_domains(test_session, archive_factory): - """ - `get_domains` gets only domain collections with Archives. - """ - archive1 = archive_factory('example.com') - archive2 = archive_factory('example.com') - archive3 = archive_factory('example.org') - test_session.commit() - - assert archive1.domain - assert archive2.domain - assert archive3.domain - - assert [i['domain'] for i in get_domains()] == ['example.com', 'example.org'] - - archive2.delete() - test_session.commit() - assert [i['domain'] for i in get_domains()] == ['example.com', 'example.org'] - - archive1.delete() - test_session.commit() - assert [i['domain'] for i in get_domains()] == ['example.org'] - - archive3.delete() - test_session.commit() - assert [i['domain'] for i in get_domains()] == [] - - @skip_ci @pytest.mark.asyncio async def test_new_archive(test_session, test_directory, fake_now, async_client): @@ -850,7 +834,7 @@ async def test_archive_download_index(test_session, test_directory, image_bytes_ content='the readability', textContent='the readability', ) - archive = await lib.model_archive_result('https://example.com', singlefile, readability, image_bytes_factory()) + archive = await model_archive_result('https://example.com', singlefile, readability, image_bytes_factory()) assert isinstance(archive, lib.Archive), 'Did not get an archive' assert archive.singlefile_path and archive.singlefile_path.exists() and \ @@ -1229,10 +1213,9 @@ def test_search_archives_by_domain(test_directory, test_session, archive_factory assert len(file_groups) == 1 -def test_link_domain_and_downloads(test_session, test_download_manager): +def test_domain_download_links(test_session, test_download_manager): """Test that downloads are linked to domain collections.""" from wrolpi.downloader import Download - from modules.archive.lib import link_domain_and_downloads # Create a domain collection with a directory collection = Collection(name='example.com', kind='domain', directory='archive/example.com') @@ -1269,7 +1252,8 @@ def test_link_domain_and_downloads(test_session, test_download_manager): assert not any(d.collection_id for d in [download1, download2, download3, download4]) - link_domain_and_downloads(test_session) + _link_downloads(test_session, domain_download_links(test_session)) + test_session.commit() assert download1.collection_id == collection.id # matched by directory (exact) assert download2.collection_id == collection.id # matched by subdirectory @@ -1277,11 +1261,10 @@ def test_link_domain_and_downloads(test_session, test_download_manager): assert download4.collection_id is None # no frequency = no link -def test_link_domain_and_downloads_by_destination(test_session, test_directory, test_download_manager): +def test_domain_download_links_by_destination(test_session, test_directory, test_download_manager): """A Download whose destination column is in a domain's directory is linked to that domain (the destination was moved out of the settings).""" from wrolpi.downloader import Download - from modules.archive.lib import link_domain_and_downloads collection = Collection(name='example.com', kind='domain', directory=test_directory / 'archive/example.com') test_session.add(collection) @@ -1294,7 +1277,8 @@ def test_link_domain_and_downloads_by_destination(test_session, test_directory, test_session.add_all([exact, below, similar]) test_session.commit() - link_domain_and_downloads(test_session) + _link_downloads(test_session, domain_download_links(test_session)) + test_session.commit() assert exact.collection_id == collection.id assert below.collection_id == collection.id diff --git a/modules/videos/lib.py b/modules/videos/lib.py index 6ad61e56..38fc58c7 100644 --- a/modules/videos/lib.py +++ b/modules/videos/lib.py @@ -1,12 +1,11 @@ import contextlib import dataclasses import html -import json import pathlib import re from dataclasses import dataclass, field from datetime import datetime -from typing import Dict, Generator, Type, List, Set +from typing import Dict, Type, List, Set from typing import Tuple, Optional import pytz @@ -23,9 +22,8 @@ from wrolpi.collections.models import validate_collection_directory from wrolpi.config_import import ConfigSection, Unreadable, chunks, media_relative from wrolpi.config_version import register_ownership from wrolpi.dates import from_timestamp -from wrolpi.db import get_db_curs, get_db_session, session_curs +from wrolpi.db import get_db_session, session_curs from wrolpi.downloader import Download, download_manager, save_downloads_config -from wrolpi.errors import UnknownDirectory from wrolpi.events import Events from wrolpi.files.lib import split_path_stem_and_suffix from wrolpi.switches import register_switch_handler, ActivateSwitchMethod @@ -1113,13 +1111,6 @@ def _link_downloads(session: Session, links: Dict[int, int]): session.flush() -def link_channel_and_downloads(session: Session): - """Associate any Download related to a Channel via its Collection (see `channel_download_links`).""" - if links := channel_download_links(session): - _link_downloads(session, links) - session.commit() - - YDL = YoutubeDL(dict(cachedir=YTDLP_CACHE_DIR)) ydl_logger = YDL.params['logger'] = logger.getChild('youtube-dl') YDL.add_default_info_extractors() @@ -1319,43 +1310,6 @@ def get_video_metadata(video) -> dict: } -def find_orphaned_video_files(directory: pathlib.Path) -> Generator[pathlib.Path, None, None]: - """Finds all files which should be associated with a video file, but a video file does not match their stem. - - Example: - video1.mp4, video1.info.json # Video file with info json. - video2.info.json # Orphaned video json. - """ - with get_db_curs() as curs: - if not directory.is_dir(): - raise UnknownDirectory() - - directory_str = str(directory).rstrip('/') - - # Query returns directory and files - files may contain relative or absolute paths - # Use indexed directory column for efficient lookup - # (Not parameterized, so `%` needs no escaping.) - curs.execute(f''' - SELECT directory, files - FROM file_group - WHERE - mimetype NOT LIKE 'video%' - AND (directory = '{directory_str}' OR directory LIKE '{directory_str}/%') - ''') - for row in curs.fetchall(): - fg_directory = pathlib.Path(row[0]) if row[0] else None - files = row[1] - if isinstance(files, str): - # Raw cursor reads return the JSON column as TEXT. - files = json.loads(files) - for file_info in files: - path = pathlib.Path(file_info['path']) - if not path.is_absolute() and fg_directory: - # Resolve relative path using directory - path = fg_directory / path - yield path - - def format_videos_destination(channel_name: str = None, channel_tag: str = None, channel_url: str = None) \ -> pathlib.Path: """Return the directory where Videos should be downloaded according to the WROLPi Config. diff --git a/modules/videos/models.py b/modules/videos/models.py index dc44f4a1..0b030ca4 100644 --- a/modules/videos/models.py +++ b/modules/videos/models.py @@ -454,19 +454,6 @@ class Video(ModelHelper, Base): return self.ffprobe_json - def get_streams_by_codec_name(self, codec_name: str) -> List[dict]: - """Return all data about all streams which match the codec_name. - - >>> video = Video() - >>> video.get_streams_by_codec_name('h264') - [ {'codec_name': 'h264', ...} ] - """ - if not self.ffprobe_json: - raise RuntimeError(f'ffprobe data has not been extracted, call Video.get_ffprobe_json().') - - streams = [i for i in self.ffprobe_json['streams'] if i['codec_name'] == codec_name] - return streams - def get_streams_by_codec_type(self, codec_type: str) -> List[dict]: """Return all data about all streams which match the codec_type. diff --git a/modules/videos/test/test_lib.py b/modules/videos/test/test_lib.py index b37d7a51..4fef71d5 100644 --- a/modules/videos/test/test_lib.py +++ b/modules/videos/test/test_lib.py @@ -1,5 +1,4 @@ import pathlib -import shutil from http import HTTPStatus import pytest @@ -7,11 +6,9 @@ import pytest from modules.videos import lib from modules.videos.downloader import ChannelDownloader, VideoDownloader from modules.videos.lib import parse_video_file_name, validate_video, get_statistics, format_videos_destination -from modules.videos.models import Video, Channel +from modules.videos.models import Channel from wrolpi.common import get_wrolpi_config from wrolpi.downloader import Download, RSSDownloader -from wrolpi.files.models import FileGroup -from wrolpi.vars import PROJECT_DIR @pytest.mark.parametrize('file_name,expected', [ @@ -183,48 +180,7 @@ async def test_get_statistics(test_session, video_factory, channel_factory): assert 'historical' in result['statistics'] -@pytest.mark.asyncio -async def test_orphaned_files(async_client, test_session, make_files_structure, test_directory, video_factory, - refresh_files, test_wrolpi_config): - # Disable ffprobe json file creation to avoid unexpected files in test assertions - get_wrolpi_config().save_ffprobe_json = False - - # A Video without associated files is not orphaned. - vid1 = video_factory(title='vid1', with_video_file=True) - # The video files will be removed... - vid2 = video_factory(title='vid2', with_video_file=True, with_caption_file=True, with_poster_ext='jpeg', - with_info_json=True) - vid3 = video_factory(title='vid3', with_video_file=True, with_poster_ext='jpg') - # This will be ignored because it is not in the "videos" subdirectory. - shutil.copy(PROJECT_DIR / 'test/example1.en.vtt', test_directory / 'vid4.en.vtt') - test_session.commit() - - # Remove vid2 video. Caption, poster, info_json are now orphaned. - vid2.video_path.unlink() - vid2_caption_paths, vid2_poster_path, vid2_info_json_path = vid2.caption_paths, vid2.poster_path, vid2.info_json_path - # Remove vid3 video. Poster is now orphaned. - vid3.video_path.unlink() - vid3_poster_path = vid3.poster_path - await refresh_files() - test_session.commit() - - # 6 files when two video files are deleted. - # (vid1, vid2[caption,poster,json], vid3 poster, vid4) - assert test_session.query(FileGroup).count() == 4 - assert test_session.query(Video).count() == 1 - - videos_directory = test_directory / 'videos' - results = lib.find_orphaned_video_files(videos_directory) - - assert sorted(list(results)) == sorted([ - vid2_caption_paths[0], - vid2_info_json_path, - vid2_poster_path, - vid3_poster_path, - ]) - - -def test_link_channel_and_downloads(test_session, channel_factory, test_download_manager): +def test_channel_download_links(test_session, channel_factory, test_download_manager): channel = channel_factory( url='https://www.youtube.com/c/LearningSelfReliance/videos', source_id='UCng5u6ASda3LNRXJN0JCQJA', @@ -239,15 +195,16 @@ def test_link_channel_and_downloads(test_session, channel_factory, test_download assert test_session.query(Download).count() == 3 assert not any(i.collection_id for i in test_download_manager.get_downloads(test_session)) - # `link_channel_and_downloads` links Downloads to Collections. - lib.link_channel_and_downloads(test_session) + # `channel_download_links` links Downloads to Collections. + lib._link_downloads(test_session, lib.channel_download_links(test_session)) + test_session.commit() assert test_session.query(Download).count() == 3 assert all(i.collection_id for i in test_download_manager.get_recurring_downloads(test_session)) assert not any(i.collection_id for i in test_download_manager.get_once_downloads(test_session)) @pytest.mark.asyncio -def test_link_channel_and_downloads_migration(async_client, test_session, channel_factory, test_download_manager): +def test_channel_download_links_migration(async_client, test_session, channel_factory, test_download_manager): """Test the 8d0d81bc9c34_channel_channel_downloads.py migration.""" # A simple Channel which has a download for its URL. channel1 = channel_factory(url='https://example.com/channel1') @@ -269,7 +226,8 @@ def test_link_channel_and_downloads_migration(async_client, test_session, channe assert channel2.directory and not channel2.downloads assert not channel3.downloads - lib.link_channel_and_downloads(test_session) + lib._link_downloads(test_session, lib.channel_download_links(test_session)) + test_session.commit() assert channel1.downloads assert channel2.downloads @@ -288,8 +246,8 @@ def test_link_channel_and_downloads_migration(async_client, test_session, channe assert not d2c.collection_id -def test_link_channel_and_downloads_destination_column(test_session, channel_factory, test_download_manager): - """Test that link_channel_and_downloads matches by download.destination column, not just settings['destination']. +def test_channel_download_links_destination_column(test_session, channel_factory, test_download_manager): + """Test that channel_download_links matches by download.destination column, not just settings['destination']. This simulates what happens when downloads are imported from config - the destination column is set directly, not via settings['destination']. @@ -309,15 +267,16 @@ def test_link_channel_and_downloads_destination_column(test_session, channel_fac assert not download.collection_id, 'Download should not be linked yet' - lib.link_channel_and_downloads(test_session) + lib._link_downloads(test_session, lib.channel_download_links(test_session)) + test_session.commit() test_session.refresh(download) assert download.collection_id == channel.collection_id, \ 'Download should be linked to channel via destination column' -def test_link_channel_and_downloads_by_source_id(test_session, channel_factory, test_download_manager): - """Test that link_channel_and_downloads matches by info_json channel_id to Channel.source_id. +def test_channel_download_links_by_source_id(test_session, channel_factory, test_download_manager): + """Test that channel_download_links matches by info_json channel_id to Channel.source_id. When ChannelDownloader runs, it populates download.info_json with channel_id. This should match against Channel.source_id even if the URLs don't match. @@ -337,7 +296,8 @@ def test_link_channel_and_downloads_by_source_id(test_session, channel_factory, assert not download.collection_id, 'Download should not be linked yet' - lib.link_channel_and_downloads(test_session) + lib._link_downloads(test_session, lib.channel_download_links(test_session)) + test_session.commit() test_session.refresh(download) assert download.collection_id == channel.collection_id, \ diff --git a/modules/videos/test/test_models.py b/modules/videos/test/test_models.py index fd9aae99..c101e219 100644 --- a/modules/videos/test/test_models.py +++ b/modules/videos/test/test_models.py @@ -16,10 +16,6 @@ async def test_ffprobe_stream_methods(simple_video): assert simple_video.get_streams_by_codec_type('audio') assert simple_video.get_streams_by_codec_type('subtitle') - assert simple_video.get_streams_by_codec_name('h264') - assert simple_video.get_streams_by_codec_name('aac') - assert simple_video.get_streams_by_codec_name('mov_text') - @pytest.mark.asyncio async def test_channel_move(async_client, test_session, test_directory, channel_factory, video_factory): diff --git a/modules/zim/lib.py b/modules/zim/lib.py index 88039615..e99456da 100644 --- a/modules/zim/lib.py +++ b/modules/zim/lib.py @@ -5,7 +5,6 @@ import re from datetime import datetime from typing import Callable, List, Tuple, Dict -import cachetools.func from libzim import Entry from sqlalchemy import or_ from sqlalchemy.orm import Session @@ -260,13 +259,6 @@ def search_all_zims(session: Session, search_str: str, tag_names: List[str] = No return all_results -@cachetools.func.lru_cache(maxsize=1_000) -def get_estimates(search_str: str) -> List[int]: - zims = Zims.get_all() - estimates = [i.estimate(search_str) for i in zims] - return estimates - - def get_zim(session: Session, zim_id: int) -> Zim: """Return the Zim record of the provided path. diff --git a/modules/zim/models.py b/modules/zim/models.py index f07292e7..5afeb50d 100644 --- a/modules/zim/models.py +++ b/modules/zim/models.py @@ -3,7 +3,7 @@ import functools import pathlib from collections import OrderedDict from datetime import datetime -from typing import List, Tuple, OrderedDict as OrderedDictType, Dict, Optional, Set +from typing import List, Tuple, OrderedDict as OrderedDictType, Dict, Optional from libzim import Archive, Searcher, Query, Entry, SuggestionSearcher from sqlalchemy import Column, Integer, BigInteger, ForeignKey, Text, tuple_, Boolean, UniqueConstraint @@ -47,20 +47,6 @@ class ZimMetadata: return d -class EntrySummary: - zim_id: int - path: str - title: str - - def __json__(self) -> Dict: - d = dict( - zim_id=self.zim_id, - path=self.path, - title=self.title, - ) - return d - - class Zim(Base, ModelHelper): """Records of Zim files. @@ -287,38 +273,6 @@ class Zim(Base, ModelHelper): entries = Zim._entries_with_tags_process(limit, offset, params, session, tags_sub_select) return entries - @staticmethod - def all_entries_with_tags(session: Session, tag_names: List[str], limit: int = 10, offset: int = 0) -> List[Entry]: - """Return Zim Entries tagged with the provided names from ALL Zims.""" - if limit < 1: - raise RuntimeError('Limit must be greater than zero') - - tags_sub_select, params = tag_names_to_zim_sub_select(tag_names, zim_id=None) - entries = Zim._entries_with_tags_process(limit, offset, params, session, tags_sub_select) - return entries - - @functools.cached_property - def all_entries(self) -> Set[EntrySummary]: - """ - Iterates over all Entries in the Archive. Ignores non-article entries (javascript, images, etc). - """ - zim = self.get_zim() - zim_id = self.id - entry_count = zim.all_entry_count - entries = set() - for entry_id in range(entry_count): - entry: Entry = zim._get_entry_by_id(entry_id) - title = entry.title - if title.startswith('m/') or title.startswith('-/') or title.startswith('I/'): - continue - - summary = EntrySummary() - summary.zim_id = zim_id - summary.path = entry.path - summary.title = title - entries.add(summary) - return entries - class Zims: """Convenience class which searches all known Zim files.""" diff --git a/modules/zim/test/test_lib.py b/modules/zim/test/test_lib.py index 1a07cf39..814d97a9 100644 --- a/modules/zim/test/test_lib.py +++ b/modules/zim/test/test_lib.py @@ -78,10 +78,10 @@ async def test_tag_zim_entry_model(async_client, test_session, zim_factory, tag_ @pytest.mark.asyncio async def test_zim_entries_with_tags(async_client, test_session, zim_factory, tag_factory): - """Can fetch Zim Entries that have Tags. Can filter only those entries that are tagged on a specific Zim.""" + """Can fetch the Entries of a specific Zim that have Tags.""" tag1, tag2 = await tag_factory(), await tag_factory() zim1, zim2 = zim_factory('zim1'), zim_factory('zim2') - # Tag Zim1 with both tags, but Zim2 shares one of the tags and is returned when no Zim is passed. + # Tag Zim1 with both tags. Zim2 shares one of the tags, but its Entry is not returned for Zim1. zim1.tag_entry(test_session, tag1.name, 'one') zim1.tag_entry(test_session, tag2.name, 'two') zim2.tag_entry(test_session, tag2.name, 'home') @@ -95,10 +95,6 @@ async def test_zim_entries_with_tags(async_client, test_session, zim_factory, ta assert len(entries) == 1 assert entries[0].path == 'two' - # Get entries from any Zim. - entries = lib.Zim.all_entries_with_tags(test_session, [tag2.name, ]) - assert {i.path for i in entries} == {'two', 'home'}, 'Tag2 was applied to `two` and `home`' - def test_get_unique_paths(): paths = ['A/Prickly_Pear', 'A/Prickly_pear', 'A/Prickly-pear', 'A/Arborescent_Prickly_Pear', @@ -176,11 +172,6 @@ async def test_zim_tags_config(async_client, test_session, test_directory, test_ assert {i.name for i in test_session.query(tags.Tag)} == {'Tag1', 'Tag2'} -def test_zim_all_entries(test_session, test_zim): - entries = [i.__json__() for i in test_zim.all_entries] - assert len(entries) == 12 - - @skip_ci @pytest.mark.asyncio async def test_zim_download(test_session, kiwix_download_zim, test_directory, test_zim_bytes, flags_lock, @@ -293,7 +284,6 @@ async def test_zim_tag_migration(await_switches, test_session, test_directory, z ] - @pytest.mark.asyncio async def test_remove_outdated_zim_files_migrates_tags(await_switches, test_session, test_directory, zim_factory, tag_factory, test_tags_config): @@ -451,15 +441,3 @@ def test_get_custom_zims_directory(async_client, test_directory, test_wrolpi_con get_wrolpi_config().zims_destination = 'custom/zims' assert lib.get_zim_directory() == (test_directory / 'custom/zims') - - -def test_get_estimates_is_cached(): - """Repeated estimates for the same search string do not re-query the Zims.""" - from unittest import mock - from modules.zim import lib - - lib.get_estimates.cache_clear() - with mock.patch.object(lib.Zims, 'get_all', return_value=[]) as get_all: - assert lib.get_estimates('cached search') == [] - assert lib.get_estimates('cached search') == [] - assert get_all.call_count == 1 diff --git a/wrolpi/collections/models.py b/wrolpi/collections/models.py index b6e403df..ddfeac7e 100644 --- a/wrolpi/collections/models.py +++ b/wrolpi/collections/models.py @@ -702,22 +702,6 @@ class Collection(ModelHelper, Base): logger.debug(f'Added {len(items)} FileGroups to Collection {self.id}') return items - def remove_file_group(self, session: Session, file_group_id: int): - """Remove a FileGroup from this Collection.""" - - item = session.query(CollectionItem).filter_by( - collection_id=self.id, - file_group_id=file_group_id - ).first() - - if item: - position = item.position - session.delete(item) - session.flush() - - # Shift remaining items down - self._shift_positions(session, position + 1, shift_by=-1) - def _shift_positions(self, session: Session, from_position: int, shift_by: int): """Helper to shift positions of items.""" session.query(CollectionItem).filter( diff --git a/wrolpi/collections/test/test_collection_lifecycle.py b/wrolpi/collections/test/test_collection_lifecycle.py index 9ddbf084..d74bf3a8 100644 --- a/wrolpi/collections/test/test_collection_lifecycle.py +++ b/wrolpi/collections/test/test_collection_lifecycle.py @@ -67,7 +67,8 @@ async def test_collection_lifecycle_end_to_end(async_client, test_session: Sessi assert v4.file_group_id in fg_ids # 6) Remove one video from the collection only (do not delete the video) - coll.remove_file_group(test_session, v2.file_group_id) + (v2_item,) = [i for i in coll.get_items(test_session) if i.file_group_id == v2.file_group_id] + assert coll.remove_item(test_session, v2_item.id) test_session.commit() items = coll.get_items(test_session) diff --git a/wrolpi/common.py b/wrolpi/common.py index 48e99e98..e08721a9 100644 --- a/wrolpi/common.py +++ b/wrolpi/common.py @@ -2594,21 +2594,6 @@ async def get_download_info(url: str, timeout: int = 60) -> DownloadFileInfo: download_logger = logger.getChild('download') -def human_bandwidth(bps: int) -> str: - """Convert bits per second to a more readable format. - - >>> human_bandwidth(2000) - # '2 Kbps' - """ - units = ['bps', 'Kbps', 'Mbps', 'Gbps', 'Tbps'] - unit = 0 - while bps > 1000 and unit <= len(units): - bps /= 1000 - unit += 1 - - return f'{int(bps)} {units[unit]}' - - modelers = [] @@ -3242,15 +3227,6 @@ def format_html_string(html: str | bytes) -> str: return soup.prettify() -def format_html_file(file: pathlib.Path): - """Reformat the contents of an HTML file to include indentation to increase readability.""" - if not file or not file.is_file(): - raise RuntimeError(f'File does not exist: {file}') - - pretty = format_html_string(file.read_text()) - replace_file(file, pretty) - - def html_file_screenshot(path: pathlib.Path | str) -> bytes: """Return a PNG screenshot of the HTML file at `path`. diff --git a/wrolpi/dates.py b/wrolpi/dates.py index b6401223..539ecab8 100644 --- a/wrolpi/dates.py +++ b/wrolpi/dates.py @@ -1,5 +1,5 @@ import logging -from datetime import datetime, timezone, timedelta +from datetime import datetime, timezone from enum import Enum from typing import Union, List @@ -152,19 +152,6 @@ def seconds_to_timestamp(seconds: Union[int, float]) -> str: return timestamp -def timedelta_to_timestamp(delta: timedelta) -> str: - """Convert a datetime.timestamp into a timestamp string. - - >>> timedelta_to_timestamp(timedelta(seconds=60)) - '00:01:00' - >>> timedelta_to_timestamp(timedelta(weeks=1, days=1, seconds=7)) - '1w 1d 00:00:07' - >>> timedelta_to_timestamp(timedelta(days=10)) - '1w 3d 00:00:00' - """ - return seconds_to_timestamp(delta.total_seconds()) - - class TZDateTime(types.TypeDecorator): """Forces all datetime to have a timezone. Stores all datetime in DB as UTC.""" impl = types.DateTime diff --git a/wrolpi/test/test_common.py b/wrolpi/test/test_common.py index 96266018..09fd7679 100644 --- a/wrolpi/test/test_common.py +++ b/wrolpi/test/test_common.py @@ -736,20 +736,6 @@ Another example paragraph Paragraph outside an element.''' -@pytest.mark.parametrize( - 'bps,expected', [ - (100, '100 bps'), - (2000, '2 Kbps'), - (7777777, '7 Mbps'), - (777777777, '777 Mbps'), - (7777777777, '7 Gbps'), - (77777777777, '77 Gbps'), - ] -) -def test_human_bandwidth(bps, expected): - assert common.human_bandwidth(bps) == expected - - def test_format_json_file(): with tempfile.TemporaryDirectory() as d: with tempfile.NamedTemporaryFile(suffix='.json', dir=d) as fh: @@ -790,29 +776,6 @@ def test_format_json_file(): assert len(list(file.parent.iterdir())) == 1 -def test_format_html_file(): - with tempfile.NamedTemporaryFile() as fh: - file = pathlib.Path(fh.name) - unformatted = 'TitleBody' - file.write_text(unformatted) - - assert file.read_text() == unformatted - - common.format_html_file(file) - assert file.read_text() == ''' - - - - Title - - - - Body - - -''' - - @pytest.mark.parametrize( 'iterable,length,step,expected', [ diff --git a/wrolpi/test/test_dates.py b/wrolpi/test/test_dates.py index 9c7a3af6..2d79040d 100644 --- a/wrolpi/test/test_dates.py +++ b/wrolpi/test/test_dates.py @@ -6,7 +6,7 @@ from sqlalchemy import Column, Integer from wrolpi import dates from wrolpi.common import Base -from wrolpi.dates import TZDateTime, timedelta_to_timestamp, seconds_to_timestamp +from wrolpi.dates import TZDateTime, seconds_to_timestamp from wrolpi.db import get_db_session, get_db_curs from wrolpi.errors import InvalidDatetime @@ -70,23 +70,6 @@ def test_seconds_to_timestamp(td, expected): assert seconds_to_timestamp(td) == expected -@pytest.mark.parametrize('td,expected', [ - (timedelta(seconds=0), '00:00:00'), - (timedelta(seconds=1), '00:00:01'), - (timedelta(seconds=60), '00:01:00'), - (timedelta(seconds=61), '00:01:01'), - (timedelta(seconds=65), '00:01:05'), - (timedelta(days=1), '1d 00:00:00'), - (timedelta(seconds=86461), '1d 00:01:01'), - (timedelta(weeks=1, days=1, seconds=7), '1w 1d 00:00:07'), - (timedelta(weeks=16, days=3, hours=17, minutes=46, seconds=39), '16w 3d 17:46:39'), - (timedelta(days=10), '1w 3d 00:00:00'), - (timedelta(days=10, microseconds=1000), '1w 3d 00:00:00'), -]) -def test_timedelta_to_timestamp(td, expected): - assert timedelta_to_timestamp(td) == expected - - @pytest.mark.parametrize('dt,expected', [ ('20010101', datetime(2001, 1, 1)), ('20050607', datetime(2005, 6, 7)),