forked from MeltanoLabs/tap-github
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_tap.py
More file actions
366 lines (319 loc) · 12.2 KB
/
test_tap.py
File metadata and controls
366 lines (319 loc) · 12.2 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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
from __future__ import annotations
import json
import re
from unittest.mock import patch
import pytest
from bs4 import BeautifulSoup
from dateutil.parser import isoparse
from requests import Response
from singer_sdk.exceptions import RetriableAPIError
from singer_sdk.helpers import _catalog as cat_helpers
from singer_sdk.singerlib import Catalog
from tap_github.repository_streams import GitHubRestStream
from tap_github.scraping import parse_counter
from tap_github.tap import TapGitHub
from .fixtures import ( # noqa: F401
alternative_sync_chidren,
repo_list_config,
username_list_config,
)
repo_list_2 = [
"MeltanoLabs/tap-github",
# mistype the repo name so we can check that the tap corrects it
"MeltanoLabs/Tap-GitLab",
# mistype the org
"meltanolabs/target-athena",
# a repo that does not exist at all
# this one has no matching record below as it should be removed
# from the list by the TempStream
"brokenOrg/does_not_exist",
]
# the same list, but without typos, for validation
repo_list_2_corrected = [
"MeltanoLabs/tap-github",
"MeltanoLabs/tap-gitlab",
"MeltanoLabs/target-athena",
]
# the github repo ids that match the repo names above
# in the same order
repo_list_2_ids = [
365087920,
416891176,
361619143,
]
@pytest.mark.repo_list(repo_list_2)
def test_validate_repo_list_config(repo_list_config): # noqa: F811
"""Verify that the repositories list is parsed correctly"""
repo_list_context = [
{
"org": repo[0].split("/")[0],
"repo": repo[0].split("/")[1],
"repo_id": repo[1],
}
for repo in zip(repo_list_2_corrected, repo_list_2_ids, strict=False)
]
tap = TapGitHub(config=repo_list_config)
partitions = tap.streams["repositories"].partitions
assert partitions == repo_list_context
def run_tap_with_config(
capsys, config_obj: dict, skip_stream: str | None, single_stream: str | None
) -> str:
"""
Run the tap with the given config and capture stdout, optionally
skipping a stream (this is meant to be the top level stream), or
running a single one.
"""
tap1 = TapGitHub(config=config_obj)
tap1.run_discovery()
catalog = Catalog.from_dict(tap1.catalog_dict)
# Reset and re-initialize with an input catalog
if skip_stream is not None:
cat_helpers.set_catalog_stream_selected(
catalog=catalog,
stream_name=skip_stream,
selected=False,
)
elif single_stream is not None:
cat_helpers.deselect_all_streams(catalog)
cat_helpers.set_catalog_stream_selected(catalog, "repositories", selected=True)
cat_helpers.set_catalog_stream_selected(
catalog, stream_name=single_stream, selected=True
)
# discard previous output to stdout (potentially from other tests)
capsys.readouterr()
with patch(
"singer_sdk.streams.core.Stream._sync_children", alternative_sync_chidren
):
tap2 = TapGitHub(config=config_obj, catalog=catalog.to_dict())
tap2.sync_all()
captured = capsys.readouterr()
return captured.out
@pytest.mark.parametrize("skip_parent_streams", [False, True])
@pytest.mark.repo_list(repo_list_2)
def test_get_a_repository_in_repo_list_mode(
capsys,
repo_list_config, # noqa: F811
skip_parent_streams,
):
"""
Discover the catalog, and request 2 repository records.
The test is parametrized to run twice, with and without
syncing the top level `repositories` stream.
"""
repo_list_config["skip_parent_streams"] = skip_parent_streams
captured_out = run_tap_with_config(
capsys,
repo_list_config,
"repositories" if skip_parent_streams else None,
single_stream=None,
)
# Verify we got the right number of records
# one per repo in the list only if we sync the "repositories" stream, 0 if not
assert captured_out.count('{"type":"RECORD","stream":"repositories"') == len(
repo_list_2_ids * (not skip_parent_streams)
)
# check that the tap corrects invalid case in config input
assert '"repo": "Tap-GitLab"' not in captured_out
assert '"org": "meltanolabs"' not in captured_out
def test_repository_child_context_includes_pull_request_capability(repo_list_config): # noqa: F811
"""Verify repository context includes the pull request capability flag."""
tap = TapGitHub(config=repo_list_config)
repository_stream = tap.streams["repositories"]
context = repository_stream.get_child_context(
{
"id": 123,
"name": "issues-pi",
"owner": {"login": "shop"},
"has_pull_requests": False,
},
None,
)
assert context["has_pull_requests"] is False
def test_repository_child_context_defaults_pull_request_capability_to_enabled(
repo_list_config, # noqa: F811
):
"""Preserve existing behavior when GitHub does not return the capability flag."""
tap = TapGitHub(config=repo_list_config)
repository_stream = tap.streams["repositories"]
context = repository_stream.get_child_context(
{
"id": 123,
"name": "tap-github",
"owner": {"login": "MeltanoLabs"},
},
None,
)
assert context["has_pull_requests"] is True
def test_pull_requests_stream_skips_repos_with_pull_requests_disabled(
repo_list_config, # noqa: F811
):
"""Do not call the pull requests API when repo metadata says it is disabled."""
tap = TapGitHub(config=repo_list_config)
pull_requests_stream = tap.streams["pull_requests"]
context = {
"org": "shop",
"repo": "issues-pi",
"repo_id": 123,
"has_pull_requests": False,
}
with (
patch.object(GitHubRestStream, "get_records") as get_records,
patch.object(pull_requests_stream.logger, "debug") as log_debug,
):
records = list(pull_requests_stream.get_records(context))
assert records == []
get_records.assert_not_called()
log_debug.assert_called_once_with(
"Repository shop/issues-pi: Pull requests not enabled, skipping API call",
)
@pytest.mark.parametrize("has_pull_requests", [True, None, 0, "missing"])
def test_pull_requests_stream_delegates_when_pull_request_capability_is_not_false(
repo_list_config, # noqa: F811
has_pull_requests,
):
"""Fail open when the capability flag is enabled, missing, or unknown."""
tap = TapGitHub(config=repo_list_config)
pull_requests_stream = tap.streams["pull_requests"]
context = {
"org": "MeltanoLabs",
"repo": "tap-github",
"repo_id": 123,
}
if has_pull_requests != "missing":
context["has_pull_requests"] = has_pull_requests
with patch.object(
GitHubRestStream,
"get_records",
return_value=iter([{"id": 456}]),
) as get_records:
records = list(pull_requests_stream.get_records(context))
assert records == [{"id": 456}]
get_records.assert_called_once_with(context)
def test_issues_stream_delegates_when_has_issues_is_false(
repo_list_config, # noqa: F811
):
"""Do not infer issues gating from repository feature metadata."""
tap = TapGitHub(config=repo_list_config)
issues_stream = tap.streams["issues"]
context = {
"org": "shop",
"repo": "issues-pi",
"repo_id": 123,
"has_issues": False,
}
with patch.object(
GitHubRestStream,
"get_records",
return_value=iter([{"id": 789}]),
) as get_records:
records = list(issues_stream.get_records(context))
assert records == [{"id": 789}]
get_records.assert_called_once_with(context)
def test_pull_requests_stream_keeps_generic_404_retriable(
repo_list_config, # noqa: F811
):
"""Pull request gating must not broaden tolerated GitHub errors."""
tap = TapGitHub(config=repo_list_config)
pull_requests_stream = tap.streams["pull_requests"]
response = Response()
response.status_code = 404
response.url = "https://api.github.com/repos/shop/issues-pi/pulls"
response.reason = "Not Found"
response._content = b'{"message": "Not Found"}'
response.headers["X-GitHub-Request-Id"] = "request-id"
with pytest.raises(RetriableAPIError, match="404 Client Error"):
pull_requests_stream.validate_response(response)
@pytest.mark.repo_list(["MeltanoLabs/tap-github"])
def test_last_state_message_is_valid(capsys, repo_list_config): # noqa: F811
"""
Validate that the last state message is not a temporary one and contains the
expected values for a stream with overridden state partitioning keys.
Run this on a single repo to avoid having to filter messages too much.
"""
repo_list_config["skip_parent_streams"] = True
captured_out = run_tap_with_config(
capsys, repo_list_config, "repositories", single_stream=None
)
# capture the messages we're interested in
state_messages = re.findall(r'{"type":"STATE","value":.*}', captured_out)
issue_comments_records = re.findall(
r'{"type":"RECORD","stream":"issue_comments",.*}', captured_out
)
assert state_messages is not None
last_state_msg = state_messages[-1]
# make sure we don't have a temporary state message at the very end
assert "progress_markers" not in last_state_msg
last_state = json.loads(last_state_msg)
last_state_updated_at = isoparse(
last_state["value"]["bookmarks"]["issue_comments"]["partitions"][0][
"replication_key_value"
]
)
latest_updated_at = max(
isoparse(json.loads(record)["record"]["updated_at"])
for record in issue_comments_records
)
assert last_state_updated_at == latest_updated_at
# case is incorrect on purpose, so we can check that the tap corrects it
# and run the test twice, with and without syncing the `users` stream
@pytest.mark.parametrize("skip_parent_streams", [False, True])
@pytest.mark.username_list(["EricBoucher", "aaRONsTeeRS"])
def test_get_a_user_in_user_usernames_mode(
capsys,
username_list_config, # noqa: F811
skip_parent_streams,
):
"""
Discover the catalog, and request 2 repository records
"""
username_list_config["skip_parent_streams"] = skip_parent_streams
captured_out = run_tap_with_config(
capsys,
username_list_config,
"users" if skip_parent_streams else None,
single_stream=None,
)
# Verify we got the right number of records:
# one per user in the list if we sync the root stream, 0 otherwise
assert captured_out.count('{"type":"RECORD","stream":"users"') == len(
username_list_config["user_usernames"] * (not skip_parent_streams)
)
# these 2 are inequalities as number will keep changing :)
assert captured_out.count('{"type":"RECORD","stream":"starred"') > 150
assert captured_out.count('{"type":"RECORD","stream":"user_contributed_to"') > 25
assert '{"username":"aaronsteers"' in captured_out
assert '{"username":"aaRONsTeeRS"' not in captured_out
assert '{"username":"EricBoucher"' not in captured_out
@pytest.mark.repo_list(["torvalds/linux"])
def test_large_list_of_contributors(capsys, repo_list_config): # noqa: F811
"""
Check that the github error message for very large lists of contributors
is handled properly (does not return any records).
"""
captured_out = run_tap_with_config(
capsys, repo_list_config, skip_stream=None, single_stream="contributors"
)
assert captured_out.count('{"type":"RECORD","stream":"contributors"') == 0
def test_web_tag_parse_counter():
"""
Check that the parser runs ok on various forms of counters.
Used in extra_metrics stream.
"""
# regular int
tag = BeautifulSoup(
'<span id="issues-repo-tab-count" title="57" class="Counter">57</span>',
"html.parser",
).span
assert parse_counter(tag) == 57
# 2k
tag = BeautifulSoup(
'<span id="issues-repo-tab-count" title="2028" class="Counter">2k</span>',
"html.parser",
).span
assert parse_counter(tag) == 2028
# 5k+. The real number is not available in the page, use this approx value
tag = BeautifulSoup(
'<span id="issues-repo-tab-count" title="5,000+" class="Counter">5k+</span>',
"html.parser",
).span
assert parse_counter(tag) == 5_000