test(torrent_api): add unit tests
This commit is contained in:
1 parent
be8e17f398
commit
d146f18144
4 files changed
+257
No files matched your search
@@ -0,0 +1,17 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
|
import sys
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def run_tests():
|
||||||
|
test_dir = Path(__file__).resolve().parent / "tests"
|
||||||
|
suite = unittest.defaultTestLoader.discover(str(test_dir), pattern="test_*.py")
|
||||||
|
if not suite.countTestCases():
|
||||||
|
raise RuntimeError(f"No tests found in {test_dir}")
|
||||||
|
return unittest.TextTestRunner(verbosity=2).run(suite).wasSuccessful()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(0 if run_tests() else 1)
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import contextlib
|
||||||
|
import io
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from torrent_api.cli import main
|
||||||
|
|
||||||
|
|
||||||
|
class MainTest(unittest.TestCase):
|
||||||
|
@patch("torrent_api.cli.Qbittorrent")
|
||||||
|
@patch.dict(
|
||||||
|
"os.environ",
|
||||||
|
{"QBITTORRENT_PRIVATE_API_KEY": "private", "QBITTORRENT_PUBLIC_API_KEY": "public"},
|
||||||
|
clear=True,
|
||||||
|
)
|
||||||
|
@patch(
|
||||||
|
"sys.argv",
|
||||||
|
[
|
||||||
|
"torrent-api", "--sort", "ratio", "--asc", "--force-start",
|
||||||
|
"--show-id", "--id", "example", "--progress-threshold", "0.5",
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_cli_calls_both_instances(self, client):
|
||||||
|
private, public = client.side_effect = [unittest.mock.Mock(), unittest.mock.Mock()]
|
||||||
|
main()
|
||||||
|
private.show_torrents.assert_called_once_with(sort_by="ratio", reverse=False, id=True)
|
||||||
|
public.show_torrents.assert_called_once_with(sort_by="ratio", reverse=False, id=True)
|
||||||
|
public.get_torrent_contents.assert_called_once_with("example", progress_threshold=0.5)
|
||||||
|
private.force_start_by_tracker.assert_called_once_with(
|
||||||
|
{"myanonamouse": True, "leo-test": True, "nordicq": True}
|
||||||
|
)
|
||||||
|
public.force_start_by_tracker.assert_not_called()
|
||||||
|
|
||||||
|
@patch.dict("os.environ", {}, clear=True)
|
||||||
|
@patch("sys.argv", ["torrent-api"])
|
||||||
|
def test_cli_requires_keys(self):
|
||||||
|
with contextlib.redirect_stderr(io.StringIO()) as stderr:
|
||||||
|
with self.assertRaises(SystemExit) as error:
|
||||||
|
main()
|
||||||
|
self.assertEqual(error.exception.code, 2)
|
||||||
|
self.assertIn("Set QBITTORRENT_PRIVATE_API_KEY", stderr.getvalue())
|
||||||
|
|
||||||
|
def test_debug_entry_point_shows_help(self):
|
||||||
|
project_dir = Path(__file__).resolve().parents[1]
|
||||||
|
result = subprocess.run(
|
||||||
|
[sys.executable, str(project_dir / "main.py"), "--help"],
|
||||||
|
cwd=project_dir,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
check=True,
|
||||||
|
)
|
||||||
|
self.assertIn("--show-id", result.stdout)
|
||||||
|
self.assertIn("--progress-threshold", result.stdout)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
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()
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import contextlib
|
||||||
|
import io
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import run_tests
|
||||||
|
|
||||||
|
|
||||||
|
class TestRunnerTest(unittest.TestCase):
|
||||||
|
def test_runner_reports_success_and_failure(self):
|
||||||
|
def fail():
|
||||||
|
raise AssertionError("test failure")
|
||||||
|
|
||||||
|
for test, expected in ((lambda: None, True), (fail, False)):
|
||||||
|
suite = unittest.TestSuite([unittest.FunctionTestCase(test)])
|
||||||
|
with self.subTest(expected=expected), patch.object(
|
||||||
|
unittest.defaultTestLoader, "discover", return_value=suite
|
||||||
|
) as discover, contextlib.redirect_stderr(io.StringIO()):
|
||||||
|
self.assertEqual(run_tests.run_tests(), expected)
|
||||||
|
discover.assert_called_once_with(
|
||||||
|
str(Path(run_tests.__file__).resolve().parent / "tests"), pattern="test_*.py"
|
||||||
|
)
|
||||||
|
|
||||||
|
@patch.object(unittest.defaultTestLoader, "discover", return_value=unittest.TestSuite())
|
||||||
|
def test_runner_rejects_empty_suite(self, discover):
|
||||||
|
with self.assertRaisesRegex(RuntimeError, "No tests found"):
|
||||||
|
run_tests.run_tests()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Reference in new issue
Block a user