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

135 lines
6.2 KiB
Python

import contextlib
import io
import subprocess
import sys
import tempfile
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.setup_logging")
@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",
"--copy-to", "/tmp/copied", "--dry-run", "--log-level", "DEBUG",
],
)
def test_cli_calls_both_instances(self, client, setup_logging):
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.show_and_copy_torrent_contents.assert_called_once_with(
"example", progress_threshold=0.5, copy_to=Path("/tmp/copied"), dry_run=True
)
private.force_start_by_tracker.assert_called_once_with(
{"myanonamouse": True, "leo-test": True, "nordicq": True}
)
public.force_start_by_tracker.assert_not_called()
setup_logging.assert_called_once_with("DEBUG")
self.assertEqual(
client.call_args_list[1].kwargs["path_mappings"],
{
"/downloads-public": "/torrent/qbittorrent-public/downloads",
"/downloads-special": "/special-torrent/torrent",
"/torrents": "/torrent/qbittorrent-public/torrents",
"/mediahost": "/torrent/qbittorrent/mediahost",
},
)
@patch.dict("os.environ", {}, clear=True)
@patch("sys.argv", ["torrent-api"])
@patch("torrent_api.cli.setup_logging")
@patch("torrent_api.cli.load_dotenv")
def test_cli_requires_keys(self, load_dotenv, setup_logging):
with self.assertLogs("torrent_api.cli", level="ERROR") as logs, \
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())
self.assertIn("Required qBittorrent API keys are not set", logs.output[0])
def test_cli_loads_env_from_entry_point_directory(self):
with tempfile.TemporaryDirectory() as working_dir, tempfile.TemporaryDirectory() as entry_dir:
Path(entry_dir, ".env").write_text(
"QBITTORRENT_PRIVATE_API_KEY=entry-private\nQBITTORRENT_PUBLIC_API_KEY=entry-public\n"
)
for frozen in (False, True):
with self.subTest(frozen=frozen), \
patch.dict("os.environ", {}, clear=True), \
patch("sys.argv", ["torrent-api"]), \
patch("sys.frozen", frozen, create=True), \
patch("sys.executable", str(Path(entry_dir, "torrent-api"))), \
patch("__main__.__file__", str(Path(working_dir if frozen else entry_dir, "main.py")),
create=True), \
patch("pathlib.Path.cwd", return_value=Path(working_dir)), \
patch("torrent_api.cli.setup_logging"), \
patch("torrent_api.cli.Qbittorrent") as client:
main()
self.assertEqual(client.call_args_list[0].args[2], "entry-private")
self.assertEqual(client.call_args_list[1].args[2], "entry-public")
def test_cli_prefers_working_env_and_existing_environment(self):
with tempfile.TemporaryDirectory() as working_dir, tempfile.TemporaryDirectory() as entry_dir:
Path(working_dir, ".env").write_text(
"QBITTORRENT_PRIVATE_API_KEY=working-private\nQBITTORRENT_PUBLIC_API_KEY=working-public\n"
)
Path(entry_dir, ".env").write_text(
"QBITTORRENT_PRIVATE_API_KEY=entry-private\nQBITTORRENT_PUBLIC_API_KEY=entry-public\n"
)
with patch.dict("os.environ", {"QBITTORRENT_PRIVATE_API_KEY": "exported"}, clear=True), \
patch("sys.argv", ["torrent-api"]), \
patch("sys.frozen", False, create=True), \
patch("__main__.__file__", str(Path(entry_dir, "main.py")), create=True), \
patch("pathlib.Path.cwd", return_value=Path(working_dir)), \
patch("torrent_api.cli.setup_logging"), \
patch("torrent_api.cli.Qbittorrent") as client:
main()
self.assertEqual(client.call_args_list[0].args[2], "exported")
self.assertEqual(client.call_args_list[1].args[2], "working-public")
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)
self.assertIn("--copy-to", result.stdout)
def test_debug_entry_point_logs_directories(self):
project_dir = Path(__file__).resolve().parents[1]
with tempfile.TemporaryDirectory() as working_dir:
Path(working_dir, ".env").touch()
result = subprocess.run(
[sys.executable, str(project_dir / "main.py")],
cwd=working_dir,
env={},
capture_output=True,
text=True,
)
self.assertEqual(result.returncode, 2)
self.assertIn(f"Working directory: {working_dir}", result.stdout)
self.assertIn(f"Execution directory: {project_dir}", result.stdout)
if __name__ == "__main__":
unittest.main()