def test_cannot_pass_both_jwt_and_oauth(self): user_agent = "brettcannon" jwt = "secret jwt" oauth_token = "secret oauth token" with pytest.raises(ValueError) as exc_info: sansio.create_headers(user_agent, oauth_token=oauth_token, jwt=jwt) assert str(exc_info.value) == "Cannot pass both oauth_token and jwt."
async def test__request(self): """Make sure that that abstract method is implemented properly.""" request_headers = sansio.create_headers("gidgethub") gh = gh_tornado.GitHubAPI("gidgethub") tornado_call = await gh._request( "GET", "https://api.github.com/rate_limit", request_headers ) data, rate_limit, _ = sansio.decipher_response(*tornado_call) assert "rate" in data
async def test__request_with_body(self): """Make sure that that abstract method is implemented properly.""" request_headers = sansio.create_headers("gidgethub") gh = gh_tornado.GitHubAPI("gidgethub") # This leads to a 404. tornado_call = await gh._request( "POST", "https://api.github.com/rate_limit", request_headers, b"bogus" ) with pytest.raises(BadRequest): sansio.decipher_response(*tornado_call)
async def test_headers_and_log(github_api: GitHubAPI) -> None: assert github_api.headers is None request_headers = sansio.create_headers("algorithms-keeper") resp = await github_api._request( "GET", "https://api.github.com/rate_limit", request_headers ) data, rate_limit, _ = sansio.decipher_response(*resp) assert "rate" in data # Response headers should now be set. assert github_api.headers is not None
async def test__request(): """Make sure that that abstract method is implemented properly.""" request_headers = sansio.create_headers("gidgethub") async with aiohttp.ClientSession() as session: gh = gh_aiohttp.GitHubAPI(session, "gidgethub") aio_call = await gh._request("GET", "https://api.github.com/rate_limit", request_headers) data, rate_limit, _ = sansio.decipher_response(*aio_call) assert "rate" in data
def delete_branch(branch_name): """ Delete the branch on GitHub """ request_headers = sansio.create_headers( "miss-islington", oauth_token=os.environ.get('GH_AUTH')) url = f"https://api.github.com/repos/miss-islington/cpython/git/refs/heads/{branch_name}" response = requests.delete(url, headers=request_headers) if response.status_code == 204: print(f"{branch_name} branch deleted.") else: print(f"Couldn't delete the branch {branch_name}")
def test_all_keys_lowercase(self): """Test all header fields are lowercase.""" user_agent = "brettcannon" test_api = "application/vnd.github.cloak-preview+json" oauth_token = "secret" headers = sansio.create_headers(user_agent, accept=test_api, oauth_token=oauth_token) assert len(headers) == 3 for key in headers.keys(): assert key == key.lower() assert headers["user-agent"] == user_agent assert headers["accept"] == test_api assert headers["authorization"] == f"token {oauth_token}"
async def check_status(event, gh, *args, **kwargs): """ Check the state change """ if event.data["commit"].get("committer") \ and event.data["commit"]["committer"]["login"] == "miss-islington": sha = event.data["sha"] status_url = f"https://api.github.com/repos/python/cpython/commits/{sha}/status" request_headers = sansio.create_headers( "miss-islington", oauth_token=os.getenv('GH_AUTH')) response = requests.get(status_url, headers=request_headers) result = response.json() all_ci_status = [status["state"] for status in result["statuses"]] all_ci_context = [status["context"] for status in result["statuses"]] print(f"miss-islington's PR state changed: {all_ci_status}") print(f"miss-islington's PR CI: {all_ci_context}") if "pending" not in all_ci_status \ and "continuous-integration/travis-ci/pr" in all_ci_context: url = "https://api.github.com/repos/miss-islington/cpython/git/refs/heads/" response = requests.get(url, headers=request_headers) for ref in response.json(): if "backport-" in ref["ref"] and ref["object"]["sha"] == sha: backport_branch_name = ref["ref"].split("/")[-1] pr_url = f"https://api.github.com/repos/python/cpython/pulls?state=open&head=miss-islington:{backport_branch_name}" pr_response = requests.get(pr_url, headers=request_headers).json() if pr_response: pr_number = pr_response[0]["number"] normalized_pr_title = util.normalize_title( pr_response[0]["title"], pr_response[0]["body"]) title_match = TITLE_RE.match(normalized_pr_title) if title_match: original_pr_number = title_match.group('pr') original_pr_url = f"https://api.github.com/repos/python/cpython/pulls/{original_pr_number}" original_pr_result = requests.get( original_pr_url, headers=request_headers).json() pr_author = original_pr_result["user"]["login"] committer = original_pr_result["merged_by"][ "login"] participants = util.get_participants( pr_author, committer) emoji = "✅" if result['state'] == "success" else "❌" util.comment_on_pr( pr_number, message= f"{participants}: Backport status check is done, and it's a {result['state']} {emoji} ." )
def close_issue(repo_full_name, issue_number): username = os.environ.get("GH_USERNAME") gh_auth = os.environ.get("GH_AUTH") request_headers = sansio.create_headers(username, oauth_token=gh_auth) data = {"state": "closed"} url = f"https://api.github.com/repos/{repo_full_name}/issues/{issue_number}" response = requests.patch(url, headers=request_headers, json=data) if response.status_code == requests.codes.created: print(f"PR created at {response.json()['html_url']}") else: print(response.status_code) print(response.text)
async def test_query(self): gh, response_data = self.gh_and_response("success-200.json") result = await gh.graphql(_SAMPLE_QUERY) assert gh.method == "POST" assert gh.url == "https://api.github.com/graphql" assert gh.headers["content-type"] == "application/json; charset=utf-8" assert gh.headers["content-length"] == str(len(gh.body)) expected_headers = sansio.create_headers( "test_abc", accept="application/json; charset=utf-8", oauth_token="oauth-token", ) for key, value in expected_headers.items(): assert gh.headers[key] == value body = json.loads(gh.body.decode("utf-8")) assert body == {"query": _SAMPLE_QUERY} assert result == response_data["data"]
def comment_on_pr(issue_number, message): """ Leave a comment on a PR/Issue """ request_headers = sansio.create_headers( "miss-islington", oauth_token=os.getenv("GH_AUTH") ) issue_comment_url = ( f"https://api.github.com/repos/python/cpython/issues/{issue_number}/comments" ) data = {"body": message} response = requests.post(issue_comment_url, headers=request_headers, json=data) if response.status_code == requests.codes.created: print(f"Commented at {response.json()['html_url']}, message: {message}") else: print(response.status_code) print(response.text) return response
def comment_on_pr(repo_full_name, issue_number, message): """ Leave a comment on a PR/Issue """ request_headers = sansio.create_headers(os.environ.get("GH_USERNAME"), oauth_token=os.getenv("GH_AUTH")) issue_comment_url = ( f"https://api.github.com/repos/{repo_full_name}/issues/{issue_number}/comments" ) data = {"body": message} response = requests.post(issue_comment_url, headers=request_headers, json=data) if response.status_code == requests.codes.created: print( f"Commented at {response.json()['html_url']}, message: {message}") else: print(response.status_code) print(response.text)
def assign_pr_to_core_dev(issue_number, coredev_login): """ Assign the PR to a core dev. Should be done when miss-islington failed to backport. """ request_headers = sansio.create_headers( "miss-islington", oauth_token=os.getenv("GH_AUTH") ) edit_issue_url = ( f"https://api.github.com/repos/python/cpython/issues/{issue_number}" ) data = {"assignees": [coredev_login]} response = requests.patch(edit_issue_url, headers=request_headers, json=data) if response.status_code == requests.codes.created: print(f"Assigned PR {issue_number} to {coredev_login}") else: print(response.status_code) print(response.text) return response
def remove_label(repo_full_name, pr_number, label): """Remove a label from the PR""" username = os.environ.get("GH_USERNAME") gh_auth = os.environ.get("GH_AUTH") request_headers = sansio.create_headers(username, oauth_token=gh_auth) url = f"https://api.github.com/repos/{repo_full_name}/pulls/{pr_number}" response = requests.get(url, headers=request_headers) pr_data = response.json() labels = [ pr_label["name"] for pr_label in pr_data["labels"] if pr_label["name"] != label ] url = f"https://api.github.com/repos/{repo_full_name}/issues/{pr_number}" data = {"labels": labels} response = requests.patch(url, headers=request_headers, json=data) print(response.status_code) print(response.text)
def create_gh_pr(self, base_branch, head_branch, *, commit_message, gh_auth): """ Create PR in GitHub """ request_headers = sansio.create_headers(self.username, oauth_token=gh_auth) title, body = normalize_commit_message(commit_message) data = { "title": title, "body": body, "head": f"{self.username}:{head_branch}", "base": base_branch, "maintainer_can_modify": True } response = requests.post(CPYTHON_CREATE_PR_URL, headers=request_headers, json=data) if response.status_code == requests.codes.created: click.echo(f"Backport PR created at {response.json()['html_url']}") else: click.echo(response.status_code) click.echo(response.text)
def test_authorization_with_jwt(self): user_agent = "brettcannon" jwt = "secret" headers = sansio.create_headers(user_agent, jwt=jwt) assert headers["user-agent"] == user_agent assert headers["authorization"] == f"bearer {jwt}"
def test_api_change(self): test_api = "application/vnd.github.cloak-preview+json" user_agent = "brettcannon" headers = sansio.create_headers(user_agent, accept=test_api) assert headers["user-agent"] == user_agent assert headers["accept"] == test_api
def test_common_case(self): user_agent = "brettcannon" oauth_token = "secret" headers = sansio.create_headers(user_agent, oauth_token=oauth_token) assert headers["user-agent"] == user_agent assert headers["authorization"] == f"token {oauth_token}"
def get_request_headers(): username = os.environ.get("GH_USERNAME") gh_auth = os.environ.get("GH_AUTH") return sansio.create_headers(username, oauth_token=gh_auth)