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

149 lines
6.7 KiB
Python

import contextlib
import io
import unittest
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.get_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_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.get_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.get_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()