|
| 1 | +import unittest |
| 2 | +from unittest.mock import patch, MagicMock |
| 3 | +import os |
| 4 | +import sys |
| 5 | + |
| 6 | +# Add the root directory to the Python path |
| 7 | +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) |
| 8 | + |
| 9 | +from github_clone import get_starred_repos, clone_repo |
| 10 | + |
| 11 | +class TestGitHubClone(unittest.TestCase): |
| 12 | + |
| 13 | + @patch('github_clone.requests.get') |
| 14 | + def test_get_starred_repos_success(self, mock_get): |
| 15 | + # Mock the API response |
| 16 | + mock_response = MagicMock() |
| 17 | + mock_response.json.return_value = [{'name': 'repo1'}, {'name': 'repo2'}] |
| 18 | + mock_response.raise_for_status = MagicMock() |
| 19 | + mock_get.return_value = mock_response |
| 20 | + |
| 21 | + repos = get_starred_repos('testuser', 'testtoken') |
| 22 | + self.assertEqual(len(repos), 2) |
| 23 | + self.assertEqual(repos[0]['name'], 'repo1') |
| 24 | + mock_get.assert_called_with('https://api.github.com/users/testuser/starred', auth=('testuser', 'testtoken')) |
| 25 | + |
| 26 | + @patch('github_clone.requests.get') |
| 27 | + def test_get_starred_repos_failure(self, mock_get): |
| 28 | + # Mock a failed API response |
| 29 | + mock_response = MagicMock() |
| 30 | + mock_response.raise_for_status.side_effect = Exception("API Error") |
| 31 | + mock_get.return_value = mock_response |
| 32 | + |
| 33 | + with self.assertRaises(Exception): |
| 34 | + get_starred_repos('testuser', 'testtoken') |
| 35 | + |
| 36 | + @patch('github_clone.git.Repo.clone_from') |
| 37 | + @patch('github_clone.os.path.exists') |
| 38 | + def test_clone_repo_new(self, mock_exists, mock_clone_from): |
| 39 | + # Mock that the repo does not exist |
| 40 | + mock_exists.return_value = False |
| 41 | + |
| 42 | + repo_info = {'name': 'new_repo', 'clone_url': 'http://example.com/new_repo.git'} |
| 43 | + clone_dir = 'test_dir' |
| 44 | + |
| 45 | + clone_repo(repo_info, clone_dir) |
| 46 | + |
| 47 | + repo_dir = os.path.join(clone_dir, repo_info['name']) |
| 48 | + mock_exists.assert_called_with(repo_dir) |
| 49 | + mock_clone_from.assert_called_with(repo_info['clone_url'], repo_dir) |
| 50 | + |
| 51 | + @patch('github_clone.git.Repo.clone_from') |
| 52 | + @patch('github_clone.os.path.exists') |
| 53 | + def test_clone_repo_exists(self, mock_exists, mock_clone_from): |
| 54 | + # Mock that the repo already exists |
| 55 | + mock_exists.return_value = True |
| 56 | + |
| 57 | + repo_info = {'name': 'existing_repo', 'clone_url': 'http://example.com/existing_repo.git'} |
| 58 | + clone_dir = 'test_dir' |
| 59 | + |
| 60 | + clone_repo(repo_info, clone_dir) |
| 61 | + |
| 62 | + repo_dir = os.path.join(clone_dir, repo_info['name']) |
| 63 | + mock_exists.assert_called_with(repo_dir) |
| 64 | + mock_clone_from.assert_not_called() |
| 65 | + |
| 66 | +if __name__ == '__main__': |
| 67 | + unittest.main() |
0 commit comments