Example #1
0
    def create_api_token(self):
        """
        Create installation token to make Github API requests.

        See
        https://developer.github.com/v3/apps/#find-installations and
        https://developer.github.com/v3/apps/#create-a-new-installation-token
        for details.

        :return: Authenticated API token
        """
        logging.info("Attempting to get list of installations")
        url = "https://api.github.com/app/installations"
        headers = self._gen_headers()
        r = requests.get(url=url, headers=headers)
        if r.status_code != 200:
            logging.error("Failed to get list of Github App installations "
                          f"with error message {r.text} "
                          f"and code {r.status_code}")
            raise GithubAPIException(r.text)
        installation_id = r.json()[0]['id']

        logging.info("Attempting to create new installation token")
        url = f"https://api.github.com/app/installations/" \
              f"{installation_id}/access_tokens"
        r = requests.post(url=url, headers=headers)
        if r.status_code != 201:
            logging.error("Failed to create new installation token "
                          f"with error message {r.text} "
                          f"and code {r.status_code}")
            raise GithubAPIException(r.text)
        return r.json()['token']
Example #2
0
 def test_handle_refresh_github_error(self):
     self.gh.org_get_teams.side_effect = GithubAPIException('error')
     with self.app.app_context():
         self.assertTupleEqual(
             self.testcommand.handle('team refresh', self.admin.slack_id),
             ('Refresh teams was unsuccessful with '
              'the following error: error', 200))
Example #3
0
 def test_handle_add_but_forgot_githubid(self):
     self.t0.github_team_id = 'githubid'
     self.gh.add_team_member.side_effect = GithubAPIException('error')
     self.assertTupleEqual(
         self.testcommand.handle(f'team add brs {self.u0.slack_id}',
                                 self.admin.slack_id),
         (TeamCommand.no_ghusername_error, 200))
Example #4
0
 def test_handle_delete_github_error(self):
     self.t0.github_team_id = '123452'
     self.gh.org_delete_team.side_effect = GithubAPIException('error')
     self.assertTupleEqual(
         self.testcommand.handle('team delete brs', self.admin.slack_id),
         ('Team delete was unsuccessful with '
          'the following error: '
          'error', 200))
Example #5
0
 def test_handle_create_github_error(self):
     self.gh.org_create_team.return_value = 'team_id'
     inputstring = "team create b-s --name 'B S'"
     self.gh.add_team_member.side_effect = GithubAPIException('error')
     self.assertTupleEqual(
         self.testcommand.handle(inputstring, self.admin.slack_id),
         ('Team creation unsuccessful with the '
          'following error: error', 200))
Example #6
0
 def test_handle_delete_github_error(self):
     """Test team command delete parser with Github error."""
     self.db.query.side_effect = GithubAPIException("error")
     self.assertTupleEqual(self.testcommand.handle("team delete brs", user),
                           ("Team delete was unsuccessful with "
                            "the following error: "
                            "error", 200))
     self.db.delete.assert_not_called()
     self.gh.org_delete_team.assert_not_called()
Example #7
0
 def test_handle_lead_github_error(self):
     self.gh.add_team_member.side_effect = GithubAPIException('error')
     with self.app.app_context():
         self.assertTupleEqual(
             self.testcommand.handle(
                 f'team lead {self.t0.github_team_name} {self.u0.slack_id}',
                 self.admin.slack_id),
             ('Edit team lead was unsuccessful with the '
              'following error: error', 200))
Example #8
0
 def test_handle_add_github_error(self):
     self.t0.github_team_id = 'githubid'
     self.u0.github_id = 'myuser'
     self.gh.add_team_member.side_effect = GithubAPIException('error')
     self.assertTupleEqual(
         self.testcommand.handle(f'team add brs {self.u0.slack_id}',
                                 self.admin.slack_id),
         ('User added unsuccessfully with the'
          ' following error: error', 200))
Example #9
0
 def test_handle_remove_github_error(self):
     self.gh.has_team_member.side_effect = GithubAPIException('error')
     with self.app.app_context():
         self.assertTupleEqual(
             self.testcommand.handle(
                 f'team remove {self.t0.github_team_name} {self.u0.slack_id}',
                 self.admin.slack_id),
             ('User removed unsuccessfully with the '
              'following error: error', 200))
     self.gh.remove_team_member.assert_not_called()
Example #10
0
 def get_team_member(self, username: str, team_id: str) -> NamedUser:
     """Return a team member with a username of username."""
     try:
         team = self.org.get_team(int(team_id))
         team_members = team.get_members()
         return next(member for member in team_members
                     if member.name == username)
     except StopIteration:
         raise GithubAPIException(
             f"User \"{username}\" does not exist in team \"{team_id}\"!")
Example #11
0
 def test_handle_refresh_github_error(self):
     """Test team command refresh parser with github error."""
     test_user = User(user)
     test_user.permissions_level = Permissions.admin
     self.db.retrieve.return_value = test_user
     self.gh.org_get_teams.side_effect = GithubAPIException("error")
     with self.app.app_context():
         self.assertTupleEqual(self.testcommand.handle("team refresh",
                                                       user),
                               ("Refresh teams was unsuccessful with "
                                "the following error: error", 200))
     self.db.store.assert_not_called()
Example #12
0
 def test_handle_create_github_error(self):
     """Test team command create parser with Github error."""
     test_user = User("userid")
     test_user.permissions_level = Permissions.admin
     test_user.github_username = "******"
     self.db.retrieve.return_value = test_user
     self.gh.org_create_team.return_value = "team_id"
     inputstring = "team create b-s --name 'B S'"
     self.gh.add_team_member.side_effect = GithubAPIException("error")
     self.assertTupleEqual(self.testcommand.handle(inputstring, user),
                           ("Team creation unsuccessful with the "
                            "following error: error", 200))
     self.db.store.assert_not_called()
Example #13
0
 def __init__(self, github_factory: DefaultGithubFactory, org: str) -> None:
     """Initialize bot by creating Github object and get organization."""
     logging.info("Creating rocket's Github interface")
     self.org_name = org
     self.github_factory = github_factory
     self.github = github_factory.create()
     try:
         self.org = self.github.get_organization(org)
         logging.info(f"Successfully fetched {org} Github organization")
     except GithubException as e:
         logging.error(f"Failed to fetch {org} Github organization with "
                       f"error message {e.data} and error code {e.status}")
         raise GithubAPIException(e.data)
Example #14
0
 def test_handle_lead_github_error(self):
     """Test team command lead parser with github error."""
     test_user = User("userid")
     test_user.permissions_level = Permissions.admin
     team = Team("BRS", "brs", "web")
     self.db.retrieve.side_effect = [test_user, test_user]
     self.db.query.return_value = [team]
     self.gh.add_team_member.side_effect = GithubAPIException("error")
     with self.app.app_context():
         self.assertTupleEqual(self.testcommand.handle("team lead brs ID",
                                                       user),
                               ("Edit team lead was unsuccessful with the "
                                "following error: error", 200))
     self.db.store.assert_not_called()
Example #15
0
 def wrapper(self, *arg, **kwargs):
     try:
         return func(self, *arg, **kwargs)
     except GithubException as e:
         logging.warning(f"GithubException raised with message {e.data}"
                         f" and error code {e.status}")
         if e.status == 401:
             logging.warning(
                 "Attempting to create new instance of pygithub interface")
             self.github = self.github_factory.create()
             logging.warning(
                 "Attempting to create new instance of organization object")
             self.org = self.github.get_organization(self.org_name)
             try:
                 return func(self, *arg, **kwargs)
             except GithubException as e:
                 logging.error("Second attempt of using pygithub interface"
                               f" failed with message {e.data} and error "
                               f"code {e.status}")
                 raise GithubAPIException(e.data)
         else:
             logging.error(f"Unable to handle error code {e.status}")
             raise GithubAPIException(e.data)
Example #16
0
 def test_handle_add_github_error(self):
     """Test team command add parser with Github Exception."""
     test_user = User("userid")
     test_user.github_username = "******"
     test_user.permissions_level = Permissions.admin
     team = Team("BRS", "brs", "web")
     team.github_team_id = "githubid"
     add_user = User("anotheruser")
     add_user.github_username = "******"
     self.db.retrieve.side_effect = [test_user, add_user]
     self.db.query.return_value = [team]
     self.gh.add_team_member.side_effect = GithubAPIException("error")
     self.assertTupleEqual(self.testcommand.handle("team add brs ID", user),
                           ("User added unsuccessfully with the"
                            " following error: error", 200))
     self.db.store.assert_not_called()
Example #17
0
 def test_handle_remove_github_error(self):
     """Test team command remove parser with github error."""
     test_user = User("userid")
     test_user.permissions_level = Permissions.admin
     team = Team("BRS", "brs", "web")
     other_user = User("anotheruser")
     other_user.github_id = "githubID"
     other_user.github_username = "******"
     self.db.retrieve.side_effect = [test_user, other_user]
     self.db.query.return_value = [team]
     self.gh.has_team_member.side_effect = GithubAPIException("error")
     with self.app.app_context():
         self.assertTupleEqual(self.testcommand.handle("team remove"
                                                       " brs ID", user),
                               ("User removed unsuccessfully with the "
                                "following error: error", 200))
     self.db.store.assert_not_called()
     self.gh.remove_team_member.assert_not_called()
Example #18
0
    def get_app_details(self):
        """
        Retrieve app details from Github Apps API.

        See
        https://developer.github.com/v3/apps/#get-the-authenticated-github-app
        for details.

        :return: Decoded JSON object containing app details
        """
        logging.info("Attempting to retrieve Github App details")
        url = "https://api.github.com/app"
        headers = self._gen_headers()
        r = requests.get(url=url, headers=headers)
        if r.status_code != 200:
            logging.error("Failed to get Github App details with message "
                          f"{r.text} and error code {r.status_code}")
            raise GithubAPIException(r.text)
        logging.info("Successfully retrieved Github App details: "
                     f"{r.json()}")
        return r.json()