Repository navigation
Expand file tree
/
Copy pathtest_github_client.py
More file actions
339 lines (296 loc) · 11.7 KB
/
Copy pathtest_github_client.py
File metadata and controls
339 lines (296 loc) · 11.7 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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
#!/usr/bin/env python3
"""
Unit tests for GitHubActionClient.
"""
import pytest
import os
from unittest.mock import Mock, patch
from claudecode.github_action_audit import GitHubActionClient
class TestGitHubActionClient:
"""Test GitHubActionClient functionality."""
def test_init_requires_token(self):
"""Test that client initialization requires GITHUB_TOKEN."""
# Remove token if it exists
original_token = os.environ.pop('GITHUB_TOKEN', None)
try:
with pytest.raises(ValueError, match="GITHUB_TOKEN environment variable required"):
GitHubActionClient()
finally:
# Restore token
if original_token:
os.environ['GITHUB_TOKEN'] = original_token
def test_init_with_token(self):
"""Test successful initialization with token."""
with patch.dict(os.environ, {'GITHUB_TOKEN': 'test-token'}):
client = GitHubActionClient()
assert client.github_token == 'test-token'
assert client.headers['Authorization'] == 'Bearer test-token'
assert 'Accept' in client.headers
assert 'X-GitHub-Api-Version' in client.headers
@patch('requests.get')
def test_get_pr_data_success(self, mock_get):
"""Test successful PR data retrieval."""
# Mock responses
pr_response = Mock()
pr_response.json.return_value = {
'number': 123,
'title': 'Test PR',
'body': 'PR description',
'user': {'login': 'testuser'},
'created_at': '2024-01-01T00:00:00Z',
'updated_at': '2024-01-01T01:00:00Z',
'state': 'open',
'head': {
'ref': 'feature-branch',
'sha': 'abc123',
'repo': {
'full_name': 'owner/repo'
}
},
'base': {
'ref': 'main',
'sha': 'def456'
},
'additions': 50,
'deletions': 10,
'changed_files': 3
}
files_response = Mock()
files_response.json.return_value = [
{
'filename': 'src/main.py',
'status': 'modified',
'additions': 30,
'deletions': 5,
'changes': 35,
'patch': '@@ -1,5 +1,10 @@\n+import os\n def main():'
},
{
'filename': 'tests/test_main.py',
'status': 'added',
'additions': 20,
'deletions': 5,
'changes': 25,
'patch': '@@ -0,0 +1,20 @@\n+def test_main():'
}
]
mock_get.side_effect = [pr_response, files_response]
with patch.dict(os.environ, {'GITHUB_TOKEN': 'test-token'}):
client = GitHubActionClient()
result = client.get_pr_data('owner/repo', 123)
# Verify API calls
assert mock_get.call_count == 2
mock_get.assert_any_call(
'https://api.github.com/repos/owner/repo/pulls/123',
headers=client.headers
)
mock_get.assert_any_call(
'https://api.github.com/repos/owner/repo/pulls/123/files?per_page=100',
headers=client.headers
)
# Verify result structure
assert result['number'] == 123
assert result['title'] == 'Test PR'
assert result['user'] == 'testuser'
assert len(result['files']) == 2
assert result['files'][0]['filename'] == 'src/main.py'
assert result['files'][1]['status'] == 'added'
@patch('requests.get')
def test_get_pr_data_null_head_repo(self, mock_get):
"""Test PR data retrieval when head repo is null (deleted fork)."""
pr_response = Mock()
pr_response.json.return_value = {
'number': 123,
'title': 'Test PR',
# Don't include body key to test the get() default
'user': {'login': 'testuser'},
'created_at': '2024-01-01T00:00:00Z',
'updated_at': '2024-01-01T01:00:00Z',
'state': 'open',
'head': {
'ref': 'feature-branch',
'sha': 'abc123',
'repo': None # Deleted fork
},
'base': {
'ref': 'main',
'sha': 'def456'
},
'additions': 50,
'deletions': 10,
'changed_files': 3
}
files_response = Mock()
files_response.json.return_value = []
mock_get.side_effect = [pr_response, files_response]
with patch.dict(os.environ, {'GITHUB_TOKEN': 'test-token'}):
client = GitHubActionClient()
result = client.get_pr_data('owner/repo', 123)
# Should use original repo name when head repo is None
assert result['head']['repo']['full_name'] == 'owner/repo'
# The implementation passes None through, test should match that
assert result['body'] == ''
@patch('requests.get')
def test_get_pr_data_api_error(self, mock_get):
"""Test PR data retrieval with API error."""
mock_response = Mock()
mock_response.raise_for_status.side_effect = Exception("API Error")
mock_get.return_value = mock_response
with patch.dict(os.environ, {'GITHUB_TOKEN': 'test-token'}):
client = GitHubActionClient()
with pytest.raises(Exception, match="API Error"):
client.get_pr_data('owner/repo', 123)
@patch('requests.get')
def test_get_pr_diff_success(self, mock_get):
"""Test successful PR diff retrieval."""
diff_content = """diff --git a/src/main.py b/src/main.py
index abc123..def456 100644
--- a/src/main.py
+++ b/src/main.py
@@ -1,5 +1,10 @@
+import os
def main():
print("Hello")
+ # New feature
+ process_data()
"""
mock_response = Mock()
mock_response.text = diff_content
mock_response.raise_for_status.return_value = None
mock_get.return_value = mock_response
with patch.dict(os.environ, {'GITHUB_TOKEN': 'test-token'}):
client = GitHubActionClient()
result = client.get_pr_diff('owner/repo', 123)
# Verify API call
mock_get.assert_called_once()
call_args = mock_get.call_args
assert call_args[0][0] == 'https://api.github.com/repos/owner/repo/pulls/123'
assert call_args[1]['headers']['Accept'] == 'application/vnd.github.diff'
# Verify result
assert 'import os' in result
assert 'process_data()' in result
@patch('requests.get')
def test_get_pr_diff_filters_generated_files(self, mock_get):
"""Test that generated files are filtered from diff."""
diff_with_generated = """diff --git a/src/main.py b/src/main.py
index abc123..def456 100644
--- a/src/main.py
+++ b/src/main.py
@@ -1,5 +1,10 @@
+import os
def main():
print("Hello")
diff --git a/generated/code.py b/generated/code.py
index 111..222 100644
--- a/generated/code.py
+++ b/generated/code.py
@@ -1,3 +1,5 @@
# @generated by protoc
+# More generated code
+print("generated")
diff --git a/src/feature.py b/src/feature.py
index 333..444 100644
--- a/src/feature.py
+++ b/src/feature.py
@@ -1,3 +1,5 @@
+# Real code
def feature():
pass
"""
mock_response = Mock()
mock_response.text = diff_with_generated
mock_response.raise_for_status.return_value = None
mock_get.return_value = mock_response
with patch.dict(os.environ, {'GITHUB_TOKEN': 'test-token'}):
client = GitHubActionClient()
result = client.get_pr_diff('owner/repo', 123)
# Verify generated file is filtered out
assert 'src/main.py' in result
assert 'src/feature.py' in result
assert 'generated/code.py' not in result
assert '@generated' not in result
assert 'More generated code' not in result
def test_filter_generated_files_edge_cases(self):
"""Test edge cases in generated file filtering."""
with patch.dict(os.environ, {'GITHUB_TOKEN': 'test-token'}):
client = GitHubActionClient()
# Empty diff
assert client._filter_generated_files('') == ''
# No diff markers - if no diff format, everything is filtered
text = "Just some random text\nwith @generated in it"
# Since there's no 'diff --git' marker, the split results in one section
# that contains @generated, so it gets filtered out
assert client._filter_generated_files(text) == ''
# Multiple generated markers
diff = """diff --git a/a.py b/a.py
@generated by tool
content
diff --git a/b.py b/b.py
normal content
diff --git a/c.py b/c.py
# This file is @generated
more content
"""
result = client._filter_generated_files(diff)
assert 'a.py' not in result
assert 'b.py' in result
assert 'c.py' not in result
class TestGitHubAPIIntegration:
"""Test GitHub API integration scenarios."""
@patch('requests.get')
def test_rate_limit_handling(self, mock_get):
"""Test that rate limit headers are respected."""
mock_response = Mock()
mock_response.headers = {
'X-RateLimit-Remaining': '0',
'X-RateLimit-Reset': '1234567890'
}
mock_response.status_code = 403
mock_response.json.return_value = {
'message': 'API rate limit exceeded'
}
mock_response.raise_for_status.side_effect = Exception("Rate limit exceeded")
mock_get.return_value = mock_response
with patch.dict(os.environ, {'GITHUB_TOKEN': 'test-token'}):
client = GitHubActionClient()
with pytest.raises(Exception, match="Rate limit exceeded"):
client.get_pr_data('owner/repo', 123)
@patch('requests.get')
def test_pagination_not_needed_for_pr_files(self, mock_get):
"""Test that PR files endpoint returns all files without pagination."""
# GitHub API returns up to 3000 files per PR without pagination
large_file_list = [
{
'filename': f'file{i}.py',
'status': 'added',
'additions': 10,
'deletions': 0,
'changes': 10,
'patch': f'@@ -0,0 +1,10 @@\n+# File {i}'
}
for i in range(100) # 100 files
]
pr_response = Mock()
pr_response.json.return_value = {
'number': 123,
'title': 'Large PR',
'body': 'Many files',
'user': {'login': 'testuser'},
'created_at': '2024-01-01T00:00:00Z',
'updated_at': '2024-01-01T01:00:00Z',
'state': 'open',
'head': {'ref': 'feature', 'sha': 'abc123', 'repo': {'full_name': 'owner/repo'}},
'base': {'ref': 'main', 'sha': 'def456'},
'additions': 1000,
'deletions': 0,
'changed_files': 100
}
files_response = Mock()
files_response.json.return_value = large_file_list
mock_get.side_effect = [pr_response, files_response]
with patch.dict(os.environ, {'GITHUB_TOKEN': 'test-token'}):
client = GitHubActionClient()
result = client.get_pr_data('owner/repo', 123)
assert len(result['files']) == 100
assert result['files'][0]['filename'] == 'file0.py'
assert result['files'][99]['filename'] == 'file99.py'