mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-26 09:56:17 -05:00
Detecting collection directories using collection formatting rather than relying on parent directory of file groups, because those are now longer always in the collection directory.
This commit is contained in:
parent
f8675d52f0
commit
fa5c116b62
6 changed files with 1365 additions and 73 deletions
|
|
@ -721,75 +721,36 @@ async def model_archive_result(url: str, singlefile: str, readability: dict, scr
|
|||
return archive
|
||||
|
||||
|
||||
def detect_domain_directory(session: Session, collection: Collection) -> Optional[pathlib.Path]:
|
||||
def detect_domain_directory(collection: Collection) -> Optional[pathlib.Path]:
|
||||
"""
|
||||
Detect if all archives for a domain collection share a common directory.
|
||||
Detect directory for domain collection using format_destination template.
|
||||
|
||||
Computes the expected domain directory using the collection's format_destination()
|
||||
method and checks if that directory exists on the filesystem.
|
||||
|
||||
Args:
|
||||
collection: The domain collection to analyze
|
||||
session: Database session
|
||||
|
||||
Returns:
|
||||
Path (relative to media directory) if all archives share a common directory within archive media directory.
|
||||
None if archives are scattered across different directories or if collection has no archives.
|
||||
Path (relative to media directory) if the expected directory exists.
|
||||
None if collection is not a domain or directory doesn't exist.
|
||||
"""
|
||||
if collection.kind != 'domain':
|
||||
return None
|
||||
|
||||
# Query all archives for this domain collection
|
||||
archives = session.query(Archive).filter_by(collection_id=collection.id).all()
|
||||
# Get the tag name if collection has a tag
|
||||
tag_name = collection.tag.name if collection.tag else None
|
||||
|
||||
if not archives:
|
||||
# No archives yet, can't determine directory
|
||||
return None
|
||||
# Compute expected directory using archive_destination template
|
||||
expected_directory = collection.format_destination(tag_name)
|
||||
|
||||
# Get all archive file paths
|
||||
paths = []
|
||||
for archive in archives:
|
||||
if archive.file_group and archive.file_group.primary_path:
|
||||
paths.append(pathlib.Path(archive.file_group.primary_path))
|
||||
# Simply check if the directory exists
|
||||
if expected_directory.is_dir():
|
||||
relative_path = get_relative_to_media_directory(expected_directory)
|
||||
logger.debug(f'Detected directory for domain {collection.name}: {relative_path}')
|
||||
return relative_path
|
||||
|
||||
if not paths:
|
||||
return None
|
||||
|
||||
# Find common ancestor directory
|
||||
# Start with the first path's parent directory
|
||||
common_dir = paths[0].parent
|
||||
|
||||
# Check if all other paths are under this directory
|
||||
for path in paths[1:]:
|
||||
try:
|
||||
# Check if path is relative to common_dir
|
||||
path.relative_to(common_dir)
|
||||
except ValueError:
|
||||
# Path is not under common_dir, find the common ancestor
|
||||
# Walk up until we find a common parent
|
||||
while common_dir != common_dir.parent: # Stop at root
|
||||
try:
|
||||
path.relative_to(common_dir)
|
||||
break # Found common ancestor
|
||||
except ValueError:
|
||||
common_dir = common_dir.parent
|
||||
|
||||
# Check if common directory is within the media directory
|
||||
media_dir = get_media_directory()
|
||||
try:
|
||||
relative_path = common_dir.relative_to(media_dir)
|
||||
except ValueError:
|
||||
# Common directory is outside media directory
|
||||
return None
|
||||
|
||||
# Check if it's within the archive directory structure
|
||||
archive_base = get_archive_directory()
|
||||
try:
|
||||
archive_base.relative_to(media_dir) # Verify archive_base is under media_dir
|
||||
common_dir.relative_to(archive_base.parent) # Verify common_dir is under archive structure
|
||||
except ValueError:
|
||||
# Not in the archive directory structure
|
||||
return None
|
||||
|
||||
logger.debug(f'Detected directory for domain {collection.name}: {relative_path}')
|
||||
return relative_path
|
||||
return None
|
||||
|
||||
|
||||
def update_domain_directories(session: Session = None) -> int:
|
||||
|
|
@ -814,7 +775,7 @@ def update_domain_directories(session: Session = None) -> int:
|
|||
|
||||
updated_count = 0
|
||||
for collection in collections:
|
||||
detected_dir = detect_domain_directory(session, collection)
|
||||
detected_dir = detect_domain_directory(collection)
|
||||
if detected_dir:
|
||||
collection.directory = detected_dir
|
||||
session.flush([collection])
|
||||
|
|
@ -866,7 +827,7 @@ def get_or_create_domain_collection(session: Session, url, directory: pathlib.Pa
|
|||
|
||||
# Auto-detect directory if not explicitly set and collection doesn't have one
|
||||
if not directory and not collection.directory:
|
||||
detected_dir = detect_domain_directory(session, collection)
|
||||
detected_dir = detect_domain_directory(collection)
|
||||
if detected_dir:
|
||||
collection.directory = detected_dir
|
||||
session.flush()
|
||||
|
|
|
|||
479
modules/archive/test/test_config_import_scenarios.py
Normal file
479
modules/archive/test/test_config_import_scenarios.py
Normal file
|
|
@ -0,0 +1,479 @@
|
|||
"""
|
||||
Tests for domain config import scenarios, specifically around directory detection
|
||||
when archives are organized in year subdirectories.
|
||||
|
||||
These tests expose the bug where detect_domain_directory() returns the year directory
|
||||
(e.g., archive/x.com/2026) instead of the domain directory (archive/x.com) when archives
|
||||
are organized with year subdirectories.
|
||||
|
||||
These tests use the REAL import flow:
|
||||
1. Create archive files on disk
|
||||
2. Run refresh_files() to trigger file indexing and archive modeling
|
||||
3. Archive modeling calls get_or_create_domain_collection() → detect_domain_directory()
|
||||
4. Verify the detected directory is correct
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from modules.archive.lib import import_domains_config
|
||||
from wrolpi import tags
|
||||
from wrolpi.collections import Collection
|
||||
|
||||
|
||||
# Valid singlefile content with the required header
|
||||
def make_singlefile_content(url: str, title: str = 'Test Article') -> str:
|
||||
return f'''<html><!--
|
||||
Page saved with SingleFile
|
||||
url: {url}
|
||||
saved date: Thu May 12 2022 00:38:02 GMT+0000 (Coordinated Universal Time)
|
||||
--><head><meta charset="utf-8">
|
||||
<title>{title}</title>
|
||||
</head>
|
||||
<body>
|
||||
{title} body contents
|
||||
</body>
|
||||
</html>
|
||||
'''
|
||||
|
||||
|
||||
class TestNonTaggedDomainDirectoryDetection:
|
||||
"""Tests that non-tagged domain directories are correctly detected."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_detect_domain_directory_non_tagged(
|
||||
self, async_client, test_session, archive_directory):
|
||||
"""
|
||||
Non-tagged domain directories should be detected when they exist.
|
||||
|
||||
If archive/example.com exists, it should be returned by detect_domain_directory()
|
||||
for a collection with no tag.
|
||||
"""
|
||||
from modules.archive.lib import detect_domain_directory
|
||||
|
||||
# Create a domain collection WITHOUT a tag
|
||||
collection = Collection(name='example.com', kind='domain', directory=None)
|
||||
test_session.add(collection)
|
||||
test_session.flush()
|
||||
|
||||
# Verify no tag
|
||||
assert collection.tag is None, 'Collection should not have a tag'
|
||||
|
||||
# Create the expected directory on filesystem
|
||||
# For non-tagged domains, format_destination(None) should return archive/example.com
|
||||
expected_dir = archive_directory / 'example.com'
|
||||
expected_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# detect_domain_directory should find this directory
|
||||
detected = detect_domain_directory(collection)
|
||||
assert detected is not None, \
|
||||
f'detect_domain_directory should find directory for non-tagged domain. Expected: archive/example.com'
|
||||
assert 'example.com' in str(detected), f'Detected directory should contain domain name, got {detected}'
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_detect_domain_directory_non_tagged_directory_missing(
|
||||
self, async_client, test_session, archive_directory):
|
||||
"""
|
||||
When directory doesn't exist, detect_domain_directory should return None.
|
||||
"""
|
||||
from modules.archive.lib import detect_domain_directory
|
||||
|
||||
# Create a domain collection WITHOUT a tag
|
||||
collection = Collection(name='missing.com', kind='domain', directory=None)
|
||||
test_session.add(collection)
|
||||
test_session.flush()
|
||||
|
||||
# DO NOT create the directory - it should not exist
|
||||
|
||||
# detect_domain_directory should return None
|
||||
detected = detect_domain_directory(collection)
|
||||
assert detected is None, \
|
||||
'detect_domain_directory should return None when directory does not exist'
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_archive_modeling_creates_non_tagged_collection_with_directory(
|
||||
self, async_client, test_session, archive_directory, make_files_structure, refresh_files):
|
||||
"""
|
||||
When archives are created for a non-tagged domain, the collection
|
||||
should be created with the correct directory auto-detected.
|
||||
|
||||
This is the full integration test: files on disk -> modeling -> collection with directory.
|
||||
"""
|
||||
# Create archive files in non-tagged domain directory (no tag subdirectory)
|
||||
domain_dir = archive_directory / 'simple.com'
|
||||
domain_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
make_files_structure({
|
||||
str(domain_dir / '2026-01-01-00-00-01_Simple Article.html'):
|
||||
make_singlefile_content('https://simple.com/article', 'Simple Article'),
|
||||
str(domain_dir / '2026-01-01-00-00-01_Simple Article.readability.json'):
|
||||
'{"url": "https://simple.com/article", "title": "Simple Article"}',
|
||||
})
|
||||
|
||||
await refresh_files()
|
||||
|
||||
# Verify domain collection was created WITHOUT a tag
|
||||
collection = test_session.query(Collection).filter_by(name='simple.com', kind='domain').one_or_none()
|
||||
assert collection is not None, 'Domain collection should have been created'
|
||||
assert collection.tag is None, 'Collection should NOT have a tag'
|
||||
|
||||
# Directory should have been auto-detected
|
||||
assert collection.directory is not None, 'Directory should have been auto-detected'
|
||||
dir_str = str(collection.directory)
|
||||
assert 'archive/simple.com' in dir_str, f'Directory should be archive/simple.com, got {dir_str}'
|
||||
|
||||
|
||||
class TestArchiveModelingWithYearSubdirs:
|
||||
"""Tests using real archive modeling flow with year subdirectories."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_archive_modeling_year_subdirectory_detection(
|
||||
self, async_client, test_session, archive_directory, make_files_structure, refresh_files):
|
||||
"""
|
||||
Bug test: When archives are in year subdirectories, the domain collection
|
||||
should have directory archive/x.com, not archive/x.com/2026.
|
||||
|
||||
Uses real refresh flow to trigger archive modeling.
|
||||
"""
|
||||
# Create archive files in year subdirectory
|
||||
year_dir = archive_directory / 'x.com' / '2026'
|
||||
year_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
make_files_structure({
|
||||
str(year_dir / '2026-01-01-00-00-01_Article 1.html'):
|
||||
make_singlefile_content('https://x.com/article1', 'Article 1'),
|
||||
str(year_dir / '2026-01-01-00-00-01_Article 1.readability.json'):
|
||||
'{"url": "https://x.com/article1", "title": "Article 1"}',
|
||||
str(year_dir / '2026-01-01-00-00-02_Article 2.html'):
|
||||
make_singlefile_content('https://x.com/article2', 'Article 2'),
|
||||
str(year_dir / '2026-01-01-00-00-02_Article 2.readability.json'):
|
||||
'{"url": "https://x.com/article2", "title": "Article 2"}',
|
||||
})
|
||||
|
||||
# Run file refresh - this triggers archive modeling which calls
|
||||
# get_or_create_domain_collection() → detect_domain_directory()
|
||||
await refresh_files()
|
||||
|
||||
# Verify domain collection was created
|
||||
collection = test_session.query(Collection).filter_by(name='x.com', kind='domain').one_or_none()
|
||||
assert collection is not None, 'Domain collection should have been created'
|
||||
|
||||
# BUG: Currently detects archive/x.com/2026 instead of archive/x.com
|
||||
# The directory should be the domain directory, not the year subdirectory
|
||||
assert collection.directory is not None, 'Directory should have been auto-detected'
|
||||
dir_str = str(collection.directory)
|
||||
assert 'archive/x.com' in dir_str, f'Directory should contain archive/x.com, got {dir_str}'
|
||||
assert '2026' not in dir_str, f'Directory should NOT contain year subdirectory, got {dir_str}'
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_archive_modeling_multiple_year_subdirectories(
|
||||
self, async_client, test_session, archive_directory, make_files_structure, refresh_files):
|
||||
"""
|
||||
When archives span multiple years, the domain collection directory
|
||||
should be the common parent (archive/example.org), not either year.
|
||||
"""
|
||||
# Create archives in different year subdirectories
|
||||
year_2025 = archive_directory / 'example.org' / '2025'
|
||||
year_2026 = archive_directory / 'example.org' / '2026'
|
||||
year_2025.mkdir(parents=True, exist_ok=True)
|
||||
year_2026.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
make_files_structure({
|
||||
str(year_2025 / '2025-06-01-00-00-01_Old Article.html'):
|
||||
make_singlefile_content('https://example.org/old', 'Old Article'),
|
||||
str(year_2025 / '2025-06-01-00-00-01_Old Article.readability.json'):
|
||||
'{"url": "https://example.org/old", "title": "Old Article"}',
|
||||
str(year_2026 / '2026-01-01-00-00-01_New Article.html'):
|
||||
make_singlefile_content('https://example.org/new', 'New Article'),
|
||||
str(year_2026 / '2026-01-01-00-00-01_New Article.readability.json'):
|
||||
'{"url": "https://example.org/new", "title": "New Article"}',
|
||||
})
|
||||
|
||||
await refresh_files()
|
||||
|
||||
collection = test_session.query(Collection).filter_by(name='example.org', kind='domain').one_or_none()
|
||||
assert collection is not None
|
||||
assert collection.directory is not None
|
||||
|
||||
dir_str = str(collection.directory)
|
||||
assert 'archive/example.org' in dir_str
|
||||
# Should not contain either year
|
||||
assert '2025' not in dir_str, f'Directory should not contain 2025, got {dir_str}'
|
||||
assert '2026' not in dir_str, f'Directory should not contain 2026, got {dir_str}'
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_archive_modeling_tagged_domain_with_year_subdirs(
|
||||
self, async_client, test_session, test_directory, archive_directory,
|
||||
make_files_structure, test_tags_config, refresh_files):
|
||||
"""
|
||||
For tagged domains, the directory should be archive/tag/domain, not archive/tag/domain/year.
|
||||
|
||||
Tags are associated via config import, not auto-detected from paths.
|
||||
"""
|
||||
from wrolpi import tags
|
||||
from modules.archive.lib import import_domains_config
|
||||
|
||||
# Create config directory
|
||||
config_dir = test_directory / 'config'
|
||||
config_dir.mkdir(exist_ok=True)
|
||||
|
||||
# Create tags config with the 'news' tag
|
||||
test_tags_config.write_text('''
|
||||
version: 0
|
||||
tags:
|
||||
news:
|
||||
color: '#FF0000'
|
||||
''')
|
||||
|
||||
# Create domains config with tag association
|
||||
domains_config_path = config_dir / 'domains.yaml'
|
||||
domains_config_path.write_text('''
|
||||
version: 0
|
||||
collections:
|
||||
- name: x.com
|
||||
kind: domain
|
||||
tag_name: news
|
||||
''')
|
||||
|
||||
# Import configs to set up tag association
|
||||
tags.import_tags_config()
|
||||
import_domains_config()
|
||||
|
||||
# Create archives in tagged domain with year subdirectory
|
||||
tagged_year_dir = archive_directory / 'news' / 'x.com' / '2026'
|
||||
tagged_year_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
make_files_structure({
|
||||
str(tagged_year_dir / '2026-01-01-00-00-01_Tagged Article.html'):
|
||||
make_singlefile_content('https://x.com/tagged', 'Tagged Article'),
|
||||
str(tagged_year_dir / '2026-01-01-00-00-01_Tagged Article.readability.json'):
|
||||
'{"url": "https://x.com/tagged", "title": "Tagged Article"}',
|
||||
})
|
||||
|
||||
await refresh_files()
|
||||
|
||||
# The collection should exist with tag association from config
|
||||
collection = test_session.query(Collection).filter_by(name='x.com', kind='domain').one_or_none()
|
||||
assert collection is not None
|
||||
assert collection.tag is not None
|
||||
assert collection.tag.name == 'news'
|
||||
|
||||
# Directory should be archive/news/x.com, not archive/news/x.com/2026
|
||||
assert collection.directory is not None
|
||||
dir_str = str(collection.directory)
|
||||
assert '2026' not in dir_str, f'Directory should not contain year, got {dir_str}'
|
||||
|
||||
|
||||
class TestConfigImportThenModeling:
|
||||
"""Tests for config import followed by archive modeling."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_config_import_then_archive_modeling(
|
||||
self, async_client, test_session, test_directory, archive_directory,
|
||||
make_files_structure, test_tags_config, refresh_files):
|
||||
"""
|
||||
Test full flow:
|
||||
1. Import domains config (creates unrestricted collection)
|
||||
2. Create archive files on disk
|
||||
3. Run refresh (triggers modeling and directory detection)
|
||||
4. Verify directory is correctly detected
|
||||
"""
|
||||
# Create tags config
|
||||
config_dir = test_directory / 'config'
|
||||
config_dir.mkdir(exist_ok=True)
|
||||
test_tags_config.write_text('''
|
||||
version: 0
|
||||
tags:
|
||||
news:
|
||||
color: '#FF0000'
|
||||
''')
|
||||
|
||||
# Create domains config - collection without directory initially
|
||||
domains_config_path = config_dir / 'domains.yaml'
|
||||
domains_config_path.write_text('''
|
||||
version: 0
|
||||
collections:
|
||||
- name: test.com
|
||||
kind: domain
|
||||
tag_name: news
|
||||
''')
|
||||
|
||||
# Import configs
|
||||
tags.import_tags_config()
|
||||
import_domains_config()
|
||||
|
||||
# Verify collection was created WITHOUT directory
|
||||
collection = test_session.query(Collection).filter_by(name='test.com', kind='domain').one()
|
||||
assert collection.tag is not None
|
||||
assert collection.tag.name == 'news'
|
||||
# Collection should be unrestricted (no directory yet)
|
||||
initial_directory = collection.directory
|
||||
|
||||
# Now create archive files in year subdirectory
|
||||
year_dir = archive_directory / 'news' / 'test.com' / '2026'
|
||||
year_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
make_files_structure({
|
||||
str(year_dir / '2026-01-01-00-00-01_Test Article.html'):
|
||||
make_singlefile_content('https://test.com/article', 'Test Article'),
|
||||
str(year_dir / '2026-01-01-00-00-01_Test Article.readability.json'):
|
||||
'{"url": "https://test.com/article", "title": "Test Article"}',
|
||||
})
|
||||
|
||||
# Run refresh to trigger archive modeling
|
||||
await refresh_files()
|
||||
|
||||
# Refresh the collection from DB
|
||||
test_session.expire(collection)
|
||||
|
||||
# Directory should now be detected - but NOT include the year
|
||||
if collection.directory is not None:
|
||||
dir_str = str(collection.directory)
|
||||
assert '2026' not in dir_str, f'Directory should not contain year, got {dir_str}'
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_full_startup_import_sequence(
|
||||
self, async_client, test_session, test_directory, archive_directory, test_tags_config):
|
||||
"""
|
||||
Replicate exact main.py import order to verify tag associations exist
|
||||
before domain directory detection runs.
|
||||
"""
|
||||
from wrolpi.tags import Tag
|
||||
|
||||
# Create tag
|
||||
news_tag = Tag(name='news')
|
||||
test_session.add(news_tag)
|
||||
test_session.commit()
|
||||
|
||||
# Create tags config
|
||||
config_dir = test_directory / 'config'
|
||||
config_dir.mkdir(exist_ok=True)
|
||||
test_tags_config.write_text('''
|
||||
version: 0
|
||||
tags:
|
||||
news:
|
||||
color: '#0000FF'
|
||||
''')
|
||||
|
||||
# Create domains config
|
||||
domains_config_path = config_dir / 'domains.yaml'
|
||||
domains_config_path.write_text('''
|
||||
version: 0
|
||||
collections:
|
||||
- name: startup-test.com
|
||||
kind: domain
|
||||
tag_name: news
|
||||
''')
|
||||
|
||||
# Import in exact main.py order
|
||||
tags.import_tags_config()
|
||||
import_domains_config()
|
||||
|
||||
# Verify tag association was created
|
||||
collection = test_session.query(Collection).filter_by(name='startup-test.com', kind='domain').one()
|
||||
assert collection.tag is not None
|
||||
assert collection.tag.name == 'news'
|
||||
|
||||
|
||||
class TestArchiveFileFormatInteraction:
|
||||
"""Tests for interaction between archive_file_format config and directory detection."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_archive_file_format_with_year_subdirectory(
|
||||
self, async_client, test_session, test_directory, archive_directory,
|
||||
make_files_structure, refresh_files, fake_now):
|
||||
"""
|
||||
Test that directory detection works correctly when archive_file_format
|
||||
includes year subdirectories.
|
||||
|
||||
This tests the interaction between:
|
||||
1. archive_file_format config (e.g., %(download_year)s/%(download_datetime)s_%(title)s.%(ext)s)
|
||||
2. detect_domain_directory() which should return archive/example.com, NOT archive/example.com/2026
|
||||
|
||||
Uses get_new_archive_files() to create files exactly as the real download flow does.
|
||||
"""
|
||||
from datetime import datetime
|
||||
from modules.archive.lib import get_new_archive_files, get_archive_downloader_config
|
||||
|
||||
# Set the fake time so we know what year subdirectory will be created
|
||||
fake_now(datetime(2026, 6, 15))
|
||||
|
||||
# Configure archive_file_format to use year subdirectories
|
||||
config = get_archive_downloader_config()
|
||||
original_format = config._config['file_name_format']
|
||||
config._config['file_name_format'] = '%(download_year)s/%(download_datetime)s_%(title)s.%(ext)s'
|
||||
|
||||
try:
|
||||
# Use get_new_archive_files to create file paths exactly as real download does
|
||||
archive_files = get_new_archive_files('https://fileformat-test.com/article', 'Test Article')
|
||||
|
||||
# Verify the files are in a year subdirectory
|
||||
assert '2026' in str(archive_files.singlefile), f'File should be in year subdir: {archive_files.singlefile}'
|
||||
|
||||
# Create the directory structure and write the files
|
||||
archive_files.singlefile.parent.mkdir(parents=True, exist_ok=True)
|
||||
archive_files.singlefile.write_text(
|
||||
make_singlefile_content('https://fileformat-test.com/article', 'Test Article'))
|
||||
archive_files.readability_json.write_text(
|
||||
'{"url": "https://fileformat-test.com/article", "title": "Test Article"}')
|
||||
|
||||
# Run refresh to trigger archive modeling
|
||||
await refresh_files()
|
||||
|
||||
# Verify domain collection was created
|
||||
collection = test_session.query(Collection).filter_by(
|
||||
name='fileformat-test.com', kind='domain').one_or_none()
|
||||
assert collection is not None, 'Domain collection should have been created'
|
||||
|
||||
# BUG: Currently detects archive/fileformat-test.com/2026 instead of archive/fileformat-test.com
|
||||
assert collection.directory is not None, 'Directory should have been auto-detected'
|
||||
dir_str = str(collection.directory)
|
||||
assert 'archive/fileformat-test.com' in dir_str, f'Directory should contain domain, got {dir_str}'
|
||||
assert '2026' not in dir_str, f'Directory should NOT contain year from file format, got {dir_str}'
|
||||
|
||||
finally:
|
||||
# Restore original format
|
||||
config._config['file_name_format'] = original_format
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_archive_file_format_multiple_downloads_same_year(
|
||||
self, async_client, test_session, test_directory, archive_directory,
|
||||
make_files_structure, refresh_files, fake_now):
|
||||
"""
|
||||
Test directory detection when multiple archives are downloaded in the same year
|
||||
using archive_file_format with year subdirectories.
|
||||
"""
|
||||
from datetime import datetime
|
||||
from modules.archive.lib import get_new_archive_files, get_archive_downloader_config
|
||||
|
||||
fake_now(datetime(2026, 3, 10))
|
||||
|
||||
config = get_archive_downloader_config()
|
||||
original_format = config._config['file_name_format']
|
||||
config._config['file_name_format'] = '%(download_year)s/%(download_datetime)s_%(title)s.%(ext)s'
|
||||
|
||||
try:
|
||||
# Create multiple archives in the same year
|
||||
for i, title in enumerate(['Article One', 'Article Two', 'Article Three'], 1):
|
||||
fake_now(datetime(2026, 3, 10, 0, 0, i)) # Different times, same year
|
||||
archive_files = get_new_archive_files(f'https://multi-test.com/article{i}', title)
|
||||
archive_files.singlefile.parent.mkdir(parents=True, exist_ok=True)
|
||||
archive_files.singlefile.write_text(
|
||||
make_singlefile_content(f'https://multi-test.com/article{i}', title))
|
||||
archive_files.readability_json.write_text(
|
||||
f'{{"url": "https://multi-test.com/article{i}", "title": "{title}"}}')
|
||||
|
||||
await refresh_files()
|
||||
|
||||
collection = test_session.query(Collection).filter_by(
|
||||
name='multi-test.com', kind='domain').one_or_none()
|
||||
assert collection is not None
|
||||
|
||||
# BUG: All archives in 2026/, so common ancestor is archive/multi-test.com/2026
|
||||
# Should be archive/multi-test.com
|
||||
assert collection.directory is not None
|
||||
dir_str = str(collection.directory)
|
||||
assert 'archive/multi-test.com' in dir_str
|
||||
assert '2026' not in dir_str, f'Directory should NOT contain year, got {dir_str}'
|
||||
|
||||
finally:
|
||||
config._config['file_name_format'] = original_format
|
||||
|
|
@ -946,7 +946,7 @@ async def test_detect_domain_directory_single_archive(async_client, test_directo
|
|||
assert 'example.com' in str(collection.directory)
|
||||
|
||||
# Verify detect_domain_directory also returns the same result
|
||||
detected = detect_domain_directory(test_session, collection)
|
||||
detected = detect_domain_directory(collection)
|
||||
assert detected is not None
|
||||
assert str(detected) == 'archive/example.com'
|
||||
|
||||
|
|
@ -967,7 +967,7 @@ async def test_detect_domain_directory_multiple_archives(async_client, test_dire
|
|||
assert collection.name == 'test.com'
|
||||
|
||||
# Detect directory
|
||||
detected = detect_domain_directory(test_session, collection)
|
||||
detected = detect_domain_directory(collection)
|
||||
assert detected is not None
|
||||
assert str(detected) == 'archive/test.com'
|
||||
|
||||
|
|
@ -982,7 +982,7 @@ def test_detect_domain_directory_no_archives(test_directory, test_session):
|
|||
test_session.flush()
|
||||
|
||||
# Detect directory - should return None
|
||||
detected = detect_domain_directory(test_session, collection)
|
||||
detected = detect_domain_directory(collection)
|
||||
assert detected is None
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -74,8 +74,18 @@ def get_channel(session: Session, *, channel_id: int = None, source_id: str = No
|
|||
directory = Path(directory)
|
||||
if not directory.is_absolute():
|
||||
directory = get_media_directory() / directory
|
||||
channel = session.query(Channel).join(Collection).filter(
|
||||
Collection.directory == str(directory)).one_or_none()
|
||||
directory = directory.absolute()
|
||||
|
||||
# Walk up the directory tree to find a matching channel
|
||||
# This allows finding channels for files in subdirectories (e.g., year subdirs)
|
||||
media_dir = get_media_directory()
|
||||
current = directory
|
||||
while current != media_dir and current != current.parent:
|
||||
channel = session.query(Channel).options(joinedload(Channel.collection)).join(Collection).filter(
|
||||
Collection.directory == str(current)).one_or_none()
|
||||
if channel:
|
||||
break
|
||||
current = current.parent
|
||||
if not channel and name:
|
||||
channel = session.query(Channel).join(Collection).filter(Collection.name == name).one_or_none()
|
||||
|
||||
|
|
|
|||
|
|
@ -223,6 +223,15 @@ class Video(ModelHelper, Base):
|
|||
logger.error(f'Unable to validate video {self.id} without primary file!')
|
||||
|
||||
logger.debug(f'Validating {self}')
|
||||
|
||||
# Look up the channel FIRST so we can use channel settings (like generate_posters)
|
||||
# during validation. Channel.get_by_path walks up the directory tree to find
|
||||
# channels even when videos are in subdirectories (e.g., year subdirs).
|
||||
session: Session = session or Session.object_session(self)
|
||||
if session and not self.channel and (channel := Channel.get_by_path(session, self.video_path.parent)):
|
||||
self.channel = channel
|
||||
logger.debug(f'{self} has Channel {channel}')
|
||||
|
||||
from .lib import validate_video
|
||||
try:
|
||||
validate_video(session, self, self.channel.generate_posters if self.channel else False)
|
||||
|
|
@ -240,12 +249,6 @@ class Video(ModelHelper, Base):
|
|||
logger.debug(f'{self} has comments')
|
||||
self.have_comments = True
|
||||
|
||||
# If this Video is in a Channel's directory, then it is part of that Channel.
|
||||
session: Session = session or Session.object_session(self)
|
||||
if session and (channel := Channel.get_by_path(session, self.video_path.parent)):
|
||||
self.channel = channel
|
||||
logger.debug(f'{self} has Channel {channel}')
|
||||
|
||||
# Set FileGroup.data with cached file paths (stored as relative filenames)
|
||||
# Paths are resolved to absolute when accessed via file_group.resolve_path()
|
||||
self.file_group.data = {
|
||||
|
|
@ -835,14 +838,41 @@ class Channel(ModelHelper, Base):
|
|||
|
||||
@staticmethod
|
||||
def get_by_path(session: Session, path: pathlib.Path) -> Optional['Channel']:
|
||||
"""
|
||||
Find a Channel whose directory contains the given path.
|
||||
|
||||
This method walks up the directory tree from the given path to find
|
||||
a Channel whose directory matches. This allows finding channels for
|
||||
files in subdirectories (e.g., year subdirectories like 2026/).
|
||||
|
||||
Args:
|
||||
session: Database session
|
||||
path: Path to search for (can be a file or directory path)
|
||||
|
||||
Returns:
|
||||
Channel if found, None otherwise
|
||||
"""
|
||||
if not path:
|
||||
raise RuntimeError('Must provide path to get Channel')
|
||||
path = pathlib.Path(path) if isinstance(path, str) else path
|
||||
path = str(path.absolute()) if path.is_absolute() else str(get_media_directory() / path)
|
||||
# Query through Collection relationship since directory is now on Collection
|
||||
if not path.is_absolute():
|
||||
path = get_media_directory() / path
|
||||
path = path.absolute()
|
||||
|
||||
from wrolpi.collections import Collection
|
||||
channel = session.query(Channel).join(Collection).filter(Collection.directory == path).one_or_none()
|
||||
return channel
|
||||
media_dir = get_media_directory()
|
||||
|
||||
# Walk up the directory tree to find a matching channel
|
||||
current = path
|
||||
while current != media_dir and current != current.parent:
|
||||
channel = session.query(Channel).join(Collection).filter(
|
||||
Collection.directory == str(current)
|
||||
).one_or_none()
|
||||
if channel:
|
||||
return channel
|
||||
current = current.parent
|
||||
|
||||
return None
|
||||
|
||||
def __json__(self) -> dict:
|
||||
d = dict(
|
||||
|
|
|
|||
812
modules/videos/test/test_channel_directory_scenarios.py
Normal file
812
modules/videos/test/test_channel_directory_scenarios.py
Normal file
|
|
@ -0,0 +1,812 @@
|
|||
"""
|
||||
Tests for channel directory detection scenarios, specifically around directory detection
|
||||
when videos are organized in year subdirectories.
|
||||
|
||||
These tests expose bugs where:
|
||||
1. Video.validate() uses exact directory match, failing for year subdirectories
|
||||
2. Videos in year subdirs don't get channel's generate_posters setting applied
|
||||
3. Channel.get_by_path() returns None for paths in subdirectories
|
||||
|
||||
These tests use the REAL modeling flow:
|
||||
1. Create video files on disk in year subdirectories
|
||||
2. Create channel with directory at parent level
|
||||
3. Run refresh_files() to trigger video modeling
|
||||
4. Verify the video is correctly associated with the channel
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from modules.videos.models import Channel, Video
|
||||
from wrolpi.collections import Collection
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestNonTaggedChannelDirectoryDetection:
|
||||
"""Tests that non-tagged channel directories work correctly."""
|
||||
|
||||
async def test_video_association_non_tagged_channel(
|
||||
self, async_client, test_session, test_directory, video_file, refresh_files):
|
||||
"""
|
||||
Videos in a non-tagged channel directory should be associated with that channel.
|
||||
|
||||
If videos/ChannelName exists and a channel is created with that directory,
|
||||
videos within should be associated with the channel.
|
||||
"""
|
||||
# Create a channel WITHOUT a tag
|
||||
channel_dir = test_directory / 'videos' / 'SimpleChannel'
|
||||
channel_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
collection = Collection(
|
||||
name='SimpleChannel',
|
||||
kind='channel',
|
||||
directory=channel_dir,
|
||||
tag_id=None, # Explicitly no tag
|
||||
)
|
||||
test_session.add(collection)
|
||||
test_session.flush([collection])
|
||||
|
||||
channel = Channel(
|
||||
collection_id=collection.id,
|
||||
url='https://example.com/simplechannel',
|
||||
)
|
||||
test_session.add(channel)
|
||||
test_session.commit()
|
||||
|
||||
# Verify no tag
|
||||
assert channel.tag is None, 'Channel should not have a tag'
|
||||
|
||||
# Create video directly in channel directory (no year subdirectory)
|
||||
video_path = channel_dir / 'Simple Video.mp4'
|
||||
video_file.rename(video_path)
|
||||
|
||||
await refresh_files()
|
||||
|
||||
# Video should be associated with the non-tagged channel
|
||||
video = test_session.query(Video).join(Video.file_group).filter(
|
||||
Video.file_group.has(primary_path=str(video_path))
|
||||
).one_or_none()
|
||||
|
||||
assert video is not None, 'Video should have been created'
|
||||
assert video.channel_id == channel.id, \
|
||||
f'Video should be associated with non-tagged channel, got channel_id={video.channel_id}'
|
||||
assert video.channel.tag is None, 'Channel should still have no tag'
|
||||
|
||||
async def test_video_association_non_tagged_channel_nested_directory(
|
||||
self, async_client, test_session, test_directory, video_file, refresh_files):
|
||||
"""
|
||||
Videos in nested directories under a non-tagged channel should be associated.
|
||||
|
||||
If videos/ChannelName/subdir exists, videos there should be associated
|
||||
with the channel at videos/ChannelName.
|
||||
"""
|
||||
# Create a channel WITHOUT a tag
|
||||
channel_dir = test_directory / 'videos' / 'NestedChannel'
|
||||
channel_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
collection = Collection(
|
||||
name='NestedChannel',
|
||||
kind='channel',
|
||||
directory=channel_dir,
|
||||
tag_id=None,
|
||||
)
|
||||
test_session.add(collection)
|
||||
test_session.flush([collection])
|
||||
|
||||
channel = Channel(
|
||||
collection_id=collection.id,
|
||||
url='https://example.com/nestedchannel',
|
||||
)
|
||||
test_session.add(channel)
|
||||
test_session.commit()
|
||||
|
||||
# Create video in a nested subdirectory
|
||||
nested_dir = channel_dir / 'season1' / 'episode1'
|
||||
nested_dir.mkdir(parents=True, exist_ok=True)
|
||||
video_path = nested_dir / 'Nested Video.mp4'
|
||||
video_file.rename(video_path)
|
||||
|
||||
await refresh_files()
|
||||
|
||||
# Video should be associated with the channel even in nested subdirectory
|
||||
video = test_session.query(Video).join(Video.file_group).filter(
|
||||
Video.file_group.has(primary_path=str(video_path))
|
||||
).one_or_none()
|
||||
|
||||
assert video is not None
|
||||
# Note: This may fail if video_cleanup doesn't run or if the LIKE clause doesn't match
|
||||
assert video.channel_id == channel.id, \
|
||||
f'Video in nested directory should be associated with channel, got channel_id={video.channel_id}'
|
||||
|
||||
async def test_channel_created_after_videos_non_tagged(
|
||||
self, async_client, test_session, test_directory, video_file,
|
||||
test_channels_config, refresh_files):
|
||||
"""
|
||||
When a non-tagged channel is created via config import AFTER videos exist,
|
||||
the videos should be claimed by the channel.
|
||||
"""
|
||||
import yaml
|
||||
from modules.videos.lib import get_channels_config
|
||||
|
||||
# Create video BEFORE channel exists
|
||||
videos_dir = test_directory / 'videos' / 'LateNonTaggedChannel'
|
||||
videos_dir.mkdir(parents=True, exist_ok=True)
|
||||
video_path = videos_dir / 'Early Video.mp4'
|
||||
video_file.rename(video_path)
|
||||
|
||||
await refresh_files()
|
||||
|
||||
# Video exists but has no channel
|
||||
video = test_session.query(Video).join(Video.file_group).filter(
|
||||
Video.file_group.has(primary_path=str(video_path))
|
||||
).one_or_none()
|
||||
assert video is not None
|
||||
assert video.channel_id is None, 'Video should not have channel before config import'
|
||||
|
||||
# Now import channel config (non-tagged channel)
|
||||
config = get_channels_config()
|
||||
config_path = config.get_file()
|
||||
|
||||
config_data = {
|
||||
'version': 0,
|
||||
'channels': [{
|
||||
'name': 'LateNonTaggedChannel',
|
||||
'directory': str(videos_dir),
|
||||
'url': 'https://example.com/latenontagged',
|
||||
# Note: no tag_name field = non-tagged channel
|
||||
}]
|
||||
}
|
||||
with open(config_path, 'w') as f:
|
||||
yaml.dump(config_data, f)
|
||||
|
||||
config.initialize()
|
||||
config.import_config()
|
||||
|
||||
# Refresh video from DB
|
||||
test_session.expire(video)
|
||||
|
||||
# Video should now be claimed by the non-tagged channel
|
||||
assert video.channel_id is not None, \
|
||||
'Video should be claimed by non-tagged channel after config import'
|
||||
|
||||
channel = test_session.query(Channel).join(Collection).filter(
|
||||
Collection.name == 'LateNonTaggedChannel'
|
||||
).one()
|
||||
assert video.channel_id == channel.id
|
||||
assert channel.tag is None, 'Channel should be non-tagged'
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestVideoModelingWithYearSubdirs:
|
||||
"""Tests using real video modeling flow with year subdirectories."""
|
||||
|
||||
async def test_video_modeling_year_subdirectory_detection(
|
||||
self, async_client, test_session, test_directory, video_file, refresh_files):
|
||||
"""
|
||||
Bug test: When videos are in year subdirectories, the video
|
||||
should be associated with the channel at the parent directory.
|
||||
|
||||
Uses real refresh flow to trigger video modeling.
|
||||
"""
|
||||
# Create channel with directory at videos/TestChannel
|
||||
channel_dir = test_directory / 'videos' / 'TestChannel'
|
||||
channel_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
collection = Collection(
|
||||
name='TestChannel',
|
||||
kind='channel',
|
||||
directory=channel_dir,
|
||||
)
|
||||
test_session.add(collection)
|
||||
test_session.flush([collection])
|
||||
|
||||
channel = Channel(
|
||||
collection_id=collection.id,
|
||||
url='https://example.com/testchannel',
|
||||
)
|
||||
test_session.add(channel)
|
||||
test_session.commit()
|
||||
|
||||
# Create video file in year subdirectory
|
||||
year_dir = channel_dir / '2026'
|
||||
year_dir.mkdir(parents=True, exist_ok=True)
|
||||
video_path = year_dir / '2026-01-01_Test Video.mp4'
|
||||
video_file.rename(video_path)
|
||||
|
||||
# Run file refresh - this triggers video modeling
|
||||
await refresh_files()
|
||||
|
||||
# Verify video was created
|
||||
video = test_session.query(Video).join(Video.file_group).filter(
|
||||
Video.file_group.has(primary_path=str(video_path))
|
||||
).one_or_none()
|
||||
assert video is not None, 'Video should have been created'
|
||||
|
||||
# BUG: Video.validate() uses Channel.get_by_path() with exact match
|
||||
# This fails because video_path.parent is videos/TestChannel/2026
|
||||
# but channel.directory is videos/TestChannel
|
||||
assert video.channel_id is not None, \
|
||||
f'Video should be associated with channel, but channel_id is None. Video path: {video_path}'
|
||||
assert video.channel_id == channel.id, \
|
||||
f'Video should be associated with TestChannel, got channel_id={video.channel_id}'
|
||||
|
||||
async def test_video_modeling_multiple_year_subdirectories(
|
||||
self, async_client, test_session, test_directory, video_file_factory, refresh_files):
|
||||
"""
|
||||
When videos span multiple years, they should all be associated
|
||||
with the same channel at the parent directory.
|
||||
"""
|
||||
# Create channel
|
||||
channel_dir = test_directory / 'videos' / 'MultiYearChannel'
|
||||
channel_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
collection = Collection(
|
||||
name='MultiYearChannel',
|
||||
kind='channel',
|
||||
directory=channel_dir,
|
||||
)
|
||||
test_session.add(collection)
|
||||
test_session.flush([collection])
|
||||
|
||||
channel = Channel(
|
||||
collection_id=collection.id,
|
||||
url='https://example.com/multiyear',
|
||||
)
|
||||
test_session.add(channel)
|
||||
test_session.commit()
|
||||
|
||||
# Create videos in different year subdirectories
|
||||
year_2025 = channel_dir / '2025'
|
||||
year_2026 = channel_dir / '2026'
|
||||
year_2025.mkdir(parents=True, exist_ok=True)
|
||||
year_2026.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
video_path_2025 = year_2025 / '2025-06-01_Old Video.mp4'
|
||||
video_path_2026 = year_2026 / '2026-01-01_New Video.mp4'
|
||||
|
||||
video_file_factory(video_path_2025)
|
||||
video_file_factory(video_path_2026)
|
||||
|
||||
await refresh_files()
|
||||
|
||||
# Both videos should be associated with the same channel
|
||||
video_2025 = test_session.query(Video).join(Video.file_group).filter(
|
||||
Video.file_group.has(primary_path=str(video_path_2025))
|
||||
).one_or_none()
|
||||
video_2026 = test_session.query(Video).join(Video.file_group).filter(
|
||||
Video.file_group.has(primary_path=str(video_path_2026))
|
||||
).one_or_none()
|
||||
|
||||
assert video_2025 is not None
|
||||
assert video_2026 is not None
|
||||
|
||||
# BUG: Both videos should belong to the channel
|
||||
assert video_2025.channel_id == channel.id, \
|
||||
f'2025 video should be in channel, got channel_id={video_2025.channel_id}'
|
||||
assert video_2026.channel_id == channel.id, \
|
||||
f'2026 video should be in channel, got channel_id={video_2026.channel_id}'
|
||||
|
||||
async def test_video_modeling_tagged_channel_with_year_subdirs(
|
||||
self, async_client, test_session, test_directory, video_file,
|
||||
test_tags_config, refresh_files):
|
||||
"""
|
||||
For tagged channels, videos in year subdirectories should still
|
||||
be associated with the channel.
|
||||
|
||||
Channel at: videos/education/TechChannel
|
||||
Video at: videos/education/TechChannel/2026/video.mp4
|
||||
"""
|
||||
from wrolpi import tags
|
||||
|
||||
# Create tag
|
||||
config_dir = test_directory / 'config'
|
||||
config_dir.mkdir(exist_ok=True)
|
||||
test_tags_config.write_text('''
|
||||
version: 0
|
||||
tags:
|
||||
education:
|
||||
color: '#00FF00'
|
||||
''')
|
||||
tags.import_tags_config()
|
||||
|
||||
# Get the tag
|
||||
from wrolpi.tags import Tag
|
||||
edu_tag = test_session.query(Tag).filter_by(name='education').one()
|
||||
|
||||
# Create channel with tag
|
||||
channel_dir = test_directory / 'videos' / 'education' / 'TechChannel'
|
||||
channel_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
collection = Collection(
|
||||
name='TechChannel',
|
||||
kind='channel',
|
||||
directory=channel_dir,
|
||||
tag_id=edu_tag.id,
|
||||
)
|
||||
test_session.add(collection)
|
||||
test_session.flush([collection])
|
||||
|
||||
channel = Channel(
|
||||
collection_id=collection.id,
|
||||
url='https://example.com/techchannel',
|
||||
)
|
||||
test_session.add(channel)
|
||||
test_session.commit()
|
||||
|
||||
# Create video in year subdirectory
|
||||
year_dir = channel_dir / '2026'
|
||||
year_dir.mkdir(parents=True, exist_ok=True)
|
||||
video_path = year_dir / '2026-01-01_Tagged Video.mp4'
|
||||
video_file.rename(video_path)
|
||||
|
||||
await refresh_files()
|
||||
|
||||
# Verify video was associated with tagged channel
|
||||
video = test_session.query(Video).join(Video.file_group).filter(
|
||||
Video.file_group.has(primary_path=str(video_path))
|
||||
).one_or_none()
|
||||
|
||||
assert video is not None
|
||||
assert video.channel_id == channel.id, \
|
||||
f'Video should be associated with tagged channel, got channel_id={video.channel_id}'
|
||||
assert video.channel.tag_name == 'education', \
|
||||
f'Channel should have education tag, got {video.channel.tag_name}'
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestGeneratePostersWithYearSubdirs:
|
||||
"""Tests for generate_posters setting with year subdirectories."""
|
||||
|
||||
async def test_generate_posters_year_subdirectory(
|
||||
self, async_client, test_session, test_directory, video_file, refresh_files):
|
||||
"""
|
||||
Bug test: When videos are in year subdirectories, the channel's
|
||||
generate_posters setting should still be applied.
|
||||
|
||||
Currently fails because Video.validate() can't find the channel
|
||||
(exact directory match), so generate_posters defaults to False.
|
||||
"""
|
||||
# Create channel with generate_posters=True
|
||||
channel_dir = test_directory / 'videos' / 'PosterChannel'
|
||||
channel_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
collection = Collection(
|
||||
name='PosterChannel',
|
||||
kind='channel',
|
||||
directory=channel_dir,
|
||||
)
|
||||
test_session.add(collection)
|
||||
test_session.flush([collection])
|
||||
|
||||
channel = Channel(
|
||||
collection_id=collection.id,
|
||||
url='https://example.com/posterchannel',
|
||||
generate_posters=True,
|
||||
)
|
||||
test_session.add(channel)
|
||||
test_session.commit()
|
||||
|
||||
# Create video in year subdirectory
|
||||
year_dir = channel_dir / '2026'
|
||||
year_dir.mkdir(parents=True, exist_ok=True)
|
||||
video_path = year_dir / '2026-01-01_Poster Video.mp4'
|
||||
video_file.rename(video_path)
|
||||
|
||||
await refresh_files()
|
||||
|
||||
video = test_session.query(Video).join(Video.file_group).filter(
|
||||
Video.file_group.has(primary_path=str(video_path))
|
||||
).one_or_none()
|
||||
|
||||
assert video is not None
|
||||
# BUG: Video should be in channel with generate_posters=True
|
||||
# But validate() can't find channel, so posters won't be generated
|
||||
assert video.channel_id == channel.id, \
|
||||
f'Video should be in channel to get generate_posters setting, got channel_id={video.channel_id}'
|
||||
|
||||
async def test_generate_posters_timing_issue(
|
||||
self, async_client, test_session, test_directory, video_file, refresh_files):
|
||||
"""
|
||||
Bug test: Poster generation happens DURING validate_video(),
|
||||
but channel association happens AFTER via video_cleanup().
|
||||
|
||||
This means videos in year subdirectories don't get posters
|
||||
generated even when channel.generate_posters=True.
|
||||
|
||||
The channel is found at validation time only via:
|
||||
1. get_channel(directory=video_path.parent) - exact match, fails for subdirs
|
||||
2. Channel.get_by_path(video_path.parent) - exact match, fails for subdirs
|
||||
|
||||
Both use exact directory matching which doesn't handle subdirectories.
|
||||
"""
|
||||
# Create channel with generate_posters=True
|
||||
channel_dir = test_directory / 'videos' / 'TimingChannel'
|
||||
channel_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
collection = Collection(
|
||||
name='TimingChannel',
|
||||
kind='channel',
|
||||
directory=channel_dir,
|
||||
)
|
||||
test_session.add(collection)
|
||||
test_session.flush([collection])
|
||||
|
||||
channel = Channel(
|
||||
collection_id=collection.id,
|
||||
url='https://example.com/timingchannel',
|
||||
generate_posters=True, # Should generate posters
|
||||
)
|
||||
test_session.add(channel)
|
||||
test_session.commit()
|
||||
|
||||
# Create video in year subdirectory (WITHOUT existing poster)
|
||||
year_dir = channel_dir / '2026'
|
||||
year_dir.mkdir(parents=True, exist_ok=True)
|
||||
video_path = year_dir / '2026-01-01_No Poster Video.mp4'
|
||||
video_file.rename(video_path)
|
||||
|
||||
# Verify no poster exists before refresh
|
||||
expected_poster = video_path.with_suffix('.jpg')
|
||||
assert not expected_poster.exists(), 'Poster should not exist before refresh'
|
||||
|
||||
await refresh_files()
|
||||
|
||||
video = test_session.query(Video).join(Video.file_group).filter(
|
||||
Video.file_group.has(primary_path=str(video_path))
|
||||
).one_or_none()
|
||||
|
||||
assert video is not None
|
||||
assert video.channel_id == channel.id, 'Video should be in channel after cleanup'
|
||||
assert video.channel.generate_posters is True, 'Channel should have generate_posters=True'
|
||||
|
||||
# BUG: Poster should have been generated because channel.generate_posters=True
|
||||
# But during validate_video(), channel wasn't found (exact match failed),
|
||||
# so generate_posters defaulted to False and poster wasn't generated.
|
||||
# By the time video_cleanup() assigns the channel, validation is already done.
|
||||
assert video.poster_path is not None, \
|
||||
'Poster should have been generated because channel.generate_posters=True'
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestChannelGetByPathWithSubdirs:
|
||||
"""Tests for Channel.get_by_path() with subdirectories."""
|
||||
|
||||
async def test_get_by_path_exact_match(
|
||||
self, async_client, test_session, test_directory):
|
||||
"""
|
||||
Channel.get_by_path() should find channel with exact directory match.
|
||||
This is the current expected behavior.
|
||||
"""
|
||||
channel_dir = test_directory / 'videos' / 'ExactChannel'
|
||||
channel_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
collection = Collection(
|
||||
name='ExactChannel',
|
||||
kind='channel',
|
||||
directory=channel_dir,
|
||||
)
|
||||
test_session.add(collection)
|
||||
test_session.flush([collection])
|
||||
|
||||
channel = Channel(
|
||||
collection_id=collection.id,
|
||||
url='https://example.com/exactchannel',
|
||||
)
|
||||
test_session.add(channel)
|
||||
test_session.commit()
|
||||
|
||||
# Exact match should work
|
||||
found_channel = Channel.get_by_path(test_session, channel_dir)
|
||||
assert found_channel is not None
|
||||
assert found_channel.id == channel.id
|
||||
|
||||
async def test_get_by_path_year_subdirectory_fails(
|
||||
self, async_client, test_session, test_directory):
|
||||
"""
|
||||
Bug demonstration: Channel.get_by_path() with year subdirectory
|
||||
returns None because it uses exact match.
|
||||
|
||||
This is the root cause of videos in year subdirs not being
|
||||
associated with their channels during validate().
|
||||
"""
|
||||
channel_dir = test_directory / 'videos' / 'SubdirChannel'
|
||||
channel_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
collection = Collection(
|
||||
name='SubdirChannel',
|
||||
kind='channel',
|
||||
directory=channel_dir,
|
||||
)
|
||||
test_session.add(collection)
|
||||
test_session.flush([collection])
|
||||
|
||||
channel = Channel(
|
||||
collection_id=collection.id,
|
||||
url='https://example.com/subdirchannel',
|
||||
)
|
||||
test_session.add(channel)
|
||||
test_session.commit()
|
||||
|
||||
# Year subdirectory lookup should find the parent channel
|
||||
year_dir = channel_dir / '2026'
|
||||
year_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# BUG: This returns None because Channel.get_by_path uses exact match
|
||||
found_channel = Channel.get_by_path(test_session, year_dir)
|
||||
# Current behavior: returns None
|
||||
# Expected behavior: should find channel at parent directory
|
||||
assert found_channel is not None, \
|
||||
'Channel.get_by_path should find channel for year subdirectory'
|
||||
assert found_channel.id == channel.id
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestGetChannelWithSubdirs:
|
||||
"""Tests for get_channel() function with subdirectories."""
|
||||
|
||||
async def test_get_channel_by_directory_exact_match(
|
||||
self, async_client, test_session, test_directory):
|
||||
"""
|
||||
get_channel() with directory param finds channel with exact match.
|
||||
"""
|
||||
from modules.videos.channel.lib import get_channel
|
||||
|
||||
channel_dir = test_directory / 'videos' / 'GetChannelExact'
|
||||
channel_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
collection = Collection(
|
||||
name='GetChannelExact',
|
||||
kind='channel',
|
||||
directory=channel_dir,
|
||||
)
|
||||
test_session.add(collection)
|
||||
test_session.flush([collection])
|
||||
|
||||
channel = Channel(
|
||||
collection_id=collection.id,
|
||||
url='https://example.com/getchannelexact',
|
||||
)
|
||||
test_session.add(channel)
|
||||
test_session.commit()
|
||||
|
||||
# Exact match should work
|
||||
found_channel = get_channel(test_session, directory=str(channel_dir), return_dict=False)
|
||||
assert found_channel is not None
|
||||
assert found_channel.id == channel.id
|
||||
|
||||
async def test_get_channel_by_directory_year_subdirectory_fails(
|
||||
self, async_client, test_session, test_directory):
|
||||
"""
|
||||
Bug demonstration: get_channel() with directory param returns None
|
||||
for year subdirectories because it uses exact match.
|
||||
|
||||
This is called from validate_video() at line 122:
|
||||
directory=video.video_path.parent
|
||||
|
||||
For videos in year subdirs, video_path.parent is the year subdir,
|
||||
not the channel's root directory.
|
||||
"""
|
||||
from modules.videos.channel.lib import get_channel
|
||||
from modules.videos.errors import UnknownChannel
|
||||
|
||||
channel_dir = test_directory / 'videos' / 'GetChannelSubdir'
|
||||
channel_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
collection = Collection(
|
||||
name='GetChannelSubdir',
|
||||
kind='channel',
|
||||
directory=channel_dir,
|
||||
)
|
||||
test_session.add(collection)
|
||||
test_session.flush([collection])
|
||||
|
||||
channel = Channel(
|
||||
collection_id=collection.id,
|
||||
url='https://example.com/getchannelsubdir',
|
||||
)
|
||||
test_session.add(channel)
|
||||
test_session.commit()
|
||||
|
||||
# Year subdirectory lookup
|
||||
year_dir = channel_dir / '2026'
|
||||
year_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# BUG: This raises UnknownChannel because get_channel uses exact match
|
||||
# Expected: should find channel at parent directory
|
||||
try:
|
||||
found_channel = get_channel(test_session, directory=str(year_dir), return_dict=False)
|
||||
assert found_channel is not None, \
|
||||
'get_channel should find channel for year subdirectory'
|
||||
assert found_channel.id == channel.id
|
||||
except UnknownChannel:
|
||||
# This is the current buggy behavior - it raises UnknownChannel
|
||||
pytest.fail('get_channel should find channel for year subdirectory, but raised UnknownChannel')
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestConfigImportThenVideoModeling:
|
||||
"""Tests for config import followed by video modeling."""
|
||||
|
||||
async def test_config_import_then_video_modeling(
|
||||
self, async_client, test_session, test_directory, video_file,
|
||||
test_channels_config, refresh_files):
|
||||
"""
|
||||
Test full flow:
|
||||
1. Import channels config (creates channel)
|
||||
2. Create video files on disk in year subdirectory
|
||||
3. Run refresh (triggers modeling)
|
||||
4. Verify video is correctly associated with channel
|
||||
"""
|
||||
import yaml
|
||||
from modules.videos.lib import get_channels_config
|
||||
|
||||
config = get_channels_config()
|
||||
config_path = config.get_file()
|
||||
|
||||
# Create channel directory
|
||||
channel_dir = test_directory / 'videos' / 'ConfigChannel'
|
||||
channel_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Write channels config
|
||||
config_data = {
|
||||
'version': 0,
|
||||
'channels': [{
|
||||
'name': 'ConfigChannel',
|
||||
'directory': str(channel_dir),
|
||||
'url': 'https://example.com/configchannel',
|
||||
}]
|
||||
}
|
||||
with open(config_path, 'w') as f:
|
||||
yaml.dump(config_data, f)
|
||||
|
||||
# Import config
|
||||
config.initialize()
|
||||
config.import_config()
|
||||
|
||||
# Verify channel was created
|
||||
channel = test_session.query(Channel).join(Collection).filter(
|
||||
Collection.name == 'ConfigChannel'
|
||||
).one_or_none()
|
||||
assert channel is not None
|
||||
|
||||
# Create video in year subdirectory
|
||||
year_dir = channel_dir / '2026'
|
||||
year_dir.mkdir(parents=True, exist_ok=True)
|
||||
video_path = year_dir / '2026-01-01_Config Video.mp4'
|
||||
video_file.rename(video_path)
|
||||
|
||||
# Run refresh to trigger video modeling
|
||||
await refresh_files()
|
||||
|
||||
# Video should be associated with channel
|
||||
video = test_session.query(Video).join(Video.file_group).filter(
|
||||
Video.file_group.has(primary_path=str(video_path))
|
||||
).one_or_none()
|
||||
|
||||
assert video is not None
|
||||
# This might pass because claim_videos_for_channels() runs after import
|
||||
# But if it runs during validate(), it will fail
|
||||
assert video.channel_id == channel.id, \
|
||||
f'Video should be associated with channel after config import, got channel_id={video.channel_id}'
|
||||
|
||||
async def test_video_before_config_import(
|
||||
self, async_client, test_session, test_directory, video_file,
|
||||
test_channels_config, refresh_files):
|
||||
"""
|
||||
Test when videos exist before channel config is imported.
|
||||
1. Create video files in year subdirectory
|
||||
2. Run refresh (video gets modeled without channel)
|
||||
3. Import channels config
|
||||
4. Verify video gets associated with channel via claim_videos_for_channels
|
||||
"""
|
||||
import yaml
|
||||
from modules.videos.lib import get_channels_config
|
||||
|
||||
# Create video in what will be the channel's year subdirectory
|
||||
channel_dir = test_directory / 'videos' / 'LateChannel'
|
||||
year_dir = channel_dir / '2026'
|
||||
year_dir.mkdir(parents=True, exist_ok=True)
|
||||
video_path = year_dir / '2026-01-01_Early Video.mp4'
|
||||
video_file.rename(video_path)
|
||||
|
||||
# Run refresh BEFORE channel config import
|
||||
await refresh_files()
|
||||
|
||||
# Video exists but has no channel
|
||||
video = test_session.query(Video).join(Video.file_group).filter(
|
||||
Video.file_group.has(primary_path=str(video_path))
|
||||
).one_or_none()
|
||||
assert video is not None
|
||||
assert video.channel_id is None, 'Video should not have channel before config import'
|
||||
|
||||
# Now import channel config
|
||||
config = get_channels_config()
|
||||
config_path = config.get_file()
|
||||
|
||||
config_data = {
|
||||
'version': 0,
|
||||
'channels': [{
|
||||
'name': 'LateChannel',
|
||||
'directory': str(channel_dir),
|
||||
'url': 'https://example.com/latechannel',
|
||||
}]
|
||||
}
|
||||
with open(config_path, 'w') as f:
|
||||
yaml.dump(config_data, f)
|
||||
|
||||
config.initialize()
|
||||
config.import_config()
|
||||
|
||||
# Refresh video from DB
|
||||
test_session.expire(video)
|
||||
|
||||
# Video should now be associated with channel via claim_videos_for_channels
|
||||
assert video.channel_id is not None, \
|
||||
'Video should be claimed by channel after config import'
|
||||
|
||||
channel = test_session.query(Channel).join(Collection).filter(
|
||||
Collection.name == 'LateChannel'
|
||||
).one()
|
||||
assert video.channel_id == channel.id
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestVideoCleanupWithYearSubdirs:
|
||||
"""Tests for video_cleanup() handling of year subdirectories."""
|
||||
|
||||
async def test_video_cleanup_claims_videos_in_year_subdirs(
|
||||
self, async_client, test_session, test_directory, video_file, refresh_files):
|
||||
"""
|
||||
Test that video_cleanup() correctly claims videos in year subdirectories.
|
||||
|
||||
video_cleanup uses SQL with LIKE clause which should handle subdirs:
|
||||
fg.directory LIKE col.directory || '/%'
|
||||
"""
|
||||
from modules.videos import video_cleanup
|
||||
|
||||
# Create channel
|
||||
channel_dir = test_directory / 'videos' / 'CleanupChannel'
|
||||
channel_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
collection = Collection(
|
||||
name='CleanupChannel',
|
||||
kind='channel',
|
||||
directory=channel_dir,
|
||||
)
|
||||
test_session.add(collection)
|
||||
test_session.flush([collection])
|
||||
|
||||
channel = Channel(
|
||||
collection_id=collection.id,
|
||||
url='https://example.com/cleanupchannel',
|
||||
)
|
||||
test_session.add(channel)
|
||||
test_session.commit()
|
||||
|
||||
# Create video in year subdirectory
|
||||
year_dir = channel_dir / '2026'
|
||||
year_dir.mkdir(parents=True, exist_ok=True)
|
||||
video_path = year_dir / '2026-01-01_Cleanup Video.mp4'
|
||||
video_file.rename(video_path)
|
||||
|
||||
# Run refresh to create video record
|
||||
await refresh_files()
|
||||
|
||||
video = test_session.query(Video).join(Video.file_group).filter(
|
||||
Video.file_group.has(primary_path=str(video_path))
|
||||
).one_or_none()
|
||||
assert video is not None
|
||||
|
||||
# Note: After refresh, video.channel_id might already be set
|
||||
# if claim_videos_for_channels ran. Let's clear it to test video_cleanup
|
||||
video.channel_id = None
|
||||
test_session.commit()
|
||||
|
||||
# Run video_cleanup
|
||||
video_cleanup()
|
||||
|
||||
# Refresh from DB
|
||||
test_session.expire(video)
|
||||
|
||||
# video_cleanup should claim the video via LIKE clause
|
||||
assert video.channel_id == channel.id, \
|
||||
f'video_cleanup should claim video in year subdir, got channel_id={video.channel_id}'
|
||||
Loading…
Add table
Add a link
Reference in a new issue