Torrent API CI / build (push) Successful in 31s
Torrent API CI / test (push) Successful in 13s
Torrent API CI / lint (push) Successful in 8s
Torrent API CI / install (mediahost) (push) Successful in 1s
Torrent API CI / install (serverhost) (push) Successful in 2s
Torrent API CI / install (vivohost) (push) Successful in 42s
Torrent API CI / install (quiethost) (push) Successful in 43s
295 lines
14 KiB
Python
295 lines
14 KiB
Python
import contextlib
|
|
import io
|
|
import tempfile
|
|
import unittest
|
|
from pathlib import Path
|
|
from unittest.mock import patch
|
|
|
|
import requests
|
|
|
|
from torrent_api import Qbittorrent, qbittorrent
|
|
|
|
|
|
class TorrentHelpersTest(unittest.TestCase):
|
|
def setUp(self):
|
|
self.instance = Qbittorrent("localhost:8080", "test", "test-key")
|
|
self.torrents = [
|
|
{"hash": "a", "name": "first", "seeding_time": 101, "ratio": 1.0},
|
|
{"hash": "b", "name": "second", "seeding_time": 100, "ratio": 2.1},
|
|
{"hash": "c", "name": "third", "seeding_time": 100, "ratio": 2.0},
|
|
]
|
|
|
|
@patch.object(qbittorrent.requests, "post")
|
|
@patch.object(Qbittorrent, "get_torrents")
|
|
def test_remove_exceeds_either_threshold_and_deletes_files(self, get_torrents, post):
|
|
get_torrents.return_value = self.torrents
|
|
|
|
removed = self.instance.remove_torrents(seed_time=100, ratio=2)
|
|
|
|
self.assertEqual(removed, self.torrents[:2])
|
|
post.assert_called_once_with(
|
|
"http://localhost:8080/api/v2/torrents/delete",
|
|
data={"hashes": "a|b", "deleteFiles": "true"},
|
|
headers={"Authorization": "Bearer test-key"},
|
|
timeout=30,
|
|
)
|
|
post.return_value.raise_for_status.assert_called_once()
|
|
|
|
@patch.object(qbittorrent.requests, "post")
|
|
@patch.object(Qbittorrent, "get_torrents")
|
|
def test_remove_single_threshold_and_keep_files(self, get_torrents, post):
|
|
get_torrents.return_value = self.torrents
|
|
self.assertEqual(
|
|
self.instance.remove_torrents(ratio=2, delete_files=False),
|
|
[self.torrents[1]],
|
|
)
|
|
self.assertEqual(post.call_args.kwargs["data"]["deleteFiles"], "false")
|
|
|
|
@patch.object(qbittorrent.requests, "post")
|
|
@patch.object(Qbittorrent, "get_torrents")
|
|
def test_remove_no_matches_or_invalid_threshold(self, get_torrents, post):
|
|
get_torrents.return_value = self.torrents
|
|
self.assertEqual(self.instance.remove_torrents(seed_time=101), [])
|
|
for kwargs in ({}, {"ratio": -1}, {"seed_time": float("nan")}, {"ratio": float("inf")}):
|
|
with self.subTest(kwargs=kwargs), self.assertRaises(ValueError):
|
|
self.instance.remove_torrents(**kwargs)
|
|
post.assert_not_called()
|
|
|
|
@patch.object(qbittorrent.requests, "post")
|
|
@patch.object(Qbittorrent, "get_torrents")
|
|
def test_remove_propagates_http_errors(self, get_torrents, post):
|
|
get_torrents.return_value = self.torrents
|
|
post.return_value.raise_for_status.side_effect = requests.HTTPError("failed")
|
|
with self.assertRaises(requests.HTTPError):
|
|
self.instance.remove_torrents(ratio=2)
|
|
|
|
@patch.object(qbittorrent.requests, "get")
|
|
@patch.object(Qbittorrent, "get_torrents")
|
|
def test_contents_by_name_or_hash(self, get_torrents, get):
|
|
get_torrents.return_value = self.torrents
|
|
get.return_value.json.return_value = [
|
|
{"name": "folder/file.txt", "progress": 1.0, "priority": 1},
|
|
{"name": "partial.txt", "progress": 0.5, "priority": 1},
|
|
{"name": "skipped.txt", "progress": 1.0, "priority": 0},
|
|
]
|
|
for identifier in ("first", "a"):
|
|
with self.subTest(identifier=identifier):
|
|
with contextlib.redirect_stdout(io.StringIO()) as output:
|
|
self.instance.show_and_copy_torrent_contents(
|
|
identifier, progress_threshold=0.5
|
|
)
|
|
self.assertIn("folder/file.txt Progress: 100% Priority: 1", output.getvalue())
|
|
self.assertIn("partial.txt", output.getvalue())
|
|
self.assertIn("Progress: 50% Priority: 1", output.getvalue())
|
|
self.assertIn("skipped.txt", output.getvalue())
|
|
get.assert_called_with(
|
|
"http://localhost:8080/api/v2/torrents/files",
|
|
params={"hash": "a"},
|
|
headers={"Authorization": "Bearer test-key"},
|
|
timeout=30,
|
|
)
|
|
self.assertEqual(get.return_value.raise_for_status.call_count, 2)
|
|
|
|
@patch.object(qbittorrent.requests, "get")
|
|
@patch.object(Qbittorrent, "get_torrents")
|
|
def test_contents_copies_only_completed_files(self, get_torrents, get):
|
|
with tempfile.TemporaryDirectory() as temporary_directory:
|
|
root = Path(temporary_directory)
|
|
source = root / "downloads"
|
|
destination = root / "copied"
|
|
(source / "torrent").mkdir(parents=True)
|
|
(source / "torrent" / "complete.txt").write_text("complete")
|
|
(source / "torrent" / "complete-second.txt").write_text("complete second")
|
|
(source / "torrent" / "partial.txt").write_text("partial")
|
|
get_torrents.return_value = [{**self.torrents[0], "save_path": str(source)}]
|
|
get.return_value.json.return_value = [
|
|
{"name": "torrent/complete.txt", "progress": 1.0, "priority": 1},
|
|
{"name": "torrent/complete-second.txt", "progress": 1.0, "priority": 1},
|
|
{"name": "torrent/partial.txt", "progress": 0.5, "priority": 1},
|
|
]
|
|
|
|
with self.assertLogs(qbittorrent.logger, level="DEBUG") as logs:
|
|
self.instance.show_and_copy_torrent_contents(
|
|
"a", progress_threshold=0.5, copy_to=destination
|
|
)
|
|
|
|
self.assertEqual((destination / "torrent" / "complete.txt").read_text(), "complete")
|
|
self.assertEqual(
|
|
(destination / "torrent" / "complete-second.txt").read_text(),
|
|
"complete second",
|
|
)
|
|
self.assertFalse((destination / "torrent" / "partial.txt").exists())
|
|
self.assertTrue(any("Copy progress: 1/2 files" in log for log in logs.output))
|
|
self.assertTrue(any("Copy progress: 2/2 files" in log for log in logs.output))
|
|
|
|
@patch.object(qbittorrent.requests, "get")
|
|
@patch.object(Qbittorrent, "get_torrents")
|
|
def test_contents_copies_from_mapped_container_path(self, get_torrents, get):
|
|
with tempfile.TemporaryDirectory() as temporary_directory:
|
|
root = Path(temporary_directory)
|
|
source = root / "host-downloads"
|
|
destination = root / "copied"
|
|
(source / "subdir" / "torrent").mkdir(parents=True)
|
|
(source / "subdir" / "torrent" / "complete.txt").write_text("complete")
|
|
self.instance.path_mappings = {
|
|
"/downloads": root / "other",
|
|
"/downloads/public": source,
|
|
}
|
|
get_torrents.return_value = [
|
|
{**self.torrents[0], "save_path": "/downloads/public/subdir"}
|
|
]
|
|
get.return_value.json.return_value = [{"name": "torrent/complete.txt", "progress": 1.0, "priority": 1}]
|
|
|
|
self.instance.show_and_copy_torrent_contents("a", copy_to=destination)
|
|
|
|
self.assertEqual((destination / "torrent" / "complete.txt").read_text(), "complete")
|
|
|
|
@patch.object(qbittorrent.requests, "get")
|
|
@patch.object(Qbittorrent, "get_torrents")
|
|
def test_contents_dry_run_uses_mapped_path(self, get_torrents, get):
|
|
self.instance.path_mappings = {"/downloads-public": "/host/downloads"}
|
|
get_torrents.return_value = [{**self.torrents[0], "save_path": "/downloads-public/subdir"}]
|
|
get.return_value.json.return_value = [{"name": "complete.txt", "progress": 1.0, "priority": 1}]
|
|
|
|
with self.assertLogs(qbittorrent.logger, level="DEBUG") as logs:
|
|
self.instance.show_and_copy_torrent_contents("a", copy_to="/copied", dry_run=True)
|
|
|
|
self.assertTrue(
|
|
any(
|
|
"would copy /host/downloads/subdir/complete.txt to /copied/complete.txt" in log
|
|
for log in logs.output
|
|
)
|
|
)
|
|
self.assertTrue(any("Copy progress: 1/1 files" in log for log in logs.output))
|
|
|
|
def test_mapping_respects_path_boundaries_and_rejects_parent_components(self):
|
|
self.instance.path_mappings = {"/downloads": "/host/downloads"}
|
|
self.assertEqual(self.instance._host_save_path("/downloads-other"), Path("/downloads-other"))
|
|
with self.assertRaisesRegex(ValueError, "Invalid torrent save path"):
|
|
self.instance._host_save_path("/downloads/../other")
|
|
|
|
@patch.object(qbittorrent, "_is_local_host", return_value=False)
|
|
@patch.object(qbittorrent.shutil, "copy2")
|
|
@patch.object(qbittorrent.requests, "get")
|
|
@patch.object(Qbittorrent, "get_torrents")
|
|
def test_contents_dry_run_logs_without_copying_or_creating_directories(
|
|
self, get_torrents, get, copy2, is_local_host
|
|
):
|
|
with tempfile.TemporaryDirectory() as temporary_directory:
|
|
root = Path(temporary_directory)
|
|
destination = root / "copied"
|
|
get_torrents.return_value = [{**self.torrents[0], "save_path": "/downloads"}]
|
|
get.return_value.json.return_value = [{"name": "folder/complete.txt", "progress": 1.0, "priority": 1}]
|
|
|
|
with self.assertLogs(qbittorrent.logger, level="DEBUG") as logs:
|
|
self.instance.show_and_copy_torrent_contents(
|
|
"a", copy_to=destination, dry_run=True
|
|
)
|
|
|
|
self.assertTrue(
|
|
any(
|
|
"Dry run: would copy /downloads/folder/complete.txt to "
|
|
f"{destination}/folder/complete.txt" in log
|
|
for log in logs.output
|
|
)
|
|
)
|
|
self.assertTrue(any("Copy progress: 1/1 files" in log for log in logs.output))
|
|
self.assertFalse(destination.exists())
|
|
copy2.assert_not_called()
|
|
is_local_host.assert_not_called()
|
|
|
|
@patch.object(qbittorrent, "_is_local_host", return_value=False)
|
|
@patch.object(qbittorrent.shutil, "copy2")
|
|
@patch.object(qbittorrent.requests, "get")
|
|
@patch.object(Qbittorrent, "get_torrents")
|
|
def test_contents_rejects_copy_when_qbittorrent_host_is_remote(
|
|
self, get_torrents, get, copy2, is_local_host
|
|
):
|
|
get_torrents.return_value = [{**self.torrents[0], "save_path": "/downloads"}]
|
|
get.return_value.json.return_value = [
|
|
{"name": "complete.txt", "progress": 1.0, "priority": 1},
|
|
]
|
|
|
|
with self.assertRaisesRegex(RuntimeError, "qBittorrent host is not local"):
|
|
self.instance.show_and_copy_torrent_contents("a", copy_to="/copied")
|
|
|
|
is_local_host.assert_called_once_with("localhost")
|
|
copy2.assert_not_called()
|
|
|
|
@patch.object(qbittorrent.socket, "socket")
|
|
@patch.object(qbittorrent.socket, "getaddrinfo")
|
|
def test_local_host_check_compares_endpoint_and_local_route_addresses(self, getaddrinfo, create_socket):
|
|
getaddrinfo.return_value = [
|
|
(qbittorrent.socket.AF_INET, qbittorrent.socket.SOCK_DGRAM, 0, "", ("192.168.1.20", 9))
|
|
]
|
|
probe = create_socket.return_value.__enter__.return_value
|
|
|
|
probe.getsockname.return_value = ("192.168.1.20", 12345)
|
|
self.assertTrue(qbittorrent._is_local_host("torrent-host"))
|
|
|
|
probe.getsockname.return_value = ("192.168.1.10", 12345)
|
|
self.assertFalse(qbittorrent._is_local_host("torrent-host"))
|
|
|
|
@patch.object(qbittorrent.requests, "get")
|
|
@patch.object(Qbittorrent, "get_torrents")
|
|
def test_contents_rejects_missing_or_ambiguous_names(self, get_torrents, get):
|
|
get_torrents.return_value = self.torrents + [
|
|
{"hash": "d", "name": "first", "seeding_time": 0, "ratio": 0}
|
|
]
|
|
for identifier in ("missing", "first"):
|
|
with self.subTest(identifier=identifier), self.assertRaises(ValueError):
|
|
self.instance.show_and_copy_torrent_contents(identifier)
|
|
get.assert_not_called()
|
|
|
|
@patch.object(qbittorrent.requests, "get")
|
|
@patch.object(Qbittorrent, "get_torrents")
|
|
def test_contents_propagates_http_errors(self, get_torrents, get):
|
|
get_torrents.return_value = self.torrents
|
|
get.return_value.raise_for_status.side_effect = requests.HTTPError("failed")
|
|
with self.assertRaises(requests.HTTPError):
|
|
self.instance.show_and_copy_torrent_contents("a")
|
|
|
|
@patch.object(qbittorrent.requests, "get")
|
|
def test_get_trackers_uses_instance_address(self, get):
|
|
get.return_value.json.return_value = [{"url": "https://tracker.example"}]
|
|
self.assertEqual(
|
|
self.instance.get_trackers("a"), [{"url": "https://tracker.example"}]
|
|
)
|
|
get.assert_called_once_with(
|
|
"http://localhost:8080/api/v2/torrents/trackers",
|
|
params={"hash": "a"},
|
|
headers={"Authorization": "Bearer test-key"},
|
|
timeout=30,
|
|
)
|
|
get.return_value.raise_for_status.assert_called_once()
|
|
|
|
@patch.object(Qbittorrent, "set_force_start")
|
|
@patch.object(Qbittorrent, "get_trackers")
|
|
@patch.object(Qbittorrent, "get_torrents")
|
|
def test_force_start_by_tracker_uses_matching_hash(self, get_torrents, get_trackers, set_force):
|
|
get_torrents.return_value = self.torrents[:1]
|
|
get_trackers.return_value = [{"url": "https://TRACKER.example"}]
|
|
self.instance.force_start_by_tracker({"tracker": False})
|
|
get_trackers.assert_called_once_with("a")
|
|
set_force.assert_called_once_with("a", False)
|
|
|
|
@patch.object(Qbittorrent, "get_torrents")
|
|
def test_show_torrents_optionally_shows_ids_in_sorted_order(self, get_torrents):
|
|
get_torrents.return_value = self.torrents[:2]
|
|
for show_id in (False, True):
|
|
with self.subTest(show_id=show_id), contextlib.redirect_stdout(io.StringIO()) as output:
|
|
kwargs = {"id": True} if show_id else {}
|
|
self.instance.show_torrents(sort_by="name", reverse=False, **kwargs)
|
|
rows = output.getvalue().splitlines()[3:]
|
|
expected = [
|
|
"first Ratio: 1.00 Seed Time: 0d (0.0h)",
|
|
"second Ratio: 2.10 Seed Time: 0d (0.0h)",
|
|
]
|
|
if show_id:
|
|
expected = [f"{row} ID: {torrent_id}" for row, torrent_id in zip(expected, ("a", "b"))]
|
|
self.assertEqual(rows, expected)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|