diff --git a/torrent_api/tests/test_main.py b/torrent_api/tests/test_main.py index feb5af0..5b49d91 100644 --- a/torrent_api/tests/test_main.py +++ b/torrent_api/tests/test_main.py @@ -52,7 +52,8 @@ class MainTest(unittest.TestCase): @patch.dict("os.environ", {}, clear=True) @patch("sys.argv", ["torrent-api"]) @patch("torrent_api.cli.setup_logging") - def test_cli_requires_keys(self, 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: @@ -61,6 +62,45 @@ class MainTest(unittest.TestCase): 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(