Ejemplo n.º 1
0
 def setUp(self):
     self.token = GitHubToken(os.environ.get('GITHUB_TEST_TOKEN', ''))
     self.comment = GitHubComment(self.token, 'gitmate-test-user/test',
                                  CommentType.COMMIT, 25047607)
     self.issue_comment = GitHubComment(self.token,
                                        'gitmate-test-user/test',
                                        CommentType.ISSUE, 309221241)
Ejemplo n.º 2
0
    def add_comment(self, body):
        """
        Adds a comment to the issue:

        >>> from os import environ
        >>> issue = GitHubIssue(GitHubToken(environ['GITHUB_TEST_TOKEN']),
        ...                     'gitmate-test-user/test', 3)
        >>> comment = issue.add_comment("Doh!")

        You can use the comment right after:

        >>> comment.body
        'Doh!'
        >>> comment.delete()

        The comment will be created by the user authenticated via the oauth
        token.

        :param body: The body of the new comment to create.
        :return: The newly created comment.
        """
        result = post(self._token, self._url + '/comments', {'body': body})

        return GitHubComment.from_data(result, self._token, self._repository,
                                       CommentType.ISSUE, result['id'])
Ejemplo n.º 3
0
    def test_verify_command_access(self, m_get_perm, m_repo, m_author):
        merge_admin_only = self.plugin_config.get_settings(
            self.repo)['merge_admin_only']
        fastforward_admin_only = self.plugin_config.get_settings(
            self.repo)['fastforward_admin_only']

        m_repo.return_value = self.repo.igitt_repo
        m_author.return_value = GitHubUser(self.repo.token,
                                           self.repo.user.username)

        m_comment = GitHubComment(self.repo.token, self.repo.igitt_repo,
                                  CommentType.ISSUE, 123)

        m_get_perm.return_value = AccessLevel.CAN_WRITE
        self.assertTrue(
            verify_command_access(m_comment, merge_admin_only,
                                  fastforward_admin_only, 'merge'))

        m_get_perm.return_value = AccessLevel.CAN_WRITE
        self.assertFalse(
            verify_command_access(m_comment, merge_admin_only,
                                  fastforward_admin_only, 'fastforward'))

        m_get_perm.return_value = AccessLevel.ADMIN
        self.assertTrue(
            verify_command_access(m_comment, merge_admin_only,
                                  fastforward_admin_only, 'fastforward'))
Ejemplo n.º 4
0
class GitHubCommentTest(IGittTestCase):
    def setUp(self):
        self.token = GitHubToken(os.environ.get('GITHUB_TEST_TOKEN', ''))
        self.comment = GitHubComment(self.token, 'gitmate-test-user/test',
                                     CommentType.COMMIT, 25047607)
        self.issue_comment = GitHubComment(self.token,
                                           'gitmate-test-user/test',
                                           CommentType.ISSUE, 309221241)

    def test_number(self):
        self.assertEqual(self.comment.number, 25047607)
        self.assertEqual(self.issue_comment.number, 309221241)

    def test_type(self):
        self.assertEqual(self.comment.type, CommentType.COMMIT)

    def test_body(self):
        self.assertEqual(self.comment.body, 'hello')

    def test_body_setter(self):
        self.issue_comment.body = 'test comment body has changed'
        self.assertEqual(self.issue_comment.body,
                         'test comment body has changed')
        self.issue_comment.body = 'test comment body to change'
        self.assertEqual(self.issue_comment.body,
                         'test comment body to change')

    def test_author(self):
        self.assertEqual(self.comment.author.username, 'nkprince007')

    def test_time(self):
        self.assertEqual(self.issue_comment.created,
                         datetime.datetime(2017, 6, 17, 15, 21, 25))
        self.assertEqual(self.issue_comment.updated,
                         datetime.datetime(2017, 10, 12, 9, 33, 13))

    def test_delete(self):
        with requests_mock.Mocker() as m:
            m.delete(requests_mock.ANY, text='{}')
            self.comment.delete()

    def test_repository(self):
        self.assertEqual(self.comment.repository.full_name,
                         'gitmate-test-user/test')
Ejemplo n.º 5
0
    def test_blocked_comment_response(self, m_body):
        @ResponderRegistrar.responder(self.plugin,
                                      MergeRequestActions.COMMENTED)
        def test_blocked_responder(mr, comment, *args, **kwargs):
            # this should never run
            return comment.body  # pragma: no cover

        mr = GitHubMergeRequest(None, 'test/1', 0)
        comment = GitHubComment(None, 'test/1', CommentType.MERGE_REQUEST, 0)
        m_body.return_value = ('Hello\n'
                               '(Powered by [GitMate.io](https://gitmate.io))')

        # ensures that the event was blocked, if it weren't it will return the
        # comment body.
        self.assertEqual([
            result.get() for result in ResponderRegistrar.respond(
                MergeRequestActions.COMMENTED, mr, comment, repo=self.repo)
        ], [])
Ejemplo n.º 6
0
    def comments(self):
        r"""
        Retrieves comments from the issue.

        >>> from os import environ
        >>> issue = GitHubIssue(GitHubToken(environ['GITHUB_TEST_TOKEN']),
        ...                     'gitmate-test-user/test', 9)
        >>> comments = issue.comments

        Now we can e.g. access the last comment:

        >>> comments[-1].body
        'Do not comment here.\n'

        :return: A list of Comment objects.
        """
        return [GitHubComment.from_data(result, self._token, self._repository,
                                        CommentType.ISSUE, result['id'])
                for result in get(self._token, self._url + '/comments')]
Ejemplo n.º 7
0
    def _handle_webhook_issue_comment(self, data, repository):
        """Handles 'issue_comment' event."""
        if data['action'] != 'deleted':
            comment_obj = GitHubComment.from_data(data['comment'], self._token,
                                                  repository,
                                                  CommentType.MERGE_REQUEST,
                                                  data['comment']['id'])

            if 'pull_request' in data['issue']:
                yield (MergeRequestActions.COMMENTED, [
                    GitHubMergeRequest.from_data(data['issue'], self._token,
                                                 repository,
                                                 data['issue']['number']),
                    comment_obj
                ])
            else:
                yield IssueActions.COMMENTED, [
                    GitHubIssue.from_data(data['issue'], self._token,
                                          repository, data['issue']['number']),
                    comment_obj
                ]
Ejemplo n.º 8
0
    def comment(self,
                message: str,
                file: Optional[str] = None,
                line: Optional[int] = None,
                mr_number: Optional[int] = None) -> GitHubComment:
        """
        Places a comment on the commit.

        >>> from os import environ
        >>> commit = GitHubCommit(GithubToken(environ['GITHUB_TEST_TOKEN']),
        ...                       'gitmate-test-user/test', '3fc4b86')

        So this line places a comment on the bottom of the commit,
        not associated to any particular piece of code:

        >>> commit.comment("An issue is here!")

        However, we can also comment on a particular file and line, if that is
        included in the diff:

        >>> commit.comment("Here in line 4, there's a spelling mistake!",
        ...                'README.md', 4)

        If you supply the ``pr_number`` argument, the comment will appear in the
        review UI of that pull request:

        >>> commit.comment("Here in line 4, there's a spelling mistake!",
        ...                'README.md', 4, mr_number=6)

        Beat that! Of course, there's a lot of error handling. If you give the
        wrong file, the comment will appear below the commit with a note about
        the commit, file and line:

        >>> commit.comment("Oh, this'll end up below!!", 'READMENOT.md', 4)

        Also if the line isn't contained in the diff GitHub won't accept that
        and it'll also end up below - sorry!

        >>> commit.comment("Oh, this'll too end up below!!", 'README.md', 8)

        If you give a pull request, the comment will appear on the PR instead:

        >>> commit.comment("Oh, this'll too end up on the PR.",
        ...                'README.md', 8, mr_number=6)

        :param message: The body of the comment.
        :param file: The file to place the comment, relative to repository root.
        :param line: The line in the file in the comment or None.
        :param mr_number: The number of a merge request if this should end up in
                          the review UI of the merge request.
        """
        data = {'body': message}

        if file is not None and line is not None:
            try:
                patch = self.get_patch_for_file(file)
                index = get_diff_index(patch, line)
                if index:  # Else, fallback to comment below file
                    data['position'] = index
                    data['path'] = file
            except ElementDoesntExistError:
                pass  # Fallback to comment below the file

        if 'position' not in data:
            file_str = '' if file is None else ', file ' + file
            line_str = '' if line is None else ', line ' + str(line)
            data['body'] = ('Comment on ' + self.sha + file_str + line_str +
                            '.\n\n' + data['body'])

        comment_type = None

        if mr_number is None:
            comment_type = CommentType.COMMIT
            res = post(self._token, self._url + '/comments', data)
        elif 'position' in data:
            comment_type = CommentType.REVIEW
            data['commit_id'] = self.sha
            res = post(
                self._token, '/repos/' + self._repository + '/pulls/' +
                str(mr_number) + '/comments', data)
        else:  # Position not available, pr number available, comment on PR
            comment_type = CommentType.ISSUE
            res = post(
                self._token, '/repos/' + self._repository + '/issues/' +
                str(mr_number) + '/comments', data)

        return GitHubComment.from_data(res, self._token, self._repository,
                                       comment_type, res['id'])