"""Tests for the shared get_credentials() function in auth.py. These test the credential parsing logic in isolation by mocking subprocess.Popen. """ import sys import unittest from unittest.mock import MagicMock, patch sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent.parent)) import auth # noqa: E402 class TestGetCredentials(unittest.TestCase): """Test the get_credentials function that parses git credential fill output.""" def _mock_popen(self, output_text): """Create a mock Popen that returns the given text from communicate().""" mock_proc = MagicMock() mock_proc.communicate.return_value = (output_text, "") return mock_proc @patch("auth.subprocess.Popen") def test_parses_standard_output(self, mock_popen_cls): mock_popen_cls.return_value = self._mock_popen( "protocol=https\nhost=gitea.example.com\nusername=admin\npassword=s3cret\n" ) user, password = auth.get_credentials("gitea.example.com") self.assertEqual(user, "admin") self.assertEqual(password, "s3cret") @patch("auth.subprocess.Popen") def test_handles_password_with_equals(self, mock_popen_cls): # Tokens often contain '=' characters mock_popen_cls.return_value = self._mock_popen( "username=bot\npassword=abc=def=ghi\n" ) user, password = auth.get_credentials("example.com") self.assertEqual(user, "bot") self.assertEqual(password, "abc=def=ghi") @patch("auth.subprocess.Popen") def test_empty_output_returns_empty(self, mock_popen_cls): mock_popen_cls.return_value = self._mock_popen("") user, password = auth.get_credentials("example.com") self.assertEqual(user, "") self.assertEqual(password, "") @patch("auth.subprocess.Popen") def test_missing_password_returns_empty(self, mock_popen_cls): mock_popen_cls.return_value = self._mock_popen("username=admin\n") user, password = auth.get_credentials("example.com") self.assertEqual(user, "admin") self.assertEqual(password, "") @patch("auth.subprocess.Popen") def test_sends_correct_stdin(self, mock_popen_cls): mock_proc = self._mock_popen("username=u\npassword=p\n") mock_popen_cls.return_value = mock_proc auth.get_credentials("gitea.prgs.cc") # Verify the correct input was sent to git credential fill mock_proc.communicate.assert_called_once_with( "protocol=https\nhost=gitea.prgs.cc\n\n" ) class TestGetAuthHeader(unittest.TestCase): """Test the get_auth_header function.""" @patch("auth.get_credentials", return_value=("user", "pass")) def test_returns_basic_header(self, _cred): header = auth.get_auth_header("example.com") self.assertIsNotNone(header) self.assertTrue(header.startswith("Basic ")) @patch("auth.get_credentials", return_value=("", "")) def test_returns_none_for_missing_creds(self, _cred): header = auth.get_auth_header("example.com") self.assertIsNone(header) class TestRepoApiUrl(unittest.TestCase): def test_url_format(self): url = auth.repo_api_url("gitea.prgs.cc", "Org", "Repo") self.assertEqual(url, "https://gitea.prgs.cc/api/v1/repos/Org/Repo") if __name__ == "__main__": unittest.main()