forked from OpenHands/OpenHands
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtest_github_service.py
More file actions
246 lines (204 loc) Β· 8.66 KB
/
test_github_service.py
File metadata and controls
246 lines (204 loc) Β· 8.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
from unittest.mock import AsyncMock, Mock, patch
import httpx
import pytest
from pydantic import SecretStr
from openhands.integrations.github.github_service import GitHubService
from openhands.integrations.service_types import (
AuthenticationError,
OwnerType,
ProviderType,
Repository,
)
from openhands.server.types import AppMode
@pytest.mark.asyncio
async def test_github_service_token_handling():
# Test initialization with SecretStr token
token = SecretStr('test-token')
service = GitHubService(user_id=None, token=token)
assert service.token == token
assert service.token.get_secret_value() == 'test-token'
# Test headers contain the token correctly
headers = await service._get_github_headers()
assert headers['Authorization'] == 'Bearer test-token'
assert headers['Accept'] == 'application/vnd.github.v3+json'
# Test initialization without token
service = GitHubService(user_id='test-user')
assert service.token == SecretStr('')
@pytest.mark.asyncio
async def test_github_service_token_refresh():
# Test that token refresh is only attempted when refresh=True
token = SecretStr('test-token')
service = GitHubService(user_id=None, token=token)
assert not service.refresh
# Test token expiry detection
assert service._has_token_expired(401)
assert not service._has_token_expired(200)
assert not service._has_token_expired(404)
# Test get_latest_token returns a copy of the current token
latest_token = await service.get_latest_token()
assert isinstance(latest_token, SecretStr)
assert latest_token.get_secret_value() == 'test-token' # Compare with known value
@pytest.mark.asyncio
async def test_github_service_fetch_data():
# Mock httpx.AsyncClient for testing API calls
mock_response = AsyncMock()
mock_response.status_code = 200
mock_response.json.return_value = {'login': 'test-user'}
mock_response.raise_for_status = Mock()
mock_client = AsyncMock()
mock_client.get.return_value = mock_response
mock_client.__aenter__.return_value = mock_client
mock_client.__aexit__.return_value = None
with patch('httpx.AsyncClient', return_value=mock_client):
service = GitHubService(user_id=None, token=SecretStr('test-token'))
_ = await service._make_request('https://api.github.com/user')
# Verify the request was made with correct headers
mock_client.get.assert_called_once()
call_args = mock_client.get.call_args
headers = call_args[1]['headers']
assert headers['Authorization'] == 'Bearer test-token'
# Test error handling with 401 status code
mock_response.status_code = 401
mock_response.raise_for_status.side_effect = httpx.HTTPStatusError(
message='401 Unauthorized', request=Mock(), response=mock_response
)
# Reset the mock to test error handling
mock_client.get.reset_mock()
mock_client.get.return_value = mock_response
with pytest.raises(AuthenticationError):
_ = await service._make_request('https://api.github.com/user')
@pytest.mark.asyncio
async def test_github_get_repositories_with_user_owner_type():
"""Test that get_repositories correctly sets owner_type field for user repositories."""
service = GitHubService(user_id=None, token=SecretStr('test-token'))
# Mock repository data for user repositories
mock_repo_data = [
{
'id': 123,
'full_name': 'test-user/test-repo',
'private': False,
'stargazers_count': 10,
'owner': {'type': 'User'}, # User repository
},
{
'id': 456,
'full_name': 'test-user/another-repo',
'private': True,
'stargazers_count': 5,
'owner': {'type': 'User'}, # User repository
},
]
with (
patch.object(service, '_fetch_paginated_repos', return_value=mock_repo_data),
patch.object(service, 'get_installations', return_value=[123]),
):
repositories = await service.get_all_repositories('pushed', AppMode.SAAS)
# Verify we got the expected number of repositories
assert len(repositories) == 2
# Verify owner_type is correctly set for user repositories
for repo in repositories:
assert repo.owner_type == OwnerType.USER
assert isinstance(repo, Repository)
assert repo.git_provider == ProviderType.GITHUB
@pytest.mark.asyncio
async def test_github_get_repositories_with_organization_owner_type():
"""Test that get_repositories correctly sets owner_type field for organization repositories."""
service = GitHubService(user_id=None, token=SecretStr('test-token'))
# Mock repository data for organization repositories
mock_repo_data = [
{
'id': 789,
'full_name': 'test-org/org-repo',
'private': False,
'stargazers_count': 25,
'owner': {'type': 'Organization'}, # Organization repository
},
{
'id': 101,
'full_name': 'test-org/another-org-repo',
'private': True,
'stargazers_count': 15,
'owner': {'type': 'Organization'}, # Organization repository
},
]
with (
patch.object(service, '_fetch_paginated_repos', return_value=mock_repo_data),
patch.object(service, 'get_installations', return_value=[123]),
):
repositories = await service.get_all_repositories('pushed', AppMode.SAAS)
# Verify we got the expected number of repositories
assert len(repositories) == 2
# Verify owner_type is correctly set for organization repositories
for repo in repositories:
assert repo.owner_type == OwnerType.ORGANIZATION
assert isinstance(repo, Repository)
assert repo.git_provider == ProviderType.GITHUB
@pytest.mark.asyncio
async def test_github_get_repositories_mixed_owner_types():
"""Test that get_repositories correctly handles mixed user and organization repositories."""
service = GitHubService(user_id=None, token=SecretStr('test-token'))
# Mock repository data with mixed owner types
mock_repo_data = [
{
'id': 123,
'full_name': 'test-user/user-repo',
'private': False,
'stargazers_count': 10,
'owner': {'type': 'User'}, # User repository
},
{
'id': 456,
'full_name': 'test-org/org-repo',
'private': True,
'stargazers_count': 25,
'owner': {'type': 'Organization'}, # Organization repository
},
]
with (
patch.object(service, '_fetch_paginated_repos', return_value=mock_repo_data),
patch.object(service, 'get_installations', return_value=[123]),
):
repositories = await service.get_all_repositories('pushed', AppMode.SAAS)
# Verify we got the expected number of repositories
assert len(repositories) == 2
# Verify owner_type is correctly set for each repository
user_repo = next(repo for repo in repositories if 'user-repo' in repo.full_name)
org_repo = next(repo for repo in repositories if 'org-repo' in repo.full_name)
assert user_repo.owner_type == OwnerType.USER
assert org_repo.owner_type == OwnerType.ORGANIZATION
@pytest.mark.asyncio
async def test_github_get_repositories_owner_type_fallback():
"""Test that owner_type defaults to USER when owner type is not 'Organization'."""
service = GitHubService(user_id=None, token=SecretStr('test-token'))
# Mock repository data with missing or unexpected owner type
mock_repo_data = [
{
'id': 123,
'full_name': 'test-user/test-repo',
'private': False,
'stargazers_count': 10,
'owner': {'type': 'User'}, # Explicitly User
},
{
'id': 456,
'full_name': 'test-user/another-repo',
'private': True,
'stargazers_count': 5,
'owner': {'type': 'Bot'}, # Unexpected type
},
{
'id': 789,
'full_name': 'test-user/third-repo',
'private': False,
'stargazers_count': 15,
'owner': {}, # Missing type
},
]
with (
patch.object(service, '_fetch_paginated_repos', return_value=mock_repo_data),
patch.object(service, 'get_installations', return_value=[123]),
):
repositories = await service.get_all_repositories('pushed', AppMode.SAAS)
# Verify all repositories default to USER owner_type
for repo in repositories:
assert repo.owner_type == OwnerType.USER