def test_client_methods_are_lower_case(self): for client in Octokit().__dict__: try: cls = getattr(Octokit(), client).__dict__ assert all(method.islower() for method in cls) except AttributeError: pass # ignore non-class attributes
def test_must_include_required_array_sub_parameters_when_used( self, mocker): mocker.patch("requests.get") data = { "owner": "owner", "repo": "repo", "name": "name", "head_sha": "master", "actions": [] } with pytest.raises(errors.OctokitParameterError) as e: Octokit().checks.create(**data) assert "property is missing required items" == str(e.value) data.update({"actions": [{"label": "blah"}]}) with pytest.raises(errors.OctokitParameterError) as e: Octokit().checks.create(**data) assert "description is a required parameter" == str(e.value) data.update({ "actions": [{ "label": "blah", "description": "x", "identifier": "a" }] }) Octokit().checks.create(**data)
def test_validate_method_parameters(self, mocker): mocker.patch("requests.get") Octokit().oauth_authorizations.get_authorization(authorization_id=100) requests.get.assert_called_once_with( "https://api.github.com/authorizations/100", params={}, headers=Octokit().headers)
def test_has_required_method_parameters(self): with pytest.raises(errors.OctokitParameterError) as e1: Octokit().oauth_authorizations.get_authorization() assert "authorization_id is a required parameter" == str(e1.value) with pytest.raises(errors.OctokitParameterError) as e2: Octokit().oauth_authorizations.get_authorization( authorization_id=None) assert "authorization_id must have a value" == str(e2.value)
def test_cannot_set_installation_authentication_with_out_required_data(self): with pytest.raises(KeyError): Octokit(auth="installation") with pytest.raises(AssertionError): Octokit(auth="installation", app_id="") with pytest.raises(KeyError): Octokit(auth="installation", app_id="42") with pytest.raises(AssertionError): Octokit(auth="installation", app_id="42", private_key="")
def test_token_auth_used_if_set(self, mocker): mocker.patch('requests.get') Octokit(auth='token', token='yak').oauth_authorizations.get_authorization(authorization_id=100) headers = dict(ChainMap(Octokit().headers, {'Authorization': 'token yak'})) requests.get.assert_called_once_with( 'https://api.github.com/authorizations/100', params={}, headers=headers, )
def test_can_speficy_the_route_specifications_used(self): from octokit import Octokit octokit = Octokit(routes="ghe-2.18") assert "/enterprise/2.18" in octokit.issues.create.__doc__ octokit = Octokit() assert "/developer.github.com" in octokit.issues.create.__doc__ octokit = Octokit(routes="api.github.com") assert "/developer.github.com" in octokit.issues.create.__doc__
def test_cannot_set_app_authentication_with_out_required_data(self): with pytest.raises(KeyError): Octokit(auth="app") with pytest.raises(AssertionError): Octokit(auth="app", app_id="") with pytest.raises(KeyError): Octokit(auth="app", app_id=42) with pytest.raises(AssertionError): Octokit(auth="app", app_id=42, private_key="")
def test_non_default_params_not_in_the_url_for_get_requests_go_in_the_query_string( self, mocker): mocker.patch("requests.get") params = {"page": 2, "per_page": 30} Octokit().oauth_authorizations.list_grants(page=2) requests.get.assert_called_once_with( "https://api.github.com/applications/grants", params=params, headers=Octokit().headers)
def test_basic_auth_used_if_set(self, mocker): mocker.patch('requests.get') Octokit(auth='basic', username='******', password='******').authorization.get(id=100) requests.get.assert_called_once_with( 'https://api.github.com/authorizations/100', params={}, headers=Octokit().headers, auth=('myuser', 'mypassword'))
def test_cannot_set_installation_authentication_with_out_required_data(self): with pytest.raises(KeyError): Octokit(auth='installation') with pytest.raises(AssertionError): Octokit(auth='installation', app_id='') with pytest.raises(KeyError): Octokit(auth='installation', app_id='42') with pytest.raises(AssertionError): Octokit(auth='installation', app_id='42', private_key='')
def test_token_auth_used_if_set(self, mocker): mocker.patch("requests.get") Octokit(auth="token", token="yak").oauth_authorizations.get_authorization( authorization_id=100) headers = dict( ChainMap(Octokit().headers, {"Authorization": "token yak"})) requests.get.assert_called_once_with( "https://api.github.com/authorizations/100", params={}, headers=headers)
def test_basic_auth_used_if_set(self, mocker): mocker.patch("requests.get") Octokit(auth="basic", username="******", password="******").oauth_authorizations.get_authorization( authorization_id=100) requests.get.assert_called_once_with( "https://api.github.com/authorizations/100", params={}, headers=Octokit().headers, auth=("myuser", "mypassword"), )
def test_cannot_set_basic_authentication_with_out_required_data(self): with pytest.raises(KeyError): Octokit(auth="basic") with pytest.raises(AssertionError): Octokit(auth="basic", username="******", password="") with pytest.raises(KeyError): Octokit(auth="basic", password="******") with pytest.raises(AssertionError): Octokit(auth="basic", username="") with pytest.raises(KeyError): Octokit(auth="basic", username="******")
def test_cannot_set_basic_authentication_with_out_required_data(self): with pytest.raises(KeyError): Octokit(auth='basic') with pytest.raises(AssertionError): Octokit(auth='basic', username='******', password='') with pytest.raises(KeyError): Octokit(auth='basic', password='******') with pytest.raises(AssertionError): Octokit(auth='basic', username='') with pytest.raises(KeyError): Octokit(auth='basic', username='******')
def test_auth_token(self): hub = Octokit(access_token='so_secret_wow') self.assertEqual(hub.authenticated, True) self.assertEqual(hub.user_authenticated, True) self.assertEqual(hub.token_authenticated, True) self.assertEqual(hub.basic_authenticated, False) self.assertEqual(hub.application_authenticated, False) with vcr.use_cassette('auth.yml'): user = hub.users('irqed').get() self.assertEqual(user['login'], 'irqed')
def test_auth_login_password(self): hub = Octokit(login='******', password='******') self.assertEqual(hub.authenticated, True) self.assertEqual(hub.user_authenticated, True) self.assertEqual(hub.basic_authenticated, True) self.assertEqual(hub.token_authenticated, False) self.assertEqual(hub.application_authenticated, False) with vcr.use_cassette('auth.yml'): user = hub.users('octocat').get() self.assertEqual(user['login'], 'octocat')
def test_must_include_required_dictionary_sub_parameters_when_used( self, mocker): mocker.patch("requests.get") data = {"owner": "owner", "repo": "repo", "name": "name"} with pytest.raises(errors.OctokitParameterError) as e: Octokit().checks.create(**data) assert "head_sha is a required parameter" == str(e.value) data.update({"head_sha": "master", "output": {"title": "blah"}}) with pytest.raises(errors.OctokitParameterError) as e: Octokit().checks.create(**data) assert "summary is a required parameter" == str(e.value) data.update({"output": {"title": "blah", "summary": "that"}}) Octokit().checks.create(**data)
def test_installation_token_is_used_if_set(self, mocker): Request = namedtuple("Request", ["json"]) get = mocker.patch("requests.get") get.return_value = Request(json=lambda: [{ "id": 13, "app_id": 1 }, { "id": 37, "app_id": 42 }]) post = mocker.patch("requests.post") post.return_value = Request(json=lambda: { "token": "v1.1f699f1069f60", "expires_at": "2016-07-11T22:14:10Z", }) with open(os.path.join(os.path.dirname(__file__), "test.pem"), "r") as f: private_key = f.read() sut = Octokit(auth="installation", app_id="42", private_key=private_key) assert sut.installation_id == 37 get = mocker.patch("requests.get") sut.oauth_authorizations.get_authorization(authorization_id=100) headers = { "Content-Type": "application/json", "Authorization": "token v1.1f699f1069f60", "accept": "application/vnd.github.machine-man-preview+json", } requests.get.assert_called_once_with( "https://api.github.com/authorizations/100", params={}, headers=headers)
def test_returned_object_has_response_attributes(self, mocker): patch = mocker.patch("requests.patch") data = { "id": 1, "number": 1347, "state": "open", "title": "Found a bug", "user": { "login": "******", "site_admin": False }, "labels": [{ "id": 208045946 }, { "id": 208045947 }], } Request = namedtuple("Request", ["json"]) patch.return_value = Request(json=lambda: data) sut = Octokit().issues.update(owner="testUser", repo="testRepo", issue_number=1) assert sut.response.id == 1 assert sut.response.number == 1347 assert sut.response.state == "open" assert str(sut.response.user) == "<class 'octokit.ResponseData'>" assert sut.response.user.login == "octocat" assert sut.response.user.site_admin is False assert sut.response.labels[0].id == 208045946
def test_does_not_use_previous_values(self, mocker): mocker.patch("requests.patch") mocker.patch("requests.post") headers = { "accept": "application/vnd.github.v3+json", "Content-Type": "application/json" } data = {"state": "closed"} issue = Octokit().issues.update(owner="testUser", repo="testRepo", issue_number=1, **data) requests.patch.assert_called_with( "https://api.github.com/repos/testUser/testRepo/issues/1", data=json.dumps(data), headers=headers) issue.pulls.create(owner="user", head="branch", base="master", title="Title", repo="testRepo") requests.post.assert_called_with( "https://api.github.com/repos/user/testRepo/pulls", data=json.dumps( { "base": "master", "head": "branch", "title": "Title" }, sort_keys=True), headers={ "Content-Type": "application/json", "accept": "application/vnd.github.v3+json" }, )
def test_installation_token_is_used_if_set(self, mocker): Request = namedtuple('Request', ['json']) get = mocker.patch('requests.get') get.return_value = Request(json=lambda: [{ 'id': 13, 'app_id': 1 }, { 'id': 37, 'app_id': 42 }]) post = mocker.patch('requests.post') post.return_value = Request(json=lambda: { 'token': 'v1.1f699f1069f60', 'expires_at': '2016-07-11T22:14:10Z' }) with open(os.path.join(os.path.dirname(__file__), 'test.pem'), 'r') as f: private_key = f.read() sut = Octokit(auth='installation', app_id='42', private_key=private_key) assert sut.installation_id == 37 get = mocker.patch('requests.get') sut.authorization.get(id=100) headers = { 'Content-Type': 'application/json', 'Authorization': 'token v1.1f699f1069f60', 'accept': 'application/vnd.github.machine-man-preview+json' } requests.get.assert_called_once_with( 'https://api.github.com/authorizations/100', params={}, headers=headers, )
def test_auth_application(self): hub = Octokit( client_id='so_id_wow', client_secret='so_secret_wow' ) self.assertEqual(hub.authenticated, True) self.assertEqual(hub.application_authenticated, True) self.assertEqual(hub.basic_authenticated, False) self.assertEqual(hub.token_authenticated, False) self.assertEqual(hub.user_authenticated, False) with vcr.use_cassette('auth.yml'): user = hub.users('mojombo').get() self.assertEqual(user['login'], 'mojombo')
def fetch_data_from_github(pull_request): pr_attrs = pull_request.split('/') # ['https:', '', 'github.com', 'owner', 'repo', 'pull', 'pull_number'] octokit = Octokit(auth='token', token=os.getenv("TOKEN")) # octokit = Octokit() pr_data = octokit.pulls.get(owner=pr_attrs[3], repo=pr_attrs[4], pull_number=int(pr_attrs[6])) commits = octokit.pulls.list_commits(owner=pr_attrs[3], repo=pr_attrs[4], pull_number=int(pr_attrs[6])) try: commit_messages = '' number_of_commits = pr_data.json["commits"] number_of_changes = pr_data.json["additions"] + pr_data.json["deletions"] number_of_files_changed = pr_data.json["changed_files"] for commit_object in commits.json: commit_messages += f'{commit_object["commit"]["message"]} ' diffs = requests.get(pr_data.json["diff_url"]).text number_of_docs_changed = get_docs_changed(diffs) return { "url": pull_request, "title": pr_data.json["title"], "body": pr_data.json["body"], "diffs": diffs, "commit_messages": commit_messages, "files_changed": number_of_files_changed, "docs_changed": number_of_docs_changed, "commits": number_of_commits, "changes": number_of_changes } except: print(f"Error in {pull_request}: ", pr_data.json)
def test_dictionary_keys_are_validated_multiple_times_in_a_row( self, mocker): mocker.patch("requests.put") headers = { "accept": "application/vnd.github.v3+json", "Content-Type": "application/json" } data = { "required_status_checks": { "strict": True, "contexts": [] }, "required_pull_request_reviews": { "dismiss_stale_reviews": True }, "enforce_admins": True, "restrictions": { "users": [], "teams": [] }, } for run in range(4): Octokit().repos.update_branch_protection( owner="user", repo="repo", branch="branch{}".format(run), **data) requests.put.assert_called_with( "https://api.github.com/repos/user/repo/branches/branch{}/protection" .format(run), data=json.dumps(data, sort_keys=True), headers=headers, )
def test_can_override_previous_values(self, mocker): mocker.patch('requests.patch') mocker.patch('requests.post') headers = { 'accept': 'application/vnd.github.v3+json', 'Content-Type': 'application/json' } data = {'state': 'closed'} issue = Octokit().issues.edit(owner='testUser', repo='testRepo', number=1, **data) requests.patch.assert_called_with( 'https://api.github.com/repos/testUser/testRepo/issues/1', data=json.dumps(data), headers=headers) issue.pulls.create(owner='user', head='branch', base='master', title='Title') requests.post.assert_called_with( 'https://api.github.com/repos/user/testRepo/pulls', data=json.dumps( { 'base': 'master', 'head': 'branch', 'title': 'Title', }, sort_keys=True), headers={ 'Content-Type': 'application/json', 'accept': 'application/vnd.github.v3+json' })
def test_returned_object_has_response_attributes(self, mocker): patch = mocker.patch('requests.patch') data = { "id": 1, "number": 1347, "state": "open", "title": "Found a bug", "user": { "login": "******", "site_admin": False }, "labels": [{ "id": 208045946, }, { "id": 208045947, }], } Request = namedtuple('Request', ['json']) patch.return_value = Request(json=lambda: data) sut = Octokit().issues.edit(owner='testUser', repo='testRepo', number=1) assert sut.response.id == 1 assert sut.response.number == 1347 assert sut.response.state == 'open' assert str(sut.response.user) == '<class \'octokit.ResponseData\'>' assert sut.response.user.login == 'octocat' assert sut.response.user.site_admin is False assert sut.response.labels[0].id == 208045946
def test_dictionary_keys_are_validated(self, mocker): mocker.patch('requests.put') headers = { 'accept': 'application/vnd.github.v3+json', 'Content-Type': 'application/json' } data = { "required_status_checks": { "strict": True, "contexts": [], }, "required_pull_request_reviews": { "dismiss_stale_reviews": True }, "enforce_admins": True, "restrictions": { "users": [], "teams": [], } } Octokit().repos.update_branch_protection(owner='user', repo='repo', branch='branch', **data) requests.put.assert_called_with( 'https://api.github.com/repos/user/repo/branches/branch/protection', data=json.dumps(data, sort_keys=True), headers=headers)
def test_pagination(self): from octokit import Octokit sut_obj = MockResponse p = Octokit().paginate(sut_obj, param='value') assert next(p) == {'page': 1, 'kwargs': {'param': 'value'}} assert next(p) == {'page': 2, 'kwargs': {'param': 'value'}} assert next(p) == {'page': 3, 'kwargs': {'param': 'value'}} assert next(p) == {'page': 4, 'kwargs': {'param': 'value'}}
def test_validate_enum_values(self): with pytest.raises(errors.OctokitParameterError) as e: Octokit().issues.update(owner="testUser", repo="testRepo", issue_number=1, state="closeddddd") assert "closeddddd is not a valid option for state; must be one of ['open', 'closed']" == str( e.value)
def test_request_has_body_parameters(self, mocker): mocker.patch("requests.post") data = {"note": "remind me", "scopes": ["public_repo"]} create = Octokit().oauth_authorizations.create_authorization(**data) requests.post.assert_called_once_with( "https://api.github.com/authorizations", data=json.dumps(data, sort_keys=True), headers=create.headers)
def test_returned_object_has_requests_response_object(self, mocker): patch = mocker.patch("requests.patch") Response = namedtuple("Response", ["json"]) patch.return_value = Response(json=lambda: {}) sut = Octokit().issues.update(owner="testUser", repo="testRepo", issue_number=1) assert sut._response.__class__.__name__ == "Response"
def test_an_exception_with_json_is_replaced_by_the_raw_text(self, mocker): patch = mocker.patch("requests.patch") Request = namedtuple("Request", ["json"]) patch.return_value = Request(json=lambda: "test") sut = Octokit().issues.update(owner="testUser", repo="testRepo", issue_number=1) assert sut.json == "test"