Files
Server-scripts/torrent_api/tests/test_qbittorrent.py
T

235 lines
11 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},
{"name": "partial.txt", "progress": 0.5},
]
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%", output.getvalue())
self.assertIn("partial.txt", output.getvalue())
self.assertIn("Progress: 50%", 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" / "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},
{"name": "torrent/partial.txt", "progress": 0.5},
]
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.assertFalse((destination / "torrent" / "partial.txt").exists())
@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}]
with self.assertLogs(qbittorrent.logger, level="DEBUG") as logs:
self.instance.show_and_copy_torrent_contents(
"a", copy_to=destination, dry_run=True
)
self.assertIn(
"Dry run: would copy /downloads/folder/complete.txt to "
f"{destination}/folder/complete.txt",
logs.output[-1],
)
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},
]
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()