Exemple #1
0
def get_repo_raw(token, repo_name):
    '''
    Access the API directly. Works around PyGitHub's inability to handle repositories that have
    been renamed. When the API redirects to the correct repo, PyGithub returns an incomplete object.

    :param token: Auth token
    :param repo_name: String containing the full repository name, i.e. namespace/repo_name

    :return: dict of repository attributes
    '''
    auth_header = {u'Authorization': u'token ' + token}
    try:
        url = u"{0}/repos/{1}".format(GITHUB_SERVER, repo_name)
        response = requests.get(url, headers=auth_header)
        response.raise_for_status()
        repo = response.json()
        if repo.get('message'):
            raise Exception(repo['message'])
    except HTTPError as exc:
        if re.match('404', exc.message):
            raise UnknownObjectException('404',
                                         {u'detail': u"Object not found"})
        raise Exception(exc.message)
    except Exception as exc:
        raise Exception(u"Failed to access GitHub API - {0}".format(
            exc.message))
    return repo
Exemple #2
0
    def test_close_pull_request(self):

        pr = Mock()
        pr.head.ref = "bla"
        self.repo.get_pull.return_value = pr
        with self.assertRaises(AssertionError):
            self.provider.close_pull_request(self.repo,
                                             self.repo,
                                             pr,
                                             "comment",
                                             prefix="pyup-")

        pr.head.ref = "pyup-bla"
        self.provider.close_pull_request(self.repo,
                                         self.repo,
                                         pr,
                                         "comment",
                                         prefix="pyup-")
        self.assertEquals(self.repo.get_git_ref().delete.call_count, 1)

        self.repo.get_pull.side_effect = UnknownObjectException(data="",
                                                                status=1)
        data = self.provider.close_pull_request(self.repo,
                                                self.repo,
                                                Mock(),
                                                "comment",
                                                prefix="pyup-")
        self.assertEqual(data, False)
Exemple #3
0
 def test_create_label(self):
     # label does not exist, need to create it
     self.repo.get_label.side_effect = UnknownObjectException(None, None)
     self.provider.get_or_create_label(self.repo, "another-label")
     self.repo.get_label.assert_called_once_with(name="another-label")
     self.repo.create_label.assert_called_once_with(name="another-label",
                                                    color="1BB0CE")
Exemple #4
0
    def test_get_default_branch(self):
        self.repo.default_branch = "foo"
        self.assertEqual(self.provider.get_default_branch(self.repo), "foo")

        p = PropertyMock(side_effect=UnknownObjectException(data="", status=1))
        type(self.repo).default_branch = p
        with self.assertRaises(errors.RepoDoesNotExistError):
            self.provider.get_default_branch(self.repo)
Exemple #5
0
    def test_issue_state_catches_UnknownObjectException(self):
        url = 'https://github.com/codesy/codesy/issues/158'

        fake_gh_client = fudge.Fake()
        (fake_gh_client.expects('get_repo').with_args('codesy/codesy').raises(
            UnknownObjectException(404, "Cannot find repo.")))

        self.assertEqual(None, issue_state(url, fake_gh_client))
    def test_unknownobjectexception_returns_correctly(self, test_input_attribute_name: str) -> None:
        """Test that the correct output is returned if an `UnknownObjectException` exception is raised."""

        # Execute the `extract_attribute_from_paginated_list_elements` function
        test_output = extract_attribute_from_paginated_list_elements(
            self.create_iterable_raises_exception(UnknownObjectException("Error", 404)), test_input_attribute_name
        )

        # Assert the output is as expected
        assert test_output is None
Exemple #7
0
def test_project():
    r = _repo()
    r._repo.get_contents = Mock(return_value=Mock(
        decoded_content=b"""name = "FooBar"\nuuid="abc-def"\n"""))
    assert r._project("name") == "FooBar"
    assert r._project("uuid") == "abc-def"
    assert r._project("name") == "FooBar"
    r._repo.get_contents.assert_called_once_with("Project.toml")
    r._repo.get_contents.side_effect = UnknownObjectException(404, "???")
    r._Repo__project = None
    with pytest.raises(InvalidProject):
        r._project("name")
Exemple #8
0
    def test_get_pull_request_committer(self):
        committ = Mock()
        committ.committer = "foo"
        pr = Mock()
        self.repo.get_pull().get_commits.return_value = [committ]
        data = self.provider.get_pull_request_committer(self.repo, pr)
        self.assertEqual(data, ["foo"])

        self.repo.get_pull.side_effect = UnknownObjectException(data="",
                                                                status=1)
        data = self.provider.get_pull_request_committer(self.repo, pr)
        self.assertEqual(data, [])
Exemple #9
0
def test_save_to_github_create(gh_mock):
    ghl = setup_data()
    repo = gh_mock.get_repo()
    obj = ghl.content_object

    # with no file already in github
    repo.get_contents.side_effect = UnknownObjectException(
        "failed", "missing", None)
    tasks.save_to_github(ghl.pk)
    repo.get_contents.assert_called_with(obj.json_file_path, ref=ghl.branch)
    gh_mock.get_author.assert_called_with(ghl.author)
    repo.create_file.assert_called_with(obj.json_file_path,
                                        f"Create {obj.json_file_path}",
                                        obj.to_json(),
                                        branch=ghl.branch,
                                        author=gh_mock.get_author())
Exemple #10
0
    def get_repo_info_summary(self, full_name_or_id):
        repo = self.get_repo_info(full_name_or_id)
        # if there is no repo name, should raise exception due to there is no repo.
        if not repo.get_name():
            raise UnknownObjectException(
                200, '{} doesn\'t exist.'.format(full_name_or_id))

        result = {
            'name': repo.get_name(),
            'full_name': repo.get_full_name(),
            'owner.login': repo.get_owner().get_login(),
            'languages': repo.get_languages(),
            'description': repo.get_description(),
            'file_structure': repo.get_file_structure()
        }
        return result
Exemple #11
0
def test_commit_sha_of_tag():
    r = _repo()
    r._repo.get_git_ref = Mock()
    r._repo.get_git_ref.return_value.object.type = "commit"
    r._repo.get_git_ref.return_value.object.sha = "c"
    assert r._commit_sha_of_tag("v1.2.3") == "c"
    r._repo.get_git_ref.assert_called_with("tags/v1.2.3")
    r._repo.get_git_ref.return_value.object.type = "tag"
    r._repo.get_git_tag = Mock()
    r._repo.get_git_tag.return_value.object.sha = "t"
    assert r._commit_sha_of_tag("v2.3.4") == "t"
    r._repo.get_git_tag.assert_called_with("c")
    r._repo.get_git_ref.return_value.object = None
    assert r._commit_sha_of_tag("v3.4.5") is None
    r._repo.get_git_ref.side_effect = UnknownObjectException(404, "???")
    assert r._commit_sha_of_tag("v4.5.6") is None
Exemple #12
0
    def test_update_index_does_not_exist(self):

        self.gh().get_user().get_repo().update_file.side_effect = UnknownObjectException(status=404, data="foo")

        runner = CliRunner()
        result = runner.invoke(update, ["--name", "testrepo", "--token", "token"])
        self.assertEqual(result.exit_code, 0)

        self.gh.assert_called_with("token")

        self.gh().get_user().get_repo.assert_called_with(name="testrepo")
        self.gh().get_user().get_repo().get_labels.assert_called_once_with()
        self.gh().get_user().get_repo().create_file.assert_called_once_with(
            branch='gh-pages',
            content='some foo',
            message='initial',
            path='/index.html'
        )
    def test_not_exists_repository(self):
        # リポジトリが存在しない場合
        # APIにアクセスしたくないため、モックで例外を投げている
        # ユニットテストとしては意味がないが、仕様記載の意味で記載しておく
        self.mock_client.get_repo.side_effect = UnknownObjectException(
            404,
            data={
                "message":
                "Not Found",
                "documentation_url":
                "https://docs.github.com/rest/reference/repos#get-a-repository",  # noqa
            },
        )

        with pytest.raises(UnknownObjectException):
            get_pr_summary(999, "GITHUB_TOKEN", "REPOSITORY_NAME")

        self.mock_github.assert_called_once_with("GITHUB_TOKEN")
        self.mock_client.get_repo.assert_called_once_with("REPOSITORY_NAME")
        self.mock_repo.get_pull.assert_not_called()
Exemple #14
0
    def test_update_index_does_not_exist(self, GithubMock):

        gh = Mock()
        GithubMock.return_value = gh

        # setup mocked label
        label = Mock()
        label.color = "171717"
        label.name = "Website"
        gh.get_user().get_repo().get_labels.return_value = [label, ]

        # set up mocked issue
        issue = Mock()
        issue.state = "open"
        issue_label = Mock()
        issue_label.color = "FF4D4D"
        issue_label.name = "major outage"
        issue.get_labels.return_value = [issue_label, label]
        comment = Mock()
        issue.get_comments.return_value = [comment, ]
        gh.get_user().get_repo().get_issues.return_value = [issue, ]
        template = Mock()
        template.decoded_content = b"some foo"
        gh.get_user().get_repo().get_file_contents.return_value = template
        gh.get_user().get_repo().update_file.side_effect = UnknownObjectException(status=404, data="foo")

        runner = CliRunner()
        result = runner.invoke(update, ["--name", "testrepo", "--token", "token"])
        self.assertEqual(result.exit_code, 0)

        GithubMock.assert_called_with("token")

        gh.get_user().get_repo.assert_called_with(name="testrepo")
        gh.get_user().get_repo().get_labels.assert_called_once_with()
        gh.get_user().get_repo().create_file.assert_called_once_with(
            branch='gh-pages',
            content='some foo',
            message='initial',
            path='/index.html'
        )
Exemple #15
0
    def get_access_token(self, installation_id, user_id=None):
        """
        Get an access token for the given installation id.
        POSTs https://api.github.com/app/installations/<installation_id>/access_tokens
        :param user_id: int
        :param installation_id: int
        :return: :class:`github.InstallationAuthorization.InstallationAuthorization`
        """
        body = {}
        if user_id:
            body = {"user_id": user_id}
        response = self.post_raw_request(
            url="https://api.github.com/app/installations/{}/access_tokens".format(
                installation_id
            ),
            headers={
                "Authorization": "Bearer {}".format(self.create_jwt()),
                "Accept": Consts.mediaTypeIntegrationPreview,
                "User-Agent": "PyGithub/Python",
            },
            json=body,
        )

        if response.status_code == 201:
            return InstallationAuthorization.InstallationAuthorization(
                requester=None,  # not required, this is a NonCompletableGithubObject
                headers={},  # not required, this is a NonCompletableGithubObject
                attributes=response.json(),
                completed=True,
            )
        elif response.status_code == 403:
            raise BadCredentialsException(
                status=response.status_code, data=response.text
            )
        elif response.status_code == 404:
            raise UnknownObjectException(
                status=response.status_code, data=response.text
            )
        raise GithubException(status=response.status_code, data=response.text)
Exemple #16
0
def test_versions(logger):
    r = _repo()
    r._Repo__registry_path = "path"
    r._registry = Mock()
    r._registry.get_contents.return_value.decoded_content = b"""
    ["1.2.3"]
    git-tree-sha1 = "abc"

    ["2.3.4"]
    git-tree-sha1 = "bcd"
    """
    assert r._versions() == {"1.2.3": "abc", "2.3.4": "bcd"}
    r._registry.get_contents.assert_called_with("path/Versions.toml")
    logger.debug.assert_not_called()
    commit = Mock()
    commit.commit.sha = "abcdef"
    r._registry.get_commits.return_value = [commit]
    delta = timedelta(days=3)
    assert r._versions(min_age=delta) == {"1.2.3": "abc", "2.3.4": "bcd"}
    r._registry.get_commits.assert_called_once()
    assert len(r._registry.get_commits.mock_calls) == 1
    [c] = r._registry.get_commits.mock_calls
    assert not c.args and len(c.kwargs) == 1 and "until" in c.kwargs
    assert isinstance(c.kwargs["until"], datetime)
    r._registry.get_contents.assert_called_with("path/Versions.toml",
                                                ref="abcdef")
    logger.debug.assert_not_called()
    r._registry.get_commits.return_value = []
    assert r._versions(min_age=delta) == {}
    logger.debug.assert_called_with("No registry commits were found")
    r._registry.get_contents.side_effect = UnknownObjectException(404, "???")
    assert r._versions() == {}
    logger.debug.assert_called_with("Versions.toml was not found ({})")
    r._Repo__registry_path = Mock(__bool__=lambda self: False)
    assert r._versions() == {}
    logger.debug.assert_called_with("Package is not registered")
from github import GithubException, UnknownObjectException
from mock import Mock, patch
from pytest import raises

from cap.modules.repos.errors import (GitError, GitIntegrationError,
                                      GitObjectNotFound,
                                      GitRequestWithInvalidSignature)
from cap.modules.repos.github_api import Github, GithubAPI


@patch.object(
    Github, 'get_repo',
    Mock(
        side_effect=UnknownObjectException(404, data={'message': 'Not Found'}))
)
def test_github_api_when_project_doesnt_exist_or_no_access():
    with raises(GitObjectNotFound):
        GithubAPI('github.com', 'owner', 'repodoesntexist')


@patch.object(Github, 'get_repo')
def test_github_api_auth_headers_when_token_provided(m_get_repo, github_token,
                                                     example_user):
    class MockProject:
        def get_branch(self, name):
            mock = Mock()
            mock.name = name
            mock.commit.sha = 'mybranchsha'
            return mock

    m_get_repo.return_value = MockProject()
Exemple #18
0
 def test_message_pr_does_not_exist(self):
     with patch.object(self.repo_mock,
                       'get_pull',
                       side_effect=UnknownObjectException(404, '')):
         self.assertRaises(InvalidPullRequestError,
                           self.api.message_pull_request, 3, 'test', 'test')
 def create_hook(self, name, config, events, active):
     raise UnknownObjectException(404, data={'message': 'Not Found'})
 def get_hook(self, hook_id):
     assert hook_id == 123
     raise UnknownObjectException(404, data={'message': 'Not Found'})
 def get_file_contents(self, filepath, ref):
     raise UnknownObjectException(404, data={'message': 'Not Found'})
Exemple #22
0
 def get_contents(var, filename, ref):
     raise UnknownObjectException(status='Failure',
                                  data='Failed data',
                                  headers=[])