Add Docs module for searching and organizing PDFs and EPUBs

Create a new Docs module that consolidates PDF and eBook handling into a
unified system with subjects and authors support. This replaces the
separate PDF/eBook modelers with a single Doc model backed by an
alembic migration (rename ebook to doc).

Key changes:
- New modules/docs package with models, API, extractors, and lib
- Subject and author metadata extraction with case-insensitive
  normalization for cleaner PDF metadata
- Frontend Docs pages with AuthorsPage, SubjectsPage using
  CollectionTable, and doc card deletion
- Global search integration for subjects and authors
- Generic collection item count support
- Frontend file card metadata adjusted to match collection sort
- Bump yt-dlp version
This commit is contained in:
Roland 2026-03-17 18:35:57 -06:00
parent 4a21499bdd
commit aefc7b1def
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
90 changed files with 4484 additions and 1189 deletions

View file

View file

@ -0,0 +1,79 @@
"""Tests for the docs API."""
import json
from http import HTTPStatus
import pytest
from modules.docs.models import Doc
@pytest.mark.asyncio
async def test_docs_statistics(async_client, test_session, test_directory, example_epub, refresh_files):
"""Doc statistics endpoint returns correct counts."""
await refresh_files()
request, response = await async_client.get('/api/docs/statistics')
assert response.status_code == HTTPStatus.OK
stats = response.json['statistics']
assert stats['doc_count'] >= 1
assert stats['epub_count'] >= 1
@pytest.mark.asyncio
async def test_docs_search(async_client, test_session, test_directory, example_epub, refresh_files):
"""Docs search endpoint works."""
await refresh_files()
content = dict(search_str='WROLPi')
request, response = await async_client.post('/api/docs/search', content=json.dumps(content))
assert response.status_code == HTTPStatus.OK
assert len(response.json['file_groups']) >= 1
@pytest.mark.asyncio
async def test_get_doc(async_client, test_session, test_directory, example_epub, refresh_files):
"""Single doc endpoint returns the doc."""
await refresh_files()
doc = test_session.query(Doc).first()
assert doc
request, response = await async_client.get(f'/api/docs/{doc.id}')
assert response.status_code == HTTPStatus.OK
assert response.json['file_group']
@pytest.mark.asyncio
async def test_docs_search_by_tag(async_client, test_session, doc_factory, tag_factory):
"""Docs can be searched by tag."""
tag = await tag_factory()
doc = doc_factory()
doc.file_group.add_tag(test_session, tag.name)
test_session.commit()
# Search with matching tag returns the doc.
content = dict(tag_names=[tag.name])
request, response = await async_client.post('/api/docs/search', content=json.dumps(content))
assert response.status_code == HTTPStatus.OK
assert response.json['totals']['file_groups'] == 1
# Search with non-existent tag returns nothing.
content = dict(tag_names=['nonexistent'])
request, response = await async_client.post('/api/docs/search', content=json.dumps(content))
assert response.status_code == HTTPStatus.OK
assert response.json['totals']['file_groups'] == 0
@pytest.mark.asyncio
async def test_delete_doc(async_client, test_session, test_directory, example_epub, refresh_files):
"""Docs can be deleted."""
await refresh_files()
doc = test_session.query(Doc).first()
assert doc
doc_id = doc.id
request, response = await async_client.delete(f'/api/docs/{doc_id}')
assert response.status_code == HTTPStatus.NO_CONTENT
assert test_session.query(Doc).filter_by(id=doc_id).one_or_none() is None

View file

@ -0,0 +1,277 @@
"""Tests for the doc_modeler."""
import shutil
from unittest.mock import patch
import pytest
from PIL import Image
from modules.docs import doc_modeler
from modules.docs.models import Doc
from wrolpi.dates import now
from wrolpi.files import lib as files_lib
from wrolpi.files.models import FileGroup
from wrolpi.files.worker import file_worker
from wrolpi.test.common import assert_dict_contains
from wrolpi.vars import PROJECT_DIR
@pytest.mark.asyncio
async def test_doc_modeler_epub(async_client, test_session, test_directory, example_epub, example_mobi, refresh_files):
"""Doc modeler indexes epub files."""
await refresh_files()
doc: Doc = test_session.query(Doc).one()
assert doc.file_group.title == 'WROLPi Test Book'
assert doc.file_group.mimetype.startswith('application/epub')
assert doc.file_group.author == 'roland'
assert doc.file_group.a_text, 'Book title was not indexed'
assert doc.file_group.b_text, 'Book author was not indexed'
assert doc.file_group.d_text, 'Book text was not indexed'
assert doc.file_group.model == 'doc'
# Both ebooks are assumed to be the same book.
assert (epubs := doc.file_group.my_files('application/epub+zip')) and len(epubs) == 1
assert (mobis := doc.file_group.my_files('application/x-mobipocket-ebook')) and len(mobis) == 1
# Cover was discovered.
assert len(doc.file_group.my_poster_files()) == 1
# A second refresh should not re-model the already-indexed doc.
with patch('modules.docs._model_doc', side_effect=AssertionError('_model_doc should not be called')):
await refresh_files()
@pytest.mark.asyncio
async def test_doc_modeler_pdf(async_client, test_session, test_directory, example_pdf, refresh_files):
"""Doc modeler indexes PDF files."""
await refresh_files()
doc: Doc = test_session.query(Doc).one()
assert doc.file_group.mimetype == 'application/pdf'
assert doc.file_group.model == 'doc'
assert doc.file_group.indexed is True
assert doc.size # Has a size.
@pytest.mark.asyncio
async def test_doc_do_model_sets_model(test_session, example_pdf):
"""Doc.do_model sets file_group.model so the FileGroup is recognized as a doc."""
files_lib._upsert_files([example_pdf], now())
file_group = test_session.query(FileGroup).one()
# Reset to simulate a newly discovered file.
file_group.model = None
file_group.indexed = False
test_session.commit()
file_group.do_model(test_session)
test_session.commit()
assert file_group.model == 'doc', 'do_model must set file_group.model'
assert file_group.indexed is True
@pytest.mark.asyncio
async def test_doc_modeler_processes_more_than_batch_limit(async_client, test_session, test_directory):
"""Doc modeler processes more than one batch of files (limit=10)."""
ebook_dir = test_directory / 'ebooks'
ebook_dir.mkdir(parents=True)
num_docs = 15
for i in range(num_docs):
path = ebook_dir / f'test_ebook_{i:03d}.epub'
shutil.copy(PROJECT_DIR / 'test/ebook example.epub', path)
# Create FileGroups.
for path in ebook_dir.iterdir():
fg = FileGroup.from_paths(test_session, path)
assert fg.mimetype.startswith('application/epub')
test_session.commit()
await doc_modeler()
doc_count = test_session.query(Doc).count()
assert doc_count == num_docs, \
f'doc_modeler should process ALL {num_docs} files, but only processed {doc_count}'
still_unindexed = test_session.query(FileGroup).filter(
FileGroup.indexed == False,
FileGroup.mimetype == 'application/epub+zip',
).count()
assert still_unindexed == 0
@pytest.mark.asyncio
async def test_doc_modeler_reindex_creates_collections(async_client, test_session, test_directory, example_epub,
refresh_files):
"""When a doc is re-indexed (indexed=false), author/subject collections should be re-created."""
from wrolpi.collections.models import Collection
from wrolpi.db import get_db_session
await refresh_files()
# Author collection was created during first modeling.
with get_db_session() as session:
doc = session.query(Doc).one()
assert doc.file_group.author == 'roland'
author_col = session.query(Collection).filter_by(kind='author', name='Roland').one_or_none()
assert author_col, 'Author collection should exist after first indexing'
# Simulate post-migration state: delete the collection and mark as unindexed.
with get_db_session(commit=True) as session:
author_col = session.query(Collection).filter_by(kind='author', name='Roland').one()
session.delete(author_col)
doc = session.query(Doc).one()
doc.file_group.indexed = False
# Verify collection is gone.
with get_db_session() as session:
assert session.query(Collection).filter_by(kind='author', name='Roland').one_or_none() is None
# Re-run the modeler.
await doc_modeler()
# Author collection should be re-created.
with get_db_session() as session:
author_col = session.query(Collection).filter_by(kind='author', name='Roland').one_or_none()
assert author_col, 'Author collection should be re-created when doc is re-indexed'
@pytest.mark.asyncio
async def test_doc_modeler_calibre_cover(test_session, async_client, test_directory, example_epub, example_mobi,
image_file, refresh_files):
"""Calibre cover near an ebook file is discovered."""
metadata = test_directory / 'metadata.opf'
metadata.touch()
cover_image = test_directory / 'cover.jpg'
shutil.move(image_file, cover_image)
await refresh_files()
doc: Doc = test_session.query(Doc).one()
assert doc.file_group.title == 'WROLPi Test Book'
assert doc.cover_path
assert {i['path'].name for i in doc.file_group.my_files()} == {'ebook example.epub', 'ebook example.mobi',
'cover.jpg'}
# Metadata and cover FileGroups were deleted.
assert test_session.query(FileGroup).count() == 1
@pytest.mark.asyncio
async def test_doc_modeler_normalizes_author(async_client, test_session, test_directory, example_epub, refresh_files):
"""Author names are normalized before creating collections (e.g. quotes stripped)."""
from wrolpi.collections.models import Collection
from wrolpi.db import get_db_session
# Patch extract_metadata to return a quoted author.
from modules.docs.extractors import DocMetadata
fake_metadata = DocMetadata(author='"Tony R. Kuphaldt"', title='Test Book')
with patch('modules.docs.extract_metadata', return_value=fake_metadata):
await refresh_files()
with get_db_session() as session:
# Collection should have normalized name (no quotes).
col = session.query(Collection).filter_by(kind='author', name='Tony R. Kuphaldt').one_or_none()
assert col, 'Author collection should have normalized name without quotes'
# No collection with the quoted name.
quoted = session.query(Collection).filter_by(kind='author', name='"Tony R. Kuphaldt"').one_or_none()
assert not quoted, 'Should not create collection with quoted author name'
@pytest.mark.asyncio
async def test_doc_modeler_validates_subject(async_client, test_session, test_directory, example_epub, refresh_files):
"""Junk subjects are rejected during modeling."""
from wrolpi.collections.models import Collection
from wrolpi.db import get_db_session
from modules.docs.extractors import DocMetadata
fake_metadata = DocMetadata(subject='01/2004', title='Test Book')
with patch('modules.docs.extract_metadata', return_value=fake_metadata):
await refresh_files()
with get_db_session() as session:
col = session.query(Collection).filter_by(kind='subject', name='01/2004').one_or_none()
assert not col, 'Should not create collection for date-like subject'
@pytest.mark.asyncio
async def test_doc_modeler_discover_local_cover(test_session, test_directory, example_epub, image_bytes_factory,
refresh_files):
"""A cover file near the eBook is discovered."""
cover_path = example_epub.with_suffix('.jpg')
cover_path.write_bytes(image_bytes_factory())
await refresh_files()
doc: Doc = test_session.query(Doc).one()
assert doc.cover_path.read_bytes() == cover_path.read_bytes()
@pytest.mark.asyncio
async def test_doc_modeler_extract_cover(test_session, test_directory, example_epub, refresh_files):
"""First image is extracted from the Ebook and used as the cover."""
await refresh_files()
doc: Doc = test_session.query(Doc).one()
# The WROLPi logo is the first image in the example epub.
assert doc.cover_path and doc.cover_path.stat().st_size == 297099
@pytest.mark.asyncio
async def test_doc_modeler_move_ebook(async_client, test_session, test_directory, example_epub, image_file, tag_factory,
refresh_files, await_background_tasks):
"""An ebook is re-indexed when moved."""
tag = await tag_factory()
shutil.move(image_file, example_epub.with_suffix('.jpg'))
await refresh_files()
doc: Doc = test_session.query(Doc).one()
assert doc.cover_path
assert_dict_contains(doc.file_group.data, dict(author='roland'))
assert sorted([i['path'] for i in doc.file_group.my_files()]) == [
test_directory / 'ebook example.epub',
test_directory / 'ebook example.jpg',
]
doc.file_group.add_tag(test_session, tag.id)
test_session.commit()
new_directory = test_directory / 'new'
new_directory.mkdir()
file_worker.queue_move(new_directory, [doc.file_group.primary_path])
await await_background_tasks()
test_session.expire_all()
doc: Doc = test_session.query(Doc).one()
assert doc.file_group.primary_path == test_directory / 'new/ebook example.epub'
assert doc.cover_path
assert_dict_contains(doc.file_group.data, dict(author='roland'))
assert sorted([i['path'] for i in doc.file_group.my_files()]) == [
test_directory / 'new/ebook example.epub',
test_directory / 'new/ebook example.jpg',
]
@pytest.mark.asyncio
async def test_doc_modeler_pdf_max_size(test_session, example_pdf):
"""The contents of a large PDF are not indexed."""
example_pdf.write_bytes(example_pdf.read_bytes() * 5000)
files_lib._upsert_files([example_pdf], now())
await doc_modeler()
file_group = test_session.query(FileGroup).one()
assert file_group.d_text is None
@pytest.mark.asyncio
async def test_doc_modeler_pdf_poster(test_session, example_pdf):
"""PDF modeler finds an image with the same stem and uses it as the poster."""
poster_path = example_pdf.with_suffix('.jpg')
Image.new('RGB', (25, 25), color='grey').save(poster_path)
files_lib._upsert_files([example_pdf, poster_path], now())
await doc_modeler()
file_group = test_session.query(FileGroup).one()
assert file_group.indexed is True
assert file_group.data is not None
assert file_group.data.get('cover_path') == poster_path.name

View file

@ -0,0 +1,142 @@
import pytest
from modules.docs.extractors import extract_epub, extract_pdf, extract_metadata, extract_docx, extract_odt, \
extract_doc, extract_cbz, DocMetadata
from wrolpi.files.models import FileGroup
@pytest.mark.asyncio
async def test_extract_epub(test_session, test_directory, example_epub):
"""Metadata can be extracted from an EPUB file."""
metadata = extract_epub(example_epub)
assert metadata.title == 'WROLPi Test Book'
assert metadata.author == 'roland'
assert metadata.text # Has text content.
assert metadata.cover_bytes # Has a cover image.
@pytest.mark.asyncio
async def test_extract_pdf(test_session, test_directory, example_pdf):
"""Metadata can be extracted from a PDF file."""
metadata = extract_pdf(example_pdf)
# PDF may or may not have title metadata; at minimum it should return something.
assert metadata is not None
assert isinstance(metadata, DocMetadata)
@pytest.mark.asyncio
async def test_extract_pdf_metadata(test_session, test_directory, example_pdf):
"""PDF extractor extracts page count, date, cover, and text."""
metadata = extract_pdf(example_pdf)
assert metadata.title == 'WROLPi Test PDF'
assert metadata.author == 'roland'
assert metadata.page_count == 3
assert metadata.published_date is not None
assert metadata.cover_bytes
assert metadata.text
@pytest.mark.asyncio
async def test_extract_docx(test_session, test_directory, example_docx):
"""DOCX extractor extracts text content."""
metadata = extract_docx(example_docx)
assert isinstance(metadata, DocMetadata)
assert metadata.title == 'Word Document'
assert metadata.text
assert 'Example Word Document' in metadata.text
@pytest.mark.asyncio
async def test_extract_odt(test_session, test_directory, example_odt):
"""ODT extractor extracts title and text."""
metadata = extract_odt(example_odt)
assert metadata.title is not None
assert metadata.text
assert 'Test Header' in metadata.text
@pytest.mark.asyncio
async def test_extract_doc(test_session, test_directory, example_doc):
"""DOC extractor extracts title from filename and text if catdoc/textutil available."""
metadata = extract_doc(example_doc)
assert metadata.title # At minimum, title from filename.
@pytest.mark.asyncio
async def test_extract_cbz(test_session, test_directory, example_cbz):
"""CBZ extractor extracts cover image."""
metadata = extract_cbz(example_cbz)
assert metadata.cover_bytes is not None
assert len(metadata.cover_bytes) > 0
@pytest.mark.asyncio
async def test_extract_cbz_comicinfo(test_session, test_directory, example_cbz_metadata):
"""CBZ extractor reads ComicInfo.xml metadata."""
metadata = extract_cbz(example_cbz_metadata)
assert metadata.title == 'Bobby Make-Believe #1'
assert metadata.author == 'Frank King'
assert metadata.publisher == 'Chicago Tribune'
assert metadata.description == 'Bobby Make-Believe is a comic strip by Frank King.'
assert metadata.language == 'en'
assert metadata.subject == 'Comic Strip'
assert metadata.page_count == 4
assert metadata.published_date.year == 1915
assert metadata.published_date.month == 6
assert metadata.published_date.day == 15
assert metadata.cover_bytes is not None
@pytest.mark.asyncio
async def test_extract_cbt(test_session, test_directory, example_cbt):
"""CBT (TAR) extractor extracts cover image."""
metadata = extract_cbz(example_cbt)
assert metadata.cover_bytes is not None
assert len(metadata.cover_bytes) > 0
@pytest.mark.asyncio
async def test_extract_cbr(test_session, test_directory, example_cbr):
"""CBR (RAR) extractor extracts cover image."""
metadata = extract_cbz(example_cbr)
assert metadata.cover_bytes is not None
assert len(metadata.cover_bytes) > 0
@pytest.mark.asyncio
async def test_extract_cb7(test_session, test_directory, example_cb7):
"""CB7 (7z) extractor extracts cover image."""
metadata = extract_cbz(example_cb7)
assert metadata.cover_bytes is not None
assert len(metadata.cover_bytes) > 0
@pytest.mark.asyncio
async def test_extract_metadata_cbt(test_session, test_directory, example_cbt):
"""extract_metadata dispatches CBT files to the comic extractor."""
fg = FileGroup.from_paths(test_session, example_cbt)
test_session.flush()
metadata = extract_metadata(fg)
assert metadata.cover_bytes is not None
assert len(metadata.cover_bytes) > 0
@pytest.mark.asyncio
async def test_extract_metadata_cb7(test_session, test_directory, example_cb7):
"""extract_metadata dispatches CB7 files to the comic extractor."""
fg = FileGroup.from_paths(test_session, example_cb7)
test_session.flush()
metadata = extract_metadata(fg)
assert metadata.cover_bytes is not None
assert len(metadata.cover_bytes) > 0
@pytest.mark.asyncio
async def test_extract_metadata_dispatches(test_session, test_directory, example_epub):
"""extract_metadata dispatches to the correct extractor based on mimetype."""
fg = FileGroup.from_paths(test_session, example_epub)
test_session.flush()
metadata = extract_metadata(fg)
assert metadata.title == 'WROLPi Test Book'
assert metadata.author == 'roland'

View file

@ -0,0 +1,250 @@
import pytest
from modules.docs.lib import is_valid_author, split_authors, get_or_create_author_collection, \
get_or_create_subject_collection, normalize_author, normalize_subject, split_subjects, is_valid_subject, \
search_authors_by_name, search_subjects_by_name
def test_is_valid_author():
"""Author validation rejects junk values."""
assert is_valid_author('John Smith')
assert is_valid_author('J.K. Rowling')
assert is_valid_author('Dr. Seuss')
# Reject junk.
assert not is_valid_author('')
assert not is_valid_author(None)
assert not is_valid_author('Administrator')
assert not is_valid_author('administrator')
assert not is_valid_author('Preferred Customer')
assert not is_valid_author('Unknown')
assert not is_valid_author('www.example.com')
assert not is_valid_author('https://example.com')
assert not is_valid_author('A') # Too short.
assert not is_valid_author('x' * 101) # Too long.
# Reject year ranges and pure numbers.
assert not is_valid_author('1483-1546')
assert not is_valid_author('1564-1616')
assert not is_valid_author('-1938')
assert not is_valid_author('1851-1915')
assert not is_valid_author('1114690')
assert not is_valid_author('1588-1679')
# Reject strings with no letters.
assert not is_valid_author('12345')
assert not is_valid_author('---')
def test_split_authors():
"""Author strings with multiple authors are split correctly."""
assert split_authors('John Smith') == ['John Smith']
assert split_authors('John Smith; Jane Doe') == ['John Smith', 'Jane Doe']
assert split_authors('John Smith & Jane Doe') == ['John Smith', 'Jane Doe']
assert split_authors('') == []
assert split_authors(None) == []
def test_normalize_author():
"""Author names are cleaned up before validation."""
# Strip surrounding quotes.
assert normalize_author('"Tony R. Kuphaldt"') == 'Tony R. Kuphaldt'
assert normalize_author('"Mrs. D.A. Lincoln"') == 'Mrs. D.A. Lincoln'
# Remove bracket suffixes.
assert normalize_author('"Mrs. A. J. Barnes." [from old catalog]') == 'Mrs. A. J. Barnes'
assert normalize_author('Catherine] [from old catalog]') == 'Catherine'
assert normalize_author('1851-1915. [from old catalog]') == '1851-1915'
assert normalize_author('"Mrs. John Sterling," [from old catalog] ed') == 'Mrs. John Sterling'
# Remove trailing birth-death years.
assert normalize_author('Caroline Althea (Stickney) 1843-1920') == 'Caroline Althea (Stickney)'
assert normalize_author('1851-1917') == '1851-1917' # All numeric, nothing to strip — normalization passes through.
# Strip trailing period (but not initials).
assert normalize_author('Carol Ann.') == 'Carol Ann'
assert normalize_author('J.K.') == 'J.K.' # Initials stay.
assert normalize_author('Dr. Seuss') == 'Dr. Seuss' # Mid-string period stays.
# Surrounding parentheses.
assert normalize_author('(Thomas Joseph Workman)') == 'Thomas Joseph Workman'
assert normalize_author('(Roland)') == 'Roland'
# Title-case normalization.
assert normalize_author('john smith') == 'John Smith'
assert normalize_author('JOHN SMITH') == 'John Smith'
assert normalize_author('John Smith') == 'John Smith'
assert normalize_author('j.k. rowling') == 'J.K. Rowling'
# Empty/None.
assert normalize_author('') is None
assert normalize_author(None) is None
assert normalize_author(' ') is None
def test_is_valid_subject():
"""Subject validation rejects junk values."""
# Valid subjects.
assert is_valid_subject('Farming')
assert is_valid_subject('Computer Science')
assert is_valid_subject('First Aid')
assert is_valid_subject('Science, Technology and Society')
# Reject empty/short/long.
assert not is_valid_subject('')
assert not is_valid_subject(None)
assert not is_valid_subject('A')
assert not is_valid_subject('x' * 151)
# Reject pure numeric/codes.
assert not is_valid_subject('00110001')
assert not is_valid_subject('062447')
assert not is_valid_subject('105642-01')
assert not is_valid_subject('106763-01')
# Reject date-like strings.
assert not is_valid_subject('01/2004')
assert not is_valid_subject('04/2005')
assert not is_valid_subject('14 June 2006')
# Reject HTML entities.
assert not is_valid_subject('something • else')
# Reject URLs.
assert not is_valid_subject('https://example.com')
assert not is_valid_subject('www.example.com')
# Reject junk names.
assert not is_valid_subject('unknown')
assert not is_valid_subject('n/a')
def test_normalize_subject():
"""Subject strings are cleaned up before validation."""
# Strip whitespace.
assert normalize_subject(' Farming ') == 'Farming'
# Decode HTML entities.
assert normalize_subject('First & Second') == 'First & Second'
# Truncate long strings.
long_subject = 'x' * 200
assert len(normalize_subject(long_subject)) == 150
# Title-case normalization.
assert normalize_subject('science fiction') == 'Science Fiction'
assert normalize_subject('SCIENCE FICTION') == 'Science Fiction'
assert normalize_subject('fairy tales') == 'Fairy Tales'
assert normalize_subject('Fairy Tales') == 'Fairy Tales'
# Empty/None.
assert normalize_subject('') is None
assert normalize_subject(None) is None
assert normalize_subject(' ') is None
def test_split_subjects():
"""Subject strings with multiple subjects are split correctly."""
# Split on bare commas (no trailing space).
assert split_subjects('First Aid,GENERAL PREP.,HEALTH') == ['First Aid', 'GENERAL PREP.', 'HEALTH']
# Split on semicolons.
assert split_subjects('Science; Technology') == ['Science', 'Technology']
# Preserve commas followed by space (legitimate compound subjects).
assert split_subjects('Science, Technology and Society') == ['Science, Technology and Society']
# Empty/None.
assert split_subjects('') == []
assert split_subjects(None) == []
def test_get_or_create_author_collection(test_session):
"""Author collections are created and reused."""
col1 = get_or_create_author_collection(test_session, 'John Smith')
assert col1 is not None
assert col1.name == 'John Smith'
assert col1.kind == 'author'
# Same author returns same collection.
col2 = get_or_create_author_collection(test_session, 'John Smith')
assert col1.id == col2.id
# Different author creates new collection.
col3 = get_or_create_author_collection(test_session, 'Jane Doe')
assert col3.id != col1.id
# Empty author returns None.
assert get_or_create_author_collection(test_session, '') is None
assert get_or_create_author_collection(test_session, None) is None
def test_get_or_create_subject_collection(test_session):
"""Subject collections are created and reused."""
col1 = get_or_create_subject_collection(test_session, 'Farming')
assert col1 is not None
assert col1.name == 'Farming'
assert col1.kind == 'subject'
col2 = get_or_create_subject_collection(test_session, 'Farming')
assert col1.id == col2.id
assert get_or_create_subject_collection(test_session, '') is None
def test_get_or_create_subject_collection_case_insensitive(test_session):
"""Subject collections with different casing reuse the same collection."""
col1 = get_or_create_subject_collection(test_session, 'Science Fiction')
col2 = get_or_create_subject_collection(test_session, 'science fiction')
col3 = get_or_create_subject_collection(test_session, 'SCIENCE FICTION')
assert col1.id == col2.id == col3.id
def test_get_or_create_author_collection_case_insensitive(test_session):
"""Author collections with different casing reuse the same collection."""
col1 = get_or_create_author_collection(test_session, 'John Smith')
col2 = get_or_create_author_collection(test_session, 'john smith')
col3 = get_or_create_author_collection(test_session, 'JOHN SMITH')
assert col1.id == col2.id == col3.id
@pytest.mark.asyncio
async def test_search_authors_by_name(test_session):
"""Search for author collections by partial name."""
get_or_create_author_collection(test_session, 'John Smith')
get_or_create_author_collection(test_session, 'Jane Doe')
get_or_create_author_collection(test_session, 'Johnny Appleseed')
# Partial match.
results = await search_authors_by_name(test_session, 'john')
assert len(results) == 2
names = [r['name'] for r in results]
assert 'John Smith' in names
assert 'Johnny Appleseed' in names
# No match.
results = await search_authors_by_name(test_session, 'nobody')
assert len(results) == 0
# Limit.
results = await search_authors_by_name(test_session, 'j', limit=1)
assert len(results) == 1
@pytest.mark.asyncio
async def test_search_subjects_by_name(test_session):
"""Search for subject collections by partial name."""
get_or_create_subject_collection(test_session, 'Science Fiction')
get_or_create_subject_collection(test_session, 'Computer Science')
get_or_create_subject_collection(test_session, 'History')
# Partial match.
results = await search_subjects_by_name(test_session, 'science')
assert len(results) == 2
names = [r['name'] for r in results]
assert 'Science Fiction' in names
assert 'Computer Science' in names
# No match.
results = await search_subjects_by_name(test_session, 'nothing')
assert len(results) == 0

View file

@ -0,0 +1,56 @@
from modules.docs.models import Doc, DOC_MIMETYPES, mimetype_is_doc
def test_doc_mimetypes():
"""All expected mimetypes are included."""
assert 'application/epub+zip' in DOC_MIMETYPES
assert 'application/x-mobipocket-ebook' in DOC_MIMETYPES
assert 'application/pdf' in DOC_MIMETYPES
assert 'application/msword' in DOC_MIMETYPES
assert 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' in DOC_MIMETYPES
assert 'application/vnd.oasis.opendocument.text' in DOC_MIMETYPES
assert 'application/x-cbz' in DOC_MIMETYPES
assert 'application/x-cbr' in DOC_MIMETYPES
def test_mimetype_is_doc():
"""mimetype_is_doc correctly identifies doc mimetypes."""
assert mimetype_is_doc('application/pdf')
assert mimetype_is_doc('application/epub+zip')
assert mimetype_is_doc('application/x-mobipocket-ebook')
assert mimetype_is_doc('application/msword')
assert not mimetype_is_doc('video/mp4')
assert not mimetype_is_doc('text/plain')
assert not mimetype_is_doc('image/jpeg')
def test_doc_model(test_session, doc_factory):
"""Doc model can be created and queried."""
doc = doc_factory(size=1024, publisher='Test Publisher', language='en', subject='Testing')
assert doc.id
assert doc.size == 1024
assert doc.publisher == 'Test Publisher'
assert doc.language == 'en'
assert doc.subject == 'Testing'
assert doc.file_group is not None
queried = test_session.query(Doc).filter_by(id=doc.id).one()
assert queried.publisher == 'Test Publisher'
def test_doc_can_model(test_session, test_directory):
"""Doc.can_model identifies correct FileGroups."""
from wrolpi.files.models import FileGroup
pdf_path = test_directory / 'test.pdf'
pdf_path.write_bytes(b'%PDF-1.4 test')
fg = FileGroup.from_paths(test_session, pdf_path)
test_session.flush()
assert Doc.can_model(fg)
# Video should not be modeled as a doc.
video_path = test_directory / 'test.mp4'
video_path.write_bytes(b'\x00\x00\x00\x1cftypisom')
fg2 = FileGroup.from_paths(test_session, video_path)
test_session.flush()
assert not Doc.can_model(fg2)