mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-12-02 12:56:24 -05:00
Creating a new Collection model for use in organizing FileGroups.
Replacing Channels and Domains with Collection. Moving downloading relationships from Channel to Collection. Created domains.yaml config to manage tagged domain collections. Adding turn-key upgrade solution in the UI.
This commit is contained in:
parent
1f7b1c8744
commit
4fae4ae1b4
115 changed files with 13309 additions and 986 deletions
|
|
@ -5,14 +5,12 @@ from unittest.mock import patch
|
|||
import pytest
|
||||
|
||||
from modules.archive import lib, Archive
|
||||
from wrolpi.files.models import FileGroup
|
||||
from wrolpi.common import get_relative_to_media_directory
|
||||
from wrolpi.test.common import skip_circleci, skip_macos
|
||||
|
||||
from wrolpi.common import get_relative_to_media_directory
|
||||
|
||||
|
||||
def check_results(test_client, data, ids):
|
||||
request, response = test_client.post('/api/archive/search', content=json.dumps(data))
|
||||
async def check_results(async_client, data, ids):
|
||||
request, response = await async_client.post('/api/archive/search', content=json.dumps(data))
|
||||
if not response.status_code == HTTPStatus.OK:
|
||||
raise AssertionError(str(response.json))
|
||||
|
||||
|
|
@ -23,25 +21,27 @@ def check_results(test_client, data, ids):
|
|||
f'{response.json["file_groups"][0]["id"]}..{response.json["file_groups"][-1]["id"]}'
|
||||
|
||||
|
||||
def test_archives_search_order(test_session, archive_directory, archive_factory, test_client):
|
||||
@pytest.mark.asyncio
|
||||
async def test_archives_search_order(test_session, archive_directory, archive_factory, async_client):
|
||||
"""Search using all orders."""
|
||||
archive_factory('example.com', 'https://example.com/one', 'my archive', 'foo bar qux')
|
||||
for order_by in lib.ARCHIVE_ORDERS:
|
||||
data = {'search_str': 'foo', 'order_by': order_by}
|
||||
request, response = test_client.post('/api/archive/search', content=json.dumps(data))
|
||||
request, response = await async_client.post('/api/archive/search', content=json.dumps(data))
|
||||
if not response.status_code == HTTPStatus.OK:
|
||||
raise AssertionError(str(response.json))
|
||||
|
||||
data = {'search_str': None, 'order_by': order_by}
|
||||
request, response = test_client.post('/api/archive/search', content=json.dumps(data))
|
||||
request, response = await async_client.post('/api/archive/search', content=json.dumps(data))
|
||||
if not response.status_code == HTTPStatus.OK:
|
||||
raise AssertionError(str(response.json))
|
||||
|
||||
|
||||
def test_archives_search(test_session, archive_directory, archive_factory, test_client):
|
||||
@pytest.mark.asyncio
|
||||
async def test_archives_search(test_session, archive_directory, archive_factory, async_client):
|
||||
"""Archives can be searched by their title and their contents."""
|
||||
# Search with no archives.
|
||||
check_results(test_client, {'search_str': 'foo'}, [])
|
||||
await check_results(async_client, {'search_str': 'foo'}, [])
|
||||
|
||||
archive_factory('example.com', 'https://example.com/one', 'my archive', 'foo bar qux')
|
||||
archive_factory('example.com', 'https://example.com/one', 'other archive', 'foo baz qux qux')
|
||||
|
|
@ -51,38 +51,38 @@ def test_archives_search(test_session, archive_directory, archive_factory, test_
|
|||
|
||||
# 1 and 2 contain "foo".
|
||||
data = {'search_str': 'foo'}
|
||||
check_results(test_client, data, [2, 1])
|
||||
await check_results(async_client, data, [2, 1])
|
||||
|
||||
# 2 and 3 contain "baz".
|
||||
data = {'search_str': 'baz'}
|
||||
check_results(test_client, data, [3, 2])
|
||||
await check_results(async_client, data, [3, 2])
|
||||
|
||||
# 1 contains "bar".
|
||||
data = {'search_str': 'bar'}
|
||||
check_results(test_client, data, [1, ])
|
||||
await check_results(async_client, data, [1, ])
|
||||
|
||||
# No archives contain "huzzah"
|
||||
data = {'search_str': 'huzzah'}
|
||||
check_results(test_client, data, [])
|
||||
await check_results(async_client, data, [])
|
||||
|
||||
# Only 3 contains "baz" and is in domain "example.org"
|
||||
data = {'search_str': 'baz', 'domain': 'example.org'}
|
||||
check_results(test_client, data, [3, ])
|
||||
await check_results(async_client, data, [3, ])
|
||||
|
||||
# 1's title contains "my", this is ignored by Postgres.
|
||||
data = {'search_str': 'my'}
|
||||
check_results(test_client, data, [])
|
||||
await check_results(async_client, data, [])
|
||||
|
||||
# 3's title contains "third".
|
||||
data = {'search_str': 'third'}
|
||||
check_results(test_client, data, [3, ])
|
||||
await check_results(async_client, data, [3, ])
|
||||
|
||||
# All contents contain "qux", but they contain different amounts. They are ordered by the amount.
|
||||
data = {'search_str': 'qux'}
|
||||
check_results(test_client, data, [3, 2, 1])
|
||||
await check_results(async_client, data, [3, 2, 1])
|
||||
|
||||
data = {'search_str': 'qux', 'order_by': 'bad order_by'}
|
||||
request, response = test_client.post('/api/archive/search', content=json.dumps(data))
|
||||
request, response = await async_client.post('/api/archive/search', content=json.dumps(data))
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST
|
||||
|
||||
|
||||
|
|
@ -106,7 +106,8 @@ async def test_search_archive_tags(test_session, async_client, archive_factory,
|
|||
assert response.json['totals']['file_groups'] == 0
|
||||
|
||||
|
||||
def test_archives_search_headline(test_session, archive_directory, archive_factory, test_client):
|
||||
@pytest.mark.asyncio
|
||||
async def test_archives_search_headline(test_session, archive_directory, archive_factory, async_client):
|
||||
"""Headlines can be requested."""
|
||||
archive_factory('example.com', 'https://example.com/one', 'my archive', 'foo bar qux')
|
||||
archive_factory('example.com', 'https://example.com/one', 'other archive', 'foo baz qux qux')
|
||||
|
|
@ -115,7 +116,7 @@ def test_archives_search_headline(test_session, archive_directory, archive_facto
|
|||
test_session.commit()
|
||||
|
||||
content = dict(search_str='foo')
|
||||
request, response = test_client.post('/api/archive/search', content=json.dumps(content))
|
||||
request, response = await async_client.post('/api/archive/search', content=json.dumps(content))
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
|
||||
# Headlines are only fetched if requested.
|
||||
|
|
@ -123,7 +124,7 @@ def test_archives_search_headline(test_session, archive_directory, archive_facto
|
|||
assert response.json['file_groups'][1]['d_headline'] is None
|
||||
|
||||
content = dict(search_str='foo', headline=True)
|
||||
request, response = test_client.post('/api/archive/search', content=json.dumps(content))
|
||||
request, response = await async_client.post('/api/archive/search', content=json.dumps(content))
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
|
||||
# Postgresql uses <b>...</b> to highlight matching words.
|
||||
|
|
@ -131,25 +132,27 @@ def test_archives_search_headline(test_session, archive_directory, archive_facto
|
|||
assert response.json['file_groups'][1]['d_headline'] == '<b>foo</b> bar qux'
|
||||
|
||||
|
||||
def test_search_offset(test_session, archive_factory, test_client):
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_offset(test_session, archive_factory, async_client):
|
||||
"""Archive search can be offset."""
|
||||
for i in range(500):
|
||||
archive_factory('example.com', f'https://example.com/{i}', contents='foo bar')
|
||||
test_session.commit()
|
||||
|
||||
data = {'search_str': None, 'offset': 0}
|
||||
check_results(test_client, data, list(range(500, 480, -1)))
|
||||
await check_results(async_client, data, list(range(500, 480, -1)))
|
||||
data = {'search_str': None, 'offset': 20}
|
||||
check_results(test_client, data, list(range(480, 460, -1)))
|
||||
await check_results(async_client, data, list(range(480, 460, -1)))
|
||||
data = {'search_str': None, 'offset': 100}
|
||||
check_results(test_client, data, list(range(400, 380, -1)))
|
||||
await check_results(async_client, data, list(range(400, 380, -1)))
|
||||
data = {'search_str': None, 'offset': 200}
|
||||
check_results(test_client, data, list(range(300, 280, -1)))
|
||||
await check_results(async_client, data, list(range(300, 280, -1)))
|
||||
data = {'search_str': None, 'offset': 500}
|
||||
check_results(test_client, data, [])
|
||||
await check_results(async_client, data, [])
|
||||
|
||||
|
||||
def test_archives_search_no_query(test_session, archive_factory, test_client):
|
||||
@pytest.mark.asyncio
|
||||
async def test_archives_search_no_query(test_session, archive_factory, async_client):
|
||||
"""Archive Search API endpoint does not require data in the body."""
|
||||
# Add 100 random archives.
|
||||
for _ in range(100):
|
||||
|
|
@ -157,83 +160,26 @@ def test_archives_search_no_query(test_session, archive_factory, test_client):
|
|||
test_session.commit()
|
||||
|
||||
# All archives are returned when no `search_str` is passed.
|
||||
request, response = test_client.post('/api/archive/search', content='{}')
|
||||
request, response = await async_client.post('/api/archive/search', content='{}')
|
||||
assert response.status_code == HTTPStatus.OK, response.json
|
||||
assert [i['id'] for i in response.json['file_groups']] == list(range(100, 80, -1))
|
||||
assert response.json['totals']['file_groups'] == 100
|
||||
|
||||
# All archives are from "example.com".
|
||||
data = dict(domain='example.com')
|
||||
request, response = test_client.post('/api/archive/search', content=json.dumps(data))
|
||||
request, response = await async_client.post('/api/archive/search', content=json.dumps(data))
|
||||
assert response.status_code == HTTPStatus.OK, response.json
|
||||
assert [i['id'] for i in response.json['file_groups']] == list(range(100, 80, -1))
|
||||
assert response.json['totals']['file_groups'] == 100
|
||||
|
||||
# No archives are from "example.org".
|
||||
data = dict(domain='example.org')
|
||||
request, response = test_client.post('/api/archive/search', content=json.dumps(data))
|
||||
request, response = await async_client.post('/api/archive/search', content=json.dumps(data))
|
||||
assert response.status_code == HTTPStatus.OK, response.json
|
||||
assert [i['id'] for i in response.json['file_groups']] == []
|
||||
assert response.json['totals']['file_groups'] == 0
|
||||
|
||||
|
||||
def test_archive_and_domain_crud(test_session, test_client, archive_factory):
|
||||
"""Getting an Archive returns it's File. Testing deleting Archives."""
|
||||
# Can get empty results.
|
||||
request, response = test_client.get(f'/api/archive/1')
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND
|
||||
request, response = test_client.get(f'/api/archive/domains')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['domains'] == []
|
||||
|
||||
archive1 = archive_factory(domain='example.com', url='https://example.com/1')
|
||||
archive2 = archive_factory(domain='example.com', url='https://example.com/1')
|
||||
test_session.commit()
|
||||
|
||||
# Archive1 has Archive2 as history.
|
||||
request, response = test_client.get(f'/api/archive/{archive1.id}')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['file_group']['id'] == archive1.id
|
||||
assert response.json['history'][0]['id'] == archive2.id
|
||||
|
||||
# Archive2 has Archive1 as history.
|
||||
request, response = test_client.get(f'/api/archive/{archive2.id}')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert archive2.id == response.json['file_group']['id']
|
||||
assert response.json['history'][0]['id'] == archive1.id
|
||||
|
||||
# Only one domain.
|
||||
request, response = test_client.get(f'/api/archive/domains')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['domains'][0]['domain'] == 'example.com'
|
||||
assert response.json['domains'][0]['size'] == 254
|
||||
|
||||
# Deleting works.
|
||||
request, response = test_client.delete(f'/api/archive/{archive1.id}')
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT
|
||||
|
||||
# Trying to delete again returns NOT_FOUND.
|
||||
request, response = test_client.delete(f'/api/archive/{archive1.id}')
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND
|
||||
|
||||
# Can't get deleted Archive.
|
||||
request, response = test_client.get(f'/api/archive/{archive1.id}')
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND
|
||||
|
||||
# Archive2 no longer has history.
|
||||
request, response = test_client.get(f'/api/archive/{archive2.id}')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['file_group']['id'] == archive2.id
|
||||
assert response.json['history'] == []
|
||||
|
||||
# No Archives, no Domains.
|
||||
request, response = test_client.delete(f'/api/archive/{archive2.id}')
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT
|
||||
request, response = test_client.get(f'/api/archive/domains')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['domains'] == []
|
||||
|
||||
|
||||
@skip_macos
|
||||
@skip_circleci
|
||||
@pytest.mark.asyncio
|
||||
|
|
@ -356,7 +302,8 @@ async def test_archive_upload_file_tracking(test_session, async_client, archive_
|
|||
# Assert screenshot properties exist
|
||||
assert archive.screenshot_path is not None, 'Archive.screenshot_path should exist'
|
||||
assert archive.screenshot_file is not None, 'Archive.screenshot_file should exist'
|
||||
assert archive.file_group.data.get('screenshot_path') == archive.screenshot_path, 'Archive screenshot should be in FileGroup.data'
|
||||
assert archive.file_group.data.get(
|
||||
'screenshot_path') == archive.screenshot_path, 'Archive screenshot should be in FileGroup.data'
|
||||
|
||||
# Assert image is in FileGroup.files
|
||||
file_paths = [f['path'] for f in archive.file_group.files]
|
||||
|
|
|
|||
139
modules/archive/test/test_collection_id_bug.py
Normal file
139
modules/archive/test/test_collection_id_bug.py
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
"""Test for collection_id bug when modeling archives from discovered files.
|
||||
|
||||
This test reproduces the bug where Archives created by model_archive()
|
||||
don't have collection_id set, causing a NOT NULL constraint violation.
|
||||
|
||||
The bug happens because:
|
||||
1. The archive_factory sets collection_id explicitly (masking the bug)
|
||||
2. But model_archive() (used in production) doesn't set collection_id
|
||||
3. This causes NULL constraint violations when indexing real files
|
||||
"""
|
||||
import pathlib
|
||||
|
||||
import pytest
|
||||
|
||||
from modules.archive import model_archive
|
||||
from modules.archive.lib import archive_strftime
|
||||
from wrolpi.collections import Collection
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_model_archive_sets_collection_id(async_client, test_session, test_directory, make_files_structure):
|
||||
"""
|
||||
Test that model_archive() creates Archives with collection_id set.
|
||||
|
||||
This test uses model_archive() (the production code path) instead of
|
||||
archive_factory, so it will detect the collection_id bug.
|
||||
"""
|
||||
import datetime
|
||||
import pytz
|
||||
|
||||
# Create archive files with a URL in the singlefile
|
||||
domain = 'example.com'
|
||||
url = f'https://{domain}/test-page'
|
||||
archive_dir = test_directory / 'archives' / domain
|
||||
archive_dir.mkdir(parents=True)
|
||||
|
||||
timestamp = archive_strftime(datetime.datetime(2000, 1, 1, 0, 0, 0).astimezone(pytz.UTC))
|
||||
title = 'Test Page'
|
||||
|
||||
# Create a minimal singlefile with URL embedded (note trailing space after SingleFile)
|
||||
singlefile_content = f'''<!DOCTYPE html> <html lang="en"><!--
|
||||
Page saved with SingleFile
|
||||
url: {url}
|
||||
saved date: Mon May 16 2022 23:51:35 GMT+0000 (Coordinated Universal Time)
|
||||
--><head><meta charset="utf-8">
|
||||
<meta name="generator" content="SingleFile">
|
||||
<title>{title}</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>{title}</h1>
|
||||
<p>Test content</p>
|
||||
</body>
|
||||
</html>'''
|
||||
|
||||
files = make_files_structure({
|
||||
str(archive_dir / f'{timestamp}_{title}.html'): singlefile_content.strip(),
|
||||
str(archive_dir / f'{timestamp}_{title}.readability.json'): '{"title": "' + title + '"}',
|
||||
})
|
||||
|
||||
from wrolpi.files.models import FileGroup
|
||||
|
||||
# Create FileGroup from the files (simulating what refresh does)
|
||||
file_paths = [pathlib.Path(f) for f in files]
|
||||
file_group = FileGroup.from_paths(test_session, *file_paths)
|
||||
|
||||
# Model the archive using the production code path
|
||||
# This should create an Archive with collection_id set
|
||||
archive = model_archive(file_group, session=test_session)
|
||||
|
||||
# The bug: collection_id is None, causing NOT NULL constraint violation
|
||||
assert archive is not None, "Archive should be created"
|
||||
assert archive.collection_id is not None, \
|
||||
"Archive.collection_id should be set (this is the bug!)"
|
||||
|
||||
# Verify the collection was created
|
||||
collection = test_session.query(Collection).filter_by(
|
||||
name=domain,
|
||||
kind='domain'
|
||||
).one_or_none()
|
||||
|
||||
assert collection is not None, "Domain collection should be created"
|
||||
assert archive.collection_id == collection.id, \
|
||||
"Archive should be linked to the domain collection"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_model_archive_extracts_url_from_singlefile(async_client, test_session, test_directory, make_files_structure):
|
||||
"""
|
||||
Test that model_archive() can extract URL from singlefile when file_group.url is None.
|
||||
|
||||
This is the second part of the fix - if the URL isn't in the file_group yet,
|
||||
we need to extract it from the singlefile content.
|
||||
"""
|
||||
import datetime
|
||||
import pytz
|
||||
|
||||
# Create archive files
|
||||
domain = 'test.org'
|
||||
url = f'https://{domain}/article'
|
||||
archive_dir = test_directory / 'archives' / domain
|
||||
archive_dir.mkdir(parents=True)
|
||||
|
||||
timestamp = archive_strftime(datetime.datetime(2000, 1, 1, 0, 0, 0).astimezone(pytz.UTC))
|
||||
|
||||
# Create singlefile with URL in saved-from comment
|
||||
singlefile_content = f'''<!DOCTYPE html> <html lang="en"><!--
|
||||
Page saved with SingleFile
|
||||
url: {url}
|
||||
saved date: Mon May 16 2022 23:51:35 GMT+0000 (Coordinated Universal Time)
|
||||
--><head><meta charset="utf-8">
|
||||
<meta name="generator" content="SingleFile">
|
||||
<title>Test Article</title>
|
||||
</head>
|
||||
<body><p>Content</p></body>
|
||||
</html>'''
|
||||
|
||||
files = make_files_structure({
|
||||
str(archive_dir / f'{timestamp}_Test.html'): singlefile_content.strip(),
|
||||
})
|
||||
|
||||
from wrolpi.files.models import FileGroup
|
||||
|
||||
# Create FileGroup from the files (simulating what refresh does)
|
||||
file_paths = [pathlib.Path(f) for f in files]
|
||||
file_group = FileGroup.from_paths(test_session, *file_paths)
|
||||
|
||||
# Model the archive - it should extract the URL from the singlefile
|
||||
archive = model_archive(file_group, session=test_session)
|
||||
|
||||
assert archive is not None
|
||||
assert archive.file_group.url == url, \
|
||||
"URL should be extracted from singlefile content"
|
||||
assert archive.collection_id is not None, \
|
||||
"collection_id should be set after URL extraction"
|
||||
|
||||
# Verify collection was created with correct domain
|
||||
collection = test_session.query(Collection).get(archive.collection_id)
|
||||
assert collection.name == domain
|
||||
assert collection.kind == 'domain'
|
||||
313
modules/archive/test/test_domain_tagging.py
Normal file
313
modules/archive/test/test_domain_tagging.py
Normal file
|
|
@ -0,0 +1,313 @@
|
|||
"""Tests for domain collection tagging functionality."""
|
||||
|
||||
import pytest
|
||||
|
||||
from wrolpi.collections import Collection
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_domain_collection_with_directory(test_session, test_directory):
|
||||
"""Domain collection can be created with a directory."""
|
||||
domain_dir = test_directory / 'archives' / 'example.com'
|
||||
domain_dir.mkdir(parents=True)
|
||||
|
||||
collection = Collection(
|
||||
name='example.com',
|
||||
kind='domain',
|
||||
directory=domain_dir
|
||||
)
|
||||
test_session.add(collection)
|
||||
test_session.commit()
|
||||
|
||||
assert collection.directory == domain_dir
|
||||
assert collection.can_be_tagged is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_unrestricted_domain_collection(test_session):
|
||||
"""Unrestricted domain collection (no directory) cannot be tagged."""
|
||||
collection = Collection(
|
||||
name='example.com',
|
||||
kind='domain',
|
||||
directory=None # Unrestricted
|
||||
)
|
||||
test_session.add(collection)
|
||||
test_session.commit()
|
||||
|
||||
assert collection.directory is None
|
||||
assert collection.can_be_tagged is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tag_domain_collection_with_directory(async_client, test_session, test_directory, tag_factory):
|
||||
"""Domain collection with directory can be tagged."""
|
||||
domain_dir = test_directory / 'archives' / 'example.com'
|
||||
domain_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
collection = Collection(
|
||||
name='example.com',
|
||||
kind='domain',
|
||||
directory=domain_dir
|
||||
)
|
||||
test_session.add(collection)
|
||||
tag = await tag_factory(name='News')
|
||||
test_session.commit()
|
||||
|
||||
# Tag the collection
|
||||
collection.set_tag('News')
|
||||
test_session.commit()
|
||||
|
||||
assert collection.tag is not None
|
||||
assert collection.tag.name == 'News'
|
||||
assert collection.tag_id == tag.id
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cannot_tag_unrestricted_domain_collection(async_client, test_session, tag_factory):
|
||||
"""Domain collection without directory cannot be tagged."""
|
||||
collection = Collection(
|
||||
name='example.com',
|
||||
kind='domain',
|
||||
directory=None # Unrestricted
|
||||
)
|
||||
test_session.add(collection)
|
||||
tag = await tag_factory(name='News')
|
||||
test_session.commit()
|
||||
|
||||
assert collection.can_be_tagged is False
|
||||
|
||||
with pytest.raises(ValueError, match='Cannot tag domain collection.*without a directory'):
|
||||
collection.set_tag('News')
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tag_domain_collection_moves_files(
|
||||
test_session, archive_factory, tag_factory, test_directory, make_files_structure, archive_directory,
|
||||
await_switches,
|
||||
):
|
||||
"""Tagging domain collection with directory moves archive files."""
|
||||
# Create domain collection with directory
|
||||
# Use archive_directory fixture to match where archive_factory creates files
|
||||
domain_dir = archive_directory / 'test.com'
|
||||
domain_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
collection = Collection(
|
||||
name='test.com',
|
||||
kind='domain',
|
||||
directory=domain_dir
|
||||
)
|
||||
test_session.add(collection)
|
||||
test_session.flush()
|
||||
|
||||
# Create archives in domain directory
|
||||
archive1 = archive_factory(domain='test.com')
|
||||
archive2 = archive_factory(domain='test.com')
|
||||
archive1.collection = collection
|
||||
archive2.collection = collection
|
||||
test_session.commit()
|
||||
|
||||
# Get file paths before move
|
||||
old_paths = []
|
||||
for archive in [archive1, archive2]:
|
||||
for path in archive.my_paths():
|
||||
old_paths.append(path)
|
||||
|
||||
assert all(p.is_file() for p in old_paths), "Files should exist before move"
|
||||
|
||||
# Create tag and assign to collection
|
||||
tag = await tag_factory(name='Tech')
|
||||
collection.set_tag('Tech')
|
||||
test_session.commit()
|
||||
|
||||
# Compute new directory and move collection
|
||||
new_directory = collection.format_directory('Tech')
|
||||
# Create the destination directory before moving
|
||||
new_directory.mkdir(parents=True, exist_ok=True)
|
||||
await collection.move_collection(new_directory, test_session)
|
||||
|
||||
# Verify files moved
|
||||
assert new_directory.is_dir(), "New directory should exist"
|
||||
assert 'Tech' in str(new_directory), "New directory should contain tag name"
|
||||
assert 'test.com' in str(new_directory), "New directory should contain domain name"
|
||||
|
||||
# Old paths should no longer exist
|
||||
for old_path in old_paths:
|
||||
assert not old_path.is_file(), f"Old file should be moved: {old_path}"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_domain_config_with_directory_and_tag(test_session, test_directory, tag_factory, async_client):
|
||||
"""Domain config can include directory and tag_name."""
|
||||
from modules.archive.lib import DomainsConfig
|
||||
|
||||
# Create config file
|
||||
config_file = test_directory / 'domains.yaml'
|
||||
config_file.write_text("""
|
||||
collections:
|
||||
- name: "example.com"
|
||||
kind: "domain"
|
||||
description: "News from example.com"
|
||||
directory: "archives/example.com"
|
||||
tag_name: "News"
|
||||
""")
|
||||
|
||||
# Create tag first
|
||||
tag = await tag_factory(name='News')
|
||||
test_session.commit()
|
||||
|
||||
# Import config
|
||||
domains_config = DomainsConfig()
|
||||
domains_config.import_config(config_file)
|
||||
|
||||
# Verify collection created with directory and tag
|
||||
collection = test_session.query(Collection).filter_by(
|
||||
name='example.com',
|
||||
kind='domain'
|
||||
).one()
|
||||
|
||||
assert collection.directory is not None
|
||||
assert 'example.com' in str(collection.directory)
|
||||
assert collection.tag is not None
|
||||
assert collection.tag.name == 'News'
|
||||
assert collection.can_be_tagged is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_domain_config_warns_tag_without_directory(test_session, test_directory, tag_factory, caplog,
|
||||
async_client):
|
||||
"""Config warns when tag_name provided without directory."""
|
||||
from modules.archive.lib import DomainsConfig
|
||||
|
||||
# Create config file with tag but no directory
|
||||
config_file = test_directory / 'domains.yaml'
|
||||
config_file.write_text("""
|
||||
collections:
|
||||
- name: "example.com"
|
||||
kind: "domain"
|
||||
tag_name: "News"
|
||||
""")
|
||||
|
||||
# Create tag first
|
||||
tag = await tag_factory(name='News')
|
||||
test_session.commit()
|
||||
|
||||
# Import config
|
||||
domains_config = DomainsConfig()
|
||||
domains_config.import_config(config_file)
|
||||
|
||||
# Verify collection created without tag
|
||||
collection = test_session.query(Collection).filter_by(
|
||||
name='example.com',
|
||||
kind='domain'
|
||||
).one()
|
||||
|
||||
assert collection.directory is None
|
||||
assert collection.tag is None # Tag ignored
|
||||
assert collection.can_be_tagged is False
|
||||
|
||||
# Check warning was logged
|
||||
assert "tags require a directory" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_domain_config_export_includes_directory_and_tag(test_session, test_directory, tag_factory, async_client):
|
||||
"""Exporting domain config includes directory and tag_name."""
|
||||
from modules.archive.lib import DomainsConfig
|
||||
from wrolpi.common import get_media_directory
|
||||
import yaml
|
||||
|
||||
# Create domain collection with directory and tag
|
||||
domain_dir = get_media_directory() / 'archives' / 'news.com'
|
||||
domain_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
collection = Collection(
|
||||
name='news.com',
|
||||
kind='domain',
|
||||
directory=domain_dir,
|
||||
description='News website'
|
||||
)
|
||||
test_session.add(collection)
|
||||
tag = await tag_factory(name='News')
|
||||
collection.set_tag('News')
|
||||
test_session.commit()
|
||||
|
||||
# Export config
|
||||
config_file = test_directory / 'domains.yaml'
|
||||
domains_config = DomainsConfig()
|
||||
domains_config.dump_config(config_file, overwrite=True)
|
||||
|
||||
# Read and verify exported config
|
||||
with open(config_file) as f:
|
||||
exported = yaml.safe_load(f)
|
||||
|
||||
assert len(exported['collections']) == 1
|
||||
domain_config = exported['collections'][0]
|
||||
assert domain_config['name'] == 'news.com'
|
||||
assert domain_config['kind'] == 'domain'
|
||||
assert 'archives/news.com' in domain_config['directory']
|
||||
assert domain_config['tag_name'] == 'News'
|
||||
assert domain_config['description'] == 'News website'
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_or_create_domain_collection_with_directory(test_session, test_directory):
|
||||
"""get_or_create_domain_collection can create collection with directory."""
|
||||
from modules.archive.lib import get_or_create_domain_collection
|
||||
from wrolpi.common import get_media_directory
|
||||
|
||||
domain_dir = get_media_directory() / 'archives' / 'test.com'
|
||||
domain_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Create with directory
|
||||
collection = get_or_create_domain_collection(
|
||||
test_session,
|
||||
'https://test.com/article',
|
||||
directory=domain_dir
|
||||
)
|
||||
|
||||
assert collection.name == 'test.com'
|
||||
assert collection.kind == 'domain'
|
||||
assert collection.directory == domain_dir
|
||||
assert collection.can_be_tagged is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_archive_destination_with_directory(test_session, test_directory):
|
||||
"""get_archive_destination returns collection directory when set."""
|
||||
from modules.archive.lib import get_archive_destination
|
||||
from wrolpi.common import get_media_directory
|
||||
|
||||
domain_dir = get_media_directory() / 'archives' / 'tagged' / 'example.com'
|
||||
domain_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
collection = Collection(
|
||||
name='example.com',
|
||||
kind='domain',
|
||||
directory=domain_dir
|
||||
)
|
||||
test_session.add(collection)
|
||||
test_session.commit()
|
||||
|
||||
destination = get_archive_destination(collection)
|
||||
|
||||
assert destination == domain_dir
|
||||
assert destination.is_dir()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_archive_destination_unrestricted(test_session):
|
||||
"""get_archive_destination returns default path for unrestricted collection."""
|
||||
from modules.archive.lib import get_archive_destination, get_archive_directory
|
||||
|
||||
collection = Collection(
|
||||
name='example.com',
|
||||
kind='domain',
|
||||
directory=None # Unrestricted
|
||||
)
|
||||
test_session.add(collection)
|
||||
test_session.commit()
|
||||
|
||||
destination = get_archive_destination(collection)
|
||||
expected = get_archive_directory() / 'example.com'
|
||||
|
||||
assert destination == expected
|
||||
|
|
@ -10,10 +10,11 @@ from PIL import Image
|
|||
from pytz import utc
|
||||
|
||||
from modules.archive import lib
|
||||
from modules.archive.lib import get_or_create_domain, get_new_archive_files, delete_archives, model_archive_result, \
|
||||
get_domains
|
||||
from modules.archive.models import Archive, Domain
|
||||
from modules.archive.lib import get_or_create_domain_collection, get_new_archive_files, delete_archives, \
|
||||
model_archive_result, get_domains
|
||||
from modules.archive.models import Archive
|
||||
from wrolpi.api_utils import CustomJSONEncoder
|
||||
from wrolpi.collections import Collection
|
||||
from wrolpi.common import get_wrolpi_config
|
||||
from wrolpi.db import get_db_session
|
||||
from wrolpi.files import lib as files_lib
|
||||
|
|
@ -37,7 +38,7 @@ def make_fake_archive_result(readability=True, screenshot=True, title=True):
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_screenshot(test_directory, test_session):
|
||||
async def test_no_screenshot(async_client, test_directory, test_session):
|
||||
singlefile, readability, screenshot = make_fake_archive_result(screenshot=False)
|
||||
archive = await model_archive_result('https://example.com', singlefile, readability, screenshot)
|
||||
assert isinstance(archive.singlefile_path, pathlib.Path)
|
||||
|
|
@ -47,7 +48,7 @@ async def test_no_screenshot(test_directory, test_session):
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_readability(test_directory, test_session):
|
||||
async def test_no_readability(async_client, test_directory, test_session):
|
||||
singlefile, readability, screenshot = make_fake_archive_result(readability=False)
|
||||
archive = await model_archive_result('https://example.com', singlefile, readability, screenshot)
|
||||
assert isinstance(archive.singlefile_path, pathlib.Path)
|
||||
|
|
@ -58,7 +59,7 @@ async def test_no_readability(test_directory, test_session):
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dict(test_session):
|
||||
async def test_dict(async_client, test_session, test_directory):
|
||||
singlefile, readability, screenshot = make_fake_archive_result()
|
||||
d = (await model_archive_result('https://example.com', singlefile, readability, screenshot)).dict()
|
||||
assert isinstance(d, dict)
|
||||
|
|
@ -66,17 +67,18 @@ async def test_dict(test_session):
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_relationships(test_session, example_singlefile):
|
||||
async def test_relationships(async_client, test_session, example_singlefile):
|
||||
with get_db_session(commit=True) as session:
|
||||
url = 'https://wrolpi.org:443'
|
||||
domain = get_or_create_domain(session, url)
|
||||
collection = get_or_create_domain_collection(session, url)
|
||||
archive = Archive.from_paths(test_session, example_singlefile)
|
||||
archive.url = url
|
||||
archive.domain_id = domain.id
|
||||
archive.collection_id = collection.id
|
||||
session.add(archive)
|
||||
session.flush()
|
||||
|
||||
assert archive.domain == domain
|
||||
assert archive.collection == collection
|
||||
assert archive.domain == 'wrolpi.org'
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
|
@ -119,8 +121,9 @@ async def test_archive_title(async_client, test_session, archive_factory, single
|
|||
assert archive1.file_group.title is None
|
||||
|
||||
|
||||
def test_archive_refresh_deleted_archive(test_client, test_session, archive_directory, archive_factory):
|
||||
"""Archives/Domains should be deleted when archive files are deleted."""
|
||||
@pytest.mark.asyncio
|
||||
async def test_archive_refresh_deleted_archive(async_client, test_session, archive_directory, archive_factory):
|
||||
"""Archives/domain collections should be deleted when archive files are deleted."""
|
||||
archive1 = archive_factory('example.com', 'https://example.com/1')
|
||||
archive2 = archive_factory('example.com', 'https://example.com/1')
|
||||
archive3 = archive_factory('example.com')
|
||||
|
|
@ -133,29 +136,30 @@ def test_archive_refresh_deleted_archive(test_client, test_session, archive_dire
|
|||
|
||||
def check_counts(archive_count, domain_count):
|
||||
assert test_session.query(Archive).count() == archive_count, 'Archive count does not match'
|
||||
assert test_session.query(Domain).count() == domain_count, 'Domain count does not match'
|
||||
assert test_session.query(Collection).filter_by(
|
||||
kind='domain').count() == domain_count, 'domain collection count does not match'
|
||||
|
||||
# All 5 archives are already in the DB.
|
||||
check_counts(archive_count=5, domain_count=2)
|
||||
test_client.post('/api/files/refresh')
|
||||
await async_client.post('/api/files/refresh')
|
||||
check_counts(archive_count=5, domain_count=1)
|
||||
|
||||
# Delete archive2's files, it's the latest for 'https://example.com/1'
|
||||
for path in archive2.my_paths():
|
||||
path.unlink()
|
||||
test_client.post('/api/files/refresh')
|
||||
await async_client.post('/api/files/refresh')
|
||||
check_counts(archive_count=4, domain_count=1)
|
||||
|
||||
# Delete archive1's files, now the URL is empty.
|
||||
for path in archive1.my_paths():
|
||||
path.unlink()
|
||||
test_client.post('/api/files/refresh')
|
||||
await async_client.post('/api/files/refresh')
|
||||
check_counts(archive_count=3, domain_count=0)
|
||||
|
||||
# Delete archive3, now there is now example.com domain
|
||||
for path in archive3.my_paths():
|
||||
path.unlink()
|
||||
test_client.post('/api/files/refresh')
|
||||
await async_client.post('/api/files/refresh')
|
||||
check_counts(archive_count=2, domain_count=0)
|
||||
|
||||
# Delete all the rest of the archives
|
||||
|
|
@ -163,12 +167,12 @@ def test_archive_refresh_deleted_archive(test_client, test_session, archive_dire
|
|||
path.unlink()
|
||||
for path in archive5.my_paths():
|
||||
path.unlink()
|
||||
test_client.post('/api/files/refresh')
|
||||
await async_client.post('/api/files/refresh')
|
||||
check_counts(archive_count=0, domain_count=0)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fills_contents_with_refresh(test_session, archive_factory, singlefile_contents_factory):
|
||||
async def test_fills_contents_with_refresh(async_client, test_session, archive_factory, singlefile_contents_factory):
|
||||
"""Refreshing archives fills in any missing contents."""
|
||||
archive1 = archive_factory('example.com', 'https://example.com/one')
|
||||
archive2 = archive_factory('example.com', 'https://example.com/one')
|
||||
|
|
@ -212,7 +216,8 @@ async def test_fills_contents_with_refresh(test_session, archive_factory, single
|
|||
assert archive3.file_group.title == 'last title' # from singlefile HTML
|
||||
|
||||
|
||||
def test_delete_archive(test_session, archive_factory):
|
||||
@pytest.mark.asyncio
|
||||
async def test_delete_archive(async_client, test_session, archive_factory):
|
||||
"""Archives can be deleted."""
|
||||
archive1 = archive_factory('example.com', 'https://example.com/1')
|
||||
archive2 = archive_factory('example.com', 'https://example.com/1')
|
||||
|
|
@ -227,30 +232,35 @@ def test_delete_archive(test_session, archive_factory):
|
|||
assert test_session.query(Archive).count() == 3
|
||||
assert test_session.query(FileGroup).count() == 3
|
||||
|
||||
# Save paths before deletion (archives become detached after delete)
|
||||
archive1_paths = list(archive1.my_paths())
|
||||
archive2_paths = list(archive2.my_paths())
|
||||
archive3_paths = list(archive3.my_paths())
|
||||
|
||||
# Delete the oldest.
|
||||
delete_archives(archive1.id, archive3.id)
|
||||
assert test_session.query(Archive).count() == 1
|
||||
assert test_session.query(FileGroup).count() == 1
|
||||
# Files were deleted.
|
||||
assert archive1.my_paths() and not any(i.is_file() for i in archive1.my_paths())
|
||||
assert archive3.my_paths() and not any(i.is_file() for i in archive3.my_paths())
|
||||
assert archive1_paths and not any(i.is_file() for i in archive1_paths)
|
||||
assert archive3_paths and not any(i.is_file() for i in archive3_paths)
|
||||
# Archive2 is untouched
|
||||
assert archive2.my_paths() and all(i.is_file() for i in archive2.my_paths())
|
||||
assert archive2_paths and all(i.is_file() for i in archive2_paths)
|
||||
|
||||
# Delete the last archive. The Domain should also be deleted.
|
||||
# Delete the last archive. The domain collection should also be deleted.
|
||||
delete_archives(archive2.id)
|
||||
assert test_session.query(Archive).count() == 0
|
||||
domain = test_session.query(Domain).one_or_none()
|
||||
domain = test_session.query(Collection).filter_by(kind='domain').one_or_none()
|
||||
assert domain is None
|
||||
|
||||
# All Files were deleted.
|
||||
assert test_session.query(FileGroup).count() == 0
|
||||
assert archive2.my_paths() and not any(i.is_file() for i in archive2.my_paths())
|
||||
assert archive2_paths and not any(i.is_file() for i in archive2_paths)
|
||||
|
||||
|
||||
def test_get_domains(test_session, archive_factory):
|
||||
"""
|
||||
`get_domains` gets only Domains with Archives.
|
||||
`get_domains` gets only domain collections with Archives.
|
||||
"""
|
||||
archive1 = archive_factory('example.com')
|
||||
archive2 = archive_factory('example.com')
|
||||
|
|
@ -316,7 +326,7 @@ async def test_new_archive(test_session, test_directory, fake_now):
|
|||
|
||||
fake_now(datetime(2000, 1, 2))
|
||||
archive2 = await model_archive_result('https://example.com', singlefile, readability, screenshot)
|
||||
# Domain is reused.
|
||||
# domain collection is reused.
|
||||
assert archive1.domain == archive2.domain
|
||||
|
||||
|
||||
|
|
@ -583,7 +593,7 @@ async def test_archive_meta(async_client, test_session, make_files_structure):
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_refresh_archives_deleted_singlefile(test_session, make_files_structure, singlefile_contents_factory):
|
||||
async def test_refresh_archives_deleted_singlefile(async_client, test_session, make_files_structure, singlefile_contents_factory):
|
||||
"""Removing a Singlefile file from a FileGroup makes that group no longer an Archive."""
|
||||
singlefile, readability = make_files_structure({
|
||||
'2022-09-04-16-20-11_The Title.html': singlefile_contents_factory(),
|
||||
|
|
@ -851,3 +861,218 @@ async def test_get_custom_archive_directory(async_client, test_directory, test_w
|
|||
|
||||
assert lib.get_archive_directory() == (test_directory / 'custom/archives')
|
||||
assert lib.get_domain_directory('https://example.com') == (test_directory / 'custom/archives/example.com')
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_detect_domain_directory_single_archive(async_client, test_directory, test_session, archive_factory):
|
||||
"""detect_domain_directory should detect directory when all archives are in same location."""
|
||||
from modules.archive.lib import detect_domain_directory
|
||||
|
||||
# Create an archive using the factory (which creates a domain collection and auto-detects directory)
|
||||
archive = archive_factory(domain='example.com', url='https://example.com/page1')
|
||||
test_session.flush()
|
||||
|
||||
# Get the collection
|
||||
collection = archive.collection
|
||||
assert collection is not None
|
||||
assert collection.name == 'example.com'
|
||||
|
||||
# Directory should have been auto-detected during collection creation
|
||||
assert collection.directory is not None
|
||||
assert 'example.com' in str(collection.directory)
|
||||
|
||||
# Verify detect_domain_directory also returns the same result
|
||||
detected = detect_domain_directory(collection, test_session)
|
||||
assert detected is not None
|
||||
assert str(detected) == 'archive/example.com'
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_detect_domain_directory_multiple_archives(async_client, test_directory, test_session, archive_factory):
|
||||
"""detect_domain_directory should detect common directory for multiple archives."""
|
||||
from modules.archive.lib import detect_domain_directory
|
||||
|
||||
# Create multiple archives in the same domain
|
||||
archive1 = archive_factory(domain='test.com', url='https://test.com/page1')
|
||||
archive2 = archive_factory(domain='test.com', url='https://test.com/page2')
|
||||
test_session.flush()
|
||||
|
||||
# Get the collection
|
||||
collection = archive1.collection
|
||||
assert collection is not None
|
||||
assert collection.name == 'test.com'
|
||||
|
||||
# Detect directory
|
||||
detected = detect_domain_directory(collection, test_session)
|
||||
assert detected is not None
|
||||
assert str(detected) == 'archive/test.com'
|
||||
|
||||
|
||||
def test_detect_domain_directory_no_archives(test_directory, test_session):
|
||||
"""detect_domain_directory should return None when collection has no archives."""
|
||||
from modules.archive.lib import detect_domain_directory
|
||||
|
||||
# Create a domain collection without archives
|
||||
collection = Collection(name='empty.com', kind='domain', directory=None)
|
||||
test_session.add(collection)
|
||||
test_session.flush()
|
||||
|
||||
# Detect directory - should return None
|
||||
detected = detect_domain_directory(collection, test_session)
|
||||
assert detected is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_or_create_domain_collection_auto_detects_directory(async_client, test_directory, test_session, archive_factory):
|
||||
"""get_or_create_domain_collection should auto-detect directory for existing archives."""
|
||||
from modules.archive.lib import get_or_create_domain_collection
|
||||
|
||||
# Create an archive first
|
||||
archive = archive_factory(domain='autodetect.com', url='https://autodetect.com/page1')
|
||||
test_session.commit()
|
||||
|
||||
# The collection should have been created with no directory initially
|
||||
# Call get_or_create_domain_collection again - should auto-detect
|
||||
collection = get_or_create_domain_collection(test_session, 'https://autodetect.com/page2')
|
||||
assert collection.directory is not None
|
||||
assert 'autodetect.com' in str(collection.directory)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_update_domain_directories(async_client, test_directory, test_session, archive_factory):
|
||||
"""update_domain_directories should fix existing collections that lost their directory."""
|
||||
from modules.archive.lib import update_domain_directories
|
||||
|
||||
# Create an archive - this creates a collection WITH directory (auto-detected)
|
||||
archive = archive_factory(domain='needsdir.com', url='https://needsdir.com/page1')
|
||||
test_session.commit()
|
||||
|
||||
# Manually clear the directory to simulate legacy data
|
||||
collection = archive.collection
|
||||
collection.directory = None
|
||||
test_session.commit()
|
||||
|
||||
# Verify collection has no directory
|
||||
assert collection.directory is None
|
||||
|
||||
# Run update
|
||||
count = update_domain_directories(test_session)
|
||||
assert count == 1
|
||||
|
||||
# Verify directory was set
|
||||
test_session.expire(collection)
|
||||
assert collection.directory is not None
|
||||
assert 'needsdir.com' in str(collection.directory)
|
||||
|
||||
|
||||
def test_collection_unique_name_kind_constraint(test_directory, test_session, archive_factory):
|
||||
"""Collections should have unique (name, kind) combinations.
|
||||
|
||||
This prevents duplicate domain collections with the same name.
|
||||
"""
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
# Create an archive which creates a domain collection
|
||||
archive = archive_factory(domain='uniquetest.com')
|
||||
test_session.commit()
|
||||
|
||||
# Get the original collection
|
||||
original_collection = archive.collection
|
||||
assert original_collection is not None
|
||||
|
||||
# Attempting to create a duplicate domain collection should fail
|
||||
duplicate_collection = Collection(name='uniquetest.com', kind='domain', directory=None)
|
||||
test_session.add(duplicate_collection)
|
||||
|
||||
with pytest.raises(IntegrityError) as exc_info:
|
||||
test_session.commit()
|
||||
|
||||
# Verify it's the unique constraint violation
|
||||
assert 'uq_collection_name_kind' in str(exc_info.value)
|
||||
test_session.rollback()
|
||||
|
||||
|
||||
def test_search_archives_by_domain(test_directory, test_session, archive_factory):
|
||||
"""search_archives should correctly filter by domain collection name."""
|
||||
from modules.archive.lib import search_archives
|
||||
|
||||
# Create archives in different domains
|
||||
archive1 = archive_factory(domain='searchtest.com')
|
||||
archive2 = archive_factory(domain='searchtest.com')
|
||||
archive3 = archive_factory(domain='other.com')
|
||||
test_session.commit()
|
||||
|
||||
# Search for archives in searchtest.com
|
||||
file_groups, total = search_archives(
|
||||
search_str=None,
|
||||
domain='searchtest.com',
|
||||
limit=10,
|
||||
offset=0,
|
||||
order=None,
|
||||
tag_names=None
|
||||
)
|
||||
|
||||
# Should return only archives from searchtest.com
|
||||
assert total == 2
|
||||
assert len(file_groups) == 2
|
||||
|
||||
# Search for other.com
|
||||
file_groups, total = search_archives(
|
||||
search_str=None,
|
||||
domain='other.com',
|
||||
limit=10,
|
||||
offset=0,
|
||||
order=None,
|
||||
tag_names=None
|
||||
)
|
||||
|
||||
assert total == 1
|
||||
assert len(file_groups) == 1
|
||||
|
||||
|
||||
def test_link_domain_and_downloads(test_session, test_download_manager):
|
||||
"""Test that downloads are linked to domain collections."""
|
||||
from wrolpi.downloader import Download
|
||||
from modules.archive.lib import link_domain_and_downloads
|
||||
|
||||
# Create a domain collection with a directory
|
||||
collection = Collection(name='example.com', kind='domain', directory='archive/example.com')
|
||||
test_session.add(collection)
|
||||
test_session.commit()
|
||||
|
||||
# 1. Download with matching destination directory (exact match)
|
||||
download1 = Download(
|
||||
url='https://other.com/rss',
|
||||
downloader='rss',
|
||||
sub_downloader='archive',
|
||||
frequency=86400,
|
||||
settings={'destination': 'archive/example.com'}
|
||||
)
|
||||
# 2. Download with destination in subdirectory
|
||||
download2 = Download(
|
||||
url='https://other.com/rss2',
|
||||
downloader='rss',
|
||||
sub_downloader='archive',
|
||||
frequency=86400,
|
||||
settings={'destination': 'archive/example.com/2025/01'}
|
||||
)
|
||||
# 3. RSS download with archive sub_downloader (matches by URL domain)
|
||||
download3 = Download(
|
||||
url='https://example.com/feed.xml',
|
||||
downloader='rss',
|
||||
sub_downloader='archive',
|
||||
frequency=86400
|
||||
)
|
||||
# 4. Download without frequency (should NOT be linked)
|
||||
download4 = Download(url='https://example.com/once', downloader='archive')
|
||||
test_session.add_all([download1, download2, download3, download4])
|
||||
test_session.commit()
|
||||
|
||||
assert not any(d.collection_id for d in [download1, download2, download3, download4])
|
||||
|
||||
link_domain_and_downloads(test_session)
|
||||
|
||||
assert download1.collection_id == collection.id # matched by directory (exact)
|
||||
assert download2.collection_id == collection.id # matched by subdirectory
|
||||
assert download3.collection_id == collection.id # matched by URL domain
|
||||
assert download4.collection_id is None # no frequency = no link
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
from datetime import datetime
|
||||
import pathlib
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from modules.archive import Domain, Archive
|
||||
from modules.archive import Archive
|
||||
from wrolpi.common import get_wrolpi_config
|
||||
|
||||
|
||||
|
|
@ -13,23 +13,23 @@ async def test_archive_download_destination(async_client, test_session, test_dir
|
|||
|
||||
wrolpi_config = get_wrolpi_config()
|
||||
|
||||
archive_factory(domain='wrolpi.org')
|
||||
domain = test_session.query(Domain).one()
|
||||
archive = archive_factory(domain='wrolpi.org')
|
||||
test_session.commit()
|
||||
|
||||
# Test the default download directory.
|
||||
assert str(domain.download_directory) == str(test_directory / 'archive/wrolpi.org')
|
||||
assert str(archive.download_directory) == str(test_directory / 'archive/wrolpi.org')
|
||||
|
||||
# Year of download is supported.
|
||||
wrolpi_config.archive_destination = 'archives/%(domain)s/%(year)s'
|
||||
assert str(domain.download_directory) == str(test_directory / 'archives/wrolpi.org/2000')
|
||||
assert str(archive.download_directory) == str(test_directory / 'archives/wrolpi.org/2000')
|
||||
|
||||
# More download date is supported.
|
||||
wrolpi_config.archive_destination = 'archive/%(domain)s/%(year)s/%(month)s/%(day)s'
|
||||
assert str(domain.download_directory) == str(test_directory / 'archive/wrolpi.org/2000/1/2')
|
||||
assert str(archive.download_directory) == str(test_directory / 'archive/wrolpi.org/2000/1/2')
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_set_screenshot(test_session, archive_factory, image_bytes_factory):
|
||||
async def test_set_screenshot(async_client, test_session, archive_factory, image_bytes_factory):
|
||||
"""Test Archive.set_screenshot() method with various scenarios."""
|
||||
|
||||
# ========== Test 1: Successfully set screenshot on archive without one ==========
|
||||
|
|
@ -84,7 +84,8 @@ async def test_set_screenshot(test_session, archive_factory, image_bytes_factory
|
|||
assert archive.screenshot_path == original_screenshot
|
||||
|
||||
# ========== Test 3: Error when trying to set non-existent screenshot file ==========
|
||||
archive_no_screenshot = archive_factory('example.com', 'https://example.com/test2', 'Test Archive 2', screenshot=False)
|
||||
archive_no_screenshot = archive_factory('example.com', 'https://example.com/test2', 'Test Archive 2',
|
||||
screenshot=False)
|
||||
test_session.commit()
|
||||
|
||||
# Try to set a screenshot that doesn't exist
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue