Example #1
0
 def test_before_page_load_osf_public_gh_private(self, mock_repo):
     self.project.is_public = True
     self.project.save()
     mock_repo.return_value = Repository.from_json({"private": True})
     message = self.node_settings.before_page_load(self.project, self.project.creator)
     mock_repo.assert_called_with(self.node_settings.user, self.node_settings.repo)
     assert_true(message)
Example #2
0
    def test_can_see_files_tab(self, mock_repo, mock_file, mock_commits):
        mock_commits.return_value = [Commit.from_json({
            "url": "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e",
            "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e",
            "commit": {
                "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e",
                "author": {
                    "name": "Monalisa Octocat",
                    "email": "*****@*****.**",
                   "date": "2011-04-14T16:00:49Z"
                }
            }
        })]

        mock_repo.return_value = Repository.from_json({
            "default_branch": "dev",
            'url': u'https://api.github.com/repos/{user}/mock-repo/git/trees/dev'.format(user=self.user),
            'sha': 'dev',
            'private': False,
            'tree': [
                {u'mode': u'100644',
                 u'path': u'coveragerc',
                 u'sha': u'92029ff5ce192425d346b598d7e7dd25f5f05185',
                 u'size': 245,
                 u'type': u'file',
                 u'url': u'https://api.github.com/repos/{user}/mock-repo/git/blobs/92029ff5ce192425d346b598d7e7dd25f5f05185'.format(user=self.user)}]
        })

        mock_file.return_value = {
            u'name': u'coveragerc',
            u'content': u'ClRleHRCbG9iOiBTaW1wbGlmaWVkIFRleHQgUHJvY2Vzc2luZwo9PT09PT09',
            u'size': 245
        }
        res = self.app.get(self.project.url, auth=self.user.auth)
        assert_in('a href="/{0}/files/"'.format(self.project._id), res)
Example #3
0
    def test_can_see_files_tab(self, mock_repo, mock_file, mock_commits):
        mock_commits.return_value = [Commit.from_json({
            "url": "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e",
            "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e",
            "commit": {
                "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e",
                "author": {
                    "name": "Monalisa Octocat",
                    "email": "*****@*****.**",
                   "date": "2011-04-14T16:00:49Z"
                }
            }
        })]

        mock_repo.return_value = Repository.from_json({
            "default_branch": "dev",
            'url': u'https://api.github.com/repos/{user}/mock-repo/git/trees/dev'.format(user=self.user),
            'sha': 'dev',
            'private': False,
            'tree': [
                {u'mode': u'100644',
                 u'path': u'coveragerc',
                 u'sha': u'92029ff5ce192425d346b598d7e7dd25f5f05185',
                 u'size': 245,
                 u'type': u'file',
                 u'url': u'https://api.github.com/repos/{user}/mock-repo/git/blobs/92029ff5ce192425d346b598d7e7dd25f5f05185'.format(user=self.user)}]
        })

        mock_file.return_value = {
            u'name': u'coveragerc',
            u'content': u'ClRleHRCbG9iOiBTaW1wbGlmaWVkIFRleHQgUHJvY2Vzc2luZwo9PT09PT09',
            u'size': 245
        }
        res = self.app.get(self.project.url, auth=self.user.auth)
        assert_in('a href="/{0}/files/"'.format(self.project._id), res)
Example #4
0
    def __init__(self, notif, session=None):
        super(Thread, self).__init__(notif, session)
        self._api = notif.get('url')
        #: Comment responsible for the notification
        self.comment = notif.get('comment', {})
        #: Thread information
        self.thread = notif.get('thread', {})

        from github3.repos import Repository
        #: Repository the comment was made on
        self.repository = Repository(notif.get('repository', {}), self)
        #: When the thread was last updated
        self.updated_at = self._strptime(notif.get('updated_at'))
        #: Id of the thread
        self.id = notif.get('id')
        #: Dictionary of urls for the thread
        self.urls = notif.get('urls')
        #: datetime object representing the last time the user read the thread
        self.last_read_at = notif.get('last_read_at')
        if self.last_read_at:
            self.last_read_at = self._strptime(self.last_read_at)
        #: The reason you're receiving the notification
        self.reason = notif.get('reason')
        #: Subject of the Notification, e.g., which issue/pull/diff is this in
        #: relation to. This is a dictionary
        self.subject = notif.get('subject')
        self.unread = notif.get('unread')
	def update_topics(self, repo: repos.Repository):
		"""
		Update the repository's topics.

		:param repo:
		"""
		# TODO: other languages detected in repo

		raw_topics = repo.topics()
		if raw_topics is None:
			topics = set()
		else:
			topics = set(raw_topics.names)

		topics.add("python")
		topics.update(self.templates.globals["keywords"])
		repo.replace_topics(sorted(map(_lower, topics)))
Example #6
0
 def __init__(self, data, session=None):
     result = data.copy()
     #: Score of the result
     self.score = result.pop('score')
     #: Text matches
     self.text_matches = result.pop('text_matches', [])
     #: Repository object
     self.repository = Repository(result, self)
Example #7
0
 def test_before_page_load_osf_private_gh_private(self, mock_repo):
     mock_repo.return_value = Repository.from_json({'private': True})
     message = self.node_settings.before_page_load(self.project, self.project.creator)
     mock_repo.assert_called_with(
         self.node_settings.user,
         self.node_settings.repo,
     )
     assert_false(message)
 def test_get_folders_not_have_auth(self, mock_repos, mock_check_authorization):
     mock_repos.return_value = [Repository.from_json(dumps({'name': 'test',
                                                      'id': '12345',
                                                      'owner':
                                                          {'login': '******'}
                                                      }))
                                ]
     self.node_settings.user_settings = None
     with pytest.raises(exceptions.InvalidAuthError):
         self.node_settings.get_folders()
Example #9
0
def get_installation_access_token(github_repo: GitHubRepository,
                                  installation_id: int):
    """
	Returns the installation access token for the given installation.

	:param github_repo:
	:param installation_id:
	"""

    headers = apps.create_jwt_headers(GITHUBAPP_KEY,
                                      GITHUBAPP_ID,
                                      expire_in=30)
    url = github_repo._build_url("app", "installations", str(installation_id),
                                 "access_tokens")
    with github_repo.session.no_auth():
        response = github_repo.session.post(url, headers=headers)
        json_response = github_repo._json(response, 201)

        return json_response["token"]
Example #10
0
def _team(payload):
    from github3.orgs import Team
    from github3.repos import Repository
    from github3.users import User
    if payload.get('team'):
        payload['team'] = Team(payload['team'], None)
    if payload.get('repo'):
        payload['repo'] = Repository(payload['repo'], None)
    if payload.get('user'):
        payload['user'] = User(payload['user'], None)
    return payload
 def test_before_page_load_osf_public_gh_private(self, mock_repo):
     self.project.is_public = True
     self.project.save()
     mock_repo.return_value = Repository.from_json(dumps({'private': True}))
     message = self.node_settings.before_page_load(self.project,
                                                   self.project.creator)
     mock_repo.assert_called_with(
         self.node_settings.user,
         self.node_settings.repo,
     )
     assert_true(message)
Example #12
0
    def repository(self, owner, repository):
        """Returns a Repository object for the specified combination of
        owner and repository

        :param str owner: (required)
        :param str repository: (required)
        :returns: :class:`Repository <github3.repos.Repository>`
        """
        json = None
        if owner and repository:
            url = self._build_url('repos', owner, repository)
            json = self._json(self._get(url), 200)
        return Repository(json, self) if json else None
    def test_get_folders(self, mock_check_authorization, mock_repos):
        mock_repos.return_value = [Repository.from_json(dumps({'name': 'test',
                                                         'id': '12345',
                                                         'owner':
                                                             {'login': '******'}
                                                         }))
                                   ]
        result = self.node_settings.get_folders()

        assert_equal(len(result), 1)
        assert_equal(result[0]['id'], '12345')
        assert_equal(result[0]['name'], 'test')
        assert_equal(result[0]['path'], 'test name/test')
        assert_equal(result[0]['kind'], 'repo')
Example #14
0
    def create_repo(self,
                    name,
                    description='',
                    homepage='',
                    private=False,
                    has_issues=True,
                    has_wiki=True,
                    has_downloads=True,
                    team_id=0,
                    auto_init=False,
                    gitignore_template=''):
        """Create a repository for this organization if the authenticated user
        is a member.

        :param str name: (required), name of the repository
        :param str description: (optional)
        :param str homepage: (optional)
        :param bool private: (optional), If ``True``, create a private
            repository. API default: ``False``
        :param bool has_issues: (optional), If ``True``, enable issues for
            this repository. API default: ``True``
        :param bool has_wiki: (optional), If ``True``, enable the wiki for
            this repository. API default: ``True``
        :param bool has_downloads: (optional), If ``True``, enable downloads
            for this repository. API default: ``True``
        :param int team_id: (optional), id of the team that will be granted
            access to this repository
        :param bool auto_init: (optional), auto initialize the repository.
        :param str gitignore_template: (optional), name of the template; this
            is ignored if auto_int = False.
        :returns: :class:`Repository <github3.repos.Repository>`

        .. warning: ``name`` should be no longer than 100 characters
        """
        url = self._build_url('repos', base_url=self._api)
        data = {
            'name': name,
            'description': description,
            'homepage': homepage,
            'private': private,
            'has_issues': has_issues,
            'has_wiki': has_wiki,
            'has_downloads': has_downloads,
            'auto_init': auto_init,
            'gitignore_template': gitignore_template
        }
        if team_id > 0:
            data.update({'team_id': team_id})
        json = self._json(self._post(url, data), 201)
        return Repository(json, self) if json else None
 def test_get_folders_not_have_auth(self, mock_repos,
                                    mock_check_authorization):
     mock_repos.return_value = [
         Repository.from_json(
             dumps({
                 'name': 'test',
                 'id': '12345',
                 'owner': {
                     'login': '******'
                 }
             }))
     ]
     self.node_settings.user_settings = None
     with pytest.raises(exceptions.InvalidAuthError):
         self.node_settings.get_folders()
Example #16
0
    def test_file_view_with_anonymous_link(self, mock_contents, mock_repo, mock_file, mock_commits):
        mock_contents.return_value = None
        mock_commits.return_value = [Commit.from_json({
            "url": "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e",
            "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e",
            "commit": {
                "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e",
                "author": {
                    "name": "Monalisa Octocat",
                    "email": "*****@*****.**",
                   "date": "2011-04-14T16:00:49Z"
                }
            }
        })]

        mock_repo.return_value = Repository.from_json({
            "default_branch": "dev",
            'url': u'https://api.github.com/repos/{user}/mock-repo/git/trees/dev'.format(user=self.user),
            'sha': 'dev',
            'private': False,
            'tree': [
                {u'mode': u'100644',
                 u'path': u'coveragerc',
                 u'sha': u'92029ff5ce192425d346b598d7e7dd25f5f05185',
                 u'size': 245,
                 u'type': u'file',
                 u'url': u'https://api.github.com/repos/{user}/mock-repo/git/blobs/92029ff5ce192425d346b598d7e7dd25f5f05185'.format(user=self.user)}]
        })

        mock_file.return_value = {
            u'name': u'coveragerc',
            u'content': u'ClRleHRCbG9iOiBTaW1wbGlmaWVkIFRleHQgUHJvY2Vzc2luZwo9PT09PT09',
            u'size': 245
        }

        link = PrivateLinkFactory(anonymous=True)
        link.nodes.append(self.project)
        link.save()
        url = self.project.web_url_for('github_view_file', path="coveragerc")
        res = self.app.get(url, {'view_only': link.key}).maybe_follow()
        assert_in("6dcb09b5b57875f334f61aebed695e2e4193db5e", res)
        assert_in("Thu Apr 14 16:00:49 2011", res)
        assert_in("file-version-history", res)
        assert_in("icon-download-alt", res)
        assert_not_in("Monalisa Octocat", res)
        assert_not_in("*****@*****.**", res)
Example #17
0
    def test_file_view_with_anonymous_link(self, mock_repo, mock_file, mock_commits):
        mock_commits.return_value = [Commit.from_json({
            "url": "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e",
            "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e",
            "commit": {
                "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e",
                "author": {
                    "name": "Monalisa Octocat",
                    "email": "*****@*****.**",
                   "date": "2011-04-14T16:00:49Z"
                }
            }
        })]

        mock_repo.return_value = Repository.from_json({
            "default_branch": "dev",
            'url': u'https://api.github.com/repos/{user}/mock-repo/git/trees/dev'.format(user=self.user),
            'sha': 'dev',
            'private': False,
            'tree': [
                {u'mode': u'100644',
                 u'path': u'coveragerc',
                 u'sha': u'92029ff5ce192425d346b598d7e7dd25f5f05185',
                 u'size': 245,
                 u'type': u'file',
                 u'url': u'https://api.github.com/repos/{user}/mock-repo/git/blobs/92029ff5ce192425d346b598d7e7dd25f5f05185'.format(user=self.user)}]
        })

        mock_file.return_value = {
            u'name': u'coveragerc',
            u'content': u'ClRleHRCbG9iOiBTaW1wbGlmaWVkIFRleHQgUHJvY2Vzc2luZwo9PT09PT09',
            u'size': 245
        }

        link = PrivateLinkFactory(anonymous=True)
        link.nodes.append(self.project)
        link.save()
        url = self.project.web_url_for('github_view_file', path="coveragerc")
        res = self.app.get(url, {'view_only': link.key}).maybe_follow()
        assert_in("6dcb09b5b57875f334f61aebed695e2e4193db5e", res)
        assert_in("Thu Apr 14 16:00:49 2011", res)
        assert_in("file-version-history", res)
        assert_in("icon-download-alt", res)
        assert_not_in("Monalisa Octocat", res)
        assert_not_in("*****@*****.**", res)
    def test_get_folders(self, mock_check_authorization, mock_repos):
        mock_repos.return_value = [
            Repository.from_json(
                dumps({
                    'name': 'test',
                    'id': '12345',
                    'owner': {
                        'login': '******'
                    }
                }))
        ]
        result = self.node_settings.get_folders()

        assert_equal(len(result), 1)
        assert_equal(result[0]['id'], '12345')
        assert_equal(result[0]['name'], 'test')
        assert_equal(result[0]['path'], 'test name/test')
        assert_equal(result[0]['kind'], 'repo')
Example #19
0
 def __init__(self, data, session=None):
     super(CodeSearchResult, self).__init__(data, session)
     self._api = data.get('url')
     #: Filename the match occurs in
     self.name = data.get('name')
     #: Path in the repository to the file
     self.path = data.get('path')
     #: SHA in which the code can be found
     self.sha = data.get('sha')
     #: URL to the Git blob endpoint
     self.git_url = data.get('git_url')
     #: URL to the HTML view of the blob
     self.html_url = data.get('html_url')
     #: Repository the code snippet belongs to
     self.repository = Repository(data.get('repository', {}), self)
     #: Score of the result
     self.score = data.get('score')
     #: Text matches
     self.text_matches = data.get('text_matches', [])
Example #20
0
    def test_file_view_deleted(self, mock_contents, mock_repo, mock_file, mock_commits):
        mock_contents.return_value = None
        mock_commits.return_value = [Commit.from_json({
            "url": "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e",
            "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e",
            "commit": {
                "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e",
                "author": {
                    "name": "Monalisa Octocat",
                    "email": "*****@*****.**",
                   "date": "2011-04-14T16:00:49Z"
                }
            }
        })]

        mock_repo.return_value = Repository.from_json({
            "default_branch": "dev",
            'url': u'https://api.github.com/repos/{user}/mock-repo/git/trees/dev'.format(user=self.user),
            'sha': 'dev',
            'private': False,
            'tree': [
                {u'mode': u'100644',
                 u'path': u'coveragerc',
                 u'sha': u'92029ff5ce192425d346b598d7e7dd25f5f05185',
                 u'size': 245,
                 u'type': u'file',
                 u'url': u'https://api.github.com/repos/{user}/mock-repo/git/blobs/92029ff5ce192425d346b598d7e7dd25f5f05185'.format(user=self.user)}]
        })

        mock_file.return_value = (None, None, None)

        url = "/project/{0}/github/file/{1}/".format(
            self.project._id,
            "coveragerc"
        )
        self.app.auth = self.user.auth
        res = self.app.get(url).maybe_follow()

        assert_in("icon-download-alt", res)
        assert_in("Thu Apr 14 16:00:49 2011", res)
        assert_in("This file does not exist at this commit", res)
        assert_in("6dcb09b5b57875f334f61aebed695e2e4193db5e", res)
Example #21
0
    def create_repo(self,
                    name,
                    description='',
                    homepage='',
                    private=False,
                    has_issues=True,
                    has_wiki=True,
                    has_downloads=True,
                    auto_init=False,
                    gitignore_template=''):
        """Create a repository for the authenticated user.

        :param str name: (required), name of the repository
        :param str description: (optional)
        :param str homepage: (optional)
        :param str private: (optional), If ``True``, create a
            private repository. API default: ``False``
        :param bool has_issues: (optional), If ``True``, enable
            issues for this repository. API default: ``True``
        :param bool has_wiki: (optional), If ``True``, enable the
            wiki for this repository. API default: ``True``
        :param bool has_downloads: (optional), If ``True``, enable
            downloads for this repository. API default: ``True``
        :param bool auto_init: (optional), auto initialize the repository
        :param str gitignore_template: (optional), name of the git template to
            use; ignored if auto_init = False.
        :returns: :class:`Repository <github3.repos.Repository>`

        .. warning: ``name`` should be no longer than 100 characters
        """
        url = self._build_url('user', 'repos')
        data = {'name': name, 'description': description,
                'homepage': homepage, 'private': private,
                'has_issues': has_issues, 'has_wiki': has_wiki,
                'has_downloads': has_downloads, 'auto_init': auto_init,
                'gitignore_template': gitignore_template}
        json = self._json(self._post(url, data=data), 201)
        return Repository(json, self) if json else None
Example #22
0
    def test_folder_list_GET_expected_behavior(self, mock_client):
        mock_repo = Repository.from_json(
            dumps({
                'name': 'test',
                'id': '12345',
                'owner': {
                    'login': '******'
                }
            }))

        mock_connection = mock.MagicMock()
        mock_client.return_value = mock_connection
        mock_connection.repos = mock.MagicMock(return_value=[mock_repo])
        mock_connection.my_orgs_repos = mock.MagicMock(
            return_value=[mock_repo])

        res = self.app.get(self.folder_url, auth=self.user.auth)

        addon_data = res.json['data'][0]['attributes']
        assert_in(addon_data['kind'], ('folder', 'repo'))
        assert_equal(addon_data['name'], self._mock_folder_result['name'])
        assert_equal(addon_data['path'], self._mock_folder_result['path'])
        assert_equal(addon_data['folder_id'], self._mock_folder_result['id'])
    def test_folder_list_GET_expected_behavior(self, mock_client):
        mock_repo = Repository.from_json(dumps({
            'name': 'test',
            'id': '12345',
            'owner':
                {'login': '******'}
        }))

        mock_connection = mock.MagicMock()
        mock_client.return_value = mock_connection
        mock_connection.repos = mock.MagicMock(return_value=[mock_repo])
        mock_connection.my_orgs_repos = mock.MagicMock(return_value=[mock_repo])

        res = self.app.get(
            self.folder_url,
            auth=self.user.auth)

        addon_data = res.json['data'][0]['attributes']
        assert_in(addon_data['kind'], ('folder', 'repo'))
        assert_equal(addon_data['name'], self._mock_folder_result['name'])
        assert_equal(addon_data['path'], self._mock_folder_result['path'])
        assert_equal(
            addon_data['folder_id'],
            self._mock_folder_result['id'])
Example #24
0
def _forkev(payload):
    from github3.repos import Repository
    if payload.get('forkee'):
        payload['forkee'] = Repository(payload['forkee'], None)
    return payload