From 8f8cbbb149f2f21de389c69f619dea494ce2196b Mon Sep 17 00:00:00 2001 From: Pierre-Yves Chibon Date: Apr 23 2019 08:07:35 +0000 Subject: [PATCH 1/2] Adjust the style test to include the tests themselves Signed-off-by: Pierre-Yves Chibon --- diff --git a/tests/test_style.py b/tests/test_style.py index 6af9509..1a32efc 100644 --- a/tests/test_style.py +++ b/tests/test_style.py @@ -21,7 +21,9 @@ import unittest import six REPO_PATH = os.path.abspath( - os.path.join(os.path.dirname(__file__), '..', 'pagure')) + os.path.join(os.path.dirname(__file__), "..", "pagure") +) +TESTS_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__))) class TestStyle(unittest.TestCase): @@ -72,7 +74,14 @@ class TestStyle(unittest.TestCase): non-zero exit code. """ black_command = [ - sys.executable, '-m', 'black', '-l', '79', '--check', REPO_PATH + sys.executable, + "-m", + "black", + "-l", + "79", + "--check", + REPO_PATH, + TESTS_PATH, ] proc = subprocess.Popen( black_command, From 73d12005523227dd4a3f5736ec57d51100c47374 Mon Sep 17 00:00:00 2001 From: Pierre-Yves Chibon Date: Apr 23 2019 09:11:51 +0000 Subject: [PATCH 2/2] Project wide black fixes, including tests, docs and all Signed-off-by: Pierre-Yves Chibon --- diff --git a/createdb.py b/createdb.py index f8a166e..3860b51 100644 --- a/createdb.py +++ b/createdb.py @@ -8,33 +8,40 @@ import os parser = argparse.ArgumentParser( - description='Create/Update the Pagure database') + description="Create/Update the Pagure database" +) parser.add_argument( - '--config', '-c', dest='config', - help='Configuration file to use for pagure.') + "--config", + "-c", + dest="config", + help="Configuration file to use for pagure.", +) parser.add_argument( - '--initial', '-i', dest='alembic_cfg', - help='With this option, the database will be automatically stamped to ' - 'the latest version according to alembic. Point to the alembic.ini ' - 'file to use.') + "--initial", + "-i", + dest="alembic_cfg", + help="With this option, the database will be automatically stamped to " + "the latest version according to alembic. Point to the alembic.ini " + "file to use.", +) args = parser.parse_args() if args.config: config = args.config - if not config.startswith('/'): + if not config.startswith("/"): here = os.path.join(os.path.dirname(os.path.abspath(__file__))) config = os.path.join(here, config) - os.environ['PAGURE_CONFIG'] = config + os.environ["PAGURE_CONFIG"] = config if args.alembic_cfg: - if not args.alembic_cfg.endswith('alembic.ini'): - print('--initial should point to the alembic.ini file to use.') + if not args.alembic_cfg.endswith("alembic.ini"): + print("--initial should point to the alembic.ini file to use.") sys.exit(1) if not os.path.exists(args.alembic_cfg): - print('The file `{0}` could not be found'.format(args.alembic_cfg)) + print("The file `{0}` could not be found".format(args.alembic_cfg)) sys.exit(2) @@ -44,7 +51,8 @@ from pagure.lib import model _config = pagure.config.reload_config() model.create_tables( - _config['DB_URL'], - _config.get('PATH_ALEMBIC_INI', args.alembic_cfg), - acls=_config.get('ACLS', {}), - debug=True) + _config["DB_URL"], + _config.get("PATH_ALEMBIC_INI", args.alembic_cfg), + acls=_config.get("ACLS", {}), + debug=True, +) diff --git a/dev-data.py b/dev-data.py index 087bb3e..f7b13f6 100644 --- a/dev-data.py +++ b/dev-data.py @@ -23,24 +23,24 @@ from pagure.lib.model import create_default_status from pagure.lib.repo import PagureRepo -''' +""" Usage: python dev-data.py --init python dev-data.py --clean python dev-data.py --populate python dev-data.py --all -''' +""" _config = pagure.config.reload_config() def empty_dev_db(session): - print('') - print('WARNING: Deleting all data from', _config['DB_URL']) + print("") + print("WARNING: Deleting all data from", _config["DB_URL"]) response = os.environ.get("FORCE_DELETE") if not response: - response = six.moves.input('Do you want to continue? (yes/no) ') - if response.lower().startswith('y'): + response = six.moves.input("Do you want to continue? (yes/no) ") + if response.lower().startswith("y"): tables = reversed(pagure.lib.model_base.BASE.metadata.sorted_tables) for tbl in tables: session.execute(tbl.delete()) @@ -49,14 +49,12 @@ def empty_dev_db(session): def insert_data(session, username, user_email): - _config['EMAIL_SEND'] = False - _config['TESTING'] = True + _config["EMAIL_SEND"] = False + _config["TESTING"] = True ###################################### # tags - item = pagure.lib.model.Tag( - tag='tag1', - ) + item = pagure.lib.model.Tag(tag="tag1") session.add(item) session.commit() @@ -64,46 +62,58 @@ def insert_data(session, username, user_email): # Users # Create a couple of users pingou = item = pagure.lib.model.User( - user='pingou', - fullname='PY C', - password=generate_hashed_value(u'testing123'), + user="pingou", + fullname="PY C", + password=generate_hashed_value("testing123"), token=None, - default_email='bar@pingou.com', + default_email="bar@pingou.com", ) session.add(item) session.commit() - print("User created: {} <{}>, {}".format(item.user, item.default_email, 'testing123')) + print( + "User created: {} <{}>, {}".format( + item.user, item.default_email, "testing123" + ) + ) foo = item = pagure.lib.model.User( - user='foo', - fullname='foo bar', - password=generate_hashed_value(u'testing123'), + user="foo", + fullname="foo bar", + password=generate_hashed_value("testing123"), token=None, - default_email='foo@bar.com', + default_email="foo@bar.com", ) session.add(item) session.commit() - print("User created: {} <{}>, {}".format(item.user, item.default_email, 'testing123')) + print( + "User created: {} <{}>, {}".format( + item.user, item.default_email, "testing123" + ) + ) you = item = pagure.lib.model.User( user=username, fullname=username, - password=generate_hashed_value(u'testing123'), + password=generate_hashed_value("testing123"), token=None, default_email=user_email, ) session.add(item) session.commit() - print("User created: {} <{}>, {}".format(item.user, item.default_email, 'testing123')) + print( + "User created: {} <{}>, {}".format( + item.user, item.default_email, "testing123" + ) + ) ###################################### # pagure_group item = pagure.lib.model.PagureGroup( - group_name='admin', - group_type='admin', + group_name="admin", + group_type="admin", user_id=pingou.id, - display_name='admin', - description='Admin Group', + display_name="admin", + description="Admin Group", ) session.add(item) session.commit() @@ -111,22 +121,22 @@ def insert_data(session, username, user_email): # Add a couple of groups so that we can list them item = pagure.lib.model.PagureGroup( - group_name='group', - group_type='user', + group_name="group", + group_type="user", user_id=pingou.id, - display_name='group group', - description='this is a group group', + display_name="group group", + description="this is a group group", ) session.add(item) session.commit() print('Created "group" group. Pingou is a member.') item = pagure.lib.model.PagureGroup( - group_name='rel-eng', - group_type='user', + group_name="rel-eng", + group_type="user", user_id=pingou.id, - display_name='Release Engineering', - description='The group of release engineers', + display_name="Release Engineering", + description="The group of release engineers", ) session.add(item) session.commit() @@ -135,86 +145,82 @@ def insert_data(session, username, user_email): # projects import shutil + # delete folder from local instance to start from a clean slate - if os.path.exists(_config['GIT_FOLDER']): - shutil.rmtree(_config['GIT_FOLDER']) + if os.path.exists(_config["GIT_FOLDER"]): + shutil.rmtree(_config["GIT_FOLDER"]) # Create projects item = project1 = pagure.lib.model.Project( user_id=pingou.id, - name='test', + name="test", is_fork=False, parent_id=None, - description='test project #1', - hook_token='aaabbbccc', + description="test project #1", + hook_token="aaabbbccc", ) - item.close_status = ['Invalid', 'Insufficient data', 'Fixed', 'Duplicate'] + item.close_status = ["Invalid", "Insufficient data", "Fixed", "Duplicate"] session.add(item) session.flush() tests.create_locks(session, item) item = project2 = pagure.lib.model.Project( user_id=pingou.id, - name='test2', + name="test2", is_fork=False, parent_id=None, - description='test project #2', - hook_token='aaabbbddd', + description="test project #2", + hook_token="aaabbbddd", ) - item.close_status = ['Invalid', 'Insufficient data', 'Fixed', 'Duplicate'] + item.close_status = ["Invalid", "Insufficient data", "Fixed", "Duplicate"] session.add(item) item = project3 = pagure.lib.model.Project( user_id=pingou.id, - name='test3', + name="test3", is_fork=False, parent_id=None, - description='namespaced test project', - hook_token='aaabbbeee', - namespace='somenamespace', + description="namespaced test project", + hook_token="aaabbbeee", + namespace="somenamespace", ) - item.close_status = ['Invalid', 'Insufficient data', 'Fixed', 'Duplicate'] + item.close_status = ["Invalid", "Insufficient data", "Fixed", "Duplicate"] session.add(item) session.commit() - tests.create_projects_git(_config['GIT_FOLDER'], bare=True) - add_content_git_repo( - os.path.join(_config['GIT_FOLDER'], 'test.git')) - tests.add_readme_git_repo( - os.path.join(_config['GIT_FOLDER'], 'test.git')) + tests.create_projects_git(_config["GIT_FOLDER"], bare=True) + add_content_git_repo(os.path.join(_config["GIT_FOLDER"], "test.git")) + tests.add_readme_git_repo(os.path.join(_config["GIT_FOLDER"], "test.git")) # Add some content to the git repo add_content_git_repo( - os.path.join(_config['GIT_FOLDER'], 'forks', 'pingou', - 'test.git')) + os.path.join(_config["GIT_FOLDER"], "forks", "pingou", "test.git") + ) tests.add_readme_git_repo( - os.path.join(_config['GIT_FOLDER'], 'forks', 'pingou', - 'test.git')) + os.path.join(_config["GIT_FOLDER"], "forks", "pingou", "test.git") + ) tests.add_commit_git_repo( - os.path.join(_config['GIT_FOLDER'], 'forks', 'pingou', - 'test.git'), ncommits=10) + os.path.join(_config["GIT_FOLDER"], "forks", "pingou", "test.git"), + ncommits=10, + ) ###################################### # user_emails item = pagure.lib.model.UserEmail( - user_id=pingou.id, - email='bar@pingou.com') + user_id=pingou.id, email="bar@pingou.com" + ) session.add(item) item = pagure.lib.model.UserEmail( - user_id=pingou.id, - email='foo@pingou.com') + user_id=pingou.id, email="foo@pingou.com" + ) session.add(item) - item = pagure.lib.model.UserEmail( - user_id=foo.id, - email='foo@bar.com') + item = pagure.lib.model.UserEmail(user_id=foo.id, email="foo@bar.com") session.add(item) - item = pagure.lib.model.UserEmail( - user_id=you.id, - email=user_email) + item = pagure.lib.model.UserEmail(user_id=you.id, email=user_email) session.add(item) session.commit() @@ -222,9 +228,7 @@ def insert_data(session, username, user_email): ###################################### # user_emails_pending email_pend = pagure.lib.model.UserEmailPending( - user_id=pingou.id, - email='foo@fp.o', - token='abcdef', + user_id=pingou.id, email="foo@fp.o", token="abcdef" ) session.add(email_pend) session.commit() @@ -234,10 +238,10 @@ def insert_data(session, username, user_email): # Add an issue and tag it so that we can list them item = pagure.lib.model.Issue( id=1001, - uid='foobar', + uid="foobar", project_id=project1.id, - title='Problem with jenkins build', - content='For some reason the tests fail at line:24', + title="Problem with jenkins build", + content="For some reason the tests fail at line:24", user_id=pingou.id, ) session.add(item) @@ -245,11 +249,11 @@ def insert_data(session, username, user_email): item = pagure.lib.model.Issue( id=1002, - uid='foobar2', + uid="foobar2", project_id=project1.id, - title='Unit tests failing', - content='Need to fix code for the unit tests to ' - 'pass so jenkins build can complete.', + title="Unit tests failing", + content="Need to fix code for the unit tests to " + "pass so jenkins build can complete.", user_id=pingou.id, ) session.add(item) @@ -257,10 +261,10 @@ def insert_data(session, username, user_email): item = pagure.lib.model.Issue( id=1003, - uid='foobar3', + uid="foobar3", project_id=project1.id, - title='Segfault during execution', - content='Index out of bounds for variable i?', + title="Segfault during execution", + content="Index out of bounds for variable i?", user_id=you.id, ) session.add(item) @@ -268,166 +272,155 @@ def insert_data(session, username, user_email): ###################################### # pagure_user_group - group = pagure.lib.query.search_groups(session, pattern=None, - group_name="rel-eng", group_type=None) + group = pagure.lib.query.search_groups( + session, pattern=None, group_name="rel-eng", group_type=None + ) item = pagure.lib.model.PagureUserGroup( - user_id=pingou.id, - group_id=group.id + user_id=pingou.id, group_id=group.id ) session.add(item) session.commit() - group = pagure.lib.query.search_groups(session, pattern=None, - group_name="admin", group_type=None) - - item = pagure.lib.model.PagureUserGroup( - user_id=you.id, - group_id=group.id + group = pagure.lib.query.search_groups( + session, pattern=None, group_name="admin", group_type=None ) + + item = pagure.lib.model.PagureUserGroup(user_id=you.id, group_id=group.id) session.add(item) session.commit() - group = pagure.lib.query.search_groups(session, pattern=None, - group_name="group", group_type=None) - - item = pagure.lib.model.PagureUserGroup( - user_id=foo.id, - group_id=group.id + group = pagure.lib.query.search_groups( + session, pattern=None, group_name="group", group_type=None ) + + item = pagure.lib.model.PagureUserGroup(user_id=foo.id, group_id=group.id) session.add(item) session.commit() ###################################### # projects_groups - group = pagure.lib.query.search_groups(session, pattern=None, - group_name="rel-eng", group_type=None) - repo = pagure.lib.query.get_authorized_project(session, 'test') + group = pagure.lib.query.search_groups( + session, pattern=None, group_name="rel-eng", group_type=None + ) + repo = pagure.lib.query.get_authorized_project(session, "test") item = pagure.lib.model.ProjectGroup( - project_id=repo.id, - group_id=group.id, - access="commit" + project_id=repo.id, group_id=group.id, access="commit" ) session.add(item) session.commit() - group = pagure.lib.query.search_groups(session, pattern=None, - group_name="admin", group_type=None) - repo = pagure.lib.query.get_authorized_project(session, 'test2') + group = pagure.lib.query.search_groups( + session, pattern=None, group_name="admin", group_type=None + ) + repo = pagure.lib.query.get_authorized_project(session, "test2") item = pagure.lib.model.ProjectGroup( - project_id=repo.id, - group_id=group.id, - access="admin" + project_id=repo.id, group_id=group.id, access="admin" ) session.add(item) session.commit() ###################################### # pull_requests - repo = pagure.lib.query.get_authorized_project(session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(session, 'test') + repo = pagure.lib.query.get_authorized_project(session, "test") + forked_repo = pagure.lib.query.get_authorized_project(session, "test") req = pagure.lib.query.new_pull_request( session=session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='Fixing code for unittest', + branch_to="master", + title="Fixing code for unittest", user=username, - status="Open" + status="Open", ) session.commit() - repo = pagure.lib.query.get_authorized_project(session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(session, 'test') + repo = pagure.lib.query.get_authorized_project(session, "test") + forked_repo = pagure.lib.query.get_authorized_project(session, "test") req = pagure.lib.query.new_pull_request( session=session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='add very nice README', + branch_to="master", + title="add very nice README", user=username, - status="Open" + status="Open", ) session.commit() - repo = pagure.lib.query.get_authorized_project(session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(session, 'test') + repo = pagure.lib.query.get_authorized_project(session, "test") + forked_repo = pagure.lib.query.get_authorized_project(session, "test") req = pagure.lib.query.new_pull_request( session=session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='Add README', + branch_to="master", + title="Add README", user=username, - status="Closed" + status="Closed", ) session.commit() - repo = pagure.lib.query.get_authorized_project(session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(session, 'test') + repo = pagure.lib.query.get_authorized_project(session, "test") + forked_repo = pagure.lib.query.get_authorized_project(session, "test") req = pagure.lib.query.new_pull_request( session=session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='Fix some containers', + branch_to="master", + title="Fix some containers", user=username, - status="Merged" + status="Merged", ) session.commit() - repo = pagure.lib.query.get_authorized_project(session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(session, 'test') + repo = pagure.lib.query.get_authorized_project(session, "test") + forked_repo = pagure.lib.query.get_authorized_project(session, "test") req = pagure.lib.query.new_pull_request( session=session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='Fix pull request statuses', + branch_to="master", + title="Fix pull request statuses", user=username, - status="Closed" + status="Closed", ) session.commit() - repo = pagure.lib.query.get_authorized_project(session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(session, 'test') + repo = pagure.lib.query.get_authorized_project(session, "test") + forked_repo = pagure.lib.query.get_authorized_project(session, "test") req = pagure.lib.query.new_pull_request( session=session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='Fixing UI of issue', + branch_to="master", + title="Fixing UI of issue", user=username, - status="Merged" + status="Merged", ) session.commit() - ##################################### # tokens tests.create_tokens(session, user_id=pingou.id, project_id=project1.id) ###################################### # user_projects - repo = pagure.lib.query.get_authorized_project(session, 'test') + repo = pagure.lib.query.get_authorized_project(session, "test") item = pagure.lib.model.ProjectUser( - project_id=repo.id, - user_id=foo.id, - access="commit" + project_id=repo.id, user_id=foo.id, access="commit" ) session.add(item) session.commit() - repo = pagure.lib.query.get_authorized_project(session, 'test2') + repo = pagure.lib.query.get_authorized_project(session, "test2") item = pagure.lib.model.ProjectUser( - project_id=repo.id, - user_id=you.id, - access="commit" + project_id=repo.id, user_id=you.id, access="commit" ) session.add(item) session.commit() @@ -436,29 +429,30 @@ def insert_data(session, username, user_email): # issue_comments item = pagure.lib.model.IssueComment( user_id=pingou.id, - issue_uid='foobar', - comment='We may need to adjust the unittests instead of the code.', + issue_uid="foobar", + comment="We may need to adjust the unittests instead of the code.", ) session.add(item) session.commit() ###################################### # issue_to_issue - repo = pagure.lib.query.get_authorized_project(session, 'test') + repo = pagure.lib.query.get_authorized_project(session, "test") all_issues = pagure.lib.query.search_issues(session, repo) - pagure.lib.query.add_issue_dependency(session, all_issues[0], - all_issues[1], 'pingou') + pagure.lib.query.add_issue_dependency( + session, all_issues[0], all_issues[1], "pingou" + ) ###################################### # pull_request_comments - user = pagure.lib.query.search_user(session, username='pingou') + user = pagure.lib.query.search_user(session, username="pingou") # only 1 pull request available atm pr = pagure.lib.query.get_pull_request_of_user(session, "pingou")[0] item = pagure.lib.model.PullRequestComment( pull_request_uid=pr.uid, user_id=user.id, comment="+1 for me. Btw, could you rebase before you merge?", - notification=0 + notification=0, ) session.add(item) session.commit() @@ -475,7 +469,7 @@ def insert_data(session, username, user_email): percent=80, comment="Jenkins build passes", url=str(pr.id), - status="success" + status="success", ) session.add(item) session.commit() @@ -489,33 +483,30 @@ def insert_data(session, username, user_email): percent=80, comment="Jenkins does not pass", url=str(pr.id), - status="failure" + status="failure", ) session.add(item) session.commit() ###################################### # pull_request_assignee - pr = pagure.lib.query.search_pull_requests(session, requestid='1006') + pr = pagure.lib.query.search_pull_requests(session, requestid="1006") pr.assignee_id = pingou.id session.commit() - pr = pagure.lib.query.search_pull_requests(session, requestid='1007') + pr = pagure.lib.query.search_pull_requests(session, requestid="1007") pr.assignee_id = you.id session.commit() - pr = pagure.lib.query.search_pull_requests(session, requestid='1004') + pr = pagure.lib.query.search_pull_requests(session, requestid="1004") pr.assignee_id = foo.id session.commit() ###################################### # tags_issues - repo = pagure.lib.query.get_authorized_project(session, 'test') + repo = pagure.lib.query.get_authorized_project(session, "test") issues = pagure.lib.query.search_issues(session, repo) - item = pagure.lib.model.TagIssue( - issue_uid=issues[0].uid, - tag='tag1', - ) + item = pagure.lib.model.TagIssue(issue_uid=issues[0].uid, tag="tag1") session.add(item) session.commit() @@ -528,55 +519,54 @@ def insert_data(session, username, user_email): # delete fork data fork_proj_location = "forks/foo/test.git" try: - shutil.rmtree(os.path.join(_config['GIT_FOLDER'], - fork_proj_location)) + shutil.rmtree(os.path.join(_config["GIT_FOLDER"], fork_proj_location)) except: - print('git folder already deleted') + print("git folder already deleted") try: - shutil.rmtree(os.path.join(_config['DOCS_FOLDER'], - fork_proj_location)) + shutil.rmtree(os.path.join(_config["DOCS_FOLDER"], fork_proj_location)) except: - print('docs folder already deleted') + print("docs folder already deleted") try: - shutil.rmtree(os.path.join(_config['TICKETS_FOLDER'], - fork_proj_location)) + shutil.rmtree( + os.path.join(_config["TICKETS_FOLDER"], fork_proj_location) + ) except: - print('tickets folder already deleted') + print("tickets folder already deleted") try: - shutil.rmtree(os.path.join(_config['REQUESTS_FOLDER'], - fork_proj_location)) + shutil.rmtree( + os.path.join(_config["REQUESTS_FOLDER"], fork_proj_location) + ) except: - print('requests folder already deleted') + print("requests folder already deleted") - repo = pagure.lib.query.get_authorized_project(session, 'test') - result = pagure.lib.query.fork_project(session, 'foo', repo) + repo = pagure.lib.query.get_authorized_project(session, "test") + result = pagure.lib.query.fork_project(session, "foo", repo) if result == 'Repo "test" cloned to "foo/test"': session.commit() -def add_content_git_repo(folder, branch='master'): +def add_content_git_repo(folder, branch="master"): """ Create some content for the specified git repo. """ if not os.path.exists(folder): os.makedirs(folder) brepo = pygit2.init_repository(folder, bare=True) - newfolder = tempfile.mkdtemp(prefix='pagure-tests') + newfolder = tempfile.mkdtemp(prefix="pagure-tests") repo = pygit2.clone_repository(folder, newfolder) # Create a file in that git repo - with open(os.path.join(newfolder, 'sources'), 'w') as stream: - stream.write('foo\n bar') - repo.index.add('sources') + with open(os.path.join(newfolder, "sources"), "w") as stream: + stream.write("foo\n bar") + repo.index.add("sources") repo.index.write() parents = [] commit = None try: - commit = repo.revparse_single( - 'HEAD' if branch == 'master' else branch) + commit = repo.revparse_single("HEAD" if branch == "master" else branch) except KeyError: pass if commit: @@ -584,15 +574,13 @@ def add_content_git_repo(folder, branch='master'): # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") repo.create_commit( - 'refs/heads/%s' % branch, # the name of the reference to update + "refs/heads/%s" % branch, # the name of the reference to update author, committer, - 'Add sources file for testing', + "Add sources file for testing", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit @@ -602,44 +590,42 @@ def add_content_git_repo(folder, branch='master'): parents = [] commit = None try: - commit = repo.revparse_single( - 'HEAD' if branch == 'master' else branch) + commit = repo.revparse_single("HEAD" if branch == "master" else branch) except KeyError: pass if commit: parents = [commit.oid.hex] - subfolder = os.path.join('folder1', 'folder2') + subfolder = os.path.join("folder1", "folder2") if not os.path.exists(os.path.join(newfolder, subfolder)): os.makedirs(os.path.join(newfolder, subfolder)) # Create a file in that git repo - with open(os.path.join(newfolder, subfolder, 'file'), 'w') as stream: - stream.write('foo\n bar\nbaz') - repo.index.add(os.path.join(subfolder, 'file')) + with open(os.path.join(newfolder, subfolder, "file"), "w") as stream: + stream.write("foo\n bar\nbaz") + repo.index.add(os.path.join(subfolder, "file")) repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") repo.create_commit( - 'refs/heads/%s' % branch, # the name of the reference to update + "refs/heads/%s" % branch, # the name of the reference to update author, committer, - 'Add some directory and a file for more testing', + "Add some directory and a file for more testing", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - parents + parents, ) # Push to origin ori_remote = repo.remotes[0] master_ref = repo.lookup_reference( - 'HEAD' if branch == 'master' else 'refs/heads/%s' % branch).resolve() - refname = '%s:%s' % (master_ref.name, master_ref.name) + "HEAD" if branch == "master" else "refs/heads/%s" % branch + ).resolve() + refname = "%s:%s" % (master_ref.name, master_ref.name) PagureRepo.push(ori_remote, refname) @@ -647,18 +633,19 @@ def add_content_git_repo(folder, branch='master'): def _get_username(): - invalid_option = ['pingou', 'foo'] + invalid_option = ["pingou", "foo"] user_name = os.environ.get("USER_NAME") if not user_name: print("") user_name = six.moves.input( - "Enter your username so we can add you into the test data: ") + "Enter your username so we can add you into the test data: " + ) cnt = 0 while not user_name.strip() or user_name in invalid_option: print("Reserved names: " + str(invalid_option)) user_name = six.moves.input( - "Enter your username so we can add you into the " - "test data: ") + "Enter your username so we can add you into the " "test data: " + ) cnt += 1 if cnt == 4: print("We asked too many times, bailing") @@ -668,7 +655,7 @@ def _get_username(): def _get_user_email(): - invalid_option = ['bar@pingou.com', 'foo@bar.com'] + invalid_option = ["bar@pingou.com", "foo@bar.com"] user_email = os.environ.get("USER_EMAIL") if not user_email: print("") @@ -687,23 +674,32 @@ def _get_user_email(): if __name__ == "__main__": - desc = "Run the dev database initialization/insertion/deletion " \ - "script for db located " + str(_config['DB_URL']) + desc = ( + "Run the dev database initialization/insertion/deletion " + "script for db located " + str(_config["DB_URL"]) + ) parser = argparse.ArgumentParser(prog="dev-data", description=desc) - parser.add_argument('-i', '--init', action="store_true", - help="Create the dev db") - parser.add_argument('-p', '--populate', action="store_true", - help="Add test data to the db") - parser.add_argument('-d', '--delete', action="store_true", - help="Wipe the dev db") - parser.add_argument('-a', '--all', action="store_true", - help="Create, Populate then Wipe the dev db") + parser.add_argument( + "-i", "--init", action="store_true", help="Create the dev db" + ) + parser.add_argument( + "-p", "--populate", action="store_true", help="Add test data to the db" + ) + parser.add_argument( + "-d", "--delete", action="store_true", help="Wipe the dev db" + ) + parser.add_argument( + "-a", + "--all", + action="store_true", + help="Create, Populate then Wipe the dev db", + ) args = parser.parse_args() # forcing the user to choose if not any(vars(args).values()): - parser.error('No arguments provided.') + parser.error("No arguments provided.") session = None @@ -712,12 +708,13 @@ if __name__ == "__main__": db_url=_config["DB_URL"], alembic_ini=None, acls=_config["ACLS"], - debug=False) + debug=False, + ) print("Database created") if args.populate or args.all: if not session: - session = pagure.lib.query.create_session(_config['DB_URL']) + session = pagure.lib.query.create_session(_config["DB_URL"]) user_name = _get_username() user_email = _get_user_email() diff --git a/dev/containers/f29-rpms-py3 b/dev/containers/f29-rpms-py3 index 5b935c6..cae0437 100644 --- a/dev/containers/f29-rpms-py3 +++ b/dev/containers/f29-rpms-py3 @@ -20,7 +20,8 @@ RUN dnf -y install \ RUN cd / \ && git clone -b $BRANCH $REPO \ - && chmod +x /pagure/dev/containers/runtests_py3.sh + && chmod +x /pagure/dev/containers/runtests_py3.sh \ + && sed -i -e "s|\['alembic',|\['alembic-3',|" /pagure/tests/test_alembic.py # Install all the requirements from the spec file and replace the macro # %{python_pkgversion} by '3' which thus installs all the py3 version of diff --git a/dev/run-tests-container.py b/dev/run-tests-container.py index 2793a26..ff7e99c 100755 --- a/dev/run-tests-container.py +++ b/dev/run-tests-container.py @@ -58,12 +58,14 @@ if __name__ == "__main__": container_files = ["fedora-pip-py3"] else: container_names = [ - "pagure-f29-rpms-py3", "pagure-c7-rpms-py2", - "pagure-fedora-pip-py3" + "pagure-f29-rpms-py3", + "pagure-c7-rpms-py2", + "pagure-fedora-pip-py3", ] container_files = [ - "f29-rpms-py3", "centos7-rpms-py2", - "fedora-pip-py3" + "f29-rpms-py3", + "centos7-rpms-py2", + "fedora-pip-py3", ] failed = [] @@ -77,7 +79,10 @@ if __name__ == "__main__": "--build-arg", "branch={}".format(os.environ.get("BRANCH") or "master"), "--build-arg", - "repo={}".format(os.environ.get("REPO") or "https://pagure.io/pagure.git"), + "repo={}".format( + os.environ.get("REPO") + or "https://pagure.io/pagure.git" + ), "--rm", "-t", container_name, @@ -105,11 +110,14 @@ if __name__ == "__main__": container_name, "-v", "{}/results_{}:/pagure/results:z".format( - os.getcwd(), container_files[idx]), + os.getcwd(), container_files[idx] + ), "-e", "BRANCH={}".format(os.environ.get("BRANCH") or "master"), "-e", - "REPO={}".format(os.environ.get("REPO") or "https://pagure.io/pagure.git"), + "REPO={}".format( + os.environ.get("REPO") or "https://pagure.io/pagure.git" + ), "--entrypoint=/bin/bash", container_name, ] @@ -125,11 +133,14 @@ if __name__ == "__main__": container_name, "-v", "{}/results_{}:/pagure/results:z".format( - os.getcwd(), container_files[idx]), + os.getcwd(), container_files[idx] + ), "-e", "BRANCH={}".format(os.environ.get("BRANCH") or "master"), "-e", - "REPO={}".format(os.environ.get("REPO") or "https://pagure.io/pagure.git"), + "REPO={}".format( + os.environ.get("REPO") or "https://pagure.io/pagure.git" + ), "-e", "TESTCASE={}".format(args.test_case or ""), container_name, diff --git a/doc/conf.py b/doc/conf.py index b683916..78bd4dd 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -16,234 +16,227 @@ import os import re pagurefile = os.path.join( - os.path.dirname(__file__), '..', 'pagure', '__init__.py') + os.path.dirname(__file__), "..", "pagure", "__init__.py" +) # Thanks to SQLAlchemy: # https://github.com/zzzeek/sqlalchemy/blob/master/setup.py#L104 with open(pagurefile) as stream: - VERSION = re.compile( - r".*__version__ = \"(.*?)\"", re.S - ).match(stream.read()).group(1) + VERSION = ( + re.compile(r".*__version__ = \"(.*?)\"", re.S) + .match(stream.read()) + .group(1) + ) # If extensions (or modules to document with autodoc) are in another # directory, add these directories to sys.path here. If the directory is # relative to the documentation root, use os.path.abspath to make it # absolute, like shown here. -#sys.path.insert(0, os.path.abspath('.')) +# sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. -#needs_sphinx = '1.0' +# needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ - 'sphinx.ext.autodoc', 'sphinx.ext.coverage', 'sphinx.ext.viewcode' + "sphinx.ext.autodoc", + "sphinx.ext.coverage", + "sphinx.ext.viewcode", ] # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] # The suffix of source filenames. -source_suffix = '.rst' +source_suffix = ".rst" # The encoding of source files. -#source_encoding = 'utf-8-sig' +# source_encoding = 'utf-8-sig' # The master toctree document. -master_doc = 'index' +master_doc = "index" # General information about the project. -project = u'pagure' -copyright = u'2015, Red Hat Inc, Pierre-Yves Chibon ' +project = u"pagure" +copyright = u"2015, Red Hat Inc, Pierre-Yves Chibon " # The version info for the project you're documenting, acts as replacement # for |version| and |release|, also used in various other places throughout # the built documents. # # The short X.Y version. -#version = __version__ +# version = __version__ version = VERSION # The full version, including alpha/beta/rc tags. -#release = '1' +# release = '1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. -#language = None +# language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: -#today = '' +# today = '' # Else, today_fmt is used as the format for a strftime call. -#today_fmt = '%B %d, %Y' +# today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. -exclude_patterns = ['_build'] +exclude_patterns = ["_build"] # The reST default role (used for this markup: `text`) to use for all # documents. -#default_role = None +# default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True +# add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). -#add_module_names = True +# add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. -#show_authors = False +# show_authors = False # The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' +pygments_style = "sphinx" # A list of ignored prefixes for module index sorting. -#modindex_common_prefix = [] +# modindex_common_prefix = [] # -- Options for HTML output ---------------------------------------------- import cloud_sptheme as csp -html_style = 'site.css' +html_style = "site.css" # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. -#html_theme = 'default' +# html_theme = 'default' html_theme = "cloud" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. -#html_theme_options = {} +# html_theme_options = {} html_theme_options = { "sidebarwidth": "200px", "max_width": "900px", "compact_width": "800px", "minimal_width": "700px", - # Style it like Fedora.. "bodyfont": "Cantarell", - "highlightcolor": "#79db32", # First Green - "sidebarbgcolor": "#FEFEFE", "sidebartrimcolor": "#FEFEFE", - "sectionbgcolor": "#FEFEFE", "sectiontrimcolor": "#FEFEFE", "sectiontextcolor": "#444444", - "relbarbgcolor": "#FEFEFE", "relbartextcolor": "#444444", "relbarlinkcolor": "#444444", - "bgcolor": "#FEFEFE", "textcolor": "#444444", - #"linkcolor": "#79db32", # First Green + # "linkcolor": "#79db32", # First Green "linkcolor": "#00009d", - "headtextcolor": "#444444", "headlinkcolor": "#444444", - - #"codebgcolor" - #"codetextcolor" + # "codebgcolor" + # "codetextcolor" "codetrimcolor": "#79db32", # First Green - "footerbgcolor": "#FEFEFE", - - "fontcssurl": "_static/site.css" + "fontcssurl": "_static/site.css", } # Add any paths that contain custom themes here, relative to this directory. -#html_theme_path = [] +# html_theme_path = [] html_theme_path = [csp.get_theme_dir()] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". -#html_title = None +# html_title = None # A shorter title for the navigation bar. Default is the same as html_title. -#html_short_title = None +# html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. -#html_logo = None +# html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. -#html_favicon = None +# html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] +html_static_path = ["_static"] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. -#html_last_updated_fmt = '%b %d, %Y' +# html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. -#html_use_smartypants = True +# html_use_smartypants = True # Custom sidebar templates, maps document names to template names. html_sidebars = { - '**': [ - 'pagure-logo.html', - 'localtoc.html', - 'relations.html', - 'sourcelink.html', - 'searchbox.html', + "**": [ + "pagure-logo.html", + "localtoc.html", + "relations.html", + "sourcelink.html", + "searchbox.html", ] } # Additional templates that should be rendered to pages, maps page names to # template names. -#html_additional_pages = {} +# html_additional_pages = {} # If false, no module index is generated. -#html_domain_indices = True +# html_domain_indices = True # If false, no index is generated. -#html_use_index = True +# html_use_index = True # If true, the index is split into individual pages for each letter. -#html_split_index = False +# html_split_index = False # If true, links to the reST sources are added to the pages. -#html_show_sourcelink = True +# html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -#html_show_sphinx = True +# html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -#html_show_copyright = True +# html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. -#html_use_opensearch = '' +# html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). -#html_file_suffix = None +# html_file_suffix = None # Output file base name for HTML help builder. -htmlhelp_basename = 'pagure' +htmlhelp_basename = "pagure" # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. #'preamble': '', } @@ -253,31 +246,33 @@ latex_elements = { # [howto/manual]). latex_documents = [ ( - 'index', 'pagure.tex', u'Pagure Documentation', - u'Pierre-Yves Chibon \\textless{}pingou@pingoured.fr\\textgreater{}', - 'manual' - ), + "index", + "pagure.tex", + u"Pagure Documentation", + u"Pierre-Yves Chibon \\textless{}pingou@pingoured.fr\\textgreater{}", + "manual", + ) ] # The name of an image file (relative to this directory) to place at the top of # the title page. -#latex_logo = None +# latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. -#latex_use_parts = False +# latex_use_parts = False # If true, show page references after internal links. -#latex_show_pagerefs = False +# latex_show_pagerefs = False # If true, show URL addresses after external links. -#latex_show_urls = False +# latex_show_urls = False # Documents to append as an appendix to all manuals. -#latex_appendices = [] +# latex_appendices = [] # If false, no module index is generated. -#latex_domain_indices = True +# latex_domain_indices = True # -- Options for manual page output --------------------------------------- @@ -285,14 +280,16 @@ latex_documents = [ # (source start file, name, description, authors, manual section). man_pages = [ ( - 'index', 'pagure', u'Pagure Documentation', - [u'Pierre-Yves Chibon '], - 1 + "index", + "pagure", + u"Pagure Documentation", + [u"Pierre-Yves Chibon "], + 1, ) ] # If true, show URL addresses after external links. -#man_show_urls = False +# man_show_urls = False # -- Options for Texinfo output ------------------------------------------- @@ -302,18 +299,21 @@ man_pages = [ # dir menu entry, description, category) texinfo_documents = [ ( - 'index', 'pagure', u'Pagure Documentation', - u'Pierre-Yves Chibon ', 'pagure', - 'Small git-centric forge', - 'Miscellaneous' - ), + "index", + "pagure", + u"Pagure Documentation", + u"Pierre-Yves Chibon ", + "pagure", + "Small git-centric forge", + "Miscellaneous", + ) ] # Documents to append as an appendix to all manuals. -#texinfo_appendices = [] +# texinfo_appendices = [] # If false, no module index is generated. -#texinfo_domain_indices = True +# texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. -#texinfo_show_urls = 'footnote' +# texinfo_show_urls = 'footnote' diff --git a/fedmsg.d/pagure.py b/fedmsg.d/pagure.py index 4e548d1..645c2d8 100644 --- a/fedmsg.d/pagure.py +++ b/fedmsg.d/pagure.py @@ -9,12 +9,7 @@ pagure producer (wsgi process). """ import socket -hostname = socket.gethostname().split('.')[0] -config = dict( - endpoints={ - "pagure.%s" % hostname: [ - "tcp://127.0.0.1:3005", - ], - }, -) +hostname = socket.gethostname().split(".")[0] + +config = dict(endpoints={"pagure.%s" % hostname: ["tcp://127.0.0.1:3005"]}) diff --git a/fedmsg.d/pagure_ci.py b/fedmsg.d/pagure_ci.py index 9ac9413..0fd0102 100644 --- a/fedmsg.d/pagure_ci.py +++ b/fedmsg.d/pagure_ci.py @@ -1,3 +1 @@ -config = { - 'integrator.enabled': True, -} +config = {"integrator.enabled": True} diff --git a/files/aclchecker.py b/files/aclchecker.py index b99b5f8..ee5cb01 100644 --- a/files/aclchecker.py +++ b/files/aclchecker.py @@ -99,7 +99,7 @@ result.update({"username": remoteuser, "cmd": cmd}) for key in result: if result[key] is None: - result[key] = '' + result[key] = "" runargs = [arg % result for arg in runner] if env: diff --git a/files/api_key_expire_mail.py b/files/api_key_expire_mail.py index 645c845..a9befb9 100755 --- a/files/api_key_expire_mail.py +++ b/files/api_key_expire_mail.py @@ -13,29 +13,29 @@ import pagure.lib.model_base import pagure.lib.notify import pagure.lib.query -if 'PAGURE_CONFIG' not in os.environ \ - and os.path.exists('/etc/pagure/pagure.cfg'): - print('Using configuration file `/etc/pagure/pagure.cfg`') - os.environ['PAGURE_CONFIG'] = '/etc/pagure/pagure.cfg' +if "PAGURE_CONFIG" not in os.environ and os.path.exists( + "/etc/pagure/pagure.cfg" +): + print("Using configuration file `/etc/pagure/pagure.cfg`") + os.environ["PAGURE_CONFIG"] = "/etc/pagure/pagure.cfg" _config = pagure.config.reload_config() def main(check=False, debug=False): - ''' The function that actually sends the email - in case the expiration date is near''' + """ The function that actually sends the email + in case the expiration date is near""" current_time = datetime.utcnow() day_diff_for_mail = [10, 5, 1] email_dates = [ email_day.date() for email_day in [ - current_time + timedelta(days=i) - for i in day_diff_for_mail + current_time + timedelta(days=i) for i in day_diff_for_mail ] ] - session = pagure.lib.model_base.create_session(_config['DB_URL']) + session = pagure.lib.model_base.create_session(_config["DB_URL"]) tokens = session.query(model.Token).all() for token in tokens: @@ -46,51 +46,63 @@ def main(check=False, debug=False): username = user.fullname or user.username user_email = user.default_email days_left = (token.expiration - datetime.utcnow()).days - subject = 'Pagure API key expiration date is near!' + subject = "Pagure API key expiration date is near!" if token.project: - text = '''Hi %s, + text = """Hi %s, Your Pagure API key %s linked to the project %s will expire in %s day(s). Please get a new key for non-interrupted service. Thanks, -Your Pagure Admin. ''' % ( +Your Pagure Admin. """ % ( username, token.description, token.project.fullname, - days_left + days_left, ) else: - text = '''Hi %s, + text = """Hi %s, Your Pagure API key %s will expire in %s day(s). Please get a new key for non-interrupted service. Thanks, -Your Pagure Admin. ''' % ( +Your Pagure Admin. """ % ( username, token.description, - days_left) + days_left, + ) if not check: msg = pagure.lib.notify.send_email(text, subject, user_email) else: - print('Sending email to %s (%s) about key: %s' % ( - username, user_email, token.id)) + print( + "Sending email to %s (%s) about key: %s" + % (username, user_email, token.id) + ) if debug: - print('Sent mail to %s' % username) + print("Sent mail to %s" % username) session.remove() if debug: - print('Done') + print("Done") -if __name__ == '__main__': +if __name__ == "__main__": parser = argparse.ArgumentParser( - description='Script to send email before the api token expires') + description="Script to send email before the api token expires" + ) parser.add_argument( - '--check', dest='check', action='store_true', default=False, - help='Print the some output but does not send any email') + "--check", + dest="check", + action="store_true", + default=False, + help="Print the some output but does not send any email", + ) parser.add_argument( - '--debug', dest='debug', action='store_true', default=False, - help='Print the debugging output') + "--debug", + dest="debug", + action="store_true", + default=False, + help="Print the debugging output", + ) args = parser.parse_args() main(debug=args.debug) diff --git a/files/emoji_clean_json.py b/files/emoji_clean_json.py index 406ed55..8a91fa4 100644 --- a/files/emoji_clean_json.py +++ b/files/emoji_clean_json.py @@ -6,27 +6,27 @@ import os import sys data = None -with open('emoji_strategy.json') as stream: +with open("emoji_strategy.json") as stream: data = json.load(stream) if not data: - print('Could not load the data from the JSON file') + print("Could not load the data from the JSON file") sys.exit(1) # Retrieve the items we keep in the JSON tokeep = {} for key in data: - if '-' in data[key]['unicode'] and data[key]['unicode'].startswith('1F'): + if "-" in data[key]["unicode"] and data[key]["unicode"].startswith("1F"): continue tokeep[key] = data[key] # Check if we have the keys of all images we kept -unicodes = [tokeep[key]['unicode'] for key in tokeep] -images = [item.replace('.png', '') for item in os.listdir('png')] +unicodes = [tokeep[key]["unicode"] for key in tokeep] +images = [item.replace(".png", "") for item in os.listdir("png")] print(set(unicodes).symmetric_difference(set(images))) -with open('emoji_strategy2.json', 'w') as stream: +with open("emoji_strategy2.json", "w") as stream: json.dump(tokeep, stream) diff --git a/files/mirror_project_in.py b/files/mirror_project_in.py index ba04f2f..7a6a306 100644 --- a/files/mirror_project_in.py +++ b/files/mirror_project_in.py @@ -13,23 +13,24 @@ import pagure.lib.model_base import pagure.lib.notify import pagure.lib.query -if 'PAGURE_CONFIG' not in os.environ \ - and os.path.exists('/etc/pagure/pagure.cfg'): - print('Using configuration file `/etc/pagure/pagure.cfg`') - os.environ['PAGURE_CONFIG'] = '/etc/pagure/pagure.cfg' +if "PAGURE_CONFIG" not in os.environ and os.path.exists( + "/etc/pagure/pagure.cfg" +): + print("Using configuration file `/etc/pagure/pagure.cfg`") + os.environ["PAGURE_CONFIG"] = "/etc/pagure/pagure.cfg" _config = pagure.config.reload_config() def main(check=False, debug=False): - ''' The function pulls in all the changes from upstream''' + """ The function pulls in all the changes from upstream""" - session = pagure.lib.model_base.create_session(_config['DB_URL']) - projects = session.query( - model.Project - ).filter( - model.Project.mirrored_from != None - ).all() + session = pagure.lib.model_base.create_session(_config["DB_URL"]) + projects = ( + session.query(model.Project) + .filter(model.Project.mirrored_from != None) + .all() + ) for project in projects: if debug: @@ -41,17 +42,26 @@ def main(check=False, debug=False): session.remove() if debug: - print('Done') + print("Done") -if __name__ == '__main__': +if __name__ == "__main__": parser = argparse.ArgumentParser( - description='Script to send email before the api token expires') + description="Script to send email before the api token expires" + ) parser.add_argument( - '--check', dest='check', action='store_true', default=False, - help='Print the some output but does not send any email') + "--check", + dest="check", + action="store_true", + default=False, + help="Print the some output but does not send any email", + ) parser.add_argument( - '--debug', dest='debug', action='store_true', default=False, - help='Print the debugging output') + "--debug", + dest="debug", + action="store_true", + default=False, + help="Print the debugging output", + ) args = parser.parse_args() main(debug=args.debug) diff --git a/pagure-ev/pagure_stream_server.py b/pagure-ev/pagure_stream_server.py index 4439c91..d1aeb00 100644 --- a/pagure-ev/pagure_stream_server.py +++ b/pagure-ev/pagure_stream_server.py @@ -33,10 +33,11 @@ from six.moves.urllib.parse import urlparse log = logging.getLogger(__name__) -if 'PAGURE_CONFIG' not in os.environ \ - and os.path.exists('/etc/pagure/pagure.cfg'): - print('Using configuration file `/etc/pagure/pagure.cfg`') - os.environ['PAGURE_CONFIG'] = '/etc/pagure/pagure.cfg' +if "PAGURE_CONFIG" not in os.environ and os.path.exists( + "/etc/pagure/pagure.cfg" +): + print("Using configuration file `/etc/pagure/pagure.cfg`") + os.environ["PAGURE_CONFIG"] = "/etc/pagure/pagure.cfg" import pagure # noqa: E402 @@ -47,17 +48,19 @@ from pagure.exceptions import PagureException, PagureEvException # noqa: E402 SERVER = None SESSION = None POOL = redis.ConnectionPool( - host=pagure.config.config['REDIS_HOST'], - port=pagure.config.config['REDIS_PORT'], - db=pagure.config.config['REDIS_DB']) + host=pagure.config.config["REDIS_HOST"], + port=pagure.config.config["REDIS_PORT"], + db=pagure.config.config["REDIS_DB"], +) def _get_session(): global SESSION if SESSION is None: - print(pagure.config.config['DB_URL']) + print(pagure.config.config["DB_URL"]) SESSION = pagure.lib.model_base.create_session( - pagure.config.config['DB_URL']) + pagure.config.config["DB_URL"] + ) return SESSION @@ -67,7 +70,7 @@ def _get_issue(repo, objid): objid (issue number). """ issue = None - if not repo.settings.get('issue_tracker', True): + if not repo.settings.get("issue_tracker", True): raise PagureEvException("No issue tracker found for this project") session = _get_session() @@ -79,7 +82,8 @@ def _get_issue(repo, objid): if issue.private: # TODO: find a way to do auth raise PagureEvException( - "This issue is private and you are not allowed to view it") + "This issue is private and you are not allowed to view it" + ) return issue @@ -88,13 +92,15 @@ def _get_pull_request(repo, objid): """Get a PullRequest instance for a given repo (Project) and objid (request number). """ - if not repo.settings.get('pull_requests', True): + if not repo.settings.get("pull_requests", True): raise PagureEvException( - "No pull-request tracker found for this project") + "No pull-request tracker found for this project" + ) session = _get_session() request = pagure.lib.query.search_pull_requests( - session, project_id=repo.id, requestid=objid) + session, project_id=repo.id, requestid=objid + ) if request is None or request.project != repo: raise PagureEvException("Pull-Request '%s' not found" % objid) @@ -105,20 +111,19 @@ def _get_pull_request(repo, objid): # Dict representing known object types that we handle requests for, # and the bound functions for getting an object instance from the # parsed path data. Has to come after the functions it binds -OBJECTS = { - 'issue': _get_issue, - 'pull-request': _get_pull_request -} +OBJECTS = {"issue": _get_issue, "pull-request": _get_pull_request} def get_obj_from_path(path): """ Return the Ticket or Request object based on the path provided. """ (username, namespace, reponame, objtype, objid) = pagure.utils.parse_path( - path) + path + ) session = _get_session() repo = pagure.lib.query.get_authorized_project( - session, reponame, user=username, namespace=namespace) + session, reponame, user=username, namespace=namespace + ) if repo is None: raise PagureEvException("Project '%s' not found" % reponame) @@ -137,9 +142,9 @@ def handle_client(client_reader, client_writer): data = None while True: # give client a chance to respond, timeout after 10 seconds - line = yield trololio.From(trololio.asyncio.wait_for( - client_reader.readline(), - timeout=10.0)) + line = yield trololio.From( + trololio.asyncio.wait_for(client_reader.readline(), timeout=10.0) + ) if not line.decode().strip(): break line = line.decode().rstrip() @@ -156,7 +161,7 @@ def handle_client(client_reader, client_writer): log.warning("No URL provided: %s" % data) return - if '/' not in data[1]: + if "/" not in data[1]: log.warning("Invalid URL provided: %s" % data[1]) return @@ -168,24 +173,25 @@ def handle_client(client_reader, client_writer): log.warning(err.message) return - origin = pagure.config.config.get('APP_URL') - if origin.endswith('/'): + origin = pagure.config.config.get("APP_URL") + if origin.endswith("/"): origin = origin[:-1] - client_writer.write(( - "HTTP/1.0 200 OK\n" - "Content-Type: text/event-stream\n" - "Cache: nocache\n" - "Connection: keep-alive\n" - "Access-Control-Allow-Origin: %s\n\n" % origin - ).encode()) - + client_writer.write( + ( + "HTTP/1.0 200 OK\n" + "Content-Type: text/event-stream\n" + "Cache: nocache\n" + "Connection: keep-alive\n" + "Access-Control-Allow-Origin: %s\n\n" % origin + ).encode() + ) conn = redis.Redis(connection_pool=POOL) subscriber = conn.pubsub(ignore_subscribe_messages=True) try: - subscriber.subscribe('pagure.%s' % obj.uid) + subscriber.subscribe("pagure.%s" % obj.uid) # Inside a while loop, wait for incoming events. oncall = 0 @@ -195,14 +201,14 @@ def handle_client(client_reader, client_writer): # Send a ping to see if the client is still alive if oncall >= 5: # Only send a ping once every 5 seconds - client_writer.write(('event: ping\n\n').encode()) + client_writer.write(("event: ping\n\n").encode()) oncall = 0 oncall += 1 yield trololio.From(client_writer.drain()) yield trololio.From(trololio.asyncio.sleep(1)) else: - log.info("Sending %s", msg['data']) - client_writer.write(('data: %s\n\n' % msg['data']).encode()) + log.info("Sending %s", msg["data"]) + client_writer.write(("data: %s\n\n" % msg["data"]).encode()) yield trololio.From(client_writer.drain()) except OSError: @@ -223,12 +229,11 @@ def handle_client(client_reader, client_writer): def stats(client_reader, client_writer): try: - log.info('Clients: %s', SERVER.active_count) - client_writer.write(( - "HTTP/1.0 200 OK\n" - "Cache: nocache\n\n" - ).encode()) - client_writer.write(('data: %s\n\n' % SERVER.active_count).encode()) + log.info("Clients: %s", SERVER.active_count) + client_writer.write( + ("HTTP/1.0 200 OK\n" "Cache: nocache\n\n").encode() + ) + client_writer.write(("data: %s\n\n" % SERVER.active_count).encode()) yield trololio.From(client_writer.drain()) except trololio.ConnectionResetError as err: @@ -247,20 +252,26 @@ def main(): coro = trololio.asyncio.start_server( handle_client, host=None, - port=pagure.config.config['EVENTSOURCE_PORT'], - loop=loop) + port=pagure.config.config["EVENTSOURCE_PORT"], + loop=loop, + ) SERVER = loop.run_until_complete(coro) log.info( - 'Serving server at {}'.format(SERVER.sockets[0].getsockname())) - if pagure.config.config.get('EV_STATS_PORT'): + "Serving server at {}".format(SERVER.sockets[0].getsockname()) + ) + if pagure.config.config.get("EV_STATS_PORT"): stats_coro = trololio.asyncio.start_server( stats, host=None, - port=pagure.config.config.get('EV_STATS_PORT'), - loop=loop) + port=pagure.config.config.get("EV_STATS_PORT"), + loop=loop, + ) stats_server = loop.run_until_complete(stats_coro) - log.info('Serving stats at {}'.format( - stats_server.sockets[0].getsockname())) + log.info( + "Serving stats at {}".format( + stats_server.sockets[0].getsockname() + ) + ) loop.run_forever() except KeyboardInterrupt: pass @@ -271,7 +282,7 @@ def main(): finally: # Close the server SERVER.close() - if pagure.config.config.get('EV_STATS_PORT'): + if pagure.config.config.get("EV_STATS_PORT"): stats_server.close() log.info("End Connection") loop.run_until_complete(SERVER.wait_closed()) @@ -279,10 +290,11 @@ def main(): log.info("End") -if __name__ == '__main__': +if __name__ == "__main__": log = logging.getLogger("") formatter = logging.Formatter( - "%(asctime)s %(levelname)s [%(module)s:%(lineno)d] %(message)s") + "%(asctime)s %(levelname)s [%(module)s:%(lineno)d] %(message)s" + ) # setup console logging log.setLevel(logging.DEBUG) diff --git a/pagure-milters/comment_email_milter.py b/pagure-milters/comment_email_milter.py index 175a553..54a2b6f 100644 --- a/pagure-milters/comment_email_milter.py +++ b/pagure-milters/comment_email_milter.py @@ -26,9 +26,10 @@ import pagure.lib.model_base import pagure.lib.query -if 'PAGURE_CONFIG' not in os.environ \ - and os.path.exists('/etc/pagure/pagure.cfg'): - os.environ['PAGURE_CONFIG'] = '/etc/pagure/pagure.cfg' +if "PAGURE_CONFIG" not in os.environ and os.path.exists( + "/etc/pagure/pagure.cfg" +): + os.environ["PAGURE_CONFIG"] = "/etc/pagure/pagure.cfg" logq = Queue(maxsize=4) @@ -36,8 +37,9 @@ _config = pagure.config.reload_config() def get_email_body(emailobj): - ''' Return the body of the email, preferably in text. - ''' + """ Return the body of the email, preferably in text. + """ + def _get_body(emailobj): """ Return the first text/plain body found if the email is multipart or just the regular payload otherwise. @@ -51,34 +53,33 @@ def get_email_body(emailobj): return _get_body(payload) body = payload.get_payload() - if payload.get_content_type() == 'text/plain': + if payload.get_content_type() == "text/plain": return body else: return emailobj.get_payload() body = _get_body(emailobj) - enc = emailobj['Content-Transfer-Encoding'] - if enc == 'base64': + enc = emailobj["Content-Transfer-Encoding"] + if enc == "base64": body = base64.decodestring(body) return body def clean_item(item): - ''' For an item provided as return the content, if there are no + """ For an item provided as return the content, if there are no <> then return the string. - ''' - if '<' in item: - item = item.split('<')[1] - if '>' in item: - item = item.split('>')[0] + """ + if "<" in item: + item = item.split("<")[1] + if ">" in item: + item = item.split(">")[0] return item class PagureMilter(Milter.Base): - def __init__(self): # A new instance with each new connection. self.id = Milter.uniqueID() # Integer incremented with each call. self.fp = None @@ -94,28 +95,28 @@ class PagureMilter(Milter.Base): # must use addheader, chgheader, replacebody to change the message # on the MTA. self.fp = BytesIO() - self.canon_from = '@'.join(parse_addr(mailfrom)) - from_txt = 'From %s %s\n' % (self.canon_from, time.ctime()) - self.fp.write(from_txt.encode('utf-8')) + self.canon_from = "@".join(parse_addr(mailfrom)) + from_txt = "From %s %s\n" % (self.canon_from, time.ctime()) + self.fp.write(from_txt.encode("utf-8")) return Milter.CONTINUE @Milter.noreply def header(self, name, hval): - ''' Headers ''' + """ Headers """ # add header to buffer header_txt = "%s: %s\n" % (name, hval) - self.fp.write(header_txt.encode('utf-8')) + self.fp.write(header_txt.encode("utf-8")) return Milter.CONTINUE @Milter.noreply def eoh(self): - ''' End of Headers ''' + """ End of Headers """ self.fp.write(b"\n") return Milter.CONTINUE @Milter.noreply def body(self, chunk): - ''' Body ''' + """ Body """ self.fp.write(chunk) return Milter.CONTINUE @@ -127,138 +128,139 @@ class PagureMilter(Milter.Base): return Milter.CONTINUE def eom(self): - ''' End of Message ''' + """ End of Message """ self.fp.seek(0) msg = email.message_from_file(self.fp) - msg_id = msg.get('In-Reply-To', None) + msg_id = msg.get("In-Reply-To", None) if msg_id is None: - self.log('No In-Reply-To, keep going') + self.log("No In-Reply-To, keep going") return Milter.CONTINUE # Ensure we don't get extra lines in the message-id - msg_id = msg_id.split('\n')[0].strip() + msg_id = msg_id.split("\n")[0].strip() - self.log('msg-ig %s' % msg_id) - self.log('To %s' % msg['to']) - self.log('Cc %s' % msg.get('cc')) - self.log('From %s' % msg['From']) + self.log("msg-ig %s" % msg_id) + self.log("To %s" % msg["to"]) + self.log("Cc %s" % msg.get("cc")) + self.log("From %s" % msg["From"]) # Check the email was sent to the right address - email_address = msg['to'] - if 'reply+' in msg.get('cc', ''): - email_address = msg['cc'] - if 'reply+' not in email_address: + email_address = msg["to"] + if "reply+" in msg.get("cc", ""): + email_address = msg["cc"] + if "reply+" not in email_address: self.log( - 'No valid recipient email found in To/Cc: %s' - % email_address) + "No valid recipient email found in To/Cc: %s" % email_address + ) return Milter.CONTINUE # Ensure the user replied to his/her own notification, not that # they are trying to forge their ID into someone else's - salt = _config.get('SALT_EMAIL') - from_email = clean_item(msg['From']) - session = pagure.lib.model_base.create_session(_config['DB_URL']) + salt = _config.get("SALT_EMAIL") + from_email = clean_item(msg["From"]) + session = pagure.lib.model_base.create_session(_config["DB_URL"]) try: user = pagure.lib.query.get_user(session, from_email) except: self.log( - "Could not find an user in the DB associated with %s" % - from_email) + "Could not find an user in the DB associated with %s" + % from_email + ) session.remove() return Milter.CONTINUE hashes = [] for email_obj in user.emails: - m = hashlib.sha512('%s%s%s' % (msg_id, salt, email_obj.email)) + m = hashlib.sha512("%s%s%s" % (msg_id, salt, email_obj.email)) hashes.append(m.hexdigest()) - tohash = email_address.split('@')[0].split('+')[-1] + tohash = email_address.split("@")[0].split("+")[-1] if tohash not in hashes: - self.log('hash list: %s' % hashes) - self.log('tohash: %s' % tohash) - self.log('Hash does not correspond to the destination') + self.log("hash list: %s" % hashes) + self.log("tohash: %s" % tohash) + self.log("Hash does not correspond to the destination") session.remove() return Milter.CONTINUE - if msg['From'] and msg['From'] == _config.get('FROM_EMAIL'): + if msg["From"] and msg["From"] == _config.get("FROM_EMAIL"): self.log("Let's not process the email we send") session.remove() return Milter.CONTINUE msg_id = clean_item(msg_id) - if msg_id and '-ticket-' in msg_id: - self.log('Processing issue') + if msg_id and "-ticket-" in msg_id: + self.log("Processing issue") session.remove() return self.handle_ticket_email(msg, msg_id) - elif msg_id and '-pull-request-' in msg_id: - self.log('Processing pull-request') + elif msg_id and "-pull-request-" in msg_id: + self.log("Processing pull-request") session.remove() return self.handle_request_email(msg, msg_id) else: - self.log('Not a pagure ticket or pull-request email, let it go') + self.log("Not a pagure ticket or pull-request email, let it go") session.remove() return Milter.CONTINUE def handle_ticket_email(self, emailobj, msg_id): - ''' Add the email as a comment on a ticket. ''' - uid = msg_id.split('-ticket-')[-1].split('@')[0] + """ Add the email as a comment on a ticket. """ + uid = msg_id.split("-ticket-")[-1].split("@")[0] parent_id = None - if '-' in uid: - uid, parent_id = uid.rsplit('-', 1) - if '/' in uid: - uid = uid.split('/')[0] - self.log('uid %s' % uid) - self.log('parent_id %s' % parent_id) + if "-" in uid: + uid, parent_id = uid.rsplit("-", 1) + if "/" in uid: + uid = uid.split("/")[0] + self.log("uid %s" % uid) + self.log("parent_id %s" % parent_id) data = { - 'objid': uid, - 'comment': get_email_body(emailobj), - 'useremail': clean_item(emailobj['From']), + "objid": uid, + "comment": get_email_body(emailobj), + "useremail": clean_item(emailobj["From"]), } - url = _config.get('APP_URL') + url = _config.get("APP_URL") - if url.endswith('/'): + if url.endswith("/"): url = url[:-1] - url = '%s/pv/ticket/comment/' % url - self.log('Calling URL: %s' % url) + url = "%s/pv/ticket/comment/" % url + self.log("Calling URL: %s" % url) req = requests.put(url, data=data) if req.status_code == 200: - self.log('Comment added') + self.log("Comment added") return Milter.ACCEPT - self.log('Could not add the comment to ticket to pagure') + self.log("Could not add the comment to ticket to pagure") self.log(req.text) return Milter.CONTINUE def handle_request_email(self, emailobj, msg_id): - ''' Add the email as a comment on a request. ''' - uid = msg_id.split('-pull-request-')[-1].split('@')[0] + """ Add the email as a comment on a request. """ + uid = msg_id.split("-pull-request-")[-1].split("@")[0] parent_id = None - if '-' in uid: - uid, parent_id = uid.rsplit('-', 1) - if '/' in uid: - uid = uid.split('/')[0] - self.log('uid %s' % uid) - self.log('parent_id %s' % parent_id) + if "-" in uid: + uid, parent_id = uid.rsplit("-", 1) + if "/" in uid: + uid = uid.split("/")[0] + self.log("uid %s" % uid) + self.log("parent_id %s" % parent_id) data = { - 'objid': uid, - 'comment': get_email_body(emailobj), - 'useremail': clean_item(emailobj['From']), + "objid": uid, + "comment": get_email_body(emailobj), + "useremail": clean_item(emailobj["From"]), } - url = _config.get('APP_URL') + url = _config.get("APP_URL") - if url.endswith('/'): + if url.endswith("/"): url = url[:-1] - url = '%s/pv/pull-request/comment/' % url - self.log('Calling URL: %s' % url) + url = "%s/pv/pull-request/comment/" % url + self.log("Calling URL: %s" % url) req = requests.put(url, data=data) if req.status_code == 200: - self.log('Comment added on PR') + self.log("Comment added on PR") return Milter.ACCEPT - self.log('Could not add the comment to PR to pagure') + self.log("Could not add the comment to PR to pagure") self.log(req.text) return Milter.CONTINUE @@ -270,11 +272,13 @@ def background(): if not t: break msg, id, ts = t - print("%s [%d]" % (time.strftime( - '%Y%b%d %H:%M:%S', time.localtime(ts)), id)) + print( + "%s [%d]" + % (time.strftime("%Y%b%d %H:%M:%S", time.localtime(ts)), id) + ) # 2005Oct13 02:34:11 [1] msg1 msg2 msg3 ... for i in msg: - print(i,) + print(i) print @@ -285,12 +289,12 @@ def main(): timeout = 600 # Register to have the Milter factory create instances of your class: Milter.factory = PagureMilter - print("%s pagure milter startup" % time.strftime('%Y%b%d %H:%M:%S')) + print("%s pagure milter startup" % time.strftime("%Y%b%d %H:%M:%S")) sys.stdout.flush() Milter.runmilter("paguremilter", socketname, timeout) logq.put(None) bt.join() - print("%s pagure milter shutdown" % time.strftime('%Y%b%d %H:%M:%S')) + print("%s pagure milter shutdown" % time.strftime("%Y%b%d %H:%M:%S")) if __name__ == "__main__": diff --git a/rundocserver.py b/rundocserver.py index f43d4de..3890d2e 100755 --- a/rundocserver.py +++ b/rundocserver.py @@ -3,7 +3,7 @@ from __future__ import unicode_literals, absolute_import # These two lines are needed to run on EL6 -__requires__ = ['jinja2 >= 2.4'] +__requires__ = ["jinja2 >= 2.4"] import pkg_resources import argparse @@ -11,42 +11,56 @@ import sys import os -parser = argparse.ArgumentParser( - description='Run the Pagure doc server') +parser = argparse.ArgumentParser(description="Run the Pagure doc server") parser.add_argument( - '--config', '-c', dest='config', - help='Configuration file to use for the pagure doc server.') + "--config", + "-c", + dest="config", + help="Configuration file to use for the pagure doc server.", +) parser.add_argument( - '--debug', dest='debug', action='store_true', + "--debug", + dest="debug", + action="store_true", default=False, - help='Expand the level of data returned.') + help="Expand the level of data returned.", +) parser.add_argument( - '--profile', dest='profile', action='store_true', + "--profile", + dest="profile", + action="store_true", default=False, - help='Profile the doc server.') + help="Profile the doc server.", +) parser.add_argument( - '--port', '-p', default=5001, - help='Port for the Pagure doc server to run on.') + "--port", + "-p", + default=5001, + help="Port for the Pagure doc server to run on.", +) parser.add_argument( - '--host', default="127.0.0.1", - help='Hostname to listen on. When set to 0.0.0.0 the server is ' - 'available externally. Defaults to 127.0.0.1 making the it only ' - 'visible on localhost') + "--host", + default="127.0.0.1", + help="Hostname to listen on. When set to 0.0.0.0 the server is " + "available externally. Defaults to 127.0.0.1 making the it only " + "visible on localhost", +) args = parser.parse_args() if args.config: config = args.config - if not config.startswith('/'): + if not config.startswith("/"): here = os.path.join(os.path.dirname(os.path.abspath(__file__))) config = os.path.join(here, config) - os.environ['PAGURE_CONFIG'] = config + os.environ["PAGURE_CONFIG"] = config from pagure.docs_server import APP if args.profile: from werkzeug.contrib.profiler import ProfilerMiddleware - APP.config['PROFILE'] = True + + APP.config["PROFILE"] = True APP.wsgi_app = ProfilerMiddleware(APP.wsgi_app, restrictions=[30]) APP.debug = True diff --git a/runserver.py b/runserver.py index b266f9d..e7a5278 100755 --- a/runserver.py +++ b/runserver.py @@ -7,56 +7,69 @@ import sys import os -parser = argparse.ArgumentParser( - description='Run the Pagure app') +parser = argparse.ArgumentParser(description="Run the Pagure app") parser.add_argument( - '--config', '-c', dest='config', - help='Configuration file to use for pagure.') + "--config", + "-c", + dest="config", + help="Configuration file to use for pagure.", +) parser.add_argument( - '--plugins', dest='plugins', - help='Configuration file for pagure plugin.') + "--plugins", dest="plugins", help="Configuration file for pagure plugin." +) parser.add_argument( - '--debug', dest='debug', action='store_true', + "--debug", + dest="debug", + action="store_true", default=False, - help='Expand the level of data returned.') + help="Expand the level of data returned.", +) parser.add_argument( - '--profile', dest='profile', action='store_true', + "--profile", + dest="profile", + action="store_true", default=False, - help='Profile Pagure.') + help="Profile Pagure.", +) parser.add_argument( - '--perf-verbose', dest='perfverbose', action='store_true', + "--perf-verbose", + dest="perfverbose", + action="store_true", default=False, - help='Enable per-request printing of performance statistics.') + help="Enable per-request printing of performance statistics.", +) parser.add_argument( - '--port', '-p', default=5000, - help='Port for the Pagure to run on.') + "--port", "-p", default=5000, help="Port for the Pagure to run on." +) parser.add_argument( - '--no-debug', action='store_true', - help='Disable debugging') + "--no-debug", action="store_true", help="Disable debugging" +) parser.add_argument( - '--host', default="127.0.0.1", - help='Hostname to listen on. When set to 0.0.0.0 the server is available ' - 'externally. Defaults to 127.0.0.1 making the it only visible on localhost') + "--host", + default="127.0.0.1", + help="Hostname to listen on. When set to 0.0.0.0 the server is available " + "externally. Defaults to 127.0.0.1 making the it only visible on localhost", +) args = parser.parse_args() if args.config: config = args.config - if not config.startswith('/'): + if not config.startswith("/"): here = os.path.join(os.path.dirname(os.path.abspath(__file__))) config = os.path.join(here, config) - os.environ['PAGURE_CONFIG'] = config + os.environ["PAGURE_CONFIG"] = config if args.plugins: config = args.plugins - if not config.startswith('/'): + if not config.startswith("/"): here = os.path.join(os.path.dirname(os.path.abspath(__file__))) config = os.path.join(here, config) - os.environ['PAGURE_PLUGIN'] = config + os.environ["PAGURE_PLUGIN"] = config if args.perfverbose: - os.environ['PAGURE_PERFREPO'] = 'true' - os.environ['PAGURE_PERFREPO_VERBOSE'] = 'true' + os.environ["PAGURE_PERFREPO"] = "true" + os.environ["PAGURE_PERFREPO_VERBOSE"] = "true" from pagure.flask_app import create_app @@ -64,7 +77,8 @@ APP = create_app() if args.profile: from werkzeug.contrib.profiler import ProfilerMiddleware - APP.config['PROFILE'] = True + + APP.config["PROFILE"] = True APP.wsgi_app = ProfilerMiddleware(APP.wsgi_app, restrictions=[30]) APP.debug = not args.no_debug diff --git a/runtests.py b/runtests.py index c2ff063..50ef9a4 100755 --- a/runtests.py +++ b/runtests.py @@ -28,12 +28,13 @@ PRINTLOCK = None RUNNING = [] FAILED = [] NUMPROCS = multiprocessing.cpu_count() - 1 -if os.environ.get('BUILD_ID'): +if os.environ.get("BUILD_ID"): NUMPROCS = multiprocessing.cpu_count() HERE = os.path.join(os.path.dirname(os.path.abspath(__file__))) LOG = logging.getLogger(__name__) + def setup_parser(): """ Set up the command line arguments supported and return the arguments """ @@ -144,7 +145,10 @@ def setup_parser(): help="Show the error files using `less`", ) parser_run.add_argument( - "-n", default=None, nargs="?", type=int, + "-n", + default=None, + nargs="?", + type=int, help="Number of failed test to show", ) parser_run.set_defaults(func=do_list) @@ -152,7 +156,8 @@ def setup_parser(): # SHOW-COVERAGE parser_run = subparsers.add_parser( "show-coverage", - help="Shows the coverage report from the data in the results folder") + help="Shows the coverage report from the data in the results folder", + ) parser_run.add_argument( "--debug", dest="debug", @@ -221,9 +226,9 @@ def remove_running(suite, failed): with PRINTLOCK: RUNNING.remove(suite) clean_line() - status = 'passed' + status = "passed" if failed: - status = 'FAILED' + status = "FAILED" print("Test suite %s: %s" % (status, suite)) print_running() @@ -255,15 +260,21 @@ class WorkerThread(threading.Thread): cmd.append("--with-cover") env = os.environ.copy() - env.update({ - "PAGURE_CONFIG": "../tests/test_config", - "COVERAGE_FILE": os.path.join( - self.results, "%s.coverage" % self.name - ), - "LANG": "en_US.UTF-8", - }) + env.update( + { + "PAGURE_CONFIG": "../tests/test_config", + "COVERAGE_FILE": os.path.join( + self.results, "%s.coverage" % self.name + ), + "LANG": "en_US.UTF-8", + } + ) proc = subprocess.Popen( - cmd, cwd=".", stdout=resfile, stderr=subprocess.STDOUT, env=env + cmd, + cwd=".", + stdout=resfile, + stderr=subprocess.STDOUT, + env=env, ) res = proc.wait() if res == 0: @@ -299,9 +310,10 @@ def do_run(args): except: print( "Could not delete the %s directory, it will be " - "wiped clean" % args.results) + "wiped clean" % args.results + ) for content in os.listdir(args.results): - os.remove(content) + os.remove(content) else: os.mkdir(args.results) @@ -313,7 +325,9 @@ def do_run(args): here = os.path.join(os.path.dirname(os.path.abspath(__file__))) failed_tests_fullpath = os.path.join(here, args.failed_tests) if not os.path.exists(failed_tests_fullpath): - print("Could not find the specified file:%s" % failed_tests_fullpath) + print( + "Could not find the specified file:%s" % failed_tests_fullpath + ) return 1 print("Loading failed tests") try: @@ -346,12 +360,15 @@ def do_rerun(args): return 1 if not os.path.exists(args.results): - print("Could not find an existing results folder at: %s" % args.results) + print( + "Could not find an existing results folder at: %s" % args.results + ) return 1 if not os.path.exists(os.path.join(args.results, "newfailed")): print( - "Could not find an failed tests in the results folder at: %s" % args.results + "Could not find an failed tests in the results folder at: %s" + % args.results ) return 1 @@ -378,9 +395,9 @@ def do_rerun(args): def _get_pyvers(args): pyvers = [2, 3] if args.py2: - pyvers = [2,] + pyvers = [2] elif args.py3: - pyvers = [3,] + pyvers = [3] un_versioned = False try: @@ -433,23 +450,45 @@ def _run_test_suites(args, suites): if len(pyvers) == 1: if pyvers[0] == 2: - subprocess.check_call([ - "sed", "-i", "-e", "s|python|python2|", - "pagure/hooks/files/hookrunner" - ]) - subprocess.check_call([ - "sed", "-i", "-e", "s|\['alembic',|\['alembic-2',|", - "tests/test_alembic.py" - ]) + subprocess.check_call( + [ + "sed", + "-i", + "-e", + "s|python|python2|", + "pagure/hooks/files/hookrunner", + ] + ) + subprocess.check_call( + [ + "sed", + "-i", + "-e", + "s|\['alembic',|\['alembic-2',|", + "tests/test_alembic.py", + ] + ) elif pyvers[0] == 3: - subprocess.check_call([ - "sed", "-i", "-e", "s|python|python3|", - "pagure/hooks/files/hookrunner" - ], cwd=HERE) - subprocess.check_call([ - "sed", "-i", "-e", "s|\['alembic',|\['alembic-3',|", - "tests/test_alembic.py" - ], cwd=HERE) + subprocess.check_call( + [ + "sed", + "-i", + "-e", + "s|python|python3|", + "pagure/hooks/files/hookrunner", + ], + cwd=HERE, + ) + subprocess.check_call( + [ + "sed", + "-i", + "-e", + "s|\['alembic',|\['alembic-3',|", + "tests/test_alembic.py", + ], + cwd=HERE, + ) for suite in suites: for pyver in pyvers: @@ -472,12 +511,14 @@ def _run_test_suites(args, suites): print() print("All work done") - subprocess.check_call([ - "git", - "checkout", - "pagure/hooks/files/hookrunner", - "tests/test_alembic.py" - ]) + subprocess.check_call( + [ + "git", + "checkout", + "pagure/hooks/files/hookrunner", + "tests/test_alembic.py", + ] + ) # Gather results print() @@ -527,12 +568,15 @@ def do_list(args): return 1 if not os.path.exists(args.results): - print("Could not find an existing results folder at: %s" % args.results) + print( + "Could not find an existing results folder at: %s" % args.results + ) return 1 if not os.path.exists(os.path.join(args.results, "newfailed")): print( - "Could not find an failed tests in the results folder at: %s" % args.results + "Could not find an failed tests in the results folder at: %s" + % args.results ) return 1 @@ -553,7 +597,7 @@ def do_list(args): failed_tests = len(suites) if args.n: - suites = suites[:args.n] + suites = suites[: args.n] print("- " + "\n- ".join(suites)) print("Total: %s test failed" % failed_tests) @@ -572,7 +616,9 @@ def do_show_coverage(args): for pyver in pyvers: coverfiles = [] for fname in os.listdir(args.results): - if fname.endswith(".coverage") and fname.startswith("py%s-" % pyver): + if fname.endswith(".coverage") and fname.startswith( + "py%s-" % pyver + ): coverfiles.append(os.path.join(args.results, fname)) cover = None @@ -583,7 +629,9 @@ def do_show_coverage(args): else: cover = COVER_PY - env = {"COVERAGE_FILE": os.path.join(args.results, "combined.coverage")} + env = { + "COVERAGE_FILE": os.path.join(args.results, "combined.coverage") + } cmd = [cover, "combine"] + coverfiles subprocess.check_call(cmd, env=env) print() diff --git a/runworker.py b/runworker.py index 320421c..4fdddf0 100755 --- a/runworker.py +++ b/runworker.py @@ -8,40 +8,46 @@ import os import subprocess -parser = argparse.ArgumentParser( - description='Run the Pagure worker') +parser = argparse.ArgumentParser(description="Run the Pagure worker") parser.add_argument( - '--config', '-c', dest='config', - help='Configuration file to use for pagure.') + "--config", + "-c", + dest="config", + help="Configuration file to use for pagure.", +) parser.add_argument( - '--debug', dest='debug', action='store_true', + "--debug", + dest="debug", + action="store_true", default=False, - help='Expand the level of data returned.') + help="Expand the level of data returned.", +) parser.add_argument( - '--noinfo', dest='noinfo', action='store_true', + "--noinfo", + dest="noinfo", + action="store_true", default=False, - help='Reduce the log level.') + help="Reduce the log level.", +) args = parser.parse_args() env = {} if args.config: config = args.config - if not config.startswith('/'): + if not config.startswith("/"): here = os.path.join(os.path.dirname(os.path.abspath(__file__))) config = os.path.join(here, config) - env['PAGURE_CONFIG'] = config + env["PAGURE_CONFIG"] = config -cmd = [ - sys.executable, '-m', 'celery', 'worker', '-A', 'pagure.lib.tasks' -] +cmd = [sys.executable, "-m", "celery", "worker", "-A", "pagure.lib.tasks"] if args.debug: - cmd.append('--loglevel=debug') + cmd.append("--loglevel=debug") elif args.noinfo: pass else: - cmd.append('--loglevel=info') + cmd.append("--loglevel=info") subp = subprocess.Popen(cmd, env=env or None) subp.wait() diff --git a/setup.py b/setup.py index 7f24828..c7d9aa6 100644 --- a/setup.py +++ b/setup.py @@ -10,17 +10,19 @@ import re from setuptools import setup -pagurefile = os.path.join(os.path.dirname(__file__), 'pagure', '__init__.py') +pagurefile = os.path.join(os.path.dirname(__file__), "pagure", "__init__.py") # Thanks to SQLAlchemy: # https://github.com/zzzeek/sqlalchemy/blob/master/setup.py#L104 with open(pagurefile) as stream: - __version__ = re.compile( - r".*__version__ = \"(.*?)\"", re.S - ).match(stream.read()).group(1) + __version__ = ( + re.compile(r".*__version__ = \"(.*?)\"", re.S) + .match(stream.read()) + .group(1) + ) -def get_requirements(requirements_file='requirements.txt'): +def get_requirements(requirements_file="requirements.txt"): """Get the contents of a file listing the requirements. :arg requirements_file: path to a requirements file @@ -32,24 +34,24 @@ def get_requirements(requirements_file='requirements.txt'): with open(requirements_file) as f: return [ - line.rstrip().split('#')[0] + line.rstrip().split("#")[0] for line in f.readlines() - if not line.startswith('#') + if not line.startswith("#") ] setup( - name='pagure', - description='A light-weight git-centered forge based on pygit2.', + name="pagure", + description="A light-weight git-centered forge based on pygit2.", version=__version__, - author='Pierre-Yves Chibon', - author_email='pingou@pingoured.fr', - maintainer='Pierre-Yves Chibon', - maintainer_email='pingou@pingoured.fr', - license='GPLv2+', - download_url='https://pagure.io/releases/pagure/', - url='https://pagure.io/pagure/', - packages=['pagure'], + author="Pierre-Yves Chibon", + author_email="pingou@pingoured.fr", + maintainer="Pierre-Yves Chibon", + maintainer_email="pingou@pingoured.fr", + license="GPLv2+", + download_url="https://pagure.io/releases/pagure/", + url="https://pagure.io/pagure/", + packages=["pagure"], include_package_data=True, install_requires=get_requirements(), entry_points=""" @@ -63,17 +65,17 @@ setup( pagure = pagure.lib.git_auth:PagureGitAuth """, classifiers=[ - 'License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)', - 'Operating System :: POSIX :: Linux', - 'Programming Language :: Python :: 2', - 'Programming Language :: Python :: 2.7', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.4', - 'Programming Language :: Python :: 3.5', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Topic :: Internet :: WWW/HTTP :: WSGI :: Application', - 'Topic :: Software Development :: Bug Tracking', - 'Topic :: Software Development :: Version Control', - ] + "License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)", + "Operating System :: POSIX :: Linux", + "Programming Language :: Python :: 2", + "Programming Language :: Python :: 2.7", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.4", + "Programming Language :: Python :: 3.5", + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", + "Topic :: Internet :: WWW/HTTP :: WSGI :: Application", + "Topic :: Software Development :: Bug Tracking", + "Topic :: Software Development :: Version Control", + ], ) diff --git a/tests/__init__.py b/tests/__init__.py index 2999dbb..149ff15 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -23,6 +23,7 @@ import tempfile import time import unittest from io import open, StringIO + logging.basicConfig(stream=sys.stderr) from bs4 import BeautifulSoup @@ -46,10 +47,11 @@ from sqlalchemy.orm import scoped_session if six.PY2: # Always enable performance counting for tests - os.environ['PAGURE_PERFREPO'] = 'true' + os.environ["PAGURE_PERFREPO"] = "true" -sys.path.insert(0, os.path.join(os.path.dirname( - os.path.abspath(__file__)), '..')) +sys.path.insert( + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") +) import pagure import pagure.api @@ -67,12 +69,12 @@ HERE = os.path.join(os.path.dirname(os.path.abspath(__file__))) LOG = logging.getLogger(__name__) LOG.setLevel(logging.INFO) -PAGLOG = logging.getLogger('pagure') +PAGLOG = logging.getLogger("pagure") PAGLOG.setLevel(logging.CRITICAL) PAGLOG.handlers = [] -if 'PYTHONPATH' not in os.environ: - os.environ['PYTHONPATH'] = os.path.normpath(os.path.join(HERE, '../')) +if "PYTHONPATH" not in os.environ: + os.environ["PYTHONPATH"] = os.path.normpath(os.path.join(HERE, "../")) CONFIG_TEMPLATE = """ GIT_FOLDER = '%(path)s/repos' @@ -119,10 +121,12 @@ REPOSPANNER_REGIONS = { # what the task actually does. -LOG.info('BUILD_ID: %s', os.environ.get('BUILD_ID')) +LOG.info("BUILD_ID: %s", os.environ.get("BUILD_ID")) WAIT_REGEX = re.compile(r"""var _url = '(\/wait\/[a-z0-9-]+\??.*)'""") + + def get_wait_target(html): """ This parses the window.location out of the HTML for the wait page. """ found = WAIT_REGEX.findall(html) @@ -133,23 +137,23 @@ def get_wait_target(html): def get_post_target(html): """ This parses the wait page form to get the POST url. """ - soup = BeautifulSoup(html, 'html.parser') - form = soup.find(id='waitform') + soup = BeautifulSoup(html, "html.parser") + form = soup.find(id="waitform") if not form: raise Exception("Not able to get the POST url in %s" % html) - return form.get('action') + return form.get("action") def get_post_args(html): """ This parses the wait page for the hidden arguments of the form. """ - soup = BeautifulSoup(html, 'html.parser') + soup = BeautifulSoup(html, "html.parser") output = {} - inputs = soup.find_all('input') + inputs = soup.find_all("input") if not inputs: raise Exception("Not able to get the POST arguments in %s" % html) for inp in inputs: - if inp.get('type') == 'hidden': - output[inp.get('name')] = inp.get('value') + if inp.get("type") == "hidden": + output[inp.get("name")] = inp.get("value") return output @@ -168,11 +172,12 @@ def create_maybe_waiter(method, getter): if 'id="waitform"' in result_text: form_url = get_post_target(result_text) form_args = get_post_args(result_text) - form_args['csrf_token'] = result_text.split( - 'name="csrf_token" type="hidden" value="')[1].split('">')[0] + form_args["csrf_token"] = result_text.split( + 'name="csrf_token" type="hidden" value="' + )[1].split('">')[0] count = 0 - while 'We are waiting for your task to finish.' in result_text: + while "We are waiting for your task to finish." in result_text: # Resolve wait page target_url = get_wait_target(result_text) if count > 10: @@ -185,11 +190,12 @@ def create_maybe_waiter(method, getter): except UnicodeDecodeError: return result if count > 50: - raise Exception('Had to wait too long') + raise Exception("Had to wait too long") else: if form_url and form_args: return method(form_url, data=form_args, follow_redirects=True) return result + return maybe_waiter @@ -201,21 +207,24 @@ def user_set(APP, user, keep_get_user=False): # flask.ext.fas_openid.FAS which otherwise kills our effort to set a # flask.g.fas_user. from flask import appcontext_pushed, g + keep = [] for meth in APP.before_request_funcs[None]: - if 'flask_fas_openid.FAS' in str(meth): + if "flask_fas_openid.FAS" in str(meth): continue keep.append(meth) APP.before_request_funcs[None] = keep def handler(sender, **kwargs): g.fas_user = user - g.fas_session_id = b'123' + g.fas_session_id = b"123" g.authenticated = True + old_get_user = pagure.flask_app._get_user if not keep_get_user: pagure.flask_app._get_user = mock.MagicMock( - return_value=pagure.lib.model.User()) + return_value=pagure.lib.model.User() + ) with appcontext_pushed.connected_to(handler, APP): yield @@ -224,7 +233,7 @@ def user_set(APP, user, keep_get_user=False): tests_state = { - "path": tempfile.mkdtemp(prefix='pagure-tests-'), + "path": tempfile.mkdtemp(prefix="pagure-tests-"), "broker": None, "broker_client": None, "results": {}, @@ -234,31 +243,25 @@ tests_state = { def _populate_db(session): # Create a couple of users item = pagure.lib.model.User( - user='pingou', - fullname='PY C', - password=b'foo', - default_email='bar@pingou.com', + user="pingou", + fullname="PY C", + password=b"foo", + default_email="bar@pingou.com", ) session.add(item) - item = pagure.lib.model.UserEmail( - user_id=1, - email='bar@pingou.com') + item = pagure.lib.model.UserEmail(user_id=1, email="bar@pingou.com") session.add(item) - item = pagure.lib.model.UserEmail( - user_id=1, - email='foo@pingou.com') + item = pagure.lib.model.UserEmail(user_id=1, email="foo@pingou.com") session.add(item) item = pagure.lib.model.User( - user='foo', - fullname='foo bar', - password=b'foo', - default_email='foo@bar.com', + user="foo", + fullname="foo bar", + password=b"foo", + default_email="foo@bar.com", ) session.add(item) - item = pagure.lib.model.UserEmail( - user_id=2, - email='foo@bar.com') + item = pagure.lib.model.UserEmail(user_id=2, email="foo@bar.com") session.add(item) session.commit() @@ -276,25 +279,36 @@ def setUp(): # file only once and then we populate it and empty it for every test case # (as opposed to creating DB file for every test case). session = pagure.lib.model.create_tables( - 'sqlite:///%s/db.sqlite' % tests_state["path"], - acls=pagure_config.get('ACLS', {}), + "sqlite:///%s/db.sqlite" % tests_state["path"], + acls=pagure_config.get("ACLS", {}), ) tests_state["db_session"] = session # Create a broker - broker_url = os.path.join(tests_state["path"], 'broker') + broker_url = os.path.join(tests_state["path"], "broker") tests_state["broker"] = broker = subprocess.Popen( - ['/usr/bin/redis-server', '--unixsocket', broker_url, '--port', - '0', '--loglevel', 'warning', '--logfile', '/dev/null'], - stdout=None, stderr=None) + [ + "/usr/bin/redis-server", + "--unixsocket", + broker_url, + "--port", + "0", + "--loglevel", + "warning", + "--logfile", + "/dev/null", + ], + stdout=None, + stderr=None, + ) broker.poll() if broker.returncode is not None: - raise Exception('Broker failed to start') + raise Exception("Broker failed to start") tests_state["broker_client"] = redis.Redis(unix_socket_path=broker_url) # Store the EagerResults to be able to retrieve them later - tests_state["eg_patcher"] = mock.patch('celery.app.task.EagerResult') + tests_state["eg_patcher"] = mock.patch("celery.app.task.EagerResult") eg_mock = tests_state["eg_patcher"].start() eg_mock.side_effect = store_eager_results @@ -316,8 +330,8 @@ class SimplePagureTest(unittest.TestCase): populate_db = True config_values = {} - @mock.patch('pagure.lib.notify.fedmsg_publish', mock.MagicMock()) - def __init__(self, method_name='runTest'): + @mock.patch("pagure.lib.notify.fedmsg_publish", mock.MagicMock()) + def __init__(self, method_name="runTest"): """ Constructor. """ unittest.TestCase.__init__(self, method_name) self.session = None @@ -330,15 +344,21 @@ class SimplePagureTest(unittest.TestCase): num_walks = 0 num_steps = 0 for reqstat in perfrepo.REQUESTS: - for walk in reqstat['walks'].values(): + for walk in reqstat["walks"].values(): num_walks += 1 - num_steps += walk['steps'] - self.assertLessEqual(num_walks, max_walks, - '%s git repo walks performed, at most %s allowed' - % (num_walks, max_walks)) - self.assertLessEqual(num_steps, max_steps, - '%s git repo steps performed, at most %s allowed' - % (num_steps, max_steps)) + num_steps += walk["steps"] + self.assertLessEqual( + num_walks, + max_walks, + "%s git repo walks performed, at most %s allowed" + % (num_walks, max_walks), + ) + self.assertLessEqual( + num_steps, + max_steps, + "%s git repo steps performed, at most %s allowed" + % (num_steps, max_steps), + ) def perfReset(self): """ Reset perfrepo stats. """ @@ -354,17 +374,17 @@ class SimplePagureTest(unittest.TestCase): # redis instances not exit, we also might accidentally use the # old database connection. # @pingou, don't delete this again... :) - raise Exception('Previous test failed!') + raise Exception("Previous test failed!") self.perfReset() - self.path = tempfile.mkdtemp(prefix='pagure-tests-path-') + self.path = tempfile.mkdtemp(prefix="pagure-tests-path-") - LOG.debug('Testdir: %s', self.path) - for folder in ['repos', 'forks', 'releases', 'remotes', 'attachments']: + LOG.debug("Testdir: %s", self.path) + for folder in ["repos", "forks", "releases", "remotes", "attachments"]: os.mkdir(os.path.join(self.path, folder)) - if hasattr(pagure.lib.query, 'REDIS') and pagure.lib.query.REDIS: + if hasattr(pagure.lib.query, "REDIS") and pagure.lib.query.REDIS: pagure.lib.query.REDIS.connection_pool.disconnect() pagure.lib.query.REDIS = None @@ -373,27 +393,26 @@ class SimplePagureTest(unittest.TestCase): # Write a config file config_values = { - 'path': self.path, - 'dburl': self.dbpath, - 'enable_docs': True, - 'docs_folder': '%s/repos/docs' % self.path, - 'enable_tickets': True, - 'tickets_folder': '%s/repos/tickets' % self.path, - 'global_path': tests_state["path"], - 'authbackend': 'gitolite3', - - 'repobridge_binary': '/usr/libexec/repobridge', - 'repospanner_gitport': str(8443 + sys.version_info.major), - 'repospanner_new_repo': 'None', - 'repospanner_admin_override': 'False', - 'repospanner_new_fork': 'True', - 'repospanner_admin_migration': 'False', + "path": self.path, + "dburl": self.dbpath, + "enable_docs": True, + "docs_folder": "%s/repos/docs" % self.path, + "enable_tickets": True, + "tickets_folder": "%s/repos/tickets" % self.path, + "global_path": tests_state["path"], + "authbackend": "gitolite3", + "repobridge_binary": "/usr/libexec/repobridge", + "repospanner_gitport": str(8443 + sys.version_info.major), + "repospanner_new_repo": "None", + "repospanner_admin_override": "False", + "repospanner_new_fork": "True", + "repospanner_admin_migration": "False", } config_values.update(self.config_values) self.config_values = config_values - config_path = os.path.join(self.path, 'config') + config_path = os.path.join(self.path, "config") if not os.path.exists(config_path): - with open(config_path, 'w') as f: + with open(config_path, "w") as f: f.write(CONFIG_TEMPLATE % self.config_values) os.environ["PAGURE_CONFIG"] = config_path pagure_config.update(reload_config()) @@ -402,10 +421,10 @@ class SimplePagureTest(unittest.TestCase): imp.reload(pagure.lib.tasks_mirror) imp.reload(pagure.lib.tasks_services) - self._app = pagure.flask_app.create_app({'DB_URL': self.dbpath}) + self._app = pagure.flask_app.create_app({"DB_URL": self.dbpath}) self.app = self._app.test_client() - self.gr_patcher = mock.patch('pagure.lib.tasks.get_result') + self.gr_patcher = mock.patch("pagure.lib.tasks.get_result") gr_mock = self.gr_patcher.start() gr_mock.side_effect = lambda tid: tests_state["results"][tid] @@ -435,23 +454,26 @@ class SimplePagureTest(unittest.TestCase): return doc or None def _prepare_db(self): - self.dbpath = 'sqlite:///%s' % os.path.join( - tests_state["path"], 'db.sqlite') + self.dbpath = "sqlite:///%s" % os.path.join( + tests_state["path"], "db.sqlite" + ) self.session = tests_state["db_session"] pagure.lib.model.create_default_status( - self.session, acls=pagure_config.get('ACLS', {})) + self.session, acls=pagure_config.get("ACLS", {}) + ) if self.populate_db: _populate_db(self.session) def _clear_database(self): tables = reversed(pagure.lib.model_base.BASE.metadata.sorted_tables) - if self.dbpath.startswith('postgresql'): - self.session.execute("TRUNCATE %s CASCADE" % ", ".join( - [t.name for t in tables])) - elif self.dbpath.startswith('sqlite'): + if self.dbpath.startswith("postgresql"): + self.session.execute( + "TRUNCATE %s CASCADE" % ", ".join([t.name for t in tables]) + ) + elif self.dbpath.startswith("sqlite"): for table in tables: self.session.execute("DELETE FROM %s" % table.name) - elif self.dbpath.startswith('mysql'): + elif self.dbpath.startswith("mysql"): self.session.execute("SET FOREIGN_KEY_CHECKS = 0") for table in tables: self.session.execute("TRUNCATE %s" % table.name) @@ -460,22 +482,28 @@ class SimplePagureTest(unittest.TestCase): def set_auth_status(self, value): """ Set the return value for the test auth """ - with open(os.path.join(self.path, 'testauth_status.json'), 'w') as statusfile: + with open( + os.path.join(self.path, "testauth_status.json"), "w" + ) as statusfile: statusfile.write(six.u(json.dumps(value))) - def get_csrf(self, url='/new', output=None): + def get_csrf(self, url="/new", output=None): """Retrieve a CSRF token from given URL.""" if output is None: output = self.app.get(url) self.assertEqual(output.status_code, 200) - return output.get_data(as_text=True).split( - 'name="csrf_token" type="hidden" value="')[1].split('">')[0] + return ( + output.get_data(as_text=True) + .split('name="csrf_token" type="hidden" value="')[1] + .split('">')[0] + ) def get_wtforms_version(self): """Returns the wtforms version as a tuple.""" import wtforms - wtforms_v = wtforms.__version__.split('.') + + wtforms_v = wtforms.__version__.split(".") for idx, val in enumerate(wtforms_v): try: val = int(val) @@ -498,7 +526,7 @@ class SimplePagureTest(unittest.TestCase): class Modeltests(SimplePagureTest): """ Model tests. """ - def setUp(self): # pylint: disable=invalid-name + def setUp(self): # pylint: disable=invalid-name """ Set up the environnment, ran before every tests. """ # Clean up test performance info super(Modeltests, self).setUp() @@ -508,7 +536,7 @@ class Modeltests(SimplePagureTest): # Refresh the DB session self.session = pagure.lib.query.create_session(self.dbpath) - def tearDown(self): # pylint: disable=invalid-name + def tearDown(self): # pylint: disable=invalid-name """ Remove the test.db database if there is one. """ tests_state["broker_client"].flushall() super(Modeltests, self).tearDown() @@ -520,26 +548,21 @@ class Modeltests(SimplePagureTest): project would be, with hooks and all setup. """ - headers = {'Authorization': 'token aaabbbcccddd'} - data = { - 'name': projectname, - 'description': 'A test repo', - } + headers = {"Authorization": "token aaabbbcccddd"} + data = {"name": projectname, "description": "A test repo"} if extra: data.update(extra) # Valid request - output = self.app.post( - '/api/0/new/', data=data, headers=headers) + output = self.app.post("/api/0/new/", data=data, headers=headers) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - {'message': 'Project "%s" created' % projectname} + data, {"message": 'Project "%s" created' % projectname} ) -class FakeGroup(object): # pylint: disable=too-few-public-methods +class FakeGroup(object): # pylint: disable=too-few-public-methods """ Fake object used to make the FakeUser object closer to the expectations. """ @@ -549,13 +572,15 @@ class FakeGroup(object): # pylint: disable=too-few-public-methods :arg name: the name given to the name attribute of this object. """ self.name = name - self.group_type = 'cla' + self.group_type = "cla" -class FakeUser(object): # pylint: disable=too-few-public-methods +class FakeUser(object): # pylint: disable=too-few-public-methods """ Fake user used to test the fedocallib library. """ - def __init__(self, groups=None, username='username', cla_done=True, id=None): + def __init__( + self, groups=None, username="username", cla_done=True, id=None + ): """ Constructor. :arg groups: list of the groups in which this fake user is supposed to be. @@ -567,15 +592,15 @@ class FakeUser(object): # pylint: disable=too-few-public-methods self.user = username self.username = username self.name = username - self.email = 'foo@bar.com' - self.default_email = 'foo@bar.com' + self.email = "foo@bar.com" + self.default_email = "foo@bar.com" self.approved_memberships = [ - FakeGroup('packager'), - FakeGroup('design-team') + FakeGroup("packager"), + FakeGroup("design-team"), ] self.dic = {} - self.dic['timezone'] = 'Europe/Paris' + self.dic["timezone"] = "Europe/Paris" self.login_time = datetime.utcnow() self.cla_done = cla_done @@ -584,51 +609,51 @@ class FakeUser(object): # pylint: disable=too-few-public-methods def create_locks(session, project): - for ltype in ('WORKER', 'WORKER_TICKET', 'WORKER_REQUEST'): + for ltype in ("WORKER", "WORKER_TICKET", "WORKER_REQUEST"): lock = pagure.lib.model.ProjectLock( - project_id=project.id, - lock_type=ltype) + project_id=project.id, lock_type=ltype + ) session.add(lock) -def create_projects(session, is_fork=False, user_id=1, hook_token_suffix=''): +def create_projects(session, is_fork=False, user_id=1, hook_token_suffix=""): """ Create some projects in the database. """ item = pagure.lib.model.Project( user_id=user_id, # pingou - name='test', + name="test", is_fork=is_fork, parent_id=1 if is_fork else None, - description='test project #1', - hook_token='aaabbbccc' + hook_token_suffix, + description="test project #1", + hook_token="aaabbbccc" + hook_token_suffix, ) - item.close_status = ['Invalid', 'Insufficient data', 'Fixed', 'Duplicate'] + item.close_status = ["Invalid", "Insufficient data", "Fixed", "Duplicate"] session.add(item) session.flush() create_locks(session, item) item = pagure.lib.model.Project( user_id=user_id, # pingou - name='test2', + name="test2", is_fork=is_fork, parent_id=2 if is_fork else None, - description='test project #2', - hook_token='aaabbbddd' + hook_token_suffix, + description="test project #2", + hook_token="aaabbbddd" + hook_token_suffix, ) - item.close_status = ['Invalid', 'Insufficient data', 'Fixed', 'Duplicate'] + item.close_status = ["Invalid", "Insufficient data", "Fixed", "Duplicate"] session.add(item) session.flush() create_locks(session, item) item = pagure.lib.model.Project( user_id=user_id, # pingou - name='test3', + name="test3", is_fork=is_fork, parent_id=3 if is_fork else None, - description='namespaced test project', - hook_token='aaabbbeee' + hook_token_suffix, - namespace='somenamespace', + description="namespaced test project", + hook_token="aaabbbeee" + hook_token_suffix, + namespace="somenamespace", ) - item.close_status = ['Invalid', 'Insufficient data', 'Fixed', 'Duplicate'] + item.close_status = ["Invalid", "Insufficient data", "Fixed", "Duplicate"] session.add(item) session.flush() create_locks(session, item) @@ -638,8 +663,11 @@ def create_projects(session, is_fork=False, user_id=1, hook_token_suffix=''): def create_projects_git(folder, bare=False): """ Create some projects in the database. """ repos = [] - for project in ['test.git', 'test2.git', - os.path.join('somenamespace', 'test3.git')]: + for project in [ + "test.git", + "test2.git", + os.path.join("somenamespace", "test3.git"), + ]: repo_path = os.path.join(folder, project) repos.append(repo_path) if not os.path.exists(repo_path): @@ -651,49 +679,46 @@ def create_projects_git(folder, bare=False): def create_tokens(session, user_id=1, project_id=1): """ Create some tokens for the project in the database. """ item = pagure.lib.model.Token( - id='aaabbbcccddd', + id="aaabbbcccddd", user_id=user_id, project_id=project_id, - expiration=datetime.utcnow() + timedelta(days=30) + expiration=datetime.utcnow() + timedelta(days=30), ) session.add(item) item = pagure.lib.model.Token( - id='foo_token', + id="foo_token", user_id=user_id, project_id=project_id, - expiration=datetime.utcnow() + timedelta(days=30) + expiration=datetime.utcnow() + timedelta(days=30), ) session.add(item) item = pagure.lib.model.Token( - id='expired_token', + id="expired_token", user_id=user_id, project_id=project_id, - expiration=datetime.utcnow() - timedelta(days=1) + expiration=datetime.utcnow() - timedelta(days=1), ) session.add(item) session.commit() -def create_tokens_acl(session, token_id='aaabbbcccddd', acl_name=None): +def create_tokens_acl(session, token_id="aaabbbcccddd", acl_name=None): """ Create some ACLs for the token. If acl_name is not set, the token will have all the ACLs enabled. """ if acl_name is None: - for aclid in range(len(pagure_config['ACLS'])): + for aclid in range(len(pagure_config["ACLS"])): token_acl = pagure.lib.model.TokenAcl( - token_id=token_id, - acl_id=aclid + 1, + token_id=token_id, acl_id=aclid + 1 ) session.add(token_acl) else: - acl = session.query(pagure.lib.model.ACL).filter_by( - name=acl_name).one() - token_acl = pagure.lib.model.TokenAcl( - token_id=token_id, - acl_id=acl.id, + acl = ( + session.query(pagure.lib.model.ACL).filter_by(name=acl_name).one() ) + token_acl = pagure.lib.model.TokenAcl(token_id=token_id, acl_id=acl.id) session.add(token_acl) session.commit() @@ -710,7 +735,7 @@ def _clone_and_top_commits(folder, branch, branch_ref=False): os.makedirs(folder) brepo = pygit2.init_repository(folder, bare=True) - newfolder = tempfile.mkdtemp(prefix='pagure-tests') + newfolder = tempfile.mkdtemp(prefix="pagure-tests") repo = pygit2.clone_repository(folder, newfolder) branch_ref_obj = None @@ -727,7 +752,7 @@ def _clone_and_top_commits(folder, branch, branch_ref=False): if branch_ref_obj: commit = repo[branch_ref_obj.peel().hex] else: - commit = repo.revparse_single('HEAD') + commit = repo.revparse_single("HEAD") except KeyError: pass if commit: @@ -736,33 +761,31 @@ def _clone_and_top_commits(folder, branch, branch_ref=False): return (repo, newfolder, parents) -def add_content_git_repo(folder, branch='master', append=None): +def add_content_git_repo(folder, branch="master", append=None): """ Create some content for the specified git repo. """ repo, newfolder, parents = _clone_and_top_commits(folder, branch) # Create a file in that git repo - filename = os.path.join(newfolder, 'sources') - content = 'foo\n bar' + filename = os.path.join(newfolder, "sources") + content = "foo\n bar" if os.path.exists(filename): - content = 'foo\n bar\nbaz' + content = "foo\n bar\nbaz" if append: content += append - with open(filename, 'w') as stream: + with open(filename, "w") as stream: stream.write(content) - repo.index.add('sources') + repo.index.add("sources") repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") commit = repo.create_commit( - 'refs/heads/%s' % branch, # the name of the reference to update + "refs/heads/%s" % branch, # the name of the reference to update author, committer, - 'Add sources file for testing', + "Add sources file for testing", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit @@ -772,51 +795,50 @@ def add_content_git_repo(folder, branch='master', append=None): if commit: parents = [commit.hex] - subfolder = os.path.join('folder1', 'folder2') + subfolder = os.path.join("folder1", "folder2") if not os.path.exists(os.path.join(newfolder, subfolder)): os.makedirs(os.path.join(newfolder, subfolder)) # Create a file in that git repo - with open(os.path.join(newfolder, subfolder, 'file'), 'w') as stream: - stream.write('foo\n bar\nbaz') - repo.index.add(os.path.join(subfolder, 'file')) - with open(os.path.join(newfolder, subfolder, u'fileŠ'), 'w') as stream: - stream.write('foo\n bar\nbaz') - repo.index.add(os.path.join(subfolder, u'fileŠ')) + with open(os.path.join(newfolder, subfolder, "file"), "w") as stream: + stream.write("foo\n bar\nbaz") + repo.index.add(os.path.join(subfolder, "file")) + with open(os.path.join(newfolder, subfolder, "fileŠ"), "w") as stream: + stream.write("foo\n bar\nbaz") + repo.index.add(os.path.join(subfolder, "fileŠ")) repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') - commit =repo.create_commit( - 'refs/heads/%s' % branch, # the name of the reference to update + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") + commit = repo.create_commit( + "refs/heads/%s" % branch, # the name of the reference to update author, committer, - 'Add some directory and a file for more testing', + "Add some directory and a file for more testing", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - parents + parents, ) # Push to origin ori_remote = repo.remotes[0] master_ref = repo.lookup_reference( - 'HEAD' if branch == 'master' else 'refs/heads/%s' % branch).resolve() - refname = '%s:%s' % (master_ref.name, master_ref.name) + "HEAD" if branch == "master" else "refs/heads/%s" % branch + ).resolve() + refname = "%s:%s" % (master_ref.name, master_ref.name) PagureRepo.push(ori_remote, refname) shutil.rmtree(newfolder) -def add_readme_git_repo(folder, readme_name='README.rst', branch='master'): +def add_readme_git_repo(folder, readme_name="README.rst", branch="master"): """ Create a README file for the specified git repo. """ repo, newfolder, parents = _clone_and_top_commits(folder, branch) - if readme_name == 'README.rst': + if readme_name == "README.rst": content = """Pagure ====== @@ -835,61 +857,62 @@ Homepage: https://github.com/pypingou/pagure Dev instance: http://209.132.184.222/ (/!\\ May change unexpectedly, it's a dev instance ;-)) """ else: - content = """Pagure + content = ( + """Pagure ====== -This is a placeholder """ + readme_name + """ +This is a placeholder """ + + readme_name + + """ that should never get displayed on the website if there is a README.rst in the repo. """ + ) # Create a file in that git repo - with open(os.path.join(newfolder, readme_name), 'w') as stream: + with open(os.path.join(newfolder, readme_name), "w") as stream: stream.write(content) repo.index.add(readme_name) repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") branch_ref = "refs/heads/%s" % branch repo.create_commit( branch_ref, # the name of the reference to update author, committer, - 'Add a README file', + "Add a README file", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - parents + parents, ) # Push to origin ori_remote = repo.remotes[0] - PagureRepo.push(ori_remote, '%s:%s' % (branch_ref, branch_ref)) + PagureRepo.push(ori_remote, "%s:%s" % (branch_ref, branch_ref)) shutil.rmtree(newfolder) -def add_commit_git_repo(folder, ncommits=10, filename='sources', - branch='master', symlink_to=None): +def add_commit_git_repo( + folder, ncommits=10, filename="sources", branch="master", symlink_to=None +): """ Create some more commits for the specified git repo. """ repo, newfolder, branch_ref_obj = _clone_and_top_commits( - folder, branch, branch_ref=True) + folder, branch, branch_ref=True + ) for index in range(ncommits): # Create a file in that git repo if symlink_to: - os.symlink( - symlink_to, - os.path.join(newfolder, filename), - ) + os.symlink(symlink_to, os.path.join(newfolder, filename)) else: - with open(os.path.join(newfolder, filename), 'a') as stream: - stream.write('Row %s\n' % index) + with open(os.path.join(newfolder, filename), "a") as stream: + stream.write("Row %s\n" % index) repo.index.add(filename) repo.index.write() @@ -899,7 +922,7 @@ def add_commit_git_repo(folder, ncommits=10, filename='sources', if branch_ref_obj: commit = repo[branch_ref_obj.peel().hex] else: - commit = repo.revparse_single('HEAD') + commit = repo.revparse_single("HEAD") except (KeyError, AttributeError): pass if commit: @@ -907,16 +930,14 @@ def add_commit_git_repo(folder, ncommits=10, filename='sources', # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") branch_ref = "refs/heads/%s" % branch repo.create_commit( branch_ref, author, committer, - 'Add row %s to %s file' % (index, filename), + "Add row %s to %s file" % (index, filename), # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit @@ -926,7 +947,7 @@ def add_commit_git_repo(folder, ncommits=10, filename='sources', # Push to origin ori_remote = repo.remotes[0] - PagureRepo.push(ori_remote, '%s:%s' % (branch_ref, branch_ref)) + PagureRepo.push(ori_remote, "%s:%s" % (branch_ref, branch_ref)) shutil.rmtree(newfolder) @@ -934,34 +955,40 @@ def add_commit_git_repo(folder, ncommits=10, filename='sources', def add_tag_git_repo(folder, tagname, obj_hash, message): """ Add a tag to the given object of the given repo annotated by given message. """ repo, newfolder, branch_ref_obj = _clone_and_top_commits( - folder, 'master', branch_ref=True) + folder, "master", branch_ref=True + ) tag_sha = repo.create_tag( tagname, obj_hash, repo.get(obj_hash).type, - pygit2.Signature('Alice Author', 'alice@authors.tld'), + pygit2.Signature("Alice Author", "alice@authors.tld"), message, ) # Push to origin ori_remote = repo.remotes[0] - PagureRepo.push(ori_remote, 'refs/tags/%s:refs/tags/%s' % (tagname, tagname)) + PagureRepo.push( + ori_remote, "refs/tags/%s:refs/tags/%s" % (tagname, tagname) + ) shutil.rmtree(newfolder) return tag_sha def add_content_to_git( - folder, branch='master', filename='sources', content='foo', - message=None): + folder, branch="master", filename="sources", content="foo", message=None +): """ Create some more commits for the specified git repo. """ repo, newfolder, branch_ref_obj = _clone_and_top_commits( - folder, branch, branch_ref=True) + folder, branch, branch_ref=True + ) # Create a file in that git repo - with open(os.path.join(newfolder, filename), 'a', encoding="utf-8") as stream: - stream.write('%s\n' % content) + with open( + os.path.join(newfolder, filename), "a", encoding="utf-8" + ) as stream: + stream.write("%s\n" % content) repo.index.add(filename) repo.index.write() @@ -971,7 +998,7 @@ def add_content_to_git( if branch_ref_obj: commit = repo[branch_ref_obj.peel().hex] else: - commit = repo.revparse_single('HEAD') + commit = repo.revparse_single("HEAD") except (KeyError, AttributeError): pass if commit: @@ -979,12 +1006,10 @@ def add_content_to_git( # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") branch_ref = "refs/heads/%s" % branch - message = message or 'Add content to file %s' % (filename) + message = message or "Add content to file %s" % (filename) repo.create_commit( branch_ref, # the name of the reference to update author, @@ -998,14 +1023,14 @@ def add_content_to_git( # Push to origin ori_remote = repo.remotes[0] - PagureRepo.push(ori_remote, '%s:%s' % (branch_ref, branch_ref)) + PagureRepo.push(ori_remote, "%s:%s" % (branch_ref, branch_ref)) shutil.rmtree(newfolder) def add_binary_git_repo(folder, filename): """ Create a fake image file for the specified git repo. """ - repo, newfolder, parents = _clone_and_top_commits(folder, 'master') + repo, newfolder, parents = _clone_and_top_commits(folder, "master") content = b"""\x00\x00\x01\x00\x01\x00\x18\x18\x00\x00\x01\x00 \x00\x88 \t\x00\x00\x16\x00\x00\x00(\x00\x00\x00\x18\x00x00\x00\x01\x00 \x00\x00\x00 @@ -1015,39 +1040,37 @@ def add_binary_git_repo(folder, filename): """ # Create a file in that git repo - with open(os.path.join(newfolder, filename), 'wb') as stream: + with open(os.path.join(newfolder, filename), "wb") as stream: stream.write(content) repo.index.add(filename) repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") repo.create_commit( - 'refs/heads/master', # the name of the reference to update + "refs/heads/master", # the name of the reference to update author, committer, - 'Add a fake image file', + "Add a fake image file", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - parents + parents, ) # Push to origin ori_remote = repo.remotes[0] - master_ref = repo.lookup_reference('HEAD').resolve() - refname = '%s:%s' % (master_ref.name, master_ref.name) + master_ref = repo.lookup_reference("HEAD").resolve() + refname = "%s:%s" % (master_ref.name, master_ref.name) PagureRepo.push(ori_remote, refname) shutil.rmtree(newfolder) -def remove_file_git_repo(folder, filename, branch='master'): +def remove_file_git_repo(folder, filename, branch="master"): """ Delete the specified file on the give git repo and branch. """ repo, newfolder, parents = _clone_and_top_commits(folder, branch) @@ -1057,26 +1080,24 @@ def remove_file_git_repo(folder, filename, branch='master'): # Write the change and commit it tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") branch_ref = "refs/heads/%s" % branch repo.create_commit( branch_ref, # the name of the reference to update author, committer, - 'Remove file %s' % filename, + "Remove file %s" % filename, # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - parents + parents, ) # Push to origin ori_remote = repo.remotes[0] - PagureRepo.push(ori_remote, '%s:%s' % (branch_ref, branch_ref)) + PagureRepo.push(ori_remote, "%s:%s" % (branch_ref, branch_ref)) shutil.rmtree(newfolder) @@ -1107,13 +1128,12 @@ def get_alerts(html): continue if class_ == "alert-dismissible": continue - severity = class_[len("alert-"):] + severity = class_[len("alert-") :] break element.find("button").decompose() # close button - alerts.append(dict( - severity=severity, - text="".join(element.stripped_strings) - )) + alerts.append( + dict(severity=severity, text="".join(element.stripped_strings)) + ) return alerts @@ -1122,6 +1142,6 @@ def definitely_wait(result): result.wait() -if __name__ == '__main__': +if __name__ == "__main__": SUITE = unittest.TestLoader().loadTestsFromTestCase(Modeltests) unittest.TextTestRunner(verbosity=2).run(SUITE) diff --git a/tests/test_alembic.py b/tests/test_alembic.py index f5614a0..1198bdf 100644 --- a/tests/test_alembic.py +++ b/tests/test_alembic.py @@ -14,9 +14,10 @@ import os import subprocess import unittest +import six -REPO_PATH = os.path.abspath( - os.path.join(os.path.dirname(__file__), '..')) + +REPO_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) class TestAlembic(unittest.TestCase): @@ -30,16 +31,16 @@ class TestAlembic(unittest.TestCase): """ proc1 = subprocess.Popen( - ['alembic', 'history'], - cwd=REPO_PATH, stdout=subprocess.PIPE) + ["alembic", "history"], cwd=REPO_PATH, stdout=subprocess.PIPE + ) proc2 = subprocess.Popen( - ['grep', ' (head), '], - stdin=proc1.stdout, stdout=subprocess.PIPE) + ["grep", " (head), "], stdin=proc1.stdout, stdout=subprocess.PIPE + ) stdout = proc2.communicate()[0] - stdout = stdout.strip().decode('utf-8').split('\n') + stdout = stdout.strip().decode("utf-8").split("\n") self.assertEqual(len(stdout), 1) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/test_dev_data.py b/tests/test_dev_data.py index 720616c..85d7e40 100644 --- a/tests/test_dev_data.py +++ b/tests/test_dev_data.py @@ -39,8 +39,9 @@ class TestDevData(tests.Modeltests): f.write("DB_URL = 'sqlite:///%s/db_dev_data.sqlite'\n" % self.path) f.write("GIT_FOLDER = '%s/repos'\n" % self.path) f.write( - "BROKER_URL = 'redis+socket://%(global_path)s/broker'\n" % \ - self.config_values) + "BROKER_URL = 'redis+socket://%(global_path)s/broker'\n" + % self.config_values + ) f.write("CELERY_CONFIG = {'task_always_eager': True}\n") env = { diff --git a/tests/test_fnmatch.py b/tests/test_fnmatch.py index e8732b1..18e1eff 100644 --- a/tests/test_fnmatch.py +++ b/tests/test_fnmatch.py @@ -27,26 +27,26 @@ class FnmatchTests(unittest.TestCase): def test_fnmatch(self): """ Test the matching done by fnmatch. """ matrix = [ - ['pagure', '*', True], - ['ns/pagure', '*', True], - ['forks/user/ns/pagure', '*', True], - ['forks/user/pagure', '*', True], - ['pagure', 'rpms/*', False], - ['rpms/pagure', 'rpms/*', True], - ['forks/user/pagure', 'rpms/*', False], - ['forks/user/pagure', 'rpms/*', False], - ['pagure', 'pagure', True], - ['rpms/pagure', 'pagure', False], - ['forks/user/pagure', 'pagure', False], - ['forks/user/pagure', 'pagure', False], - ['pagure', 'pag*', True], - ['rpms/pagure', 'pag*', False], - ['forks/user/pagure', 'pag*', False], - ['forks/user/pagure', 'pag*', False], + ["pagure", "*", True], + ["ns/pagure", "*", True], + ["forks/user/ns/pagure", "*", True], + ["forks/user/pagure", "*", True], + ["pagure", "rpms/*", False], + ["rpms/pagure", "rpms/*", True], + ["forks/user/pagure", "rpms/*", False], + ["forks/user/pagure", "rpms/*", False], + ["pagure", "pagure", True], + ["rpms/pagure", "pagure", False], + ["forks/user/pagure", "pagure", False], + ["forks/user/pagure", "pagure", False], + ["pagure", "pag*", True], + ["rpms/pagure", "pag*", False], + ["forks/user/pagure", "pag*", False], + ["forks/user/pagure", "pag*", False], ] for row in matrix: self.assertEqual(fnmatch.fnmatch(row[0], row[1]), row[2]) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/test_pagure_admin.py b/tests/test_pagure_admin.py index 55dcf96..a8254db 100644 --- a/tests/test_pagure_admin.py +++ b/tests/test_pagure_admin.py @@ -22,8 +22,9 @@ import munch # noqa from mock import patch, MagicMock # noqa from six import StringIO # noqa -sys.path.insert(0, os.path.join(os.path.dirname( - os.path.abspath(__file__)), '..')) +sys.path.insert( + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") +) import pagure.config # noqa import pagure.exceptions # noqa: E402 @@ -47,29 +48,28 @@ class PagureAdminAdminTokenEmptytests(tests.Modeltests): """ Test the do_create_admin_token function of pagure-admin without user. """ - args = munch.Munch({'user': "pingou"}) + args = munch.Munch({"user": "pingou"}) with self.assertRaises(pagure.exceptions.PagureException) as cm: pagure.cli.admin.do_create_admin_token(args) - self.assertEqual( - cm.exception.args[0], - 'No user "pingou" found' - ) + self.assertEqual(cm.exception.args[0], 'No user "pingou" found') def test_do_list_admin_token_empty(self): """ Test the do_list_admin_token function of pagure-admin when there are not tokens in the db. """ - list_args = munch.Munch({ - 'user': None, - 'token': None, - 'active': False, - 'expired': False, - 'all': False, - }) + list_args = munch.Munch( + { + "user": None, + "token": None, + "active": False, + "expired": False, + "all": False, + } + ) with tests.capture_output() as output: pagure.cli.admin.do_list_admin_token(list_args) output = output.getvalue() - self.assertEqual(output, 'No admin tokens found\n') + self.assertEqual(output, "No admin tokens found\n") class PagureAdminAdminRefreshGitolitetests(tests.Modeltests): @@ -84,15 +84,13 @@ class PagureAdminAdminRefreshGitolitetests(tests.Modeltests): # Create the user pingou item = pagure.lib.model.User( - user='pingou', - fullname='PY C', - password='foo', - default_email='bar@pingou.com', + user="pingou", + fullname="PY C", + password="foo", + default_email="bar@pingou.com", ) self.session.add(item) - item = pagure.lib.model.UserEmail( - user_id=1, - email='bar@pingou.com') + item = pagure.lib.model.UserEmail(user_id=1, email="bar@pingou.com") self.session.add(item) self.session.commit() @@ -102,22 +100,22 @@ class PagureAdminAdminRefreshGitolitetests(tests.Modeltests): # Add a group msg = pagure.lib.query.add_group( self.session, - group_name='foo', - display_name='foo group', + group_name="foo", + display_name="foo group", description=None, - group_type='bar', - user='pingou', + group_type="bar", + user="pingou", is_admin=False, blacklist=[], ) self.session.commit() - self.assertEqual(msg, 'User `pingou` added to the group `foo`.') + self.assertEqual(msg, "User `pingou` added to the group `foo`.") # Make the imported pagure use the correct db session pagure.cli.admin.session = self.session - @patch('pagure.cli.admin._ask_confirmation') - @patch('pagure.lib.git_auth.get_git_auth_helper') + @patch("pagure.cli.admin._ask_confirmation") + @patch("pagure.lib.git_auth.get_git_auth_helper") def test_do_refresh_gitolite_no_args(self, get_helper, conf): """ Test the do_generate_acl function with no special args. """ conf.return_value = True @@ -125,16 +123,17 @@ class PagureAdminAdminRefreshGitolitetests(tests.Modeltests): get_helper.return_value = helper args = munch.Munch( - {'group': None, 'project': None, 'all_': False, 'user': None}) + {"group": None, "project": None, "all_": False, "user": None} + ) pagure.cli.admin.do_generate_acl(args) get_helper.assert_called_with() args = helper.generate_acls.call_args - self.assertIsNone(args[1].get('group')) - self.assertIsNone(args[1].get('project')) + self.assertIsNone(args[1].get("group")) + self.assertIsNone(args[1].get("project")) - @patch('pagure.cli.admin._ask_confirmation') - @patch('pagure.lib.git_auth.get_git_auth_helper') + @patch("pagure.cli.admin._ask_confirmation") + @patch("pagure.lib.git_auth.get_git_auth_helper") def test_do_refresh_gitolite_all_project(self, get_helper, conf): """ Test the do_generate_acl function for all projects. """ conf.return_value = True @@ -142,16 +141,17 @@ class PagureAdminAdminRefreshGitolitetests(tests.Modeltests): get_helper.return_value = helper args = munch.Munch( - {'group': None, 'project': None, 'all_': True, 'user': None}) + {"group": None, "project": None, "all_": True, "user": None} + ) pagure.cli.admin.do_generate_acl(args) get_helper.assert_called_with() args = helper.generate_acls.call_args - self.assertIsNone(args[1].get('group')) - self.assertEqual(args[1].get('project'), -1) + self.assertIsNone(args[1].get("group")) + self.assertEqual(args[1].get("project"), -1) - @patch('pagure.cli.admin._ask_confirmation') - @patch('pagure.lib.git_auth.get_git_auth_helper') + @patch("pagure.cli.admin._ask_confirmation") + @patch("pagure.lib.git_auth.get_git_auth_helper") def test_do_refresh_gitolite_one_project(self, get_helper, conf): """ Test the do_generate_acl function for a certain project. """ conf.return_value = True @@ -159,16 +159,17 @@ class PagureAdminAdminRefreshGitolitetests(tests.Modeltests): get_helper.return_value = helper args = munch.Munch( - {'group': None, 'project': 'test', 'all_': False, 'user': None}) + {"group": None, "project": "test", "all_": False, "user": None} + ) pagure.cli.admin.do_generate_acl(args) get_helper.assert_called_with() args = helper.generate_acls.call_args - self.assertIsNone(args[1].get('group')) - self.assertEqual(args[1].get('project').fullname, 'test') + self.assertIsNone(args[1].get("group")) + self.assertEqual(args[1].get("project").fullname, "test") - @patch('pagure.cli.admin._ask_confirmation') - @patch('pagure.lib.git_auth.get_git_auth_helper') + @patch("pagure.cli.admin._ask_confirmation") + @patch("pagure.lib.git_auth.get_git_auth_helper") def test_do_refresh_gitolite_one_project_and_all(self, get_helper, conf): """ Test the do_generate_acl function for a certain project and all. """ @@ -177,16 +178,17 @@ class PagureAdminAdminRefreshGitolitetests(tests.Modeltests): get_helper.return_value = helper args = munch.Munch( - {'group': None, 'project': 'test', 'all_': True, 'user': None}) + {"group": None, "project": "test", "all_": True, "user": None} + ) pagure.cli.admin.do_generate_acl(args) get_helper.assert_called_with() args = helper.generate_acls.call_args - self.assertIsNone(args[1].get('group')) - self.assertEqual(args[1].get('project'), -1) + self.assertIsNone(args[1].get("group")) + self.assertEqual(args[1].get("project"), -1) - @patch('pagure.cli.admin._ask_confirmation') - @patch('pagure.lib.git_auth.get_git_auth_helper') + @patch("pagure.cli.admin._ask_confirmation") + @patch("pagure.lib.git_auth.get_git_auth_helper") def test_do_refresh_gitolite_one_group(self, get_helper, conf): """ Test the do_generate_acl function for a certain group. """ conf.return_value = True @@ -194,13 +196,14 @@ class PagureAdminAdminRefreshGitolitetests(tests.Modeltests): get_helper.return_value = helper args = munch.Munch( - {'group': 'foo', 'project': None, 'all_': False, 'user': None}) + {"group": "foo", "project": None, "all_": False, "user": None} + ) pagure.cli.admin.do_generate_acl(args) get_helper.assert_called_with() args = helper.generate_acls.call_args - self.assertEqual(args[1].get('group').group_name, 'foo') - self.assertIsNone(args[1].get('project')) + self.assertEqual(args[1].get("group").group_name, "foo") + self.assertIsNone(args[1].get("project")) class PagureAdminAdminTokentests(tests.Modeltests): @@ -215,84 +218,88 @@ class PagureAdminAdminTokentests(tests.Modeltests): # Create the user pingou item = pagure.lib.model.User( - user='pingou', - fullname='PY C', - password='foo', - default_email='bar@pingou.com', + user="pingou", + fullname="PY C", + password="foo", + default_email="bar@pingou.com", ) self.session.add(item) - item = pagure.lib.model.UserEmail( - user_id=1, - email='bar@pingou.com') + item = pagure.lib.model.UserEmail(user_id=1, email="bar@pingou.com") self.session.add(item) self.session.commit() # Make the imported pagure use the correct db session pagure.cli.admin.session = self.session - @patch('pagure.cli.admin._get_input') - @patch('pagure.cli.admin._ask_confirmation') + @patch("pagure.cli.admin._get_input") + @patch("pagure.cli.admin._ask_confirmation") def test_do_create_admin_token(self, conf, rinp): """ Test the do_create_admin_token function of pagure-admin. """ conf.return_value = True - rinp.return_value = '1,2,3' + rinp.return_value = "1,2,3" - args = munch.Munch({'user': 'pingou'}) + args = munch.Munch({"user": "pingou"}) pagure.cli.admin.do_create_admin_token(args) # Check the outcome - list_args = munch.Munch({ - 'user': None, - 'token': None, - 'active': False, - 'expired': False, - 'all': False, - }) + list_args = munch.Munch( + { + "user": None, + "token": None, + "active": False, + "expired": False, + "all": False, + } + ) with tests.capture_output() as output: pagure.cli.admin.do_list_admin_token(list_args) output = output.getvalue() self.assertNotEqual(output, 'No user "pingou" found\n') - self.assertEqual(len(output.split('\n')), 2) - self.assertIn(' -- pingou -- ', output) + self.assertEqual(len(output.split("\n")), 2) + self.assertIn(" -- pingou -- ", output) - @patch('pagure.cli.admin._get_input') - @patch('pagure.cli.admin._ask_confirmation') + @patch("pagure.cli.admin._get_input") + @patch("pagure.cli.admin._ask_confirmation") def test_do_list_admin_token(self, conf, rinp): """ Test the do_list_admin_token function of pagure-admin. """ # Create an admin token to use conf.return_value = True - rinp.return_value = '1,2,3' + rinp.return_value = "1,2,3" - args = munch.Munch({'user': 'pingou'}) + args = munch.Munch({"user": "pingou"}) pagure.cli.admin.do_create_admin_token(args) # Retrieve all tokens - list_args = munch.Munch({ - 'user': None, - 'token': None, - 'active': False, - 'expired': False, - 'all': False, - }) + list_args = munch.Munch( + { + "user": None, + "token": None, + "active": False, + "expired": False, + "all": False, + } + ) with tests.capture_output() as output: pagure.cli.admin.do_list_admin_token(list_args) output = output.getvalue() self.assertNotEqual(output, 'No user "pingou" found\n') - self.assertEqual(len(output.split('\n')), 2) - self.assertIn(' -- pingou -- ', output) + self.assertEqual(len(output.split("\n")), 2) + self.assertIn(" -- pingou -- ", output) # Retrieve pfrields's tokens - list_args = munch.Munch({ - 'user': 'pfrields', - 'token': None, - 'active': False, - 'expired': False, - 'all': False, - }) + list_args = munch.Munch( + { + "user": "pfrields", + "token": None, + "active": False, + "expired": False, + "all": False, + } + ) with tests.capture_output() as output: pagure.cli.admin.do_list_admin_token(list_args) output = output.getvalue() - self.assertEqual(output, 'No admin tokens found\n') + self.assertEqual(output, "No admin tokens found\n") def test_do_list_admin_token_non_admin_acls(self): """ Test the do_list_admin_token function of pagure-admin for a token @@ -300,76 +307,85 @@ class PagureAdminAdminTokentests(tests.Modeltests): pagure.lib.query.add_token_to_user( self.session, project=None, - acls=['issue_assign', 'pull_request_subscribe'], - username='pingou') + acls=["issue_assign", "pull_request_subscribe"], + username="pingou", + ) # Retrieve all admin tokens - list_args = munch.Munch({ - 'user': None, - 'token': None, - 'active': False, - 'expired': False, - 'all': False, - }) + list_args = munch.Munch( + { + "user": None, + "token": None, + "active": False, + "expired": False, + "all": False, + } + ) with tests.capture_output() as output: pagure.cli.admin.do_list_admin_token(list_args) output = output.getvalue() - self.assertEqual(output, 'No admin tokens found\n') + self.assertEqual(output, "No admin tokens found\n") # Retrieve all tokens - list_args = munch.Munch({ - 'user': None, - 'token': None, - 'active': False, - 'expired': False, - 'all': True, - }) + list_args = munch.Munch( + { + "user": None, + "token": None, + "active": False, + "expired": False, + "all": True, + } + ) with tests.capture_output() as output: pagure.cli.admin.do_list_admin_token(list_args) output = output.getvalue() self.assertNotEqual(output, 'No user "pingou" found\n') - self.assertEqual(len(output.split('\n')), 2) - self.assertIn(' -- pingou -- ', output) + self.assertEqual(len(output.split("\n")), 2) + self.assertIn(" -- pingou -- ", output) - @patch('pagure.cli.admin._get_input') - @patch('pagure.cli.admin._ask_confirmation') + @patch("pagure.cli.admin._get_input") + @patch("pagure.cli.admin._ask_confirmation") def test_do_info_admin_token(self, conf, rinp): """ Test the do_info_admin_token function of pagure-admin. """ # Create an admin token to use conf.return_value = True - rinp.return_value = '2,4,5' + rinp.return_value = "2,4,5" - args = munch.Munch({'user': 'pingou'}) + args = munch.Munch({"user": "pingou"}) pagure.cli.admin.do_create_admin_token(args) # Retrieve the token - list_args = munch.Munch({ - 'user': None, - 'token': None, - 'active': False, - 'expired': False, - 'all': False, - }) + list_args = munch.Munch( + { + "user": None, + "token": None, + "active": False, + "expired": False, + "all": False, + } + ) with tests.capture_output() as output: pagure.cli.admin.do_list_admin_token(list_args) output = output.getvalue() self.assertNotEqual(output, 'No user "pingou" found\n') - self.assertEqual(len(output.split('\n')), 2) - self.assertIn(' -- pingou -- ', output) + self.assertEqual(len(output.split("\n")), 2) + self.assertIn(" -- pingou -- ", output) - token = output.split(' ', 1)[0] + token = output.split(" ", 1)[0] - args = munch.Munch({'token': token}) + args = munch.Munch({"token": token}) with tests.capture_output() as output: pagure.cli.admin.do_info_admin_token(args) output = output.getvalue() - self.assertIn(' -- pingou -- ', output.split('\n', 1)[0]) + self.assertIn(" -- pingou -- ", output.split("\n", 1)[0]) self.assertEqual( - output.split('\n', 1)[1], '''ACLs: + output.split("\n", 1)[1], + """ACLs: - issue_create - pull_request_comment - pull_request_flag -''') +""", + ) def test_do_info_admin_token_non_admin_acl(self): """ Test the do_info_admin_token function of pagure-admin for a @@ -377,297 +393,320 @@ class PagureAdminAdminTokentests(tests.Modeltests): pagure.lib.query.add_token_to_user( self.session, project=None, - acls=['issue_assign', 'pull_request_subscribe'], - username='pingou') + acls=["issue_assign", "pull_request_subscribe"], + username="pingou", + ) # Retrieve the token - list_args = munch.Munch({ - 'user': None, - 'token': None, - 'active': False, - 'expired': False, - 'all': True, - }) + list_args = munch.Munch( + { + "user": None, + "token": None, + "active": False, + "expired": False, + "all": True, + } + ) with tests.capture_output() as output: pagure.cli.admin.do_list_admin_token(list_args) output = output.getvalue() self.assertNotEqual(output, 'No user "pingou" found\n') - self.assertEqual(len(output.split('\n')), 2) - self.assertIn(' -- pingou -- ', output) + self.assertEqual(len(output.split("\n")), 2) + self.assertIn(" -- pingou -- ", output) - token = output.split(' ', 1)[0] + token = output.split(" ", 1)[0] - args = munch.Munch({'token': token}) + args = munch.Munch({"token": token}) with tests.capture_output() as output: pagure.cli.admin.do_info_admin_token(args) output = output.getvalue() - self.assertIn(' -- pingou -- ', output.split('\n', 1)[0]) + self.assertIn(" -- pingou -- ", output.split("\n", 1)[0]) self.assertEqual( - output.split('\n', 1)[1], '''ACLs: + output.split("\n", 1)[1], + """ACLs: - issue_assign - pull_request_subscribe -''') +""", + ) - @patch('pagure.cli.admin._get_input') - @patch('pagure.cli.admin._ask_confirmation') + @patch("pagure.cli.admin._get_input") + @patch("pagure.cli.admin._ask_confirmation") def test_do_expire_admin_token(self, conf, rinp): """ Test the do_expire_admin_token function of pagure-admin. """ - if 'BUILD_ID' in os.environ: - raise unittest.case.SkipTest('Skipping on jenkins/el7') + if "BUILD_ID" in os.environ: + raise unittest.case.SkipTest("Skipping on jenkins/el7") # Create an admin token to use conf.return_value = True - rinp.return_value = '1,2,3' + rinp.return_value = "1,2,3" - args = munch.Munch({'user': 'pingou'}) + args = munch.Munch({"user": "pingou"}) pagure.cli.admin.do_create_admin_token(args) # Retrieve the token - list_args = munch.Munch({ - 'user': None, - 'token': None, - 'active': False, - 'expired': False, - 'all': False, - }) + list_args = munch.Munch( + { + "user": None, + "token": None, + "active": False, + "expired": False, + "all": False, + } + ) with tests.capture_output() as output: pagure.cli.admin.do_list_admin_token(list_args) output = output.getvalue() self.assertNotEqual(output, 'No user "pingou" found\n') - self.assertEqual(len(output.split('\n')), 2) - self.assertIn(' -- pingou -- ', output) + self.assertEqual(len(output.split("\n")), 2) + self.assertIn(" -- pingou -- ", output) - token = output.split(' ', 1)[0] + token = output.split(" ", 1)[0] # Before - list_args = munch.Munch({ - 'user': None, - 'token': None, - 'active': True, - 'expired': False, - 'all': False, - }) + list_args = munch.Munch( + { + "user": None, + "token": None, + "active": True, + "expired": False, + "all": False, + } + ) with tests.capture_output() as output: pagure.cli.admin.do_list_admin_token(list_args) output = output.getvalue() - self.assertNotEqual(output, 'No admin tokens found\n') - self.assertEqual(len(output.split('\n')), 2) - self.assertIn(' -- pingou -- ', output) + self.assertNotEqual(output, "No admin tokens found\n") + self.assertEqual(len(output.split("\n")), 2) + self.assertIn(" -- pingou -- ", output) # Expire the token - args = munch.Munch({'token': token}) + args = munch.Munch({"token": token}) pagure.cli.admin.do_expire_admin_token(args) # After - list_args = munch.Munch({ - 'user': None, - 'token': None, - 'active': True, - 'expired': False, - 'all': False, - }) + list_args = munch.Munch( + { + "user": None, + "token": None, + "active": True, + "expired": False, + "all": False, + } + ) with tests.capture_output() as output: pagure.cli.admin.do_list_admin_token(list_args) output = output.getvalue() - self.assertEqual(output, 'No admin tokens found\n') + self.assertEqual(output, "No admin tokens found\n") - @patch('pagure.cli.admin._get_input') - @patch('pagure.cli.admin._ask_confirmation') + @patch("pagure.cli.admin._get_input") + @patch("pagure.cli.admin._ask_confirmation") def test_do_update_admin_token_invalid_date(self, conf, rinp): """ Test the do_update_admin_token function of pagure-admin with an invalid date. """ - if 'BUILD_ID' in os.environ: - raise unittest.case.SkipTest('Skipping on jenkins/el7') + if "BUILD_ID" in os.environ: + raise unittest.case.SkipTest("Skipping on jenkins/el7") # Create an admin token to use conf.return_value = True - rinp.return_value = '1,2,3' + rinp.return_value = "1,2,3" - args = munch.Munch({'user': 'pingou'}) + args = munch.Munch({"user": "pingou"}) pagure.cli.admin.do_create_admin_token(args) # Retrieve the token - list_args = munch.Munch({ - 'user': None, - 'token': None, - 'active': False, - 'expired': False, - 'all': False, - }) + list_args = munch.Munch( + { + "user": None, + "token": None, + "active": False, + "expired": False, + "all": False, + } + ) with tests.capture_output() as output: pagure.cli.admin.do_list_admin_token(list_args) output = output.getvalue() self.assertNotEqual(output, 'No user "pingou" found\n') - self.assertEqual(len(output.split('\n')), 2) - self.assertIn(' -- pingou -- ', output) + self.assertEqual(len(output.split("\n")), 2) + self.assertIn(" -- pingou -- ", output) - token = output.split(' ', 1)[0] - current_expiration = output.split(' ', 1)[1] + token = output.split(" ", 1)[0] + current_expiration = output.split(" ", 1)[1] # Set the expiration date to the token - args = munch.Munch({'token': token, 'date': 'aa-bb-cc'}) + args = munch.Munch({"token": token, "date": "aa-bb-cc"}) self.assertRaises( pagure.exceptions.PagureException, pagure.cli.admin.do_update_admin_token, - args + args, ) - @patch('pagure.cli.admin._get_input') - @patch('pagure.cli.admin._ask_confirmation') + @patch("pagure.cli.admin._get_input") + @patch("pagure.cli.admin._ask_confirmation") def test_do_update_admin_token_invalid_date2(self, conf, rinp): """ Test the do_update_admin_token function of pagure-admin with an invalid date. """ - if 'BUILD_ID' in os.environ: - raise unittest.case.SkipTest('Skipping on jenkins/el7') + if "BUILD_ID" in os.environ: + raise unittest.case.SkipTest("Skipping on jenkins/el7") # Create an admin token to use conf.return_value = True - rinp.return_value = '1,2,3' + rinp.return_value = "1,2,3" - args = munch.Munch({'user': 'pingou'}) + args = munch.Munch({"user": "pingou"}) pagure.cli.admin.do_create_admin_token(args) # Retrieve the token - list_args = munch.Munch({ - 'user': None, - 'token': None, - 'active': False, - 'expired': False, - 'all': False, - }) + list_args = munch.Munch( + { + "user": None, + "token": None, + "active": False, + "expired": False, + "all": False, + } + ) with tests.capture_output() as output: pagure.cli.admin.do_list_admin_token(list_args) output = output.getvalue() self.assertNotEqual(output, 'No user "pingou" found\n') - self.assertEqual(len(output.split('\n')), 2) - self.assertIn(' -- pingou -- ', output) + self.assertEqual(len(output.split("\n")), 2) + self.assertIn(" -- pingou -- ", output) - token = output.split(' ', 1)[0] - current_expiration = output.split(' ', 1)[1] + token = output.split(" ", 1)[0] + current_expiration = output.split(" ", 1)[1] # Set the expiration date to the token - args = munch.Munch({'token': token, 'date': '2017-18-01'}) + args = munch.Munch({"token": token, "date": "2017-18-01"}) self.assertRaises( pagure.exceptions.PagureException, pagure.cli.admin.do_update_admin_token, - args + args, ) - @patch('pagure.cli.admin._get_input') - @patch('pagure.cli.admin._ask_confirmation') + @patch("pagure.cli.admin._get_input") + @patch("pagure.cli.admin._ask_confirmation") def test_do_update_admin_token_invalid_date3(self, conf, rinp): """ Test the do_update_admin_token function of pagure-admin with an invalid date (is today). """ - if 'BUILD_ID' in os.environ: - raise unittest.case.SkipTest('Skipping on jenkins/el7') + if "BUILD_ID" in os.environ: + raise unittest.case.SkipTest("Skipping on jenkins/el7") # Create an admin token to use conf.return_value = True - rinp.return_value = '1,2,3' + rinp.return_value = "1,2,3" - args = munch.Munch({'user': 'pingou'}) + args = munch.Munch({"user": "pingou"}) pagure.cli.admin.do_create_admin_token(args) # Retrieve the token - list_args = munch.Munch({ - 'user': None, - 'token': None, - 'active': False, - 'expired': False, - 'all': False, - }) + list_args = munch.Munch( + { + "user": None, + "token": None, + "active": False, + "expired": False, + "all": False, + } + ) with tests.capture_output() as output: pagure.cli.admin.do_list_admin_token(list_args) output = output.getvalue() self.assertNotEqual(output, 'No user "pingou" found\n') - self.assertEqual(len(output.split('\n')), 2) - self.assertIn(' -- pingou -- ', output) + self.assertEqual(len(output.split("\n")), 2) + self.assertIn(" -- pingou -- ", output) - token = output.split(' ', 1)[0] - current_expiration = output.split(' ', 1)[1] + token = output.split(" ", 1)[0] + current_expiration = output.split(" ", 1)[1] # Set the expiration date to the token - args = munch.Munch({ - 'token': token, 'date': datetime.datetime.utcnow().date() - }) + args = munch.Munch( + {"token": token, "date": datetime.datetime.utcnow().date()} + ) self.assertRaises( pagure.exceptions.PagureException, pagure.cli.admin.do_update_admin_token, - args + args, ) - @patch('pagure.cli.admin._get_input') - @patch('pagure.cli.admin._ask_confirmation') + @patch("pagure.cli.admin._get_input") + @patch("pagure.cli.admin._ask_confirmation") def test_do_update_admin_token(self, conf, rinp): """ Test the do_update_admin_token function of pagure-admin. """ - if 'BUILD_ID' in os.environ: - raise unittest.case.SkipTest('Skipping on jenkins/el7') + if "BUILD_ID" in os.environ: + raise unittest.case.SkipTest("Skipping on jenkins/el7") # Create an admin token to use conf.return_value = True - rinp.return_value = '1,2,3' + rinp.return_value = "1,2,3" - args = munch.Munch({'user': 'pingou'}) + args = munch.Munch({"user": "pingou"}) pagure.cli.admin.do_create_admin_token(args) # Retrieve the token - list_args = munch.Munch({ - 'user': None, - 'token': None, - 'active': False, - 'expired': False, - 'all': False, - }) + list_args = munch.Munch( + { + "user": None, + "token": None, + "active": False, + "expired": False, + "all": False, + } + ) with tests.capture_output() as output: pagure.cli.admin.do_list_admin_token(list_args) output = output.getvalue() self.assertNotEqual(output, 'No user "pingou" found\n') - self.assertEqual(len(output.split('\n')), 2) - self.assertIn(' -- pingou -- ', output) + self.assertEqual(len(output.split("\n")), 2) + self.assertIn(" -- pingou -- ", output) - token = output.split(' ', 1)[0] - current_expiration = output.strip().split(' -- ', 2)[-1] + token = output.split(" ", 1)[0] + current_expiration = output.strip().split(" -- ", 2)[-1] # Before - list_args = munch.Munch({ - 'user': None, - 'token': None, - 'active': True, - 'expired': False, - 'all': False, - }) + list_args = munch.Munch( + { + "user": None, + "token": None, + "active": True, + "expired": False, + "all": False, + } + ) with tests.capture_output() as output: pagure.cli.admin.do_list_admin_token(list_args) output = output.getvalue() - self.assertNotEqual(output, 'No admin tokens found\n') - self.assertEqual(len(output.split('\n')), 2) - self.assertIn(' -- pingou -- ', output) + self.assertNotEqual(output, "No admin tokens found\n") + self.assertEqual(len(output.split("\n")), 2) + self.assertIn(" -- pingou -- ", output) - deadline = datetime.datetime.utcnow().date() \ - + datetime.timedelta(days=3) + deadline = datetime.datetime.utcnow().date() + datetime.timedelta( + days=3 + ) # Set the expiration date to the token - args = munch.Munch({ - 'token': token, - 'date': deadline.strftime('%Y-%m-%d') - }) + args = munch.Munch( + {"token": token, "date": deadline.strftime("%Y-%m-%d")} + ) pagure.cli.admin.do_update_admin_token(args) # After - list_args = munch.Munch({ - 'user': None, - 'token': None, - 'active': True, - 'expired': False, - 'all': False, - }) + list_args = munch.Munch( + { + "user": None, + "token": None, + "active": True, + "expired": False, + "all": False, + } + ) with tests.capture_output() as output: pagure.cli.admin.do_list_admin_token(list_args) output = output.getvalue() - self.assertEqual(output.split(' ', 1)[0], token) + self.assertEqual(output.split(" ", 1)[0], token) self.assertNotEqual( - output.strip().split(' -- ', 2)[-1], - current_expiration) + output.strip().split(" -- ", 2)[-1], current_expiration + ) class PagureAdminGetWatchTests(tests.Modeltests): @@ -682,41 +721,39 @@ class PagureAdminGetWatchTests(tests.Modeltests): # Create the user pingou item = pagure.lib.model.User( - user='pingou', - fullname='PY C', - password='foo', - default_email='bar@pingou.com', + user="pingou", + fullname="PY C", + password="foo", + default_email="bar@pingou.com", ) self.session.add(item) - item = pagure.lib.model.UserEmail( - user_id=1, - email='bar@pingou.com') + item = pagure.lib.model.UserEmail(user_id=1, email="bar@pingou.com") self.session.add(item) # Create the user foo item = pagure.lib.model.User( - user='foo', - fullname='foo B.', - password='foob', - default_email='foo@pingou.com', + user="foo", + fullname="foo B.", + password="foob", + default_email="foo@pingou.com", ) self.session.add(item) # Create two projects for the user pingou item = pagure.lib.model.Project( user_id=1, # pingou - name='test', - description='namespaced test project', - hook_token='aaabbbeee', - namespace='somenamespace', + name="test", + description="namespaced test project", + hook_token="aaabbbeee", + namespace="somenamespace", ) self.session.add(item) item = pagure.lib.model.Project( user_id=1, # pingou - name='test', - description='Test project', - hook_token='aaabbbccc', + name="test", + description="Test project", + hook_token="aaabbbccc", namespace=None, ) self.session.add(item) @@ -730,25 +767,16 @@ class PagureAdminGetWatchTests(tests.Modeltests): """ Test the get-watch function of pagure-admin with an unknown project. """ - args = munch.Munch({ - 'project': 'foobar', - 'user': 'pingou', - }) + args = munch.Munch({"project": "foobar", "user": "pingou"}) with self.assertRaises(pagure.exceptions.PagureException) as cm: pagure.cli.admin.do_get_watch_status(args) - self.assertEqual( - cm.exception.args[0], - 'No project found with: foobar' - ) + self.assertEqual(cm.exception.args[0], "No project found with: foobar") def test_get_watch_get_project_invalid_project(self): """ Test the get-watch function of pagure-admin with an invalid project. """ - args = munch.Munch({ - 'project': 'fo/o/bar', - 'user': 'pingou', - }) + args = munch.Munch({"project": "fo/o/bar", "user": "pingou"}) with self.assertRaises(pagure.exceptions.PagureException) as cm: pagure.cli.admin.do_get_watch_status(args) self.assertEqual( @@ -759,77 +787,65 @@ class PagureAdminGetWatchTests(tests.Modeltests): def test_get_watch_get_project_invalid_user(self): """ Test the get-watch function of pagure-admin on a invalid user. """ - args = munch.Munch({ - 'project': 'test', - 'user': 'beebop', - }) + args = munch.Munch({"project": "test", "user": "beebop"}) with self.assertRaises(pagure.exceptions.PagureException) as cm: pagure.cli.admin.do_get_watch_status(args) - self.assertEqual( - cm.exception.args[0], - 'No user "beebop" found' - ) + self.assertEqual(cm.exception.args[0], 'No user "beebop" found') def test_get_watch_get_project(self): """ Test the get-watch function of pagure-admin on a regular project. """ - args = munch.Munch({ - 'project': 'test', - 'user': 'pingou', - }) + args = munch.Munch({"project": "test", "user": "pingou"}) with tests.capture_output() as output: pagure.cli.admin.do_get_watch_status(args) output = output.getvalue() self.assertEqual( - 'On test user: pingou is watching the following items: ' - 'issues, pull-requests\n', output) + "On test user: pingou is watching the following items: " + "issues, pull-requests\n", + output, + ) def test_get_watch_get_project_not_watching(self): """ Test the get-watch function of pagure-admin on a regular project. """ - args = munch.Munch({ - 'project': 'test', - 'user': 'foo', - }) + args = munch.Munch({"project": "test", "user": "foo"}) with tests.capture_output() as output: pagure.cli.admin.do_get_watch_status(args) output = output.getvalue() self.assertEqual( - 'On test user: foo is watching the following items: None\n', - output) + "On test user: foo is watching the following items: None\n", output + ) def test_get_watch_get_project_namespaced(self): """ Test the get-watch function of pagure-admin on a namespaced project. """ - args = munch.Munch({ - 'project': 'somenamespace/test', - 'user': 'pingou', - }) + args = munch.Munch({"project": "somenamespace/test", "user": "pingou"}) with tests.capture_output() as output: pagure.cli.admin.do_get_watch_status(args) output = output.getvalue() self.assertEqual( - 'On somenamespace/test user: pingou is watching the following ' - 'items: issues, pull-requests\n', output) + "On somenamespace/test user: pingou is watching the following " + "items: issues, pull-requests\n", + output, + ) def test_get_watch_get_project_namespaced_not_watching(self): """ Test the get-watch function of pagure-admin on a namespaced project. """ - args = munch.Munch({ - 'project': 'somenamespace/test', - 'user': 'foo', - }) + args = munch.Munch({"project": "somenamespace/test", "user": "foo"}) with tests.capture_output() as output: pagure.cli.admin.do_get_watch_status(args) output = output.getvalue() with tests.capture_output() as _discarded: pagure.cli.admin.do_get_watch_status(args) self.assertEqual( - 'On somenamespace/test user: foo is watching the following ' - 'items: None\n', output) + "On somenamespace/test user: foo is watching the following " + "items: None\n", + output, + ) class PagureAdminUpdateWatchTests(tests.Modeltests): @@ -844,41 +860,39 @@ class PagureAdminUpdateWatchTests(tests.Modeltests): # Create the user pingou item = pagure.lib.model.User( - user='pingou', - fullname='PY C', - password='foo', - default_email='bar@pingou.com', + user="pingou", + fullname="PY C", + password="foo", + default_email="bar@pingou.com", ) self.session.add(item) - item = pagure.lib.model.UserEmail( - user_id=1, - email='bar@pingou.com') + item = pagure.lib.model.UserEmail(user_id=1, email="bar@pingou.com") self.session.add(item) # Create the user foo item = pagure.lib.model.User( - user='foo', - fullname='foo B.', - password='foob', - default_email='foo@pingou.com', + user="foo", + fullname="foo B.", + password="foob", + default_email="foo@pingou.com", ) self.session.add(item) # Create two projects for the user pingou item = pagure.lib.model.Project( user_id=1, # pingou - name='test', - description='namespaced test project', - hook_token='aaabbbeee', - namespace='somenamespace', + name="test", + description="namespaced test project", + hook_token="aaabbbeee", + namespace="somenamespace", ) self.session.add(item) item = pagure.lib.model.Project( user_id=1, # pingou - name='test', - description='Test project', - hook_token='aaabbbccc', + name="test", + description="Test project", + hook_token="aaabbbccc", namespace=None, ) self.session.add(item) @@ -892,27 +906,20 @@ class PagureAdminUpdateWatchTests(tests.Modeltests): """ Test the update-watch function of pagure-admin on an unknown project. """ - args = munch.Munch({ - 'project': 'foob', - 'user': 'pingou', - 'status': '1' - }) + args = munch.Munch( + {"project": "foob", "user": "pingou", "status": "1"} + ) with self.assertRaises(pagure.exceptions.PagureException) as cm: pagure.cli.admin.do_update_watch_status(args) - self.assertEqual( - cm.exception.args[0], - 'No project found with: foob' - ) + self.assertEqual(cm.exception.args[0], "No project found with: foob") def test_get_watch_update_project_invalid_project(self): """ Test the update-watch function of pagure-admin on an invalid project. """ - args = munch.Munch({ - 'project': 'fo/o/b', - 'user': 'pingou', - 'status': '1' - }) + args = munch.Munch( + {"project": "fo/o/b", "user": "pingou", "status": "1"} + ) with self.assertRaises(pagure.exceptions.PagureException) as cm: pagure.cli.admin.do_update_watch_status(args) self.assertEqual( @@ -923,32 +930,23 @@ class PagureAdminUpdateWatchTests(tests.Modeltests): def test_get_watch_update_project_invalid_user(self): """ Test the update-watch function of pagure-admin on an invalid user. """ - args = munch.Munch({ - 'project': 'test', - 'user': 'foob', - 'status': '1' - }) + args = munch.Munch({"project": "test", "user": "foob", "status": "1"}) with self.assertRaises(pagure.exceptions.PagureException) as cm: pagure.cli.admin.do_update_watch_status(args) - self.assertEqual( - cm.exception.args[0], - 'No user "foob" found' - ) + self.assertEqual(cm.exception.args[0], 'No user "foob" found') def test_get_watch_update_project_invalid_status(self): """ Test the update-watch function of pagure-admin with an invalid status. """ - args = munch.Munch({ - 'project': 'test', - 'user': 'pingou', - 'status': '10' - }) + args = munch.Munch( + {"project": "test", "user": "pingou", "status": "10"} + ) with self.assertRaises(pagure.exceptions.PagureException) as cm: pagure.cli.admin.do_update_watch_status(args) self.assertEqual( cm.exception.args[0], - 'Invalid status provided: 10 not in -1, 0, 1, 2, 3' + "Invalid status provided: 10 not in -1, 0, 1, 2, 3", ) def test_get_watch_update_project_no_effect(self): @@ -956,39 +954,37 @@ class PagureAdminUpdateWatchTests(tests.Modeltests): project - nothing changed. """ - args = munch.Munch({ - 'project': 'test', - 'user': 'pingou', - }) + args = munch.Munch({"project": "test", "user": "pingou"}) with tests.capture_output() as output: pagure.cli.admin.do_get_watch_status(args) output = output.getvalue() self.assertEqual( - 'On test user: pingou is watching the following items: ' - 'issues, pull-requests\n', output) - - args = munch.Munch({ - 'project': 'test', - 'user': 'pingou', - 'status': '1' - }) + "On test user: pingou is watching the following items: " + "issues, pull-requests\n", + output, + ) + + args = munch.Munch( + {"project": "test", "user": "pingou", "status": "1"} + ) with tests.capture_output() as output: pagure.cli.admin.do_update_watch_status(args) output = output.getvalue() self.assertEqual( - 'Updating watch status of pingou to 1 (watch issues and PRs) ' - 'on test\n', output) + "Updating watch status of pingou to 1 (watch issues and PRs) " + "on test\n", + output, + ) - args = munch.Munch({ - 'project': 'test', - 'user': 'pingou', - }) + args = munch.Munch({"project": "test", "user": "pingou"}) with tests.capture_output() as output: pagure.cli.admin.do_get_watch_status(args) output = output.getvalue() self.assertEqual( - 'On test user: pingou is watching the following items: ' - 'issues, pull-requests\n', output) + "On test user: pingou is watching the following items: " + "issues, pull-requests\n", + output, + ) class PagureAdminReadOnlyTests(tests.Modeltests): @@ -1003,32 +999,30 @@ class PagureAdminReadOnlyTests(tests.Modeltests): # Create the user pingou item = pagure.lib.model.User( - user='pingou', - fullname='PY C', - password='foo', - default_email='bar@pingou.com', + user="pingou", + fullname="PY C", + password="foo", + default_email="bar@pingou.com", ) self.session.add(item) - item = pagure.lib.model.UserEmail( - user_id=1, - email='bar@pingou.com') + item = pagure.lib.model.UserEmail(user_id=1, email="bar@pingou.com") self.session.add(item) # Create two projects for the user pingou item = pagure.lib.model.Project( user_id=1, # pingou - name='test', - description='namespaced test project', - hook_token='aaabbbeee', - namespace='somenamespace', + name="test", + description="namespaced test project", + hook_token="aaabbbeee", + namespace="somenamespace", ) self.session.add(item) item = pagure.lib.model.Project( user_id=1, # pingou - name='test', - description='Test project', - hook_token='aaabbbccc', + name="test", + description="Test project", + hook_token="aaabbbccc", namespace=None, ) self.session.add(item) @@ -1043,33 +1037,22 @@ class PagureAdminReadOnlyTests(tests.Modeltests): project. """ - args = munch.Munch({ - 'project': 'foob', - 'user': None, - 'ro': None, - }) + args = munch.Munch({"project": "foob", "user": None, "ro": None}) with self.assertRaises(pagure.exceptions.PagureException) as cm: pagure.cli.admin.do_read_only(args) - self.assertEqual( - cm.exception.args[0], - 'No project found with: foob' - ) + self.assertEqual(cm.exception.args[0], "No project found with: foob") def test_read_only_invalid_project(self): """ Test the read-only function of pagure-admin on an invalid project. """ - args = munch.Munch({ - 'project': 'fo/o/b', - 'user': None, - 'ro': None, - }) + args = munch.Munch({"project": "fo/o/b", "user": None, "ro": None}) with self.assertRaises(pagure.exceptions.PagureException) as cm: pagure.cli.admin.do_read_only(args) self.assertEqual( cm.exception.args[0], - 'Invalid project name, has more than one "/": fo/o/b' + 'Invalid project name, has more than one "/": fo/o/b', ) def test_read_only(self): @@ -1077,34 +1060,31 @@ class PagureAdminReadOnlyTests(tests.Modeltests): a non-namespaced project. """ - args = munch.Munch({ - 'project': 'test', - 'user': None, - 'ro': None, - }) + args = munch.Munch({"project": "test", "user": None, "ro": None}) with tests.capture_output() as output: pagure.cli.admin.do_read_only(args) output = output.getvalue() self.assertEqual( - 'The current read-only flag of the project test is set to True\n', - output) + "The current read-only flag of the project test is set to True\n", + output, + ) def test_read_only_namespace(self): """ Test the read-only function of pagure-admin to get status of a namespaced project. """ - args = munch.Munch({ - 'project': 'somenamespace/test', - 'user': None, - 'ro': None, - }) + args = munch.Munch( + {"project": "somenamespace/test", "user": None, "ro": None} + ) with tests.capture_output() as output: pagure.cli.admin.do_read_only(args) output = output.getvalue() self.assertEqual( - 'The current read-only flag of the project somenamespace/test '\ - 'is set to True\n', output) + "The current read-only flag of the project somenamespace/test " + "is set to True\n", + output, + ) def test_read_only_namespace_changed(self): """ Test the read-only function of pagure-admin to set the status of @@ -1112,42 +1092,42 @@ class PagureAdminReadOnlyTests(tests.Modeltests): """ # Before - args = munch.Munch({ - 'project': 'somenamespace/test', - 'user': None, - 'ro': None, - }) + args = munch.Munch( + {"project": "somenamespace/test", "user": None, "ro": None} + ) with tests.capture_output() as output: pagure.cli.admin.do_read_only(args) output = output.getvalue() self.assertEqual( - 'The current read-only flag of the project somenamespace/test '\ - 'is set to True\n', output) - - args = munch.Munch({ - 'project': 'somenamespace/test', - 'user': None, - 'ro': 'false', - }) + "The current read-only flag of the project somenamespace/test " + "is set to True\n", + output, + ) + + args = munch.Munch( + {"project": "somenamespace/test", "user": None, "ro": "false"} + ) with tests.capture_output() as output: pagure.cli.admin.do_read_only(args) output = output.getvalue() self.assertEqual( - 'The read-only flag of the project somenamespace/test has been ' - 'set to False\n', output) + "The read-only flag of the project somenamespace/test has been " + "set to False\n", + output, + ) # After - args = munch.Munch({ - 'project': 'somenamespace/test', - 'user': None, - 'ro': None, - }) + args = munch.Munch( + {"project": "somenamespace/test", "user": None, "ro": None} + ) with tests.capture_output() as output: pagure.cli.admin.do_read_only(args) output = output.getvalue() self.assertEqual( - 'The current read-only flag of the project somenamespace/test '\ - 'is set to False\n', output) + "The current read-only flag of the project somenamespace/test " + "is set to False\n", + output, + ) def test_read_only_no_change(self): """ Test the read-only function of pagure-admin to set the status of @@ -1155,42 +1135,35 @@ class PagureAdminReadOnlyTests(tests.Modeltests): """ # Before - args = munch.Munch({ - 'project': 'test', - 'user': None, - 'ro': None, - }) + args = munch.Munch({"project": "test", "user": None, "ro": None}) with tests.capture_output() as output: pagure.cli.admin.do_read_only(args) output = output.getvalue() self.assertEqual( - 'The current read-only flag of the project test '\ - 'is set to True\n', output) - - args = munch.Munch({ - 'project': 'test', - 'user': None, - 'ro': 'true', - }) + "The current read-only flag of the project test " + "is set to True\n", + output, + ) + + args = munch.Munch({"project": "test", "user": None, "ro": "true"}) with tests.capture_output() as output: pagure.cli.admin.do_read_only(args) output = output.getvalue() self.assertEqual( - 'The read-only flag of the project test has been ' - 'set to True\n', output) + "The read-only flag of the project test has been " "set to True\n", + output, + ) # After - args = munch.Munch({ - 'project': 'test', - 'user': None, - 'ro': None, - }) + args = munch.Munch({"project": "test", "user": None, "ro": None}) with tests.capture_output() as output: pagure.cli.admin.do_read_only(args) output = output.getvalue() self.assertEqual( - 'The current read-only flag of the project test '\ - 'is set to True\n', output) + "The current read-only flag of the project test " + "is set to True\n", + output, + ) class PagureNewGroupTests(tests.Modeltests): @@ -1205,15 +1178,13 @@ class PagureNewGroupTests(tests.Modeltests): # Create the user pingou item = pagure.lib.model.User( - user='pingou', - fullname='PY C', - password='foo', - default_email='bar@pingou.com', + user="pingou", + fullname="PY C", + password="foo", + default_email="bar@pingou.com", ) self.session.add(item) - item = pagure.lib.model.UserEmail( - user_id=1, - email='bar@pingou.com') + item = pagure.lib.model.UserEmail(user_id=1, email="bar@pingou.com") self.session.add(item) self.session.commit() @@ -1229,17 +1200,19 @@ class PagureNewGroupTests(tests.Modeltests): is missing from the args. """ - args = munch.Munch({ - 'group_name': 'foob', - 'display': None, - 'description': None, - 'username': 'pingou', - }) + args = munch.Munch( + { + "group_name": "foob", + "display": None, + "description": None, + "username": "pingou", + } + ) with self.assertRaises(pagure.exceptions.PagureException) as cm: pagure.cli.admin.do_new_group(args) self.assertEqual( cm.exception.args[0], - 'A display name must be provided for the group' + "A display name must be provided for the group", ) groups = pagure.lib.query.search_groups(self.session) @@ -1250,19 +1223,21 @@ class PagureNewGroupTests(tests.Modeltests): is missing from the args. """ - args = munch.Munch({ - 'group_name': 'foob', - 'display': 'foo group', - 'description': None, - 'username': None, - }) + args = munch.Munch( + { + "group_name": "foob", + "display": "foo group", + "description": None, + "username": None, + } + ) with self.assertRaises(pagure.exceptions.PagureException) as cm: pagure.cli.admin.do_new_group(args) self.assertEqual( cm.exception.args[0], - 'An username must be provided to associate with the group' + "An username must be provided to associate with the group", ) groups = pagure.lib.query.search_groups(self.session) @@ -1273,20 +1248,22 @@ class PagureNewGroupTests(tests.Modeltests): are provided. """ - args = munch.Munch({ - 'group_name': 'foob', - 'display': 'foo group', - 'description': None, - 'username': 'pingou', - }) + args = munch.Munch( + { + "group_name": "foob", + "display": "foo group", + "description": None, + "username": "pingou", + } + ) pagure.cli.admin.do_new_group(args) groups = pagure.lib.query.search_groups(self.session) self.assertEqual(len(groups), 1) - @patch.dict('pagure.config.config', {'ENABLE_GROUP_MNGT': False}) - @patch('pagure.cli.admin._ask_confirmation') + @patch.dict("pagure.config.config", {"ENABLE_GROUP_MNGT": False}) + @patch("pagure.cli.admin._ask_confirmation") def test_new_group_grp_mngt_off_no(self, conf): """ Test the new-group function of pagure-admin when all arguments are provided and ENABLE_GROUP_MNGT if off in the config and the user @@ -1294,20 +1271,22 @@ class PagureNewGroupTests(tests.Modeltests): """ conf.return_value = False - args = munch.Munch({ - 'group_name': 'foob', - 'display': 'foo group', - 'description': None, - 'username': 'pingou', - }) + args = munch.Munch( + { + "group_name": "foob", + "display": "foo group", + "description": None, + "username": "pingou", + } + ) pagure.cli.admin.do_new_group(args) groups = pagure.lib.query.search_groups(self.session) self.assertEqual(len(groups), 0) - @patch.dict('pagure.config.config', {'ENABLE_GROUP_MNGT': False}) - @patch('pagure.cli.admin._ask_confirmation') + @patch.dict("pagure.config.config", {"ENABLE_GROUP_MNGT": False}) + @patch("pagure.cli.admin._ask_confirmation") def test_new_group_grp_mngt_off_yes(self, conf): """ Test the new-group function of pagure-admin when all arguments are provided and ENABLE_GROUP_MNGT if off in the config and the user @@ -1315,37 +1294,41 @@ class PagureNewGroupTests(tests.Modeltests): """ conf.return_value = True - args = munch.Munch({ - 'group_name': 'foob', - 'display': 'foo group', - 'description': None, - 'username': 'pingou', - }) + args = munch.Munch( + { + "group_name": "foob", + "display": "foo group", + "description": None, + "username": "pingou", + } + ) pagure.cli.admin.do_new_group(args) groups = pagure.lib.query.search_groups(self.session) self.assertEqual(len(groups), 1) - @patch.dict('pagure.config.config', {'BLACKLISTED_GROUPS': ['foob']}) + @patch.dict("pagure.config.config", {"BLACKLISTED_GROUPS": ["foob"]}) def test_new_group_grp_mngt_off_yes(self): """ Test the new-group function of pagure-admin when all arguments are provided but the group is black listed. """ - args = munch.Munch({ - 'group_name': 'foob', - 'display': 'foo group', - 'description': None, - 'username': 'pingou', - }) + args = munch.Munch( + { + "group_name": "foob", + "display": "foo group", + "description": None, + "username": "pingou", + } + ) with self.assertRaises(pagure.exceptions.PagureException) as cm: pagure.cli.admin.do_new_group(args) self.assertEqual( cm.exception.args[0], - 'This group name has been blacklisted, please choose another one' + "This group name has been blacklisted, please choose another one", ) groups = pagure.lib.query.search_groups(self.session) @@ -1364,15 +1347,13 @@ class PagureListGroupEmptyTests(tests.Modeltests): # Create the user pingou item = pagure.lib.model.User( - user='pingou', - fullname='PY C', - password='foo', - default_email='bar@pingou.com', + user="pingou", + fullname="PY C", + password="foo", + default_email="bar@pingou.com", ) self.session.add(item) - item = pagure.lib.model.UserEmail( - user_id=1, - email='bar@pingou.com') + item = pagure.lib.model.UserEmail(user_id=1, email="bar@pingou.com") self.session.add(item) self.session.commit() @@ -1383,7 +1364,7 @@ class PagureListGroupEmptyTests(tests.Modeltests): groups = pagure.lib.query.search_groups(self.session) self.assertEqual(len(groups), 0) - @patch('sys.stdout', new_callable=StringIO) + @patch("sys.stdout", new_callable=StringIO) def test_no_groups(self, mock_stdout): """ Test the list-groups function of pagure-admin when there are no groups in the database @@ -1394,7 +1375,7 @@ class PagureListGroupEmptyTests(tests.Modeltests): self.assertEqual( mock_stdout.getvalue(), - 'No groups found in this pagure instance.\n' + "No groups found in this pagure instance.\n", ) groups = pagure.lib.query.search_groups(self.session) @@ -1413,27 +1394,25 @@ class PagureListGroupTests(tests.Modeltests): # Create the user pingou item = pagure.lib.model.User( - user='pingou', - fullname='PY C', - password='foo', - default_email='bar@pingou.com', + user="pingou", + fullname="PY C", + password="foo", + default_email="bar@pingou.com", ) self.session.add(item) - item = pagure.lib.model.UserEmail( - user_id=1, - email='bar@pingou.com') + item = pagure.lib.model.UserEmail(user_id=1, email="bar@pingou.com") self.session.add(item) # Create a group pagure.lib.query.add_group( self.session, - group_name='JL', - display_name='Justice League', - description='Nope, it\'s not JLA anymore', - group_type='user', - user='pingou', + group_name="JL", + display_name="Justice League", + description="Nope, it's not JLA anymore", + group_type="user", + user="pingou", is_admin=False, - blacklist=[] + blacklist=[], ) self.session.commit() @@ -1444,7 +1423,7 @@ class PagureListGroupTests(tests.Modeltests): groups = pagure.lib.query.search_groups(self.session) self.assertEqual(len(groups), 1) - @patch('sys.stdout', new_callable=StringIO) + @patch("sys.stdout", new_callable=StringIO) def test_list_groups(self, mock_stdout): """ Test the list-groups function of pagure-admin when there is one group in the database @@ -1455,8 +1434,7 @@ class PagureListGroupTests(tests.Modeltests): self.assertEqual( mock_stdout.getvalue(), - 'List of groups on this Pagure instance:\n' - 'Group: 1 - name JL\n' + "List of groups on this Pagure instance:\n" "Group: 1 - name JL\n", ) groups = pagure.lib.query.search_groups(self.session) @@ -1475,15 +1453,13 @@ class PagureBlockUserTests(tests.Modeltests): # Create the user pingou item = pagure.lib.model.User( - user='pingou', - fullname='PY C', - password='foo', - default_email='bar@pingou.com', + user="pingou", + fullname="PY C", + password="foo", + default_email="bar@pingou.com", ) self.session.add(item) - item = pagure.lib.model.UserEmail( - user_id=1, - email='bar@pingou.com') + item = pagure.lib.model.UserEmail(user_id=1, email="bar@pingou.com") self.session.add(item) self.session.commit() @@ -1491,7 +1467,7 @@ class PagureBlockUserTests(tests.Modeltests): # Make the imported pagure use the correct db session pagure.cli.admin.session = self.session - user = pagure.lib.query.get_user(self.session, 'pingou') + user = pagure.lib.query.get_user(self.session, "pingou") self.assertIsNone(user.refuse_sessions_before) def test_missing_date(self): @@ -1499,18 +1475,15 @@ class PagureBlockUserTests(tests.Modeltests): provided. """ - args = munch.Munch({ - 'username': 'pingou', - 'date': None, - }) + args = munch.Munch({"username": "pingou", "date": None}) with self.assertRaises(pagure.exceptions.PagureException) as cm: pagure.cli.admin.do_block_user(args) self.assertEqual( cm.exception.args[0], - 'Invalid date submitted: None, not of the format YYYY-MM-DD' + "Invalid date submitted: None, not of the format YYYY-MM-DD", ) - user = pagure.lib.query.get_user(self.session, 'pingou') + user = pagure.lib.query.get_user(self.session, "pingou") self.assertIsNone(user.refuse_sessions_before) def test_missing_username(self): @@ -1518,20 +1491,14 @@ class PagureBlockUserTests(tests.Modeltests): is missing from the args. """ - args = munch.Munch({ - 'date': '2018-06-11', - 'username': None, - }) + args = munch.Munch({"date": "2018-06-11", "username": None}) with self.assertRaises(pagure.exceptions.PagureException) as cm: pagure.cli.admin.do_block_user(args) - self.assertEqual( - cm.exception.args[0], - 'An username must be specified' - ) + self.assertEqual(cm.exception.args[0], "An username must be specified") - user = pagure.lib.query.get_user(self.session, 'pingou') + user = pagure.lib.query.get_user(self.session, "pingou") self.assertIsNone(user.refuse_sessions_before) def test_invalid_username(self): @@ -1539,20 +1506,14 @@ class PagureBlockUserTests(tests.Modeltests): provided does correspond to any user in the DB. """ - args = munch.Munch({ - 'date': '2018-06-11', - 'username': 'invalid' - }) + args = munch.Munch({"date": "2018-06-11", "username": "invalid"}) with self.assertRaises(pagure.exceptions.PagureException) as cm: pagure.cli.admin.do_block_user(args) - self.assertEqual( - cm.exception.args[0], - 'No user "invalid" found' - ) + self.assertEqual(cm.exception.args[0], 'No user "invalid" found') - user = pagure.lib.query.get_user(self.session, 'pingou') + user = pagure.lib.query.get_user(self.session, "pingou") self.assertIsNone(user.refuse_sessions_before) def test_invalide_date(self): @@ -1560,38 +1521,32 @@ class PagureBlockUserTests(tests.Modeltests): date is incorrect. """ - args = munch.Munch({ - 'date': '2018-14-05', - 'username': 'pingou', - }) + args = munch.Munch({"date": "2018-14-05", "username": "pingou"}) with self.assertRaises(pagure.exceptions.PagureException) as cm: pagure.cli.admin.do_block_user(args) self.assertEqual( cm.exception.args[0], - 'Invalid date submitted: 2018-14-05, not of the format YYYY-MM-DD' + "Invalid date submitted: 2018-14-05, not of the format YYYY-MM-DD", ) - user = pagure.lib.query.get_user(self.session, 'pingou') + user = pagure.lib.query.get_user(self.session, "pingou") self.assertIsNone(user.refuse_sessions_before) - @patch('pagure.cli.admin._ask_confirmation', MagicMock(return_value=True)) + @patch("pagure.cli.admin._ask_confirmation", MagicMock(return_value=True)) def test_block_user(self): """ Test the block-user function of pagure-admin when all arguments are provided correctly. """ - args = munch.Munch({ - 'date': '2050-12-31', - 'username': 'pingou', - }) + args = munch.Munch({"date": "2050-12-31", "username": "pingou"}) pagure.cli.admin.do_block_user(args) - user = pagure.lib.query.get_user(self.session, 'pingou') + user = pagure.lib.query.get_user(self.session, "pingou") self.assertIsNotNone(user.refuse_sessions_before) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/test_pagure_exclude_group_index.py b/tests/test_pagure_exclude_group_index.py index 7a5efc5..aca3dd6 100644 --- a/tests/test_pagure_exclude_group_index.py +++ b/tests/test_pagure_exclude_group_index.py @@ -17,13 +17,15 @@ import os import mock -sys.path.insert(0, os.path.join(os.path.dirname( - os.path.abspath(__file__)), '..')) +sys.path.insert( + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") +) import pagure.lib.query import pagure.lib.model import tests + class PagureExcludeGroupIndex(tests.Modeltests): """ Tests the EXCLUDE_GROUP_INDEX configuration key in pagure """ @@ -32,71 +34,66 @@ class PagureExcludeGroupIndex(tests.Modeltests): super(PagureExcludeGroupIndex, self).setUp() tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'repos'), bare=True) + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) # Create a ``provenpackger`` group: msg = pagure.lib.query.add_group( self.session, - group_name='provenpackager', - display_name='Proven Packagers', - description='Packagers having access to all the repo', - group_type='user', - user='pingou', + group_name="provenpackager", + display_name="Proven Packagers", + description="Packagers having access to all the repo", + group_type="user", + user="pingou", is_admin=False, blacklist=[], ) self.session.commit() self.assertEqual( - msg, 'User `pingou` added to the group `provenpackager`.') + msg, "User `pingou` added to the group `provenpackager`." + ) # Add the `provenpackager` group to the test2 project - project = pagure.lib.query._get_project(self.session, 'test2') + project = pagure.lib.query._get_project(self.session, "test2") msg = pagure.lib.query.add_group_to_project( session=self.session, project=project, - new_group='provenpackager', - user='pingou', + new_group="provenpackager", + user="pingou", ) self.session.commit() - self.assertEqual(msg, 'Group added') + self.assertEqual(msg, "Group added") def test_defaults_pingou(self): """ Test which repo pingou has by default. """ repos = pagure.lib.query.search_projects( - self.session, - username='pingou', - fork=False, + self.session, username="pingou", fork=False ) self.assertEqual(len(repos), 3) - for idx, name in enumerate(['test', 'test2', 'test3']): + for idx, name in enumerate(["test", "test2", "test3"]): self.assertEqual(repos[idx].name, name) def test_defaults_foo(self): """ Test which repo foo has by default. """ repos = pagure.lib.query.search_projects( - self.session, - username='foo', - fork=False, + self.session, username="foo", fork=False ) self.assertEqual(len(repos), 0) - def test_add_foo_test(self): """ Test adding foo to the test project. """ group = pagure.lib.query.search_groups( - self.session, group_name='provenpackager') - self.assertEqual(group.group_name, 'provenpackager') + self.session, group_name="provenpackager" + ) + self.assertEqual(group.group_name, "provenpackager") # List all foo's project before (ie: there should be none) repos = pagure.lib.query.search_projects( - self.session, - username='foo', - fork=False, + self.session, username="foo", fork=False ) self.assertEqual(len(repos), 0) @@ -104,47 +101,48 @@ class PagureExcludeGroupIndex(tests.Modeltests): # Adding `foo` to the `provenpackager` group msg = pagure.lib.query.add_user_to_group( self.session, - username='foo', + username="foo", group=group, - user='pingou', + user="pingou", is_admin=False, ) self.assertEqual( - msg, 'User `foo` added to the group `provenpackager`.') + msg, "User `foo` added to the group `provenpackager`." + ) # Test that foo has now one project, via the provenpackager group repos = pagure.lib.query.search_projects( - self.session, - username='foo', - fork=False, + self.session, username="foo", fork=False ) self.assertEqual(len(repos), 1) - self.assertEqual(repos[0].name, 'test2') + self.assertEqual(repos[0].name, "test2") def test_excluding_provenpackager(self): """ Test retrieving user's repo with a group excluded. """ # Add `foo` to `provenpackager` group = pagure.lib.query.search_groups( - self.session, group_name='provenpackager') - self.assertEqual(group.group_name, 'provenpackager') + self.session, group_name="provenpackager" + ) + self.assertEqual(group.group_name, "provenpackager") msg = pagure.lib.query.add_user_to_group( self.session, - username='foo', + username="foo", group=group, - user='pingou', + user="pingou", is_admin=False, ) self.assertEqual( - msg, 'User `foo` added to the group `provenpackager`.') + msg, "User `foo` added to the group `provenpackager`." + ) # Get foo's project outside of proven packager repos = pagure.lib.query.search_projects( self.session, - username='foo', - exclude_groups=['provenpackager'], + username="foo", + exclude_groups=["provenpackager"], fork=False, ) @@ -153,21 +151,19 @@ class PagureExcludeGroupIndex(tests.Modeltests): # Get pingou's project outside of proven packager (nothing changes) repos = pagure.lib.query.search_projects( self.session, - username='pingou', - exclude_groups=['provenpackager'], + username="pingou", + exclude_groups=["provenpackager"], fork=False, ) repos2 = pagure.lib.query.search_projects( - self.session, - username='pingou', - fork=False, + self.session, username="pingou", fork=False ) self.assertEqual(repos, repos2) self.assertEqual(len(repos), 3) - for idx, name in enumerate(['test', 'test2', 'test3']): + for idx, name in enumerate(["test", "test2", "test3"]): self.assertEqual(repos[idx].name, name) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/test_pagure_flask.py b/tests/test_pagure_flask.py index 45010dc..00e56ed 100644 --- a/tests/test_pagure_flask.py +++ b/tests/test_pagure_flask.py @@ -20,8 +20,9 @@ import munch import pygit2 import werkzeug -sys.path.insert(0, os.path.join(os.path.dirname( - os.path.abspath(__file__)), '..')) +sys.path.insert( + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") +) import pagure.lib.query import pagure.lib.model @@ -37,24 +38,29 @@ class PagureGetRemoteRepoPath(tests.SimplePagureTest): super(PagureGetRemoteRepoPath, self).setUp() tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'repos'), bare=True) - tests.add_content_git_repo(os.path.join(self.path, 'repos', 'test2.git')) + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) + tests.add_content_git_repo( + os.path.join(self.path, "repos", "test2.git") + ) @mock.patch( - 'pagure.lib.repo.PagureRepo.pull', - mock.MagicMock(side_effect=pygit2.GitError)) + "pagure.lib.repo.PagureRepo.pull", + mock.MagicMock(side_effect=pygit2.GitError), + ) def test_passing(self): """ Test get_remote_repo_path in pagure. """ output = pagure.utils.get_remote_repo_path( - os.path.join(self.path, 'repos', 'test2.git'), 'master', - ignore_non_exist=True) + os.path.join(self.path, "repos", "test2.git"), + "master", + ignore_non_exist=True, + ) - self.assertTrue(output.endswith('repos_test2.git_master')) + self.assertTrue(output.endswith("repos_test2.git_master")) def test_is_repo_committer_logged_out(self): """ Test is_repo_committer in pagure when there is no logged in user. """ - repo = pagure.lib.query._get_project(self.session, 'test') + repo = pagure.lib.query._get_project(self.session, "test") with self.app.application.app_context(): output = pagure.utils.is_repo_committer(repo) self.assertFalse(output) @@ -62,13 +68,13 @@ class PagureGetRemoteRepoPath(tests.SimplePagureTest): def test_is_repo_committer_logged_in(self): """ Test is_repo_committer in pagure with the appropriate user logged in. """ - repo = pagure.lib.query._get_project(self.session, 'test') + repo = pagure.lib.query._get_project(self.session, "test") g = munch.Munch() - g.fas_user = tests.FakeUser(username='pingou') + g.fas_user = tests.FakeUser(username="pingou") g.authenticated = True g.session = self.session - with mock.patch('flask.g', g): + with mock.patch("flask.g", g): output = pagure.utils.is_repo_committer(repo) self.assertTrue(output) @@ -78,45 +84,46 @@ class PagureGetRemoteRepoPath(tests.SimplePagureTest): # Create group msg = pagure.lib.query.add_group( self.session, - group_name='packager', - display_name='packager', - description='The Fedora packager groups', - group_type='user', - user='pingou', + group_name="packager", + display_name="packager", + description="The Fedora packager groups", + group_type="user", + user="pingou", is_admin=False, - blacklist=[]) + blacklist=[], + ) self.session.commit() - self.assertEqual(msg, 'User `pingou` added to the group `packager`.') + self.assertEqual(msg, "User `pingou` added to the group `packager`.") # Add user to group - group = pagure.lib.query.search_groups(self.session, group_name='packager') + group = pagure.lib.query.search_groups( + self.session, group_name="packager" + ) msg = pagure.lib.query.add_user_to_group( self.session, - username='foo', + username="foo", group=group, - user='pingou', - is_admin=True) + user="pingou", + is_admin=True, + ) self.session.commit() - self.assertEqual(msg, 'User `foo` added to the group `packager`.') + self.assertEqual(msg, "User `foo` added to the group `packager`.") # Add group packager to project test - project = pagure.lib.query._get_project(self.session, 'test') + project = pagure.lib.query._get_project(self.session, "test") msg = pagure.lib.query.add_group_to_project( - self.session, - project=project, - new_group='packager', - user='pingou', + self.session, project=project, new_group="packager", user="pingou" ) self.session.commit() - self.assertEqual(msg, 'Group added') + self.assertEqual(msg, "Group added") - repo = pagure.lib.query._get_project(self.session, 'test') + repo = pagure.lib.query._get_project(self.session, "test") g = munch.Munch() - g.fas_user = tests.FakeUser(username='foo') + g.fas_user = tests.FakeUser(username="foo") g.authenticated = True g.session = self.session - with mock.patch('flask.g', g): + with mock.patch("flask.g", g): output = pagure.utils.is_repo_committer(repo) self.assertTrue(output) @@ -126,195 +133,191 @@ class PagureGetRemoteRepoPath(tests.SimplePagureTest): # Create group msg = pagure.lib.query.add_group( self.session, - group_name='packager', - display_name='packager', - description='The Fedora packager groups', - group_type='user', - user='pingou', + group_name="packager", + display_name="packager", + description="The Fedora packager groups", + group_type="user", + user="pingou", is_admin=False, - blacklist=[]) + blacklist=[], + ) self.session.commit() - self.assertEqual(msg, 'User `pingou` added to the group `packager`.') + self.assertEqual(msg, "User `pingou` added to the group `packager`.") # Add user to group - group = pagure.lib.query.search_groups(self.session, group_name='packager') + group = pagure.lib.query.search_groups( + self.session, group_name="packager" + ) msg = pagure.lib.query.add_user_to_group( self.session, - username='foo', + username="foo", group=group, - user='pingou', - is_admin=True) + user="pingou", + is_admin=True, + ) self.session.commit() - self.assertEqual(msg, 'User `foo` added to the group `packager`.') + self.assertEqual(msg, "User `foo` added to the group `packager`.") # Add group packager to project test - project = pagure.lib.query._get_project(self.session, 'test') + project = pagure.lib.query._get_project(self.session, "test") msg = pagure.lib.query.add_group_to_project( self.session, project=project, - new_group='packager', - user='pingou', - access='ticket', + new_group="packager", + user="pingou", + access="ticket", ) self.session.commit() - self.assertEqual(msg, 'Group added') + self.assertEqual(msg, "Group added") - repo = pagure.lib.query._get_project(self.session, 'test') + repo = pagure.lib.query._get_project(self.session, "test") g = munch.Munch() - g.fas_user = tests.FakeUser(username='foo') + g.fas_user = tests.FakeUser(username="foo") g.authenticated = True g.session = self.session - with mock.patch('flask.g', g): + with mock.patch("flask.g", g): output = pagure.utils.is_repo_committer(repo) self.assertFalse(output) def test_is_repo_committer_logged_in_wrong_user(self): """ Test is_repo_committer in pagure with the wrong user logged in. """ - repo = pagure.lib.query._get_project(self.session, 'test') + repo = pagure.lib.query._get_project(self.session, "test") g = munch.Munch() g.fas_user = tests.FakeUser() g.authenticated = True g.session = self.session - with mock.patch('flask.g', g): + with mock.patch("flask.g", g): output = pagure.utils.is_repo_committer(repo) self.assertFalse(output) # Mocked config - config = { - 'provenpackager': {} - } + config = {"provenpackager": {}} - @mock.patch.dict('pagure.config.config', {'EXTERNAL_COMMITTER': config}) + @mock.patch.dict("pagure.config.config", {"EXTERNAL_COMMITTER": config}) def test_is_repo_committer_external_committer_generic_no_member(self): """ Test is_repo_committer in pagure with EXTERNAL_COMMITTER configured to give access to all the provenpackager, but the user is not one. """ - repo = pagure.lib.query._get_project(self.session, 'test') + repo = pagure.lib.query._get_project(self.session, "test") user = tests.FakeUser() g = munch.Munch() g.fas_user = user g.authenticated = True g.session = self.session - with mock.patch('flask.g', g): + with mock.patch("flask.g", g): output = pagure.utils.is_repo_committer(repo) self.assertFalse(output) - @mock.patch.dict('pagure.config.config', {'EXTERNAL_COMMITTER': config}) + @mock.patch.dict("pagure.config.config", {"EXTERNAL_COMMITTER": config}) def test_is_repo_committer_external_committer_generic_member(self): """ Test is_repo_committer in pagure with EXTERNAL_COMMITTER configured to give access to all the provenpackager, and the user is one """ - repo = pagure.lib.query._get_project(self.session, 'test') + repo = pagure.lib.query._get_project(self.session, "test") g = munch.Munch() - g.fas_user = tests.FakeUser(username='foo') - g.fas_user.groups.append('provenpackager') + g.fas_user = tests.FakeUser(username="foo") + g.fas_user.groups.append("provenpackager") g.authenticated = True g.session = self.session - with mock.patch('flask.g', g): + with mock.patch("flask.g", g): output = pagure.utils.is_repo_committer(repo) self.assertTrue(output) - config = { - 'provenpackager': { - 'exclude': ['test'] - } - } + config = {"provenpackager": {"exclude": ["test"]}} - @mock.patch.dict('pagure.config.config', {'EXTERNAL_COMMITTER': config}) + @mock.patch.dict("pagure.config.config", {"EXTERNAL_COMMITTER": config}) def test_is_repo_committer_external_committer_excluding_one(self): """ Test is_repo_committer in pagure with EXTERNAL_COMMITTER configured to give access to all the provenpackager but for this one repo """ - repo = pagure.lib.query._get_project(self.session, 'test') + repo = pagure.lib.query._get_project(self.session, "test") g = munch.Munch() g.fas_user = tests.FakeUser() - g.fas_user.groups.append('provenpackager') + g.fas_user.groups.append("provenpackager") g.authenticated = True g.session = self.session - with mock.patch('flask.g', g): + with mock.patch("flask.g", g): output = pagure.utils.is_repo_committer(repo) self.assertFalse(output) - @mock.patch.dict('pagure.config.config', {'EXTERNAL_COMMITTER': config}) + @mock.patch.dict("pagure.config.config", {"EXTERNAL_COMMITTER": config}) def test_is_repo_committer_owner_external_committer_excluding_one(self): """ Test is_repo_committer in pagure with EXTERNAL_COMMITTER configured to give access to all the provenpackager but for this one repo, but the user is still a direct committer """ - repo = pagure.lib.query._get_project(self.session, 'test') + repo = pagure.lib.query._get_project(self.session, "test") g = munch.Munch() - g.fas_user = tests.FakeUser(username='pingou') - g.fas_user.groups.append('provenpackager') + g.fas_user = tests.FakeUser(username="pingou") + g.fas_user.groups.append("provenpackager") g.authenticated = True g.session = self.session - with mock.patch('flask.g', g): + with mock.patch("flask.g", g): output = pagure.utils.is_repo_committer(repo) self.assertTrue(output) - config = { - 'provenpackager': { - 'restrict': ['test'] - } - } + config = {"provenpackager": {"restrict": ["test"]}} - @mock.patch.dict('pagure.config.config', {'EXTERNAL_COMMITTER': config}) + @mock.patch.dict("pagure.config.config", {"EXTERNAL_COMMITTER": config}) def test_is_repo_committer_external_committer_restricted_not_member(self): """ Test is_repo_committer in pagure with EXTERNAL_COMMITTER configured to give access the provenpackager just for one repo """ - repo = pagure.lib.query._get_project(self.session, 'test') + repo = pagure.lib.query._get_project(self.session, "test") g = munch.Munch() g.fas_user = tests.FakeUser() g.authenticated = True g.session = self.session - with mock.patch('flask.g', g): + with mock.patch("flask.g", g): output = pagure.utils.is_repo_committer(repo) self.assertFalse(output) - @mock.patch.dict('pagure.config.config', {'EXTERNAL_COMMITTER': config}) + @mock.patch.dict("pagure.config.config", {"EXTERNAL_COMMITTER": config}) def test_is_repo_committer_external_committer_restricting_to_one(self): """ Test is_repo_committer in pagure with EXTERNAL_COMMITTER configured to give access the provenpackager just for one repo """ - repo = pagure.lib.query._get_project(self.session, 'test') + repo = pagure.lib.query._get_project(self.session, "test") g = munch.Munch() - g.fas_user = tests.FakeUser(username='foo') + g.fas_user = tests.FakeUser(username="foo") g.authenticated = True - g.fas_user.groups.append('provenpackager') + g.fas_user.groups.append("provenpackager") g.session = self.session - with mock.patch('flask.g', g): + with mock.patch("flask.g", g): output = pagure.utils.is_repo_committer(repo) self.assertTrue(output) - @mock.patch.dict('pagure.config.config', {'EXTERNAL_COMMITTER': config}) - def test_is_repo_committer_external_committer_restricting_another_one(self): + @mock.patch.dict("pagure.config.config", {"EXTERNAL_COMMITTER": config}) + def test_is_repo_committer_external_committer_restricting_another_one( + self + ): """ Test is_repo_committer in pagure with EXTERNAL_COMMITTER configured to give access the provenpackager just for one repo not this one """ - repo = pagure.lib.query._get_project(self.session, 'test2') + repo = pagure.lib.query._get_project(self.session, "test2") g = munch.Munch() - g.fas_user = tests.FakeUser(username='foo') + g.fas_user = tests.FakeUser(username="foo") g.authenticated = True - g.fas_user.groups.append('provenpackager') + g.fas_user.groups.append("provenpackager") g.session = self.session - with mock.patch('flask.g', g): + with mock.patch("flask.g", g): output = pagure.utils.is_repo_committer(repo) self.assertFalse(output) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/test_pagure_flask_api.py b/tests/test_pagure_flask_api.py index 1bb5aa6..2cb96c0 100644 --- a/tests/test_pagure_flask_api.py +++ b/tests/test_pagure_flask_api.py @@ -18,8 +18,9 @@ import os import json from mock import patch, MagicMock -sys.path.insert(0, os.path.join(os.path.dirname( - os.path.abspath(__file__)), '..')) +sys.path.insert( + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") +) import pagure.api import pagure.flask_app @@ -35,168 +36,171 @@ class PagureFlaskApitests(tests.SimplePagureTest): def test_api_doc(self): """ Test the API documentation page. """ print(dir(self.app)) - output = self.app.get('/api/0/') + output = self.app.get("/api/0/") output_text = output.get_data(as_text=True) + self.assertIn(" API | pagure - Pagure\n", output_text) self.assertIn( - ' API | pagure - Pagure\n', output_text) - self.assertIn( - '  Pagure API Reference\n \n', output_text) + "  Pagure API Reference\n \n", output_text + ) def test_api_doc_authenticated(self): """ Test the API documentation page. """ - user = tests.FakeUser(username='foo') + user = tests.FakeUser(username="foo") with tests.user_set(self.app.application, user): - output = self.app.get('/api/0/') + output = self.app.get("/api/0/") output_text = output.get_data(as_text=True) self.assertIn( - ' API | pagure - Pagure\n', output_text) + " API | pagure - Pagure\n", output_text + ) self.assertIn( - '  Pagure API Reference\n \n', output_text) + "  Pagure API Reference\n \n", output_text + ) def test_api_get_request_data(self): - data = {'foo': 'bar'} + data = {"foo": "bar"} # test_request_context doesn't set flask.g, but some teardown # functions try to use that, so let's exclude them self._app.teardown_request_funcs = {} with self._app.test_request_context( - '/api/0/version', method="POST", data=data): - self.assertEqual(pagure.api.get_request_data()['foo'], 'bar') + "/api/0/version", method="POST", data=data + ): + self.assertEqual(pagure.api.get_request_data()["foo"], "bar") data = json.dumps(data) - with self._app.test_request_context('/api/0/version', data=data, - content_type='application/json'): - self.assertEqual(pagure.api.get_request_data()['foo'], 'bar') + with self._app.test_request_context( + "/api/0/version", data=data, content_type="application/json" + ): + self.assertEqual(pagure.api.get_request_data()["foo"], "bar") def test_api_version_old_url(self): """ Test the api_version function. """ - output = self.app.get('/api/0/version') + output = self.app.get("/api/0/version") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(data['version'], pagure.__api_version__) - self.assertEqual(sorted(data.keys()), ['version']) + self.assertEqual(data["version"], pagure.__api_version__) + self.assertEqual(sorted(data.keys()), ["version"]) def test_api_version_new_url(self): """ Test the api_version function at its new url. """ - output = self.app.get('/api/0/-/version') + output = self.app.get("/api/0/-/version") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(data['version'], pagure.__api_version__) - self.assertEqual(sorted(data.keys()), ['version']) + self.assertEqual(data["version"], pagure.__api_version__) + self.assertEqual(sorted(data.keys()), ["version"]) def test_api_project_tags(self): """ Test the api_project_tags function. """ tests.create_projects(self.session) - output = self.app.get('/api/0/foo/tags/') + output = self.app.get("/api/0/foo/tags/") self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(set(data.keys()), set(['output', 'error'])) - self.assertEqual(data['output'], 'notok') - self.assertEqual(data['error'], 'Project not found') + self.assertEqual(set(data.keys()), set(["output", "error"])) + self.assertEqual(data["output"], "notok") + self.assertEqual(data["error"], "Project not found") - output = self.app.get('/api/0/test/tags/') + output = self.app.get("/api/0/test/tags/") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(sorted(data.keys()), ['tags', 'total_tags']) - self.assertEqual(data['tags'], []) - self.assertEqual(data['total_tags'], 0) + self.assertEqual(sorted(data.keys()), ["tags", "total_tags"]) + self.assertEqual(data["tags"], []) + self.assertEqual(data["total_tags"], 0) # Add an issue and tag it so that we can list them item = pagure.lib.model.Issue( id=1, - uid='foobar', + uid="foobar", project_id=1, - title='issue', - content='a bug report', + title="issue", + content="a bug report", user_id=1, # pingou ) self.session.add(item) self.session.commit() item = pagure.lib.model.TagColored( - tag='tag1', tag_color='DeepBlueSky', project_id=1, + tag="tag1", tag_color="DeepBlueSky", project_id=1 ) self.session.add(item) self.session.commit() item = pagure.lib.model.TagIssueColored( - issue_uid='foobar', - tag_id=item.id + issue_uid="foobar", tag_id=item.id ) self.session.add(item) self.session.commit() - output = self.app.get('/api/0/test/tags/') + output = self.app.get("/api/0/test/tags/") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(sorted(data.keys()), ['tags', 'total_tags']) - self.assertEqual(data['tags'], ['tag1']) - self.assertEqual(data['total_tags'], 1) + self.assertEqual(sorted(data.keys()), ["tags", "total_tags"]) + self.assertEqual(data["tags"], ["tag1"]) + self.assertEqual(data["total_tags"], 1) - output = self.app.get('/api/0/test/tags/?pattern=t') + output = self.app.get("/api/0/test/tags/?pattern=t") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(sorted(data.keys()), ['tags', 'total_tags']) - self.assertEqual(data['tags'], ['tag1']) - self.assertEqual(data['total_tags'], 1) + self.assertEqual(sorted(data.keys()), ["tags", "total_tags"]) + self.assertEqual(data["tags"], ["tag1"]) + self.assertEqual(data["total_tags"], 1) - output = self.app.get('/api/0/test/tags/?pattern=p') + output = self.app.get("/api/0/test/tags/?pattern=p") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(sorted(data.keys()), ['tags', 'total_tags']) - self.assertEqual(data['tags'], []) - self.assertEqual(data['total_tags'], 0) + self.assertEqual(sorted(data.keys()), ["tags", "total_tags"]) + self.assertEqual(data["tags"], []) + self.assertEqual(data["total_tags"], 0) def test_api_groups(self): """ Test the api_groups function. """ # Add a couple of groups so that we can list them item = pagure.lib.model.PagureGroup( - group_name='group1', - group_type='user', - display_name='User group', + group_name="group1", + group_type="user", + display_name="User group", user_id=1, # pingou ) self.session.add(item) item = pagure.lib.model.PagureGroup( - group_name='rel-eng', - group_type='user', - display_name='Release engineering group', + group_name="rel-eng", + group_type="user", + display_name="Release engineering group", user_id=1, # pingou ) self.session.add(item) self.session.commit() - output = self.app.get('/api/0/groups') + output = self.app.get("/api/0/groups") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(data['groups'], ['group1', 'rel-eng']) + self.assertEqual(data["groups"], ["group1", "rel-eng"]) self.assertEqual( - sorted(data.keys()), - ['groups', 'pagination', 'total_groups']) - self.assertEqual(data['total_groups'], 2) + sorted(data.keys()), ["groups", "pagination", "total_groups"] + ) + self.assertEqual(data["total_groups"], 2) - output = self.app.get('/api/0/groups?pattern=re') + output = self.app.get("/api/0/groups?pattern=re") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(data['groups'], ['rel-eng']) + self.assertEqual(data["groups"], ["rel-eng"]) self.assertEqual( - sorted(data.keys()), - ['groups', 'pagination', 'total_groups']) - self.assertEqual(data['total_groups'], 1) + sorted(data.keys()), ["groups", "pagination", "total_groups"] + ) + self.assertEqual(data["total_groups"], 1) def test_api_whoami_unauth(self): """ Test the api_whoami function. """ - output = self.app.post('/api/0/-/whoami') + output = self.app.post("/api/0/-/whoami") self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) self.assertEqual( data, { - u'error': u'Invalid or expired token. Please visit ' - 'http://localhost.localdomain/settings#api-keys to get or ' - 'renew your API token.', - u'error_code': u'EINVALIDTOK' - } + "error": "Invalid or expired token. Please visit " + "http://localhost.localdomain/settings#api-keys to get or " + "renew your API token.", + "error_code": "EINVALIDTOK", + }, ) def test_api_whoami_invalid_auth(self): @@ -204,20 +208,20 @@ class PagureFlaskApitests(tests.SimplePagureTest): tests.create_projects(self.session) tests.create_tokens(self.session) - headers = {'Authorization': 'token invalid'} + headers = {"Authorization": "token invalid"} - output = self.app.post('/api/0/-/whoami', headers=headers) + output = self.app.post("/api/0/-/whoami", headers=headers) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) self.assertEqual( data, { - u'error': u'Invalid or expired token. Please visit ' - 'http://localhost.localdomain/settings#api-keys to get or ' - 'renew your API token.', - u'error_code': u'EINVALIDTOK', - u'errors': 'Invalid token', - } + "error": "Invalid or expired token. Please visit " + "http://localhost.localdomain/settings#api-keys to get or " + "renew your API token.", + "error_code": "EINVALIDTOK", + "errors": "Invalid token", + }, ) def test_api_whoami_auth(self): @@ -225,59 +229,61 @@ class PagureFlaskApitests(tests.SimplePagureTest): tests.create_projects(self.session) tests.create_tokens(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} - output = self.app.post('/api/0/-/whoami', headers=headers) + output = self.app.post("/api/0/-/whoami", headers=headers) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(data, {u'username': u'pingou'}) + self.assertEqual(data, {"username": "pingou"}) def test_api_error_codes(self): """ Test the api_error_codes endpoint. """ - output = self.app.get('/api/0/-/error_codes') + output = self.app.get("/api/0/-/error_codes") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertEqual(len(data), 36) self.assertEqual( sorted(data.keys()), - sorted([ - 'EDATETIME', - 'EDBERROR', - 'EGITERROR', - 'EINVALIDISSUEFIELD', - 'EINVALIDISSUEFIELD_LINK', - 'EINVALIDPERPAGEVALUE', - 'EINVALIDPRIORITY', - 'EINVALIDREQ', - 'EINVALIDTOK', - 'EISSUENOTALLOWED', - 'EMODIFYPROJECTNOTALLOWED', - 'ENEWPROJECTDISABLED', - 'ENOCODE', - 'ENOCOMMENT', - 'ENOCOMMIT', - 'ENOGROUP', - 'ENOISSUE', - 'ENOPRCLOSE', - 'ENOPROJECT', - 'ENOPROJECTS', - 'ENOPRSTATS', - 'ENOREQ', - 'ENOSIGNEDOFF', - 'ENOTASSIGNED', - 'ENOTASSIGNEE', - 'ENOTHIGHENOUGH', - 'ENOTMAINADMIN', - 'ENOUSER', - 'EPRCONFLICTS', - 'EPRNOTALLOWED', - 'EPRSCORE', - 'EPULLREQUESTSDISABLED', - 'ETIMESTAMP', - 'ETRACKERDISABLED', - 'ETRACKERREADONLY', - 'EUBLOCKED', - ]) + sorted( + [ + "EDATETIME", + "EDBERROR", + "EGITERROR", + "EINVALIDISSUEFIELD", + "EINVALIDISSUEFIELD_LINK", + "EINVALIDPERPAGEVALUE", + "EINVALIDPRIORITY", + "EINVALIDREQ", + "EINVALIDTOK", + "EISSUENOTALLOWED", + "EMODIFYPROJECTNOTALLOWED", + "ENEWPROJECTDISABLED", + "ENOCODE", + "ENOCOMMENT", + "ENOCOMMIT", + "ENOGROUP", + "ENOISSUE", + "ENOPRCLOSE", + "ENOPROJECT", + "ENOPROJECTS", + "ENOPRSTATS", + "ENOREQ", + "ENOSIGNEDOFF", + "ENOTASSIGNED", + "ENOTASSIGNEE", + "ENOTHIGHENOUGH", + "ENOTMAINADMIN", + "ENOUSER", + "EPRCONFLICTS", + "EPRNOTALLOWED", + "EPRSCORE", + "EPULLREQUESTSDISABLED", + "ETIMESTAMP", + "ETRACKERDISABLED", + "ETRACKERREADONLY", + "EUBLOCKED", + ] + ), ) @patch("pagure.lib.tasks.get_result") @@ -300,10 +306,9 @@ class PagureFlaskApitests(tests.SimplePagureTest): self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertEqual( - data, - {"ready": True, "status": "finished", "successful": True} + data, {"ready": True, "status": "finished", "successful": True} ) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/test_pagure_flask_api_auth.py b/tests/test_pagure_flask_api_auth.py index f0d6a64..d5c49b6 100644 --- a/tests/test_pagure_flask_api_auth.py +++ b/tests/test_pagure_flask_api_auth.py @@ -18,8 +18,9 @@ import os import json from mock import patch -sys.path.insert(0, os.path.join(os.path.dirname( - os.path.abspath(__file__)), '..')) +sys.path.insert( + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") +) import pagure.api import pagure.lib @@ -33,21 +34,23 @@ class PagureFlaskApiAuthtests(tests.SimplePagureTest): """ Test the authentication when there is nothing in the database. """ - output = self.app.post('/api/0/foo/new_issue') + output = self.app.post("/api/0/foo/new_issue") self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.name, - data['error_code']) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data['error']) + self.assertEqual( + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) - headers = {'Authorization': 'token aabbbccc'} + headers = {"Authorization": "token aabbbccc"} - output = self.app.post('/api/0/foo/new_issue', headers=headers) + output = self.app.post("/api/0/foo/new_issue", headers=headers) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.name, - data['error_code']) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data['error']) + self.assertEqual( + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) def test_auth_noacl(self): """ Test the authentication when the token does not have any ACL. @@ -55,21 +58,23 @@ class PagureFlaskApiAuthtests(tests.SimplePagureTest): tests.create_projects(self.session) tests.create_tokens(self.session) - output = self.app.post('/api/0/test/new_issue') + output = self.app.post("/api/0/test/new_issue") self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.name, - data['error_code']) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data['error']) + self.assertEqual( + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} - output = self.app.post('/api/0/test/new_issue', headers=headers) + output = self.app.post("/api/0/test/new_issue", headers=headers) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.name, - data['error_code']) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data['error']) + self.assertEqual( + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) def test_auth_expired(self): """ Test the authentication when the token has expired. @@ -77,21 +82,23 @@ class PagureFlaskApiAuthtests(tests.SimplePagureTest): tests.create_projects(self.session) tests.create_tokens(self.session) - output = self.app.post('/api/0/test/new_issue') + output = self.app.post("/api/0/test/new_issue") self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.name, - data['error_code']) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data['error']) + self.assertEqual( + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) - headers = {'Authorization': 'token expired_token'} + headers = {"Authorization": "token expired_token"} - output = self.app.post('/api/0/test/new_issue', headers=headers) + output = self.app.post("/api/0/test/new_issue", headers=headers) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.name, - data['error_code']) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data['error']) + self.assertEqual( + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) def test_auth(self): """ Test the token based authentication. @@ -100,30 +107,31 @@ class PagureFlaskApiAuthtests(tests.SimplePagureTest): tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - output = self.app.post('/api/0/test/new_issue') + output = self.app.post("/api/0/test/new_issue") self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.name, - data['error_code']) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data['error']) + self.assertEqual( + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} - output = self.app.post('/api/0/test/new_issue', headers=headers) + output = self.app.post("/api/0/test/new_issue", headers=headers) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - "error": "Invalid or incomplete input submitted", - "error_code": "EINVALIDREQ", - "errors": { - "issue_content": ["This field is required."], - "title": ["This field is required."] - } - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": { + "issue_content": ["This field is required."], + "title": ["This field is required."], + }, + }, ) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/test_pagure_flask_api_fork.py b/tests/test_pagure_flask_api_fork.py index 00acee5..b53759c 100644 --- a/tests/test_pagure_flask_api_fork.py +++ b/tests/test_pagure_flask_api_fork.py @@ -19,8 +19,9 @@ import os import json from mock import patch, MagicMock -sys.path.insert(0, os.path.join(os.path.dirname( - os.path.abspath(__file__)), '..')) +sys.path.insert( + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") +) import pagure.lib.query import pagure.default_config @@ -36,9 +37,9 @@ class PagureFlaskApiForktests(tests.Modeltests): """ Set up the environnment, ran before every tests. """ super(PagureFlaskApiForktests, self).setUp() - pagure.config.config['REQUESTS_FOLDER'] = None + pagure.config.config["REQUESTS_FOLDER"] = None - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_api_pull_request_views_pr_disabled(self): """ Test the api_pull_request_views method of the flask api when PR are disabled. """ @@ -48,41 +49,42 @@ class PagureFlaskApiForktests(tests.Modeltests): tests.create_tokens_acl(self.session) # Create a pull-request - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") forked_repo = pagure.lib.query.get_authorized_project( - self.session, 'test') + self.session, "test" + ) req = pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") settings = repo.settings - settings['pull_requests'] = False + settings["pull_requests"] = False repo.settings = settings self.session.add(repo) self.session.commit() - output = self.app.get('/api/0/test/pull-requests') + output = self.app.get("/api/0/test/pull-requests") self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - u'error': u'Pull-Request have been deactivated for this project', - u'error_code': u'EPULLREQUESTSDISABLED' - } + "error": "Pull-Request have been deactivated for this project", + "error_code": "EPULLREQUESTSDISABLED", + }, ) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_api_pull_request_views_pr_closed(self): """ Test the api_pull_request_views method of the flask api to list the closed PRs. """ @@ -92,164 +94,175 @@ class PagureFlaskApiForktests(tests.Modeltests): tests.create_tokens_acl(self.session) # Create a pull-request - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") forked_repo = pagure.lib.query.get_authorized_project( - self.session, 'test') + self.session, "test" + ) req = pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") - output = self.app.get('/api/0/test/pull-requests?status=closed') + output = self.app.get("/api/0/test/pull-requests?status=closed") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." self.assertDictEqual( data, { - u'args': { - u'assignee': None, - u'author': None, - u'page': 1, - u'per_page': 20, - u'status': u'closed' + "args": { + "assignee": None, + "author": None, + "page": 1, + "per_page": 20, + "status": "closed", }, - u'pagination': { - u'first': u'http://localhost...', - u'last': u'http://localhost...', - u'next': None, - u'page': 1, - u'pages': 0, - u'per_page': 20, - u'prev': None + "pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "page": 1, + "pages": 0, + "per_page": 20, + "prev": None, }, - u'requests': [], - u'total_requests': 0 - } + "requests": [], + "total_requests": 0, + }, ) # Close the PR and try again pagure.lib.query.close_pull_request( - self.session, request=req, user='pingou', merged=False) + self.session, request=req, user="pingou", merged=False + ) - output = self.app.get('/api/0/test/pull-requests?status=closed') + output = self.app.get("/api/0/test/pull-requests?status=closed") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertEqual( sorted(data.keys()), - ['args', 'pagination', 'requests', 'total_requests']) + ["args", "pagination", "requests", "total_requests"], + ) self.assertDictEqual( - data['args'], + data["args"], { - u'assignee': None, - u'author': None, - u'page': 1, - u'per_page': 20, - u'status': u'closed' - } + "assignee": None, + "author": None, + "page": 1, + "per_page": 20, + "status": "closed", + }, ) - self.assertEqual(data['total_requests'], 1) + self.assertEqual(data["total_requests"], 1) # Create two closed pull-requests - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test" + ) pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='closed pullrequest by user foo on repo test', - user='foo', - status='Closed', + branch_to="master", + title="closed pullrequest by user foo on repo test", + user="foo", + status="Closed", ) - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test" + ) pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='closed pullrequest by user pingou on repo test', - user='pingou', + branch_to="master", + title="closed pullrequest by user pingou on repo test", + user="pingou", status="Closed", ) self.session.commit() - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test" + ) pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='merged pullrequest by user pingou on repo test', - user='pingou', + branch_to="master", + title="merged pullrequest by user pingou on repo test", + user="pingou", status="Merged", ) self.session.commit() - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test" + ) pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='merged pullrequest by user foo on repo test', - user='foo', - status='Merged', + branch_to="master", + title="merged pullrequest by user foo on repo test", + user="foo", + status="Merged", ) self.session.commit() # Test the API view of closed pull-requests - output = self.app.get( - '/api/0/test/pull-requests?status=closed') + output = self.app.get("/api/0/test/pull-requests?status=closed") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 3) + self.assertEqual(len(data["requests"]), 3) self.assertEqual( sorted(data.keys()), - [u'args', u'pagination', u'requests', u'total_requests']) - for req in data['requests']: - self.assertEqual(req['status'], 'Closed') - self.assertEqual(data['args']['status'], "closed") - self.assertEqual(data['args']['page'], 1) + ["args", "pagination", "requests", "total_requests"], + ) + for req in data["requests"]: + self.assertEqual(req["status"], "Closed") + self.assertEqual(data["args"]["status"], "closed") + self.assertEqual(data["args"]["page"], 1) - self.assertEqual(data['total_requests'], 3) + self.assertEqual(data["total_requests"], 3) # Test the API view of merged pull-requests - output = self.app.get( - '/api/0/test/pull-requests?status=merged') + output = self.app.get("/api/0/test/pull-requests?status=merged") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 2) + self.assertEqual(len(data["requests"]), 2) self.assertEqual( sorted(data.keys()), - [u'args', u'pagination', u'requests', u'total_requests']) - for req in data['requests']: - self.assertEqual(req['status'], 'Merged') - self.assertEqual(data['args']['status'], "merged") - self.assertEqual(data['args']['page'], 1) - self.assertEqual(data['total_requests'], 2) - - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + ["args", "pagination", "requests", "total_requests"], + ) + for req in data["requests"]: + self.assertEqual(req["status"], "Merged") + self.assertEqual(data["args"]["status"], "merged") + self.assertEqual(data["args"]["page"], 1) + self.assertEqual(data["total_requests"], 2) + + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_api_pull_request_views_all_pr(self): """ Test the api_pull_request_views method of the flask api to list all PRs. """ @@ -259,64 +272,67 @@ class PagureFlaskApiForktests(tests.Modeltests): tests.create_tokens_acl(self.session) # Create a pull-request - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") forked_repo = pagure.lib.query.get_authorized_project( - self.session, 'test') + self.session, "test" + ) req = pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") - output = self.app.get('/api/0/test/pull-requests?status=all') + output = self.app.get("/api/0/test/pull-requests?status=all") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertEqual( sorted(data.keys()), - ['args', 'pagination', 'requests', 'total_requests']) + ["args", "pagination", "requests", "total_requests"], + ) self.assertDictEqual( - data['args'], + data["args"], { - u'assignee': None, - u'author': None, - u'page': 1, - u'per_page': 20, - u'status': u'all' - } + "assignee": None, + "author": None, + "page": 1, + "per_page": 20, + "status": "all", + }, ) - self.assertEqual(data['total_requests'], 1) + self.assertEqual(data["total_requests"], 1) # Close the PR and try again pagure.lib.query.close_pull_request( - self.session, request=req, user='pingou', - merged=False) + self.session, request=req, user="pingou", merged=False + ) - output = self.app.get('/api/0/test/pull-requests?status=all') + output = self.app.get("/api/0/test/pull-requests?status=all") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertEqual( sorted(data.keys()), - ['args', 'pagination', 'requests', 'total_requests']) + ["args", "pagination", "requests", "total_requests"], + ) self.assertDictEqual( - data['args'], + data["args"], { - u'assignee': None, - u'author': None, - u'page': 1, - u'per_page': 20, - u'status': u'all' - } + "assignee": None, + "author": None, + "page": 1, + "per_page": 20, + "status": "all", + }, ) - self.assertEqual(data['total_requests'], 1) + self.assertEqual(data["total_requests"], 1) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_pull_request_views(self, send_email): """ Test the api_pull_request_views method of the flask api. """ send_email.return_value = True @@ -326,187 +342,178 @@ class PagureFlaskApiForktests(tests.Modeltests): tests.create_tokens_acl(self.session) # Create a pull-request - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") forked_repo = pagure.lib.query.get_authorized_project( - self.session, 'test') + self.session, "test" + ) req = pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") # Invalid repo - output = self.app.get('/api/0/foo/pull-requests') + output = self.app.get("/api/0/foo/pull-requests") self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) # List pull-requests - output = self.app.get('/api/0/test/pull-requests') + output = self.app.get("/api/0/test/pull-requests") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['requests'][0]['date_created'] = '1431414800' - data['requests'][0]['updated_on'] = '1431414800' - data['requests'][0]['project']['date_created'] = '1431414800' - data['requests'][0]['project']['date_modified'] = '1431414800' - data['requests'][0]['repo_from']['date_created'] = '1431414800' - data['requests'][0]['repo_from']['date_modified'] = '1431414800' - data['requests'][0]['uid'] = '1431414800' - data['requests'][0]['last_updated'] = '1431414800' - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + data["requests"][0]["date_created"] = "1431414800" + data["requests"][0]["updated_on"] = "1431414800" + data["requests"][0]["project"]["date_created"] = "1431414800" + data["requests"][0]["project"]["date_modified"] = "1431414800" + data["requests"][0]["repo_from"]["date_created"] = "1431414800" + data["requests"][0]["repo_from"]["date_modified"] = "1431414800" + data["requests"][0]["uid"] = "1431414800" + data["requests"][0]["last_updated"] = "1431414800" + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." expected_data = { "args": { "assignee": None, "author": None, "page": 1, "per_page": 20, - "status": True + "status": True, }, - 'pagination': { - "first": 'http://localhost...', - "last": 'http://localhost...', - "next": None, - "page": 1, - "pages": 1, - "per_page": 20, - "prev": None + "pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "page": 1, + "pages": 1, + "per_page": 20, + "prev": None, }, - "requests": [{ - "assignee": None, - "branch": "master", - "branch_from": "master", - "cached_merge_status": "unknown", - "closed_at": None, - "closed_by": None, - "comments": [], - "commit_start": None, - "commit_stop": None, - "date_created": "1431414800", - "id": 1, - "initial_comment": None, - "last_updated": "1431414800", - "project": { - "access_groups": { - "admin": [], - "commit": [], - "ticket": [] - }, - "access_users": { - "admin": [], - "commit": [], - "owner": ["pingou"], - "ticket": [] - }, - "close_status": [ - "Invalid", - "Insufficient data", - "Fixed", - "Duplicate" - ], - "custom_keys": [], + "requests": [ + { + "assignee": None, + "branch": "master", + "branch_from": "master", + "cached_merge_status": "unknown", + "closed_at": None, + "closed_by": None, + "comments": [], + "commit_start": None, + "commit_stop": None, "date_created": "1431414800", - "date_modified": "1431414800", - "description": "test project #1", - "fullname": "test", - "url_path": "test", "id": 1, - "milestones": {}, - "name": "test", - "namespace": None, - "parent": None, - "priorities": {}, - "tags": [], - "user": { - "fullname": "PY C", - "name": "pingou" - } - }, - "remote_git": None, - "repo_from": { - "access_groups": { - "admin": [], - "commit": [], - "ticket": []}, - "access_users": { - "admin": [], - "commit": [], - "owner": ["pingou"], - "ticket": [] + "initial_comment": None, + "last_updated": "1431414800", + "project": { + "access_groups": { + "admin": [], + "commit": [], + "ticket": [], + }, + "access_users": { + "admin": [], + "commit": [], + "owner": ["pingou"], + "ticket": [], + }, + "close_status": [ + "Invalid", + "Insufficient data", + "Fixed", + "Duplicate", + ], + "custom_keys": [], + "date_created": "1431414800", + "date_modified": "1431414800", + "description": "test project #1", + "fullname": "test", + "url_path": "test", + "id": 1, + "milestones": {}, + "name": "test", + "namespace": None, + "parent": None, + "priorities": {}, + "tags": [], + "user": {"fullname": "PY C", "name": "pingou"}, }, - "close_status": [ - "Invalid", - "Insufficient data", - "Fixed", - "Duplicate" - ], - "custom_keys": [], - "date_created": "1431414800", - "date_modified": "1431414800", - "description": "test project #1", - "fullname": "test", - "url_path": "test", - "id": 1, - "milestones": {}, - "name": "test", - "namespace": None, - "parent": None, - "priorities": {}, + "remote_git": None, + "repo_from": { + "access_groups": { + "admin": [], + "commit": [], + "ticket": [], + }, + "access_users": { + "admin": [], + "commit": [], + "owner": ["pingou"], + "ticket": [], + }, + "close_status": [ + "Invalid", + "Insufficient data", + "Fixed", + "Duplicate", + ], + "custom_keys": [], + "date_created": "1431414800", + "date_modified": "1431414800", + "description": "test project #1", + "fullname": "test", + "url_path": "test", + "id": 1, + "milestones": {}, + "name": "test", + "namespace": None, + "parent": None, + "priorities": {}, + "tags": [], + "user": {"fullname": "PY C", "name": "pingou"}, + }, + "status": "Open", "tags": [], - "user": { - "fullname": "PY C", - "name": "pingou" - } - }, - "status": "Open", - "tags": [], - "threshold_reached": None, - "title": "test pull-request", - "uid": "1431414800", - "updated_on": "1431414800", - "user": { - "fullname": "PY C", - "name": "pingou" + "threshold_reached": None, + "title": "test pull-request", + "uid": "1431414800", + "updated_on": "1431414800", + "user": {"fullname": "PY C", "name": "pingou"}, } - }], - "total_requests": 1 + ], + "total_requests": 1, } self.assertDictEqual(data, expected_data) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Access Pull-Request authenticated - output = self.app.get('/api/0/test/pull-requests', headers=headers) + output = self.app.get("/api/0/test/pull-requests", headers=headers) self.assertEqual(output.status_code, 200) data2 = json.loads(output.get_data(as_text=True)) - data2['requests'][0]['date_created'] = '1431414800' - data2['requests'][0]['updated_on'] = '1431414800' - data2['requests'][0]['project']['date_created'] = '1431414800' - data2['requests'][0]['project']['date_modified'] = '1431414800' - data2['requests'][0]['repo_from']['date_created'] = '1431414800' - data2['requests'][0]['repo_from']['date_modified'] = '1431414800' - data2['requests'][0]['uid'] = '1431414800' - data2['requests'][0]['last_updated'] = '1431414800' - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data2['pagination'][k] = 'http://localhost...' + data2["requests"][0]["date_created"] = "1431414800" + data2["requests"][0]["updated_on"] = "1431414800" + data2["requests"][0]["project"]["date_created"] = "1431414800" + data2["requests"][0]["project"]["date_modified"] = "1431414800" + data2["requests"][0]["repo_from"]["date_created"] = "1431414800" + data2["requests"][0]["repo_from"]["date_modified"] = "1431414800" + data2["requests"][0]["uid"] = "1431414800" + data2["requests"][0]["last_updated"] = "1431414800" + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data2["pagination"][k] = "http://localhost..." self.assertDictEqual(data, data2) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_pull_request_view_pr_disabled(self, send_email): """ Test the api_pull_request_view method of the flask api. """ send_email.return_value = True @@ -515,40 +522,42 @@ class PagureFlaskApiForktests(tests.Modeltests): tests.create_tokens_acl(self.session) # Create a pull-request - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test" + ) req = pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") settings = repo.settings - settings['pull_requests'] = False + settings["pull_requests"] = False repo.settings = settings self.session.add(repo) self.session.commit() - output = self.app.get('/api/0/test/pull-request/1') + output = self.app.get("/api/0/test/pull-request/1") self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - u'error': u'Pull-Request have been deactivated for this project', - u'error_code': u'EPULLREQUESTSDISABLED' - } + "error": "Pull-Request have been deactivated for this project", + "error_code": "EPULLREQUESTSDISABLED", + }, ) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_pull_request_view(self, send_email): """ Test the api_pull_request_view method of the flask api. """ send_email.return_value = True @@ -557,57 +566,51 @@ class PagureFlaskApiForktests(tests.Modeltests): tests.create_tokens_acl(self.session) # Create a pull-request - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test" + ) req = pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") # Invalid repo - output = self.app.get('/api/0/foo/pull-request/1') + output = self.app.get("/api/0/foo/pull-request/1") self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) # Invalid issue for this repo - output = self.app.get('/api/0/test2/pull-request/1') + output = self.app.get("/api/0/test2/pull-request/1") self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Pull-Request not found", - "error_code": "ENOREQ", - } + data, {"error": "Pull-Request not found", "error_code": "ENOREQ"} ) # Valid issue - output = self.app.get('/api/0/test/pull-request/1') + output = self.app.get("/api/0/test/pull-request/1") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['date_created'] = '1431414800' - data['updated_on'] = '1431414800' - data['project']['date_created'] = '1431414800' - data['project']['date_modified'] = '1431414800' - data['repo_from']['date_created'] = '1431414800' - data['repo_from']['date_modified'] = '1431414800' - data['uid'] = '1431414800' - data['last_updated'] = '1431414800' + data["date_created"] = "1431414800" + data["updated_on"] = "1431414800" + data["project"]["date_created"] = "1431414800" + data["project"]["date_modified"] = "1431414800" + data["repo_from"]["date_created"] = "1431414800" + data["repo_from"]["date_modified"] = "1431414800" + data["uid"] = "1431414800" + data["last_updated"] = "1431414800" expected_data = { "assignee": None, "branch": "master", @@ -623,22 +626,18 @@ class PagureFlaskApiForktests(tests.Modeltests): "initial_comment": None, "last_updated": "1431414800", "project": { - "access_groups": { - "admin": [], - "commit": [], - "ticket": [] - }, + "access_groups": {"admin": [], "commit": [], "ticket": []}, "access_users": { "admin": [], "commit": [], "owner": ["pingou"], - "ticket": [] + "ticket": [], }, "close_status": [ "Invalid", "Insufficient data", "Fixed", - "Duplicate" + "Duplicate", ], "custom_keys": [], "date_created": "1431414800", @@ -653,44 +652,37 @@ class PagureFlaskApiForktests(tests.Modeltests): "parent": None, "priorities": {}, "tags": [], - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, }, "remote_git": None, "repo_from": { - "access_groups": { - "admin": [], - "commit": [], - "ticket": []}, + "access_groups": {"admin": [], "commit": [], "ticket": []}, "access_users": { "admin": [], "commit": [], "owner": ["pingou"], - "ticket": []}, + "ticket": [], + }, "close_status": [ "Invalid", "Insufficient data", "Fixed", - "Duplicate"], - "custom_keys": [], - "date_created": "1431414800", - "date_modified": "1431414800", - "description": "test project #1", - "fullname": "test", - "url_path": "test", - "id": 1, - "milestones": {}, - "name": "test", - "namespace": None, - "parent": None, - "priorities": {}, - "tags": [], - "user": { - "fullname": "PY C", - "name": "pingou" - } + "Duplicate", + ], + "custom_keys": [], + "date_created": "1431414800", + "date_modified": "1431414800", + "description": "test project #1", + "fullname": "test", + "url_path": "test", + "id": 1, + "milestones": {}, + "name": "test", + "namespace": None, + "parent": None, + "priorities": {}, + "tags": [], + "user": {"fullname": "PY C", "name": "pingou"}, }, "status": "Open", "tags": [], @@ -698,31 +690,28 @@ class PagureFlaskApiForktests(tests.Modeltests): "title": "test pull-request", "uid": "1431414800", "updated_on": "1431414800", - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, } self.assertDictEqual(data, expected_data) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Access Pull-Request authenticated - output = self.app.get('/api/0/test/pull-request/1', headers=headers) + output = self.app.get("/api/0/test/pull-request/1", headers=headers) self.assertEqual(output.status_code, 200) data2 = json.loads(output.get_data(as_text=True)) - data2['date_created'] = '1431414800' - data2['project']['date_created'] = '1431414800' - data2['project']['date_modified'] = '1431414800' - data2['repo_from']['date_created'] = '1431414800' - data2['repo_from']['date_modified'] = '1431414800' - data2['uid'] = '1431414800' - data2['date_created'] = '1431414800' - data2['updated_on'] = '1431414800' - data2['last_updated'] = '1431414800' + data2["date_created"] = "1431414800" + data2["project"]["date_created"] = "1431414800" + data2["project"]["date_modified"] = "1431414800" + data2["repo_from"]["date_created"] = "1431414800" + data2["repo_from"]["date_modified"] = "1431414800" + data2["uid"] = "1431414800" + data2["date_created"] = "1431414800" + data2["updated_on"] = "1431414800" + data2["last_updated"] = "1431414800" self.assertDictEqual(data, data2) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_pull_request_by_uid_view(self, send_email): """ Test the api_pull_request_by_uid_view method of the flask api. """ send_email.return_value = True @@ -731,45 +720,43 @@ class PagureFlaskApiForktests(tests.Modeltests): tests.create_tokens_acl(self.session) # Create a pull-request - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test" + ) req = pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") uid = req.uid # Invalid request - output = self.app.get('/api/0/pull-requests/{}'.format(uid + 'aaa')) + output = self.app.get("/api/0/pull-requests/{}".format(uid + "aaa")) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Pull-Request not found", - "error_code": "ENOREQ", - } + data, {"error": "Pull-Request not found", "error_code": "ENOREQ"} ) # Valid issue - output = self.app.get('/api/0/pull-requests/{}'.format(uid)) + output = self.app.get("/api/0/pull-requests/{}".format(uid)) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['date_created'] = '1431414800' - data['updated_on'] = '1431414800' - data['project']['date_created'] = '1431414800' - data['project']['date_modified'] = '1431414800' - data['repo_from']['date_created'] = '1431414800' - data['repo_from']['date_modified'] = '1431414800' - data['last_updated'] = '1431414800' + data["date_created"] = "1431414800" + data["updated_on"] = "1431414800" + data["project"]["date_created"] = "1431414800" + data["project"]["date_modified"] = "1431414800" + data["repo_from"]["date_created"] = "1431414800" + data["repo_from"]["date_modified"] = "1431414800" + data["last_updated"] = "1431414800" expected_data = { "assignee": None, "branch": "master", @@ -785,22 +772,18 @@ class PagureFlaskApiForktests(tests.Modeltests): "initial_comment": None, "last_updated": "1431414800", "project": { - "access_groups": { - "admin": [], - "commit": [], - "ticket": [] - }, + "access_groups": {"admin": [], "commit": [], "ticket": []}, "access_users": { "admin": [], "commit": [], "owner": ["pingou"], - "ticket": [] + "ticket": [], }, "close_status": [ "Invalid", "Insufficient data", "Fixed", - "Duplicate" + "Duplicate", ], "custom_keys": [], "date_created": "1431414800", @@ -815,44 +798,37 @@ class PagureFlaskApiForktests(tests.Modeltests): "parent": None, "priorities": {}, "tags": [], - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, }, "remote_git": None, "repo_from": { - "access_groups": { - "admin": [], - "commit": [], - "ticket": []}, + "access_groups": {"admin": [], "commit": [], "ticket": []}, "access_users": { "admin": [], "commit": [], "owner": ["pingou"], - "ticket": []}, + "ticket": [], + }, "close_status": [ "Invalid", "Insufficient data", "Fixed", - "Duplicate"], - "custom_keys": [], - "date_created": "1431414800", - "date_modified": "1431414800", - "description": "test project #1", - "fullname": "test", - "url_path": "test", - "id": 1, - "milestones": {}, - "name": "test", - "namespace": None, - "parent": None, - "priorities": {}, - "tags": [], - "user": { - "fullname": "PY C", - "name": "pingou" - } + "Duplicate", + ], + "custom_keys": [], + "date_created": "1431414800", + "date_modified": "1431414800", + "description": "test project #1", + "fullname": "test", + "url_path": "test", + "id": 1, + "milestones": {}, + "name": "test", + "namespace": None, + "parent": None, + "priorities": {}, + "tags": [], + "user": {"fullname": "PY C", "name": "pingou"}, }, "status": "Open", "tags": [], @@ -860,30 +836,29 @@ class PagureFlaskApiForktests(tests.Modeltests): "title": "test pull-request", "uid": uid, "updated_on": "1431414800", - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, } self.assertDictEqual(data, expected_data) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Access Pull-Request authenticated - output = self.app.get('/api/0/pull-requests/{}'.format(uid), headers=headers) + output = self.app.get( + "/api/0/pull-requests/{}".format(uid), headers=headers + ) self.assertEqual(output.status_code, 200) data2 = json.loads(output.get_data(as_text=True)) - data2['date_created'] = '1431414800' - data2['project']['date_created'] = '1431414800' - data2['project']['date_modified'] = '1431414800' - data2['repo_from']['date_created'] = '1431414800' - data2['repo_from']['date_modified'] = '1431414800' - data2['date_created'] = '1431414800' - data2['updated_on'] = '1431414800' - data2['last_updated'] = '1431414800' + data2["date_created"] = "1431414800" + data2["project"]["date_created"] = "1431414800" + data2["project"]["date_modified"] = "1431414800" + data2["repo_from"]["date_created"] = "1431414800" + data2["repo_from"]["date_modified"] = "1431414800" + data2["date_created"] = "1431414800" + data2["updated_on"] = "1431414800" + data2["last_updated"] = "1431414800" self.assertDictEqual(data, data2) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_pull_request_close_pr_disabled(self, send_email): """ Test the api_pull_request_close method of the flask api. """ send_email.return_value = True @@ -893,43 +868,46 @@ class PagureFlaskApiForktests(tests.Modeltests): tests.create_tokens_acl(self.session) # Create the pull-request to close - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test" + ) req = pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") settings = repo.settings - settings['pull_requests'] = False + settings["pull_requests"] = False repo.settings = settings self.session.add(repo) self.session.commit() - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} output = self.app.post( - '/api/0/test/pull-request/1/close', headers=headers) + "/api/0/test/pull-request/1/close", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - u'error': u'Pull-Request have been deactivated for this project', - u'error_code': u'EPULLREQUESTSDISABLED' - } + "error": "Pull-Request have been deactivated for this project", + "error_code": "EPULLREQUESTSDISABLED", + }, ) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_pull_request_close(self, send_email): """ Test the api_pull_request_close method of the flask api. """ send_email.return_value = True @@ -939,62 +917,63 @@ class PagureFlaskApiForktests(tests.Modeltests): tests.create_tokens_acl(self.session) # Create the pull-request to close - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test" + ) req = pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Invalid project output = self.app.post( - '/api/0/foo/pull-request/1/close', headers=headers) + "/api/0/foo/pull-request/1/close", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) # Valid token, wrong project output = self.app.post( - '/api/0/test2/pull-request/1/close', headers=headers) + "/api/0/test2/pull-request/1/close", headers=headers + ) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.name, - data['error_code']) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data['error']) + self.assertEqual( + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) # Invalid PR output = self.app.post( - '/api/0/test/pull-request/2/close', headers=headers) + "/api/0/test/pull-request/2/close", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - {'error': 'Pull-Request not found', 'error_code': "ENOREQ"} + data, {"error": "Pull-Request not found", "error_code": "ENOREQ"} ) # Create a token for foo for this project item = pagure.lib.model.Token( - id='foobar_token', + id="foobar_token", user_id=2, project_id=1, - expiration=datetime.datetime.utcnow() + datetime.timedelta( - days=30) + expiration=datetime.datetime.utcnow() + + datetime.timedelta(days=30), ) self.session.add(item) self.session.commit() @@ -1002,333 +981,355 @@ class PagureFlaskApiForktests(tests.Modeltests): # Allow the token to close PR acls = pagure.lib.query.get_acls(self.session) for acl in acls: - if acl.name == 'pull_request_close': + if acl.name == "pull_request_close": break item = pagure.lib.model.TokenAcl( - token_id='foobar_token', - acl_id=acl.id, + token_id="foobar_token", acl_id=acl.id ) self.session.add(item) self.session.commit() - headers = {'Authorization': 'token foobar_token'} + headers = {"Authorization": "token foobar_token"} # User not admin output = self.app.post( - '/api/0/test/pull-request/1/close', headers=headers) + "/api/0/test/pull-request/1/close", headers=headers + ) self.assertEqual(output.status_code, 403) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - 'error': 'You are not allowed to merge/close pull-request ' - 'for this project', - 'error_code': "ENOPRCLOSE", - } + "error": "You are not allowed to merge/close pull-request " + "for this project", + "error_code": "ENOPRCLOSE", + }, ) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Close PR output = self.app.post( - '/api/0/test/pull-request/1/close', headers=headers) + "/api/0/test/pull-request/1/close", headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {"message": "Pull-request closed!"} - ) + self.assertDictEqual(data, {"message": "Pull-request closed!"}) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_pull_request_merge_pr_disabled(self, send_email): """ Test the api_pull_request_merge method of the flask api when PR are disabled. """ send_email.return_value = True tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'repos'), bare=True) - tests.create_projects_git(os.path.join(self.path, 'requests'), - bare=True) - tests.add_readme_git_repo(os.path.join(self.path, 'repos', 'test.git')) - tests.add_commit_git_repo(os.path.join(self.path, 'repos', 'test.git'), - branch='test') + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) + tests.create_projects_git( + os.path.join(self.path, "requests"), bare=True + ) + tests.add_readme_git_repo(os.path.join(self.path, "repos", "test.git")) + tests.add_commit_git_repo( + os.path.join(self.path, "repos", "test.git"), branch="test" + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Create the pull-request to close - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test" + ) req = pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='test', + branch_from="test", repo_to=repo, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") settings = repo.settings - settings['pull_requests'] = False + settings["pull_requests"] = False repo.settings = settings self.session.add(repo) self.session.commit() - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} output = self.app.post( - '/api/0/test/pull-request/1/merge', headers=headers) + "/api/0/test/pull-request/1/merge", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - u'error': u'Pull-Request have been deactivated for this project', - u'error_code': u'EPULLREQUESTSDISABLED' - } + "error": "Pull-Request have been deactivated for this project", + "error_code": "EPULLREQUESTSDISABLED", + }, ) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_pull_request_merge_only_assigned(self, send_email): """ Test the api_pull_request_merge method of the flask api when only assignee can merge the PR and the PR isn't assigned. """ send_email.return_value = True tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'repos'), bare=True) - tests.create_projects_git(os.path.join(self.path, 'requests'), - bare=True) - tests.add_readme_git_repo(os.path.join(self.path, 'repos', 'test.git')) - tests.add_commit_git_repo(os.path.join(self.path, 'repos', 'test.git'), - branch='test') + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) + tests.create_projects_git( + os.path.join(self.path, "requests"), bare=True + ) + tests.add_readme_git_repo(os.path.join(self.path, "repos", "test.git")) + tests.add_commit_git_repo( + os.path.join(self.path, "repos", "test.git"), branch="test" + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Create the pull-request to close - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test" + ) req = pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='test', + branch_from="test", repo_to=repo, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") settings = repo.settings - settings['Only_assignee_can_merge_pull-request'] = True + settings["Only_assignee_can_merge_pull-request"] = True repo.settings = settings self.session.add(repo) self.session.commit() - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} output = self.app.post( - '/api/0/test/pull-request/1/merge', headers=headers) + "/api/0/test/pull-request/1/merge", headers=headers + ) self.assertEqual(output.status_code, 403) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - u'error': u'This request must be assigned to be merged', - u'error_code': u'ENOTASSIGNED' - } + "error": "This request must be assigned to be merged", + "error_code": "ENOTASSIGNED", + }, ) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_pull_request_merge_only_assigned_not_assignee( - self, send_email): + self, send_email + ): """ Test the api_pull_request_merge method of the flask api when only assignee can merge the PR and the PR isn't assigned to the user asking to merge. """ send_email.return_value = True tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'repos'), bare=True) - tests.create_projects_git(os.path.join(self.path, 'requests'), - bare=True) - tests.add_readme_git_repo(os.path.join(self.path, 'repos', 'test.git')) - tests.add_commit_git_repo(os.path.join(self.path, 'repos', 'test.git'), - branch='test') + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) + tests.create_projects_git( + os.path.join(self.path, "requests"), bare=True + ) + tests.add_readme_git_repo(os.path.join(self.path, "repos", "test.git")) + tests.add_commit_git_repo( + os.path.join(self.path, "repos", "test.git"), branch="test" + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Create the pull-request to close - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test" + ) req = pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='test', + branch_from="test", repo_to=repo, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') - req.assignee = pagure.lib.query.search_user(self.session, 'foo') + self.assertEqual(req.title, "test pull-request") + req.assignee = pagure.lib.query.search_user(self.session, "foo") self.session.add(req) self.session.commit() - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") settings = repo.settings - settings['Only_assignee_can_merge_pull-request'] = True + settings["Only_assignee_can_merge_pull-request"] = True repo.settings = settings self.session.add(repo) self.session.commit() - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} output = self.app.post( - '/api/0/test/pull-request/1/merge', headers=headers) + "/api/0/test/pull-request/1/merge", headers=headers + ) self.assertEqual(output.status_code, 403) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - u'error': u'Only the assignee can merge this review', - u'error_code': u'ENOTASSIGNEE' - } + "error": "Only the assignee can merge this review", + "error_code": "ENOTASSIGNEE", + }, ) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_pull_request_merge_minimal_score(self, send_email): """ Test the api_pull_request_merge method of the flask api when a PR requires a certain minimal score to be merged. """ send_email.return_value = True tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'repos'), bare=True) - tests.create_projects_git(os.path.join(self.path, 'requests'), - bare=True) - tests.add_readme_git_repo(os.path.join(self.path, 'repos', 'test.git')) - tests.add_commit_git_repo(os.path.join(self.path, 'repos', 'test.git'), - branch='test') + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) + tests.create_projects_git( + os.path.join(self.path, "requests"), bare=True + ) + tests.add_readme_git_repo(os.path.join(self.path, "repos", "test.git")) + tests.add_commit_git_repo( + os.path.join(self.path, "repos", "test.git"), branch="test" + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Create the pull-request to close - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test" + ) req = pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='test', + branch_from="test", repo_to=repo, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") settings = repo.settings - settings['Minimum_score_to_merge_pull-request'] = 2 + settings["Minimum_score_to_merge_pull-request"] = 2 repo.settings = settings self.session.add(repo) self.session.commit() - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} output = self.app.post( - '/api/0/test/pull-request/1/merge', headers=headers) + "/api/0/test/pull-request/1/merge", headers=headers + ) self.assertEqual(output.status_code, 403) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - u'error': u'This request does not have the minimum review ' - 'score necessary to be merged', - u'error_code': u'EPRSCORE' - } + "error": "This request does not have the minimum review " + "score necessary to be merged", + "error_code": "EPRSCORE", + }, ) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_pull_request_merge(self, send_email): """ Test the api_pull_request_merge method of the flask api. """ send_email.return_value = True tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'repos'), bare=True) - tests.create_projects_git(os.path.join(self.path, 'requests'), - bare=True) - tests.add_readme_git_repo(os.path.join(self.path, 'repos', 'test.git')) - tests.add_commit_git_repo(os.path.join(self.path, 'repos', 'test.git'), - branch='test') + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) + tests.create_projects_git( + os.path.join(self.path, "requests"), bare=True + ) + tests.add_readme_git_repo(os.path.join(self.path, "repos", "test.git")) + tests.add_commit_git_repo( + os.path.join(self.path, "repos", "test.git"), branch="test" + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Create the pull-request to close - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test" + ) req = pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='test', + branch_from="test", repo_to=repo, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Invalid project output = self.app.post( - '/api/0/foo/pull-request/1/merge', headers=headers) + "/api/0/foo/pull-request/1/merge", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) # Valid token, wrong project output = self.app.post( - '/api/0/test2/pull-request/1/merge', headers=headers) + "/api/0/test2/pull-request/1/merge", headers=headers + ) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.name, - data['error_code']) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data['error']) + self.assertEqual( + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) # Invalid PR output = self.app.post( - '/api/0/test/pull-request/2/merge', headers=headers) + "/api/0/test/pull-request/2/merge", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - {'error': 'Pull-Request not found', 'error_code': "ENOREQ"} + data, {"error": "Pull-Request not found", "error_code": "ENOREQ"} ) # Create a token for foo for this project item = pagure.lib.model.Token( - id='foobar_token', + id="foobar_token", user_id=2, project_id=1, - expiration=datetime.datetime.utcnow() + datetime.timedelta( - days=30) + expiration=datetime.datetime.utcnow() + + datetime.timedelta(days=30), ) self.session.add(item) self.session.commit() @@ -1336,84 +1337,84 @@ class PagureFlaskApiForktests(tests.Modeltests): # Allow the token to merge PR acls = pagure.lib.query.get_acls(self.session) for acl in acls: - if acl.name == 'pull_request_merge': + if acl.name == "pull_request_merge": break item = pagure.lib.model.TokenAcl( - token_id='foobar_token', - acl_id=acl.id, + token_id="foobar_token", acl_id=acl.id ) self.session.add(item) self.session.commit() - headers = {'Authorization': 'token foobar_token'} + headers = {"Authorization": "token foobar_token"} # User not admin output = self.app.post( - '/api/0/test/pull-request/1/merge', headers=headers) + "/api/0/test/pull-request/1/merge", headers=headers + ) self.assertEqual(output.status_code, 403) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - 'error': 'You are not allowed to merge/close pull-request ' - 'for this project', - 'error_code': "ENOPRCLOSE", - } + "error": "You are not allowed to merge/close pull-request " + "for this project", + "error_code": "ENOPRCLOSE", + }, ) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Merge PR output = self.app.post( - '/api/0/test/pull-request/1/merge', headers=headers) + "/api/0/test/pull-request/1/merge", headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {"message": "Changes merged!"} - ) + self.assertDictEqual(data, {"message": "Changes merged!"}) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_pull_request_merge_conflicting(self, send_email): """ Test the api_pull_request_merge method of the flask api. """ send_email.return_value = True tests.create_projects(self.session) tests.add_content_git_repo( - os.path.join(self.path, "repos", "test.git")) + os.path.join(self.path, "repos", "test.git") + ) # Fork - project = pagure.lib.query.get_authorized_project( - self.session, 'test') + project = pagure.lib.query.get_authorized_project(self.session, "test") task = pagure.lib.query.fork_project( - session=self.session, - user='pingou', - repo=project, + session=self.session, user="pingou", repo=project ) self.session.commit() self.assertEqual( task.get(), - {'endpoint': 'ui_ns.view_repo', - 'repo': 'test', - 'namespace': None, - 'username': 'pingou'}) + { + "endpoint": "ui_ns.view_repo", + "repo": "test", + "namespace": None, + "username": "pingou", + }, + ) # Add content to the fork tests.add_content_to_git( os.path.join(self.path, "repos", "forks", "pingou", "test.git"), - filename="foobar", content="content from the fork") + filename="foobar", + content="content from the fork", + ) # Add content to the main repo, so they conflict tests.add_content_to_git( os.path.join(self.path, "repos", "test.git"), - filename="foobar", content="content from the main repo") + filename="foobar", + content="content from the main repo", + ) - project = pagure.lib.query.get_authorized_project( - self.session, 'test') + project = pagure.lib.query.get_authorized_project(self.session, "test") fork = pagure.lib.query.get_authorized_project( - self.session, - 'test', - user='pingou', + self.session, "test", user="pingou" ) tests.create_tokens(self.session) @@ -1423,104 +1424,106 @@ class PagureFlaskApiForktests(tests.Modeltests): req = pagure.lib.query.new_pull_request( session=self.session, repo_from=fork, - branch_from='master', + branch_from="master", repo_to=project, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Merge PR output = self.app.post( - '/api/0/test/pull-request/1/merge', headers=headers) + "/api/0/test/pull-request/1/merge", headers=headers + ) self.assertEqual(output.status_code, 409) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - 'error': 'This pull-request conflicts and thus cannot be merged', - 'error_code': 'EPRCONFLICTS' - } + "error": "This pull-request conflicts and thus cannot be merged", + "error_code": "EPRCONFLICTS", + }, ) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_pull_request_merge_user_token(self, send_email): """ Test the api_pull_request_merge method of the flask api. """ send_email.return_value = True tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'repos'), bare=True) - tests.create_projects_git(os.path.join(self.path, 'requests'), - bare=True) - tests.add_readme_git_repo(os.path.join(self.path, 'repos', 'test.git')) - tests.add_commit_git_repo(os.path.join(self.path, 'repos', 'test.git'), - branch='test') + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) + tests.create_projects_git( + os.path.join(self.path, "requests"), bare=True + ) + tests.add_readme_git_repo(os.path.join(self.path, "repos", "test.git")) + tests.add_commit_git_repo( + os.path.join(self.path, "repos", "test.git"), branch="test" + ) tests.create_tokens(self.session, project_id=None) tests.create_tokens_acl(self.session) # Create the pull-request to close - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test" + ) req = pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='test', + branch_from="test", repo_to=repo, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Invalid project output = self.app.post( - '/api/0/foo/pull-request/1/merge', headers=headers) + "/api/0/foo/pull-request/1/merge", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) # Valid token, invalid PR output = self.app.post( - '/api/0/test2/pull-request/1/merge', headers=headers) + "/api/0/test2/pull-request/1/merge", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - {'error': 'Pull-Request not found', 'error_code': "ENOREQ"} + data, {"error": "Pull-Request not found", "error_code": "ENOREQ"} ) # Valid token, invalid PR - other project output = self.app.post( - '/api/0/test/pull-request/2/merge', headers=headers) + "/api/0/test/pull-request/2/merge", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - {'error': 'Pull-Request not found', 'error_code': "ENOREQ"} + data, {"error": "Pull-Request not found", "error_code": "ENOREQ"} ) # Create a token for foo for this project item = pagure.lib.model.Token( - id='foobar_token', + id="foobar_token", user_id=2, project_id=1, - expiration=datetime.datetime.utcnow() + datetime.timedelta( - days=30) + expiration=datetime.datetime.utcnow() + + datetime.timedelta(days=30), ) self.session.add(item) self.session.commit() @@ -1529,44 +1532,42 @@ class PagureFlaskApiForktests(tests.Modeltests): acls = pagure.lib.query.get_acls(self.session) acl = None for acl in acls: - if acl.name == 'pull_request_merge': + if acl.name == "pull_request_merge": break item = pagure.lib.model.TokenAcl( - token_id='foobar_token', - acl_id=acl.id, + token_id="foobar_token", acl_id=acl.id ) self.session.add(item) self.session.commit() - headers = {'Authorization': 'token foobar_token'} + headers = {"Authorization": "token foobar_token"} # User not admin output = self.app.post( - '/api/0/test/pull-request/1/merge', headers=headers) + "/api/0/test/pull-request/1/merge", headers=headers + ) self.assertEqual(output.status_code, 403) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - 'error': 'You are not allowed to merge/close pull-request ' - 'for this project', - 'error_code': "ENOPRCLOSE", - } + "error": "You are not allowed to merge/close pull-request " + "for this project", + "error_code": "ENOPRCLOSE", + }, ) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Merge PR output = self.app.post( - '/api/0/test/pull-request/1/merge', headers=headers) + "/api/0/test/pull-request/1/merge", headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {"message": "Changes merged!"} - ) + self.assertDictEqual(data, {"message": "Changes merged!"}) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_pull_request_add_comment(self, mockemail): """ Test the api_pull_request_add_comment method of the flask api. """ mockemail.return_value = True @@ -1575,110 +1576,106 @@ class PagureFlaskApiForktests(tests.Modeltests): tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Invalid project output = self.app.post( - '/api/0/foo/pull-request/1/comment', headers=headers) + "/api/0/foo/pull-request/1/comment", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) # Valid token, wrong project output = self.app.post( - '/api/0/test2/pull-request/1/comment', headers=headers) + "/api/0/test2/pull-request/1/comment", headers=headers + ) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.name, - data['error_code']) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data['error']) + self.assertEqual( + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) # No input output = self.app.post( - '/api/0/test/pull-request/1/comment', headers=headers) + "/api/0/test/pull-request/1/comment", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Pull-Request not found", - "error_code": "ENOREQ", - } + data, {"error": "Pull-Request not found", "error_code": "ENOREQ"} ) # Create a pull-request - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test" + ) req = pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") # Check comments before self.session.commit() request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual(len(request.comments), 0) - data = { - 'title': 'test issue', - } + data = {"title": "test issue"} # Incomplete request output = self.app.post( - '/api/0/test/pull-request/1/comment', data=data, headers=headers) + "/api/0/test/pull-request/1/comment", data=data, headers=headers + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - "error": "Invalid or incomplete input submitted", - "error_code": "EINVALIDREQ", - "errors": {"comment": ["This field is required."]} - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": {"comment": ["This field is required."]}, + }, ) # No change self.session.commit() request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual(len(request.comments), 0) - data = { - 'comment': 'This is a very interesting question', - } + data = {"comment": "This is a very interesting question"} # Valid request output = self.app.post( - '/api/0/test/pull-request/1/comment', data=data, headers=headers) + "/api/0/test/pull-request/1/comment", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'Comment added'} - ) + self.assertDictEqual(data, {"message": "Comment added"}) # One comment added self.session.commit() request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual(len(request.comments), 1) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_api_pull_request_add_comment_wrong_user(self): """ Test the api_pull_request_add_comment method of the flask api when the user is not found in the DB. """ @@ -1687,41 +1684,45 @@ class PagureFlaskApiForktests(tests.Modeltests): tests.create_tokens(self.session, project_id=None) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Create a pull-request - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test" + ) req = pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") - data = { - 'comment': 'This is a very interesting question', - } + data = {"comment": "This is a very interesting question"} # Valid request - with patch('pagure.lib.query.add_pull_request_comment', - side_effect=pagure.exceptions.PagureException('error')): + with patch( + "pagure.lib.query.add_pull_request_comment", + side_effect=pagure.exceptions.PagureException("error"), + ): output = self.app.post( - '/api/0/test/pull-request/1/comment', data=data, headers=headers) + "/api/0/test/pull-request/1/comment", + data=data, + headers=headers, + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - {u'error': u'error', u'error_code': u'ENOCODE'} + data, {"error": "error", "error_code": "ENOCODE"} ) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_api_pull_request_add_comment_pr_disabled(self): """ Test the api_pull_request_add_comment method of the flask api when PRs are disabled. """ @@ -1730,55 +1731,57 @@ class PagureFlaskApiForktests(tests.Modeltests): tests.create_tokens(self.session, project_id=None) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Create a pull-request - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test" + ) req = pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") settings = repo.settings - settings['pull_requests'] = False + settings["pull_requests"] = False repo.settings = settings self.session.add(repo) self.session.commit() - data = { - 'comment': 'This is a very interesting question', - } + data = {"comment": "This is a very interesting question"} # Valid request output = self.app.post( - '/api/0/test/pull-request/1/comment', data=data, headers=headers) + "/api/0/test/pull-request/1/comment", data=data, headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - u'error': u'Pull-Request have been deactivated for this project', - u'error_code': u'EPULLREQUESTSDISABLED' - } + "error": "Pull-Request have been deactivated for this project", + "error_code": "EPULLREQUESTSDISABLED", + }, ) # no comment added self.session.commit() request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual(len(request.comments), 0) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_pull_request_add_comment_user_token(self, mockemail): """ Test the api_pull_request_add_comment method of the flask api. """ mockemail.return_value = True @@ -1787,114 +1790,105 @@ class PagureFlaskApiForktests(tests.Modeltests): tests.create_tokens(self.session, project_id=None) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Invalid project output = self.app.post( - '/api/0/foo/pull-request/1/comment', headers=headers) + "/api/0/foo/pull-request/1/comment", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) # Valid token, invalid request output = self.app.post( - '/api/0/test2/pull-request/1/comment', headers=headers) + "/api/0/test2/pull-request/1/comment", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Pull-Request not found", - "error_code": "ENOREQ", - } + data, {"error": "Pull-Request not found", "error_code": "ENOREQ"} ) # Valid token, invalid request in another project output = self.app.post( - '/api/0/test/pull-request/1/comment', headers=headers) + "/api/0/test/pull-request/1/comment", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Pull-Request not found", - "error_code": "ENOREQ", - } + data, {"error": "Pull-Request not found", "error_code": "ENOREQ"} ) # Create a pull-request - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test" + ) req = pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") # Check comments before self.session.commit() request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual(len(request.comments), 0) - data = { - 'title': 'test issue', - } + data = {"title": "test issue"} # Incomplete request output = self.app.post( - '/api/0/test/pull-request/1/comment', data=data, headers=headers) + "/api/0/test/pull-request/1/comment", data=data, headers=headers + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - "error": "Invalid or incomplete input submitted", - "error_code": "EINVALIDREQ", - "errors": {"comment": ["This field is required."]} - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": {"comment": ["This field is required."]}, + }, ) # No change self.session.commit() request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual(len(request.comments), 0) - data = { - 'comment': 'This is a very interesting question', - } + data = {"comment": "This is a very interesting question"} # Valid request output = self.app.post( - '/api/0/test/pull-request/1/comment', data=data, headers=headers) + "/api/0/test/pull-request/1/comment", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'Comment added'} - ) + self.assertDictEqual(data, {"message": "Comment added"}) # One comment added self.session.commit() request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual(len(request.comments), 1) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_subscribe_pull_request_pr_disabled(self, p_send_email): """ Test the api_subscribe_pull_request method of the flask api. """ p_send_email.return_value = True @@ -1903,45 +1897,46 @@ class PagureFlaskApiForktests(tests.Modeltests): tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") settings = repo.settings - settings['pull_requests'] = False + settings["pull_requests"] = False repo.settings = settings self.session.add(repo) self.session.commit() - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Invalid project output = self.app.post( - '/api/0/test/pull-request/1/subscribe', headers=headers) + "/api/0/test/pull-request/1/subscribe", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - u'error': u'Pull-Request have been deactivated for this project', - u'error_code': u'EPULLREQUESTSDISABLED' - } + "error": "Pull-Request have been deactivated for this project", + "error_code": "EPULLREQUESTSDISABLED", + }, ) - @patch('pagure.lib.git.update_git') - @patch('pagure.lib.notify.send_email') - def test_api_subscribe_pull_request_invalid_token(self, p_send_email, p_ugt): + @patch("pagure.lib.git.update_git") + @patch("pagure.lib.notify.send_email") + def test_api_subscribe_pull_request_invalid_token( + self, p_send_email, p_ugt + ): """ Test the api_subscribe_pull_request method of the flask api. """ p_send_email.return_value = True p_ugt.return_value = True item = pagure.lib.model.User( - user='bar', - fullname='bar foo', - password='foo', - default_email='bar@bar.com', + user="bar", + fullname="bar foo", + password="foo", + default_email="bar@bar.com", ) self.session.add(item) - item = pagure.lib.model.UserEmail( - user_id=3, - email='bar@bar.com') + item = pagure.lib.model.UserEmail(user_id=3, email="bar@bar.com") self.session.add(item) self.session.commit() @@ -1950,64 +1945,64 @@ class PagureFlaskApiForktests(tests.Modeltests): tests.create_tokens(self.session, user_id=3, project_id=2) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Create pull-request - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") req = pagure.lib.query.new_pull_request( session=self.session, repo_from=repo, - branch_from='feature', + branch_from="feature", repo_to=repo, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") # Check subscribtion before - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual( pagure.lib.query.get_watch_list(self.session, request), - set(['pingou'])) + set(["pingou"]), + ) data = {} output = self.app.post( - '/api/0/test/pull-request/1/subscribe', - data=data, headers=headers) + "/api/0/test/pull-request/1/subscribe", data=data, headers=headers + ) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - u'error': u'Invalid or expired token. Please visit ' - 'http://localhost.localdomain/settings#api-keys to get or ' - 'renew your API token.', - u'error_code': u'EINVALIDTOK' - } + "error": "Invalid or expired token. Please visit " + "http://localhost.localdomain/settings#api-keys to get or " + "renew your API token.", + "error_code": "EINVALIDTOK", + }, ) - @patch('pagure.lib.git.update_git') - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.git.update_git") + @patch("pagure.lib.notify.send_email") def test_api_subscribe_pull_request(self, p_send_email, p_ugt): """ Test the api_subscribe_pull_request method of the flask api. """ p_send_email.return_value = True p_ugt.return_value = True item = pagure.lib.model.User( - user='bar', - fullname='bar foo', - password='foo', - default_email='bar@bar.com', + user="bar", + fullname="bar foo", + password="foo", + default_email="bar@bar.com", ) self.session.add(item) - item = pagure.lib.model.UserEmail( - user_id=3, - email='bar@bar.com') + item = pagure.lib.model.UserEmail(user_id=3, email="bar@bar.com") self.session.add(item) self.session.commit() @@ -2016,169 +2011,178 @@ class PagureFlaskApiForktests(tests.Modeltests): tests.create_tokens(self.session, user_id=3) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Invalid project output = self.app.post( - '/api/0/foo/pull-request/1/subscribe', headers=headers) + "/api/0/foo/pull-request/1/subscribe", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) # Valid token, wrong project output = self.app.post( - '/api/0/test2/pull-request/1/subscribe', headers=headers) + "/api/0/test2/pull-request/1/subscribe", headers=headers + ) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.name, - data['error_code']) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data['error']) + self.assertEqual( + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) # No input output = self.app.post( - '/api/0/test/pull-request/1/subscribe', headers=headers) + "/api/0/test/pull-request/1/subscribe", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - 'error': 'Pull-Request not found', - 'error_code': 'ENOREQ' - } + data, {"error": "Pull-Request not found", "error_code": "ENOREQ"} ) # Create pull-request - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") req = pagure.lib.query.new_pull_request( session=self.session, repo_from=repo, - branch_from='feature', + branch_from="feature", repo_to=repo, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") # Check subscribtion before - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual( pagure.lib.query.get_watch_list(self.session, request), - set(['pingou'])) + set(["pingou"]), + ) # Unsubscribe - no changes data = {} output = self.app.post( - '/api/0/test/pull-request/1/subscribe', - data=data, headers=headers) + "/api/0/test/pull-request/1/subscribe", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( data, - {'message': 'You are no longer watching this pull-request', - 'avatar_url': 'https://seccdn.libravatar.org/avatar/...', - 'user': 'bar', - } + { + "message": "You are no longer watching this pull-request", + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + "user": "bar", + }, ) data = {} output = self.app.post( - '/api/0/test/pull-request/1/subscribe', - data=data, headers=headers) + "/api/0/test/pull-request/1/subscribe", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( data, - {'message': 'You are no longer watching this pull-request', - 'avatar_url': 'https://seccdn.libravatar.org/avatar/...', - 'user': 'bar', - } + { + "message": "You are no longer watching this pull-request", + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + "user": "bar", + }, ) # No change - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual( pagure.lib.query.get_watch_list(self.session, request), - set(['pingou'])) + set(["pingou"]), + ) # Subscribe - data = {'status': True} + data = {"status": True} output = self.app.post( - '/api/0/test/pull-request/1/subscribe', - data=data, headers=headers) + "/api/0/test/pull-request/1/subscribe", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( data, - {'message': 'You are now watching this pull-request', - 'avatar_url': 'https://seccdn.libravatar.org/avatar/...', - 'user': 'bar', - } + { + "message": "You are now watching this pull-request", + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + "user": "bar", + }, ) # Subscribe - no changes - data = {'status': True} + data = {"status": True} output = self.app.post( - '/api/0/test/pull-request/1/subscribe', - data=data, headers=headers) + "/api/0/test/pull-request/1/subscribe", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( data, - {'message': 'You are now watching this pull-request', - 'avatar_url': 'https://seccdn.libravatar.org/avatar/...', - 'user': 'bar', - } + { + "message": "You are now watching this pull-request", + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + "user": "bar", + }, ) - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual( pagure.lib.query.get_watch_list(self.session, request), - set(['pingou', 'bar'])) + set(["pingou", "bar"]), + ) # Unsubscribe data = {} output = self.app.post( - '/api/0/test/pull-request/1/subscribe', - data=data, headers=headers) + "/api/0/test/pull-request/1/subscribe", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( data, - {'message': 'You are no longer watching this pull-request', - 'avatar_url': 'https://seccdn.libravatar.org/avatar/...', - 'user': 'bar', - } + { + "message": "You are no longer watching this pull-request", + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + "user": "bar", + }, ) - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual( pagure.lib.query.get_watch_list(self.session, request), - set(['pingou'])) + set(["pingou"]), + ) - @patch('pagure.lib.git.update_git') - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.git.update_git") + @patch("pagure.lib.notify.send_email") def test_api_subscribe_pull_request_logged_in(self, p_send_email, p_ugt): """ Test the api_subscribe_pull_request method of the flask api when the user is logged in via the UI. """ @@ -2186,15 +2190,13 @@ class PagureFlaskApiForktests(tests.Modeltests): p_ugt.return_value = True item = pagure.lib.model.User( - user='bar', - fullname='bar foo', - password='foo', - default_email='bar@bar.com', + user="bar", + fullname="bar foo", + password="foo", + default_email="bar@bar.com", ) self.session.add(item) - item = pagure.lib.model.UserEmail( - user_id=3, - email='bar@bar.com') + item = pagure.lib.model.UserEmail(user_id=3, email="bar@bar.com") self.session.add(item) self.session.commit() @@ -2204,1112 +2206,1212 @@ class PagureFlaskApiForktests(tests.Modeltests): tests.create_tokens_acl(self.session) # Create pull-request - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") req = pagure.lib.query.new_pull_request( session=self.session, repo_from=repo, - branch_from='feature', + branch_from="feature", repo_to=repo, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") # Check subscribtion before - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual( pagure.lib.query.get_watch_list(self.session, request), - set(['pingou'])) + set(["pingou"]), + ) # Subscribe - user = tests.FakeUser(username='foo') + user = tests.FakeUser(username="foo") with tests.user_set(self.app.application, user): - data = {'status': True} + data = {"status": True} output = self.app.post( - '/api/0/test/pull-request/1/subscribe', data=data) + "/api/0/test/pull-request/1/subscribe", data=data + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( data, - {'message': 'You are now watching this pull-request', - 'avatar_url': 'https://seccdn.libravatar.org/avatar/...', - 'user': 'foo', - } + { + "message": "You are now watching this pull-request", + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + "user": "foo", + }, ) # Check subscribtions after - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual( pagure.lib.query.get_watch_list(self.session, request), - set(['pingou', 'foo'])) + set(["pingou", "foo"]), + ) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_api_pull_request_open_invalid_project(self): """ Test the api_pull_request_create method of the flask api when not the project doesn't exist. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'repos'), bare=True) - tests.create_projects_git(os.path.join(self.path, 'requests'), - bare=True) - tests.add_readme_git_repo(os.path.join(self.path, 'repos', 'test.git')) - tests.add_commit_git_repo(os.path.join(self.path, 'repos', 'test.git'), - branch='test') + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) + tests.create_projects_git( + os.path.join(self.path, "requests"), bare=True + ) + tests.add_readme_git_repo(os.path.join(self.path, "repos", "test.git")) + tests.add_commit_git_repo( + os.path.join(self.path, "repos", "test.git"), branch="test" + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'initial_comment': 'Nothing much, the changes speak for themselves', - 'branch_to': 'master', - 'branch_from': 'test', + "initial_comment": "Nothing much, the changes speak for themselves", + "branch_to": "master", + "branch_from": "test", } output = self.app.post( - '/api/0/foobar/pull-request/new', headers=headers, data=data) + "/api/0/foobar/pull-request/new", headers=headers, data=data + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - {'error': 'Project not found', 'error_code': 'ENOPROJECT'} + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_api_pull_request_open_missing_title(self): """ Test the api_pull_request_create method of the flask api when not title is submitted. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'repos'), bare=True) - tests.create_projects_git(os.path.join(self.path, 'requests'), - bare=True) - tests.add_readme_git_repo(os.path.join(self.path, 'repos', 'test.git')) - tests.add_commit_git_repo(os.path.join(self.path, 'repos', 'test.git'), - branch='test') + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) + tests.create_projects_git( + os.path.join(self.path, "requests"), bare=True + ) + tests.add_readme_git_repo(os.path.join(self.path, "repos", "test.git")) + tests.add_commit_git_repo( + os.path.join(self.path, "repos", "test.git"), branch="test" + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'initial_comment': 'Nothing much, the changes speak for themselves', - 'branch_to': 'master', - 'branch_from': 'test', + "initial_comment": "Nothing much, the changes speak for themselves", + "branch_to": "master", + "branch_from": "test", } output = self.app.post( - '/api/0/test/pull-request/new', headers=headers, data=data) + "/api/0/test/pull-request/new", headers=headers, data=data + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - 'error': 'Invalid or incomplete input submitted', - 'error_code': 'EINVALIDREQ', - 'errors': {'title': ['This field is required.']} - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": {"title": ["This field is required."]}, + }, ) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_api_pull_request_open_missing_branch_to(self): """ Test the api_pull_request_create method of the flask api when not branch to is submitted. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'repos'), bare=True) - tests.create_projects_git(os.path.join(self.path, 'requests'), - bare=True) - tests.add_readme_git_repo(os.path.join(self.path, 'repos', 'test.git')) - tests.add_commit_git_repo(os.path.join(self.path, 'repos', 'test.git'), - branch='test') + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) + tests.create_projects_git( + os.path.join(self.path, "requests"), bare=True + ) + tests.add_readme_git_repo(os.path.join(self.path, "repos", "test.git")) + tests.add_commit_git_repo( + os.path.join(self.path, "repos", "test.git"), branch="test" + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'title': 'Test PR', - 'initial_comment': 'Nothing much, the changes speak for themselves', - 'branch_from': 'test', + "title": "Test PR", + "initial_comment": "Nothing much, the changes speak for themselves", + "branch_from": "test", } output = self.app.post( - '/api/0/test/pull-request/new', headers=headers, data=data) + "/api/0/test/pull-request/new", headers=headers, data=data + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - 'error': 'Invalid or incomplete input submitted', - 'error_code': 'EINVALIDREQ', - 'errors': {'branch_to': ['This field is required.']} - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": {"branch_to": ["This field is required."]}, + }, ) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_api_pull_request_open_missing_branch_from(self): """ Test the api_pull_request_create method of the flask api when not branch from is submitted. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'repos'), bare=True) - tests.create_projects_git(os.path.join(self.path, 'requests'), - bare=True) - tests.add_readme_git_repo(os.path.join(self.path, 'repos', 'test.git')) - tests.add_commit_git_repo(os.path.join(self.path, 'repos', 'test.git'), - branch='test') + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) + tests.create_projects_git( + os.path.join(self.path, "requests"), bare=True + ) + tests.add_readme_git_repo(os.path.join(self.path, "repos", "test.git")) + tests.add_commit_git_repo( + os.path.join(self.path, "repos", "test.git"), branch="test" + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'title': 'Test PR', - 'initial_comment': 'Nothing much, the changes speak for themselves', - 'branch_to': 'master', + "title": "Test PR", + "initial_comment": "Nothing much, the changes speak for themselves", + "branch_to": "master", } output = self.app.post( - '/api/0/test/pull-request/new', headers=headers, data=data) + "/api/0/test/pull-request/new", headers=headers, data=data + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - 'error': 'Invalid or incomplete input submitted', - 'error_code': 'EINVALIDREQ', - 'errors': {'branch_from': ['This field is required.']} - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": {"branch_from": ["This field is required."]}, + }, ) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_api_pull_request_open_pr_disabled(self): """ Test the api_pull_request_create method of the flask api when the parent repo disabled pull-requests. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'repos'), bare=True) - tests.create_projects_git(os.path.join(self.path, 'requests'), - bare=True) - tests.add_readme_git_repo(os.path.join(self.path, 'repos', 'test.git')) - tests.add_commit_git_repo(os.path.join(self.path, 'repos', 'test.git'), - branch='test') + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) + tests.create_projects_git( + os.path.join(self.path, "requests"), bare=True + ) + tests.add_readme_git_repo(os.path.join(self.path, "repos", "test.git")) + tests.add_commit_git_repo( + os.path.join(self.path, "repos", "test.git"), branch="test" + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Check the behavior if the project disabled the issue tracker - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") settings = repo.settings - settings['pull_requests'] = False + settings["pull_requests"] = False repo.settings = settings self.session.add(repo) self.session.commit() - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'title': 'Test PR', - 'initial_comment': 'Nothing much, the changes speak for themselves', - 'branch_to': 'master', - 'branch_from': 'test', + "title": "Test PR", + "initial_comment": "Nothing much, the changes speak for themselves", + "branch_to": "master", + "branch_from": "test", } output = self.app.post( - '/api/0/test/pull-request/new', headers=headers, data=data) + "/api/0/test/pull-request/new", headers=headers, data=data + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - 'error': 'Pull-Request have been deactivated for this project', - 'error_code': 'EPULLREQUESTSDISABLED' - } + "error": "Pull-Request have been deactivated for this project", + "error_code": "EPULLREQUESTSDISABLED", + }, ) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_api_pull_request_open_signed_pr(self): """ Test the api_pull_request_create method of the flask api when the parent repo enforces signed-off pull-requests. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'repos'), bare=True) - tests.create_projects_git(os.path.join(self.path, 'requests'), - bare=True) - tests.add_readme_git_repo(os.path.join(self.path, 'repos', 'test.git')) - tests.add_commit_git_repo(os.path.join(self.path, 'repos', 'test.git'), - branch='test') + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) + tests.create_projects_git( + os.path.join(self.path, "requests"), bare=True + ) + tests.add_readme_git_repo(os.path.join(self.path, "repos", "test.git")) + tests.add_commit_git_repo( + os.path.join(self.path, "repos", "test.git"), branch="test" + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Check the behavior if the project disabled the issue tracker - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") settings = repo.settings - settings['Enforce_signed-off_commits_in_pull-request'] = True + settings["Enforce_signed-off_commits_in_pull-request"] = True repo.settings = settings self.session.add(repo) self.session.commit() - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'title': 'Test PR', - 'initial_comment': 'Nothing much, the changes speak for themselves', - 'branch_to': 'master', - 'branch_from': 'test', + "title": "Test PR", + "initial_comment": "Nothing much, the changes speak for themselves", + "branch_to": "master", + "branch_from": "test", } output = self.app.post( - '/api/0/test/pull-request/new', headers=headers, data=data) + "/api/0/test/pull-request/new", headers=headers, data=data + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - 'error': 'This repo enforces that all commits are signed ' - 'off by their author.', - 'error_code': 'ENOSIGNEDOFF' - } + "error": "This repo enforces that all commits are signed " + "off by their author.", + "error_code": "ENOSIGNEDOFF", + }, ) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_api_pull_request_open_invalid_branch_from(self): """ Test the api_pull_request_create method of the flask api when the branch from does not exist. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'repos'), bare=True) - tests.create_projects_git(os.path.join(self.path, 'requests'), - bare=True) - tests.add_readme_git_repo(os.path.join(self.path, 'repos', 'test.git')) - tests.add_commit_git_repo(os.path.join(self.path, 'repos', 'test.git'), - branch='test') + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) + tests.create_projects_git( + os.path.join(self.path, "requests"), bare=True + ) + tests.add_readme_git_repo(os.path.join(self.path, "repos", "test.git")) + tests.add_commit_git_repo( + os.path.join(self.path, "repos", "test.git"), branch="test" + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Check the behavior if the project disabled the issue tracker - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") settings = repo.settings - settings['Enforce_signed-off_commits_in_pull-request'] = True + settings["Enforce_signed-off_commits_in_pull-request"] = True repo.settings = settings self.session.add(repo) self.session.commit() - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'title': 'Test PR', - 'initial_comment': 'Nothing much, the changes speak for themselves', - 'branch_to': 'master', - 'branch_from': 'foobarbaz', + "title": "Test PR", + "initial_comment": "Nothing much, the changes speak for themselves", + "branch_to": "master", + "branch_from": "foobarbaz", } output = self.app.post( - '/api/0/test/pull-request/new', headers=headers, data=data) + "/api/0/test/pull-request/new", headers=headers, data=data + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - 'error': 'Invalid or incomplete input submitted', - 'error_code': 'EINVALIDREQ', - 'errors': 'Branch foobarbaz does not exist' - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": "Branch foobarbaz does not exist", + }, ) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_api_pull_request_open_invalid_token(self): """ Test the api_pull_request_create method of the flask api when queried with an invalid token. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'repos'), bare=True) - tests.create_projects_git(os.path.join(self.path, 'requests'), - bare=True) - tests.add_readme_git_repo(os.path.join(self.path, 'repos', 'test.git')) - tests.add_commit_git_repo(os.path.join(self.path, 'repos', 'test.git'), - branch='test') + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) + tests.create_projects_git( + os.path.join(self.path, "requests"), bare=True + ) + tests.add_readme_git_repo(os.path.join(self.path, "repos", "test.git")) + tests.add_commit_git_repo( + os.path.join(self.path, "repos", "test.git"), branch="test" + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'title': 'Test PR', - 'initial_comment': 'Nothing much, the changes speak for themselves', - 'branch_to': 'master', - 'branch_from': 'foobarbaz', + "title": "Test PR", + "initial_comment": "Nothing much, the changes speak for themselves", + "branch_to": "master", + "branch_from": "foobarbaz", } output = self.app.post( - '/api/0/test2/pull-request/new', headers=headers, data=data) + "/api/0/test2/pull-request/new", headers=headers, data=data + ) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - u'error': u'Invalid or expired token. Please visit ' - 'http://localhost.localdomain/settings#api-keys to get or ' - 'renew your API token.', - u'error_code': u'EINVALIDTOK', - } + "error": "Invalid or expired token. Please visit " + "http://localhost.localdomain/settings#api-keys to get or " + "renew your API token.", + "error_code": "EINVALIDTOK", + }, ) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_api_pull_request_open_invalid_access(self): """ Test the api_pull_request_create method of the flask api when the user opening the PR doesn't have commit access. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'repos'), bare=True) - tests.create_projects_git(os.path.join(self.path, 'requests'), - bare=True) - tests.add_readme_git_repo(os.path.join(self.path, 'repos', 'test.git')) - tests.add_commit_git_repo(os.path.join(self.path, 'repos', 'test.git'), - branch='test') + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) + tests.create_projects_git( + os.path.join(self.path, "requests"), bare=True + ) + tests.add_readme_git_repo(os.path.join(self.path, "repos", "test.git")) + tests.add_commit_git_repo( + os.path.join(self.path, "repos", "test.git"), branch="test" + ) tests.create_tokens(self.session, user_id=2) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'title': 'Test PR', - 'initial_comment': 'Nothing much, the changes speak for themselves', - 'branch_to': 'master', - 'branch_from': 'foobarbaz', + "title": "Test PR", + "initial_comment": "Nothing much, the changes speak for themselves", + "branch_to": "master", + "branch_from": "foobarbaz", } output = self.app.post( - '/api/0/test/pull-request/new', headers=headers, data=data) + "/api/0/test/pull-request/new", headers=headers, data=data + ) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - u'error': u'You do not have sufficient permissions to ' - u'perform this action', - u'error_code': u'ENOTHIGHENOUGH' - } + "error": "You do not have sufficient permissions to " + "perform this action", + "error_code": "ENOTHIGHENOUGH", + }, ) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_api_pull_request_open_invalid_branch_to(self): """ Test the api_pull_request_create method of the flask api when the branch to does not exist. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'repos'), bare=True) - tests.create_projects_git(os.path.join(self.path, 'requests'), - bare=True) - tests.add_readme_git_repo(os.path.join(self.path, 'repos', 'test.git')) - tests.add_commit_git_repo(os.path.join(self.path, 'repos', 'test.git'), - branch='test') + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) + tests.create_projects_git( + os.path.join(self.path, "requests"), bare=True + ) + tests.add_readme_git_repo(os.path.join(self.path, "repos", "test.git")) + tests.add_commit_git_repo( + os.path.join(self.path, "repos", "test.git"), branch="test" + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Check the behavior if the project disabled the issue tracker - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") settings = repo.settings - settings['Enforce_signed-off_commits_in_pull-request'] = True + settings["Enforce_signed-off_commits_in_pull-request"] = True repo.settings = settings self.session.add(repo) self.session.commit() - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'title': 'Test PR', - 'initial_comment': 'Nothing much, the changes speak for themselves', - 'branch_to': 'foobarbaz', - 'branch_from': 'test', + "title": "Test PR", + "initial_comment": "Nothing much, the changes speak for themselves", + "branch_to": "foobarbaz", + "branch_from": "test", } output = self.app.post( - '/api/0/test/pull-request/new', headers=headers, data=data) + "/api/0/test/pull-request/new", headers=headers, data=data + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - 'error': 'Invalid or incomplete input submitted', - 'error_code': 'EINVALIDREQ', - 'errors': 'Branch foobarbaz could not be found in the ' - 'target repo' - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": "Branch foobarbaz could not be found in the " + "target repo", + }, ) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_api_pull_request_open_project_token_different_project(self): """Test the api_pull_request_create method with the project token of a different project - fails""" tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'repos'), bare=True) - tests.create_projects_git(os.path.join(self.path, 'requests'), - bare=True) - tests.add_readme_git_repo(os.path.join(self.path, 'repos', 'test.git')) - tests.add_commit_git_repo(os.path.join(self.path, 'repos', 'test.git'), - branch='test') + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) + tests.create_projects_git( + os.path.join(self.path, "requests"), bare=True + ) + tests.add_readme_git_repo(os.path.join(self.path, "repos", "test.git")) + tests.add_commit_git_repo( + os.path.join(self.path, "repos", "test.git"), branch="test" + ) tests.create_tokens(self.session, project_id=2) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token foo_token'} + headers = {"Authorization": "token foo_token"} data = { - 'title': 'Test of PR', - 'inicial comment': 'Some readme adjustment', - 'branch_to': 'master', - 'branch_from': 'test' + "title": "Test of PR", + "inicial comment": "Some readme adjustment", + "branch_to": "master", + "branch_from": "test", } output = self.app.post( - '/api/0/test/pull-request/new', headers=headers, data=data) + "/api/0/test/pull-request/new", headers=headers, data=data + ) self.assertEqual(output.status_code, 401) - - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_api_pull_request_open_user_token_invalid_acls(self): """Test the api_pull_request_create method with the user token, but with no acls for opening pull request - fails""" tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'repos'), bare=True) - tests.create_projects_git(os.path.join(self.path, 'requests'), - bare=True) - tests.add_readme_git_repo(os.path.join(self.path, 'repos', 'test.git')) - tests.add_commit_git_repo(os.path.join(self.path, 'repos', 'test.git'), - branch='test') + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) + tests.create_projects_git( + os.path.join(self.path, "requests"), bare=True + ) + tests.add_readme_git_repo(os.path.join(self.path, "repos", "test.git")) + tests.add_commit_git_repo( + os.path.join(self.path, "repos", "test.git"), branch="test" + ) tests.create_tokens(self.session, project_id=None) - for acl in ("create_project", "fork_project", "modify_project", - "update_watch_status"): + for acl in ( + "create_project", + "fork_project", + "modify_project", + "update_watch_status", + ): tests.create_tokens_acl(self.session, acl_name=acl) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'title': 'Test of PR', - 'initial_comment': 'Some readme adjustment', - 'branch_to': 'master', - 'branch_from': 'test', - } + "title": "Test of PR", + "initial_comment": "Some readme adjustment", + "branch_to": "master", + "branch_from": "test", + } output = self.app.post( - '/api/0/test/pull-request/new', headers=headers, data=data) + "/api/0/test/pull-request/new", headers=headers, data=data + ) self.assertEqual(output.status_code, 401) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_api_pull_request_open_from_branch_to_origin(self): """Test the api_pull_request_create method from a fork to a master, with project token of a origin with all the acls""" tests.create_projects(self.session) - tests.create_projects(self.session, is_fork=True, hook_token_suffix='foo') + tests.create_projects( + self.session, is_fork=True, hook_token_suffix="foo" + ) project_query = self.session.query(pagure.lib.model.Project) - for project in project_query.filter_by(name='test').all(): + for project in project_query.filter_by(name="test").all(): if project.parent_id == None: parent = project else: child = project - tests.create_projects_git(os.path.join(self.path, 'repos'), bare=True) - tests.create_projects_git(os.path.join(self.path, 'requests'), - bare=True) - tests.add_readme_git_repo(os.path.join(self.path, 'repos', 'forks', - 'pingou', 'test.git'), branch='branch') - tests.add_commit_git_repo(os.path.join(self.path, 'repos', 'forks', - 'pingou', 'test.git'), branch='branch') + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) + tests.create_projects_git( + os.path.join(self.path, "requests"), bare=True + ) + tests.add_readme_git_repo( + os.path.join(self.path, "repos", "forks", "pingou", "test.git"), + branch="branch", + ) + tests.add_commit_git_repo( + os.path.join(self.path, "repos", "forks", "pingou", "test.git"), + branch="branch", + ) # Create tokens parent_token = pagure.lib.model.Token( - id='iamparenttoken', + id="iamparenttoken", user_id=parent.user_id, project_id=parent.id, - expiration=datetime.datetime.utcnow() + datetime.timedelta(days=30) + expiration=datetime.datetime.utcnow() + + datetime.timedelta(days=30), ) self.session.add(parent_token) fork_token = pagure.lib.model.Token( - id='iamforktoken', + id="iamforktoken", user_id=child.user_id, project_id=child.id, - expiration=datetime.datetime.utcnow() + datetime.timedelta(days=30) + expiration=datetime.datetime.utcnow() + + datetime.timedelta(days=30), ) self.session.add(fork_token) self.session.commit() - tests.create_tokens_acl(self.session, token_id='iamparenttoken') + tests.create_tokens_acl(self.session, token_id="iamparenttoken") for acl in pagure.default_config.CROSS_PROJECT_ACLS: - tests.create_tokens_acl(self.session, token_id='iamforktoken', - acl_name=acl) - - headers = {'Authorization': 'token iamforktoken'} - - data = { - 'title': 'war of tomatoes', - 'initial_comment': 'the manifest', - 'branch_to': 'master', - 'branch_from': 'branch', - } - - output = self.app.post('/api/0/fork/pingou/test/pull-request/new', - headers=headers, data=data) - self.assertEqual(output.status_code, 200) - - - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) - def test_api_pull_request_open(self): - """ Test the api_pull_request_create method of the flask api. """ + tests.create_tokens_acl( + self.session, token_id="iamforktoken", acl_name=acl + ) - tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'repos'), bare=True) - tests.create_projects_git(os.path.join(self.path, 'requests'), - bare=True) - tests.add_readme_git_repo(os.path.join(self.path, 'repos', 'test.git')) - tests.add_commit_git_repo(os.path.join(self.path, 'repos', 'test.git'), - branch='test') - tests.create_tokens(self.session) - tests.create_tokens_acl(self.session) + headers = {"Authorization": "token iamforktoken"} - headers = {'Authorization': 'token aaabbbcccddd'} data = { - 'title': 'Test PR', - 'initial_comment': 'Nothing much, the changes speak for themselves', - 'branch_to': 'master', - 'branch_from': 'test', + "title": "war of tomatoes", + "initial_comment": "the manifest", + "branch_to": "master", + "branch_from": "branch", } output = self.app.post( - '/api/0/test/pull-request/new', headers=headers, data=data) - self.assertEqual(output.status_code, 200) - data = json.loads(output.get_data(as_text=True)) - data['project']['date_created'] = '1516348115' - data['project']['date_modified'] = '1516348115' - data['repo_from']['date_created'] = '1516348115' - data['repo_from']['date_modified'] = '1516348115' - data['uid'] = 'e8b68df8711648deac67c3afed15a798' - data['commit_start'] = '114f1b468a5f05e635fcb6394273f3f907386eab' - data['commit_stop'] = '114f1b468a5f05e635fcb6394273f3f907386eab' - data['date_created'] = '1516348115' - data['last_updated'] = '1516348115' - data['updated_on'] = '1516348115' - self.assertDictEqual( - data, - { - 'assignee': None, - 'branch': 'master', - 'branch_from': 'test', - 'cached_merge_status': 'unknown', - 'closed_at': None, - 'closed_by': None, - 'comments': [], - 'commit_start': '114f1b468a5f05e635fcb6394273f3f907386eab', - 'commit_stop': '114f1b468a5f05e635fcb6394273f3f907386eab', - 'date_created': '1516348115', - 'id': 1, - 'initial_comment': 'Nothing much, the changes speak for themselves', - 'last_updated': '1516348115', - 'project': {'access_groups': {'admin': [], - 'commit': [], - 'ticket':[]}, - 'access_users': {'admin': [], - 'commit': [], - 'owner': ['pingou'], - 'ticket': []}, - 'close_status': ['Invalid', - 'Insufficient data', - 'Fixed', - 'Duplicate'], - 'custom_keys': [], - 'date_created': '1516348115', - 'date_modified': '1516348115', - 'description': 'test project #1', - 'fullname': 'test', - 'id': 1, - 'milestones': {}, - 'name': 'test', - 'namespace': None, - 'parent': None, - 'priorities': {}, - 'tags': [], - 'url_path': 'test', - 'user': {'fullname': 'PY C', 'name': 'pingou'}}, - 'remote_git': None, - 'repo_from': {'access_groups': {'admin': [], - 'commit': [], - 'ticket': []}, - 'access_users': {'admin': [], - 'commit': [], - 'owner': ['pingou'], - 'ticket': []}, - 'close_status': ['Invalid', - 'Insufficient data', - 'Fixed', - 'Duplicate'], - 'custom_keys': [], - 'date_created': '1516348115', - 'date_modified': '1516348115', - 'description': 'test project #1', - 'fullname': 'test', - 'id': 1, - 'milestones': {}, - 'name': 'test', - 'namespace': None, - 'parent': None, - 'priorities': {}, - 'tags': [], - 'url_path': 'test', - 'user': {'fullname': 'PY C', 'name': 'pingou'}}, - 'status': 'Open', - "tags": [], - 'threshold_reached': None, - 'title': 'Test PR', - 'uid': 'e8b68df8711648deac67c3afed15a798', - 'updated_on': '1516348115', - 'user': {'fullname': 'PY C', 'name': 'pingou'} - } + "/api/0/fork/pingou/test/pull-request/new", + headers=headers, + data=data, ) + self.assertEqual(output.status_code, 200) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) - def test_api_pull_request_open_missing_initial_comment(self): - """ Test the api_pull_request_create method of the flask api when - not initial comment is submitted. - """ + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) + def test_api_pull_request_open(self): + """ Test the api_pull_request_create method of the flask api. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'repos'), bare=True) - tests.create_projects_git(os.path.join(self.path, 'requests'), - bare=True) - tests.add_readme_git_repo(os.path.join(self.path, 'repos', 'test.git')) - tests.add_commit_git_repo(os.path.join(self.path, 'repos', 'test.git'), - branch='test') + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) + tests.create_projects_git( + os.path.join(self.path, "requests"), bare=True + ) + tests.add_readme_git_repo(os.path.join(self.path, "repos", "test.git")) + tests.add_commit_git_repo( + os.path.join(self.path, "repos", "test.git"), branch="test" + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'title': 'Test PR', - 'branch_to': 'master', - 'branch_from': 'test', + "title": "Test PR", + "initial_comment": "Nothing much, the changes speak for themselves", + "branch_to": "master", + "branch_from": "test", } output = self.app.post( - '/api/0/test/pull-request/new', headers=headers, data=data) + "/api/0/test/pull-request/new", headers=headers, data=data + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['project']['date_created'] = '1516348115' - data['project']['date_modified'] = '1516348115' - data['repo_from']['date_created'] = '1516348115' - data['repo_from']['date_modified'] = '1516348115' - data['uid'] = 'e8b68df8711648deac67c3afed15a798' - data['commit_start'] = '114f1b468a5f05e635fcb6394273f3f907386eab' - data['commit_stop'] = '114f1b468a5f05e635fcb6394273f3f907386eab' - data['date_created'] = '1516348115' - data['last_updated'] = '1516348115' - data['updated_on'] = '1516348115' + data["project"]["date_created"] = "1516348115" + data["project"]["date_modified"] = "1516348115" + data["repo_from"]["date_created"] = "1516348115" + data["repo_from"]["date_modified"] = "1516348115" + data["uid"] = "e8b68df8711648deac67c3afed15a798" + data["commit_start"] = "114f1b468a5f05e635fcb6394273f3f907386eab" + data["commit_stop"] = "114f1b468a5f05e635fcb6394273f3f907386eab" + data["date_created"] = "1516348115" + data["last_updated"] = "1516348115" + data["updated_on"] = "1516348115" self.assertDictEqual( data, { - 'assignee': None, - 'branch': 'master', - 'branch_from': 'test', - 'cached_merge_status': 'unknown', - 'closed_at': None, - 'closed_by': None, - 'comments': [], - 'commit_start': '114f1b468a5f05e635fcb6394273f3f907386eab', - 'commit_stop': '114f1b468a5f05e635fcb6394273f3f907386eab', - 'date_created': '1516348115', - 'id': 1, - 'initial_comment': None, - 'last_updated': '1516348115', - 'project': {'access_groups': {'admin': [], - 'commit': [], - 'ticket':[]}, - 'access_users': {'admin': [], - 'commit': [], - 'owner': ['pingou'], - 'ticket': []}, - 'close_status': ['Invalid', - 'Insufficient data', - 'Fixed', - 'Duplicate'], - 'custom_keys': [], - 'date_created': '1516348115', - 'date_modified': '1516348115', - 'description': 'test project #1', - 'fullname': 'test', - 'id': 1, - 'milestones': {}, - 'name': 'test', - 'namespace': None, - 'parent': None, - 'priorities': {}, - 'tags': [], - 'url_path': 'test', - 'user': {'fullname': 'PY C', 'name': 'pingou'}}, - 'remote_git': None, - 'repo_from': {'access_groups': {'admin': [], - 'commit': [], - 'ticket': []}, - 'access_users': {'admin': [], - 'commit': [], - 'owner': ['pingou'], - 'ticket': []}, - 'close_status': ['Invalid', - 'Insufficient data', - 'Fixed', - 'Duplicate'], - 'custom_keys': [], - 'date_created': '1516348115', - 'date_modified': '1516348115', - 'description': 'test project #1', - 'fullname': 'test', - 'id': 1, - 'milestones': {}, - 'name': 'test', - 'namespace': None, - 'parent': None, - 'priorities': {}, - 'tags': [], - 'url_path': 'test', - 'user': {'fullname': 'PY C', 'name': 'pingou'}}, - 'status': 'Open', - "tags": [], - 'threshold_reached': None, - 'title': 'Test PR', - 'uid': 'e8b68df8711648deac67c3afed15a798', - 'updated_on': '1516348115', - 'user': {'fullname': 'PY C', 'name': 'pingou'} - } - ) - -class PagureFlaskApiForkPRDiffStatstests(tests.Modeltests): - """ Tests for the flask API of pagure for the diff stats endpoint of PRs - """ - - maxDiff = None - - def setUp(self): - """ Set up the environnment, ran before every tests. """ - super(PagureFlaskApiForkPRDiffStatstests, self).setUp() - - pagure.config.config['REQUESTS_FOLDER'] = None - - tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'repos'), bare=True) - tests.create_projects_git(os.path.join(self.path, 'requests'), - bare=True) - tests.add_readme_git_repo(os.path.join(self.path, 'repos', 'test.git')) - tests.add_commit_git_repo( - os.path.join(self.path, 'repos', 'test.git'), ncommits=5) - tests.add_commit_git_repo( - os.path.join(self.path, 'repos', 'test.git'), branch='test') - + "assignee": None, + "branch": "master", + "branch_from": "test", + "cached_merge_status": "unknown", + "closed_at": None, + "closed_by": None, + "comments": [], + "commit_start": "114f1b468a5f05e635fcb6394273f3f907386eab", + "commit_stop": "114f1b468a5f05e635fcb6394273f3f907386eab", + "date_created": "1516348115", + "id": 1, + "initial_comment": "Nothing much, the changes speak for themselves", + "last_updated": "1516348115", + "project": { + "access_groups": {"admin": [], "commit": [], "ticket": []}, + "access_users": { + "admin": [], + "commit": [], + "owner": ["pingou"], + "ticket": [], + }, + "close_status": [ + "Invalid", + "Insufficient data", + "Fixed", + "Duplicate", + ], + "custom_keys": [], + "date_created": "1516348115", + "date_modified": "1516348115", + "description": "test project #1", + "fullname": "test", + "id": 1, + "milestones": {}, + "name": "test", + "namespace": None, + "parent": None, + "priorities": {}, + "tags": [], + "url_path": "test", + "user": {"fullname": "PY C", "name": "pingou"}, + }, + "remote_git": None, + "repo_from": { + "access_groups": {"admin": [], "commit": [], "ticket": []}, + "access_users": { + "admin": [], + "commit": [], + "owner": ["pingou"], + "ticket": [], + }, + "close_status": [ + "Invalid", + "Insufficient data", + "Fixed", + "Duplicate", + ], + "custom_keys": [], + "date_created": "1516348115", + "date_modified": "1516348115", + "description": "test project #1", + "fullname": "test", + "id": 1, + "milestones": {}, + "name": "test", + "namespace": None, + "parent": None, + "priorities": {}, + "tags": [], + "url_path": "test", + "user": {"fullname": "PY C", "name": "pingou"}, + }, + "status": "Open", + "tags": [], + "threshold_reached": None, + "title": "Test PR", + "uid": "e8b68df8711648deac67c3afed15a798", + "updated_on": "1516348115", + "user": {"fullname": "PY C", "name": "pingou"}, + }, + ) + + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) + def test_api_pull_request_open_missing_initial_comment(self): + """ Test the api_pull_request_create method of the flask api when + not initial comment is submitted. + """ + + tests.create_projects(self.session) + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) + tests.create_projects_git( + os.path.join(self.path, "requests"), bare=True + ) + tests.add_readme_git_repo(os.path.join(self.path, "repos", "test.git")) + tests.add_commit_git_repo( + os.path.join(self.path, "repos", "test.git"), branch="test" + ) + tests.create_tokens(self.session) + tests.create_tokens_acl(self.session) + + headers = {"Authorization": "token aaabbbcccddd"} + data = { + "title": "Test PR", + "branch_to": "master", + "branch_from": "test", + } + + output = self.app.post( + "/api/0/test/pull-request/new", headers=headers, data=data + ) + self.assertEqual(output.status_code, 200) + data = json.loads(output.get_data(as_text=True)) + data["project"]["date_created"] = "1516348115" + data["project"]["date_modified"] = "1516348115" + data["repo_from"]["date_created"] = "1516348115" + data["repo_from"]["date_modified"] = "1516348115" + data["uid"] = "e8b68df8711648deac67c3afed15a798" + data["commit_start"] = "114f1b468a5f05e635fcb6394273f3f907386eab" + data["commit_stop"] = "114f1b468a5f05e635fcb6394273f3f907386eab" + data["date_created"] = "1516348115" + data["last_updated"] = "1516348115" + data["updated_on"] = "1516348115" + self.assertDictEqual( + data, + { + "assignee": None, + "branch": "master", + "branch_from": "test", + "cached_merge_status": "unknown", + "closed_at": None, + "closed_by": None, + "comments": [], + "commit_start": "114f1b468a5f05e635fcb6394273f3f907386eab", + "commit_stop": "114f1b468a5f05e635fcb6394273f3f907386eab", + "date_created": "1516348115", + "id": 1, + "initial_comment": None, + "last_updated": "1516348115", + "project": { + "access_groups": {"admin": [], "commit": [], "ticket": []}, + "access_users": { + "admin": [], + "commit": [], + "owner": ["pingou"], + "ticket": [], + }, + "close_status": [ + "Invalid", + "Insufficient data", + "Fixed", + "Duplicate", + ], + "custom_keys": [], + "date_created": "1516348115", + "date_modified": "1516348115", + "description": "test project #1", + "fullname": "test", + "id": 1, + "milestones": {}, + "name": "test", + "namespace": None, + "parent": None, + "priorities": {}, + "tags": [], + "url_path": "test", + "user": {"fullname": "PY C", "name": "pingou"}, + }, + "remote_git": None, + "repo_from": { + "access_groups": {"admin": [], "commit": [], "ticket": []}, + "access_users": { + "admin": [], + "commit": [], + "owner": ["pingou"], + "ticket": [], + }, + "close_status": [ + "Invalid", + "Insufficient data", + "Fixed", + "Duplicate", + ], + "custom_keys": [], + "date_created": "1516348115", + "date_modified": "1516348115", + "description": "test project #1", + "fullname": "test", + "id": 1, + "milestones": {}, + "name": "test", + "namespace": None, + "parent": None, + "priorities": {}, + "tags": [], + "url_path": "test", + "user": {"fullname": "PY C", "name": "pingou"}, + }, + "status": "Open", + "tags": [], + "threshold_reached": None, + "title": "Test PR", + "uid": "e8b68df8711648deac67c3afed15a798", + "updated_on": "1516348115", + "user": {"fullname": "PY C", "name": "pingou"}, + }, + ) + + +class PagureFlaskApiForkPRDiffStatstests(tests.Modeltests): + """ Tests for the flask API of pagure for the diff stats endpoint of PRs + """ + + maxDiff = None + + def setUp(self): + """ Set up the environnment, ran before every tests. """ + super(PagureFlaskApiForkPRDiffStatstests, self).setUp() + + pagure.config.config["REQUESTS_FOLDER"] = None + + tests.create_projects(self.session) + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) + tests.create_projects_git( + os.path.join(self.path, "requests"), bare=True + ) + tests.add_readme_git_repo(os.path.join(self.path, "repos", "test.git")) + tests.add_commit_git_repo( + os.path.join(self.path, "repos", "test.git"), ncommits=5 + ) + tests.add_commit_git_repo( + os.path.join(self.path, "repos", "test.git"), branch="test" + ) + # Create the pull-request to close - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") req = pagure.lib.query.new_pull_request( session=self.session, repo_from=repo, - branch_from='test', + branch_from="test", repo_to=repo, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") - @patch('pagure.lib.git.update_git', MagicMock(return_value=True)) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.git.update_git", MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_api_pull_request_diffstats_no_repo(self): """ Test the api_pull_request_merge method of the flask api. """ - output = self.app.get('/api/0/invalid/pull-request/404/diffstats') + output = self.app.get("/api/0/invalid/pull-request/404/diffstats") self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertEqual( - data, - {'error': 'Project not found', 'error_code': 'ENOPROJECT'} + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) - @patch('pagure.lib.git.update_git', MagicMock(return_value=True)) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.git.update_git", MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_api_pull_request_diffstats_no_pr(self): """ Test the api_pull_request_merge method of the flask api. """ - output = self.app.get('/api/0/test/pull-request/404/diffstats') + output = self.app.get("/api/0/test/pull-request/404/diffstats") self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertEqual( - data, - {'error': 'Pull-Request not found', 'error_code': 'ENOREQ'} + data, {"error": "Pull-Request not found", "error_code": "ENOREQ"} ) - @patch('pagure.lib.git.update_git', MagicMock(return_value=True)) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.git.update_git", MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_api_pull_request_diffstats_file_modified(self): """ Test the api_pull_request_merge method of the flask api. """ - output = self.app.get('/api/0/test/pull-request/1/diffstats') + output = self.app.get("/api/0/test/pull-request/1/diffstats") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertEqual( data, { - 'sources': { - 'lines_added': 10, - 'lines_removed': 0, + "sources": { + "lines_added": 10, + "lines_removed": 0, "new_id": "540916fbd3d825d14cc0c0b2397606fda69379ce", "old_id": "265f133a7c94ede4cb183dd808219c5bf9e08f87", - 'old_path': 'sources', - 'status': 'M' + "old_path": "sources", + "status": "M", } - } + }, ) - @patch('pagure.lib.git.update_git', MagicMock(return_value=True)) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.git.update_git", MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_api_pull_request_diffstats_file_added_mofidied(self): """ Test the api_pull_request_merge method of the flask api. """ tests.add_commit_git_repo( - os.path.join(self.path, 'repos', 'test.git'), ncommits=5) + os.path.join(self.path, "repos", "test.git"), ncommits=5 + ) tests.add_readme_git_repo( - os.path.join(self.path, 'repos', 'test.git'), - readme_name='README.md', branch='test') + os.path.join(self.path, "repos", "test.git"), + readme_name="README.md", + branch="test", + ) - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") self.assertEqual(len(repo.requests), 1) - output = self.app.get('/api/0/test/pull-request/1/diffstats') + output = self.app.get("/api/0/test/pull-request/1/diffstats") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertTrue( - data in - [ + data + in [ { - "README.md": { - "lines_added": 5, - "lines_removed": 0, - "new_id": "bd913ea153650b94f33f53e5164c36a28b761bf4", - "old_id": "0000000000000000000000000000000000000000", - "old_path": "README.md", - "status": "A" - }, - "sources": { - "lines_added": 5, - "lines_removed": 0, - "new_id": "540916fbd3d825d14cc0c0b2397606fda69379ce", - "old_id": "293500070b9dfc6ab66e31383f8f7fccf6a95fe2", - "old_path": "sources", - "status": "M" - } + "README.md": { + "lines_added": 5, + "lines_removed": 0, + "new_id": "bd913ea153650b94f33f53e5164c36a28b761bf4", + "old_id": "0000000000000000000000000000000000000000", + "old_path": "README.md", + "status": "A", + }, + "sources": { + "lines_added": 5, + "lines_removed": 0, + "new_id": "540916fbd3d825d14cc0c0b2397606fda69379ce", + "old_id": "293500070b9dfc6ab66e31383f8f7fccf6a95fe2", + "old_path": "sources", + "status": "M", + }, }, { - "README.md": { - "lines_added": 5, - "lines_removed": 0, - "new_id": "bd913ea153650b94f33f53e5164c36a28b761bf4", - "old_id": "0000000000000000000000000000000000000000", - "old_path": "README.md", - "status": "A" - }, - "sources": { - "lines_added": 10, - "lines_removed": 0, - "new_id": "540916fbd3d825d14cc0c0b2397606fda69379ce", - "old_id": "265f133a7c94ede4cb183dd808219c5bf9e08f87", - "old_path": "sources", - "status": "M" - } - } + "README.md": { + "lines_added": 5, + "lines_removed": 0, + "new_id": "bd913ea153650b94f33f53e5164c36a28b761bf4", + "old_id": "0000000000000000000000000000000000000000", + "old_path": "README.md", + "status": "A", + }, + "sources": { + "lines_added": 10, + "lines_removed": 0, + "new_id": "540916fbd3d825d14cc0c0b2397606fda69379ce", + "old_id": "265f133a7c94ede4cb183dd808219c5bf9e08f87", + "old_path": "sources", + "status": "M", + }, + }, ] ) - @patch('pagure.lib.git.update_git', MagicMock(return_value=True)) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.git.update_git", MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_api_pull_request_diffstats_file_modified_deleted(self): """ Test the api_pull_request_merge method of the flask api. """ - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") self.assertEqual(len(repo.requests), 1) pagure.lib.tasks.update_pull_request(repo.requests[0].uid) tests.add_readme_git_repo( - os.path.join(self.path, 'repos', 'test.git'), - readme_name='README.md', branch='test') + os.path.join(self.path, "repos", "test.git"), + readme_name="README.md", + branch="test", + ) tests.remove_file_git_repo( - os.path.join(self.path, 'repos', 'test.git'), - filename='sources', branch='test') + os.path.join(self.path, "repos", "test.git"), + filename="sources", + branch="test", + ) - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") self.assertEqual(len(repo.requests), 1) pagure.lib.tasks.update_pull_request(repo.requests[0].uid) - output = self.app.get('/api/0/test/pull-request/1/diffstats') + output = self.app.get("/api/0/test/pull-request/1/diffstats") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertEqual( data, { - "README.md": { - "lines_added": 5, - "lines_removed": 0, - "new_id": "bd913ea153650b94f33f53e5164c36a28b761bf4", - "old_id": "0000000000000000000000000000000000000000", - "old_path": "README.md", - "status": "A" - }, - "sources": { - "lines_added": 0, - "lines_removed": 5, - "new_id": "0000000000000000000000000000000000000000", - "old_id": "265f133a7c94ede4cb183dd808219c5bf9e08f87", - "old_path": "sources", - "status": "D" - } - } + "README.md": { + "lines_added": 5, + "lines_removed": 0, + "new_id": "bd913ea153650b94f33f53e5164c36a28b761bf4", + "old_id": "0000000000000000000000000000000000000000", + "old_path": "README.md", + "status": "A", + }, + "sources": { + "lines_added": 0, + "lines_removed": 5, + "new_id": "0000000000000000000000000000000000000000", + "old_id": "265f133a7c94ede4cb183dd808219c5bf9e08f87", + "old_path": "sources", + "status": "D", + }, + }, ) + class PagureApiThresholdReachedTests(tests.Modeltests): """ Test the behavior of the threshold_reached value returned by the API. """ + maxDiff = None def _clean_data(self, data): - data['project']['date_created'] = '1516348115' - data['project']['date_modified'] = '1516348115' - data['repo_from']['date_created'] = '1516348115' - data['repo_from']['date_modified'] = '1516348115' - data['uid'] = 'e8b68df8711648deac67c3afed15a798' - data['commit_start'] = '114f1b468a5f05e635fcb6394273f3f907386eab' - data['commit_stop'] = '114f1b468a5f05e635fcb6394273f3f907386eab' - data['date_created'] = '1516348115' - data['last_updated'] = '1516348115' - data['updated_on'] = '1516348115' - data['comments'] = [] # Let's not check the comments + data["project"]["date_created"] = "1516348115" + data["project"]["date_modified"] = "1516348115" + data["repo_from"]["date_created"] = "1516348115" + data["repo_from"]["date_modified"] = "1516348115" + data["uid"] = "e8b68df8711648deac67c3afed15a798" + data["commit_start"] = "114f1b468a5f05e635fcb6394273f3f907386eab" + data["commit_stop"] = "114f1b468a5f05e635fcb6394273f3f907386eab" + data["date_created"] = "1516348115" + data["last_updated"] = "1516348115" + data["updated_on"] = "1516348115" + data["comments"] = [] # Let's not check the comments return data - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def setUp(self): """ Set up the environment for the tests. """ super(PagureApiThresholdReachedTests, self).setUp() tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'repos'), bare=True) - tests.create_projects_git(os.path.join(self.path, 'requests'), - bare=True) - tests.add_readme_git_repo(os.path.join(self.path, 'repos', 'test.git')) - tests.add_commit_git_repo(os.path.join(self.path, 'repos', 'test.git'), - branch='test') + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) + tests.create_projects_git( + os.path.join(self.path, "requests"), bare=True + ) + tests.add_readme_git_repo(os.path.join(self.path, "repos", "test.git")) + tests.add_commit_git_repo( + os.path.join(self.path, "repos", "test.git"), branch="test" + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Add a token for user `foo` item = pagure.lib.model.Token( - id='aaabbbcccddd_foo', + id="aaabbbcccddd_foo", user_id=2, project_id=1, expiration=datetime.datetime.utcnow() - + datetime.timedelta(days=30) + + datetime.timedelta(days=30), ) self.session.add(item) self.session.commit() tests.create_tokens_acl(self.session, token_id="aaabbbcccddd_foo") # Add a minimal required score: - repo = pagure.lib.query._get_project(self.session, 'test') + repo = pagure.lib.query._get_project(self.session, "test") settings = repo.settings - settings['Minimum_score_to_merge_pull-request'] = 2 + settings["Minimum_score_to_merge_pull-request"] = 2 repo.settings = settings self.session.add(repo) self.session.commit() - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'title': 'Test PR', - 'initial_comment': 'Nothing much, the changes speak for themselves', - 'branch_to': 'master', - 'branch_from': 'test', + "title": "Test PR", + "initial_comment": "Nothing much, the changes speak for themselves", + "branch_to": "master", + "branch_from": "test", } output = self.app.post( - '/api/0/test/pull-request/new', headers=headers, data=data) + "/api/0/test/pull-request/new", headers=headers, data=data + ) self.assertEqual(output.status_code, 200) self.expected_data = { - 'assignee': None, - 'branch': 'master', - 'branch_from': 'test', - 'cached_merge_status': 'unknown', - 'closed_at': None, - 'closed_by': None, - 'comments': [], - 'commit_start': '114f1b468a5f05e635fcb6394273f3f907386eab', - 'commit_stop': '114f1b468a5f05e635fcb6394273f3f907386eab', - 'date_created': '1516348115', - 'id': 1, - 'initial_comment': 'Nothing much, the changes speak for themselves', - 'last_updated': '1516348115', - 'project': {'access_groups': {'admin': [], - 'commit': [], - 'ticket':[]}, - 'access_users': {'admin': [], - 'commit': [], - 'owner': ['pingou'], - 'ticket': []}, - 'close_status': ['Invalid', - 'Insufficient data', - 'Fixed', - 'Duplicate'], - 'custom_keys': [], - 'date_created': '1516348115', - 'date_modified': '1516348115', - 'description': 'test project #1', - 'fullname': 'test', - 'id': 1, - 'milestones': {}, - 'name': 'test', - 'namespace': None, - 'parent': None, - 'priorities': {}, - 'tags': [], - 'url_path': 'test', - 'user': {'fullname': 'PY C', 'name': 'pingou'}}, - 'remote_git': None, - 'repo_from': {'access_groups': {'admin': [], - 'commit': [], - 'ticket': []}, - 'access_users': {'admin': [], - 'commit': [], - 'owner': ['pingou'], - 'ticket': []}, - 'close_status': ['Invalid', - 'Insufficient data', - 'Fixed', - 'Duplicate'], - 'custom_keys': [], - 'date_created': '1516348115', - 'date_modified': '1516348115', - 'description': 'test project #1', - 'fullname': 'test', - 'id': 1, - 'milestones': {}, - 'name': 'test', - 'namespace': None, - 'parent': None, - 'priorities': {}, - 'tags': [], - 'url_path': 'test', - 'user': {'fullname': 'PY C', 'name': 'pingou'}}, - 'status': 'Open', + "assignee": None, + "branch": "master", + "branch_from": "test", + "cached_merge_status": "unknown", + "closed_at": None, + "closed_by": None, + "comments": [], + "commit_start": "114f1b468a5f05e635fcb6394273f3f907386eab", + "commit_stop": "114f1b468a5f05e635fcb6394273f3f907386eab", + "date_created": "1516348115", + "id": 1, + "initial_comment": "Nothing much, the changes speak for themselves", + "last_updated": "1516348115", + "project": { + "access_groups": {"admin": [], "commit": [], "ticket": []}, + "access_users": { + "admin": [], + "commit": [], + "owner": ["pingou"], + "ticket": [], + }, + "close_status": [ + "Invalid", + "Insufficient data", + "Fixed", + "Duplicate", + ], + "custom_keys": [], + "date_created": "1516348115", + "date_modified": "1516348115", + "description": "test project #1", + "fullname": "test", + "id": 1, + "milestones": {}, + "name": "test", + "namespace": None, + "parent": None, + "priorities": {}, + "tags": [], + "url_path": "test", + "user": {"fullname": "PY C", "name": "pingou"}, + }, + "remote_git": None, + "repo_from": { + "access_groups": {"admin": [], "commit": [], "ticket": []}, + "access_users": { + "admin": [], + "commit": [], + "owner": ["pingou"], + "ticket": [], + }, + "close_status": [ + "Invalid", + "Insufficient data", + "Fixed", + "Duplicate", + ], + "custom_keys": [], + "date_created": "1516348115", + "date_modified": "1516348115", + "description": "test project #1", + "fullname": "test", + "id": 1, + "milestones": {}, + "name": "test", + "namespace": None, + "parent": None, + "priorities": {}, + "tags": [], + "url_path": "test", + "user": {"fullname": "PY C", "name": "pingou"}, + }, + "status": "Open", "tags": [], - 'threshold_reached': None, - 'title': 'Test PR', - 'uid': 'e8b68df8711648deac67c3afed15a798', - 'updated_on': '1516348115', - 'user': {'fullname': 'PY C', 'name': 'pingou'} + "threshold_reached": None, + "title": "Test PR", + "uid": "e8b68df8711648deac67c3afed15a798", + "updated_on": "1516348115", + "user": {"fullname": "PY C", "name": "pingou"}, } def test_api_pull_request_no_comments(self): @@ -3317,7 +3419,7 @@ class PagureApiThresholdReachedTests(tests.Modeltests): """ # Check the PR with 0 comment: - output = self.app.get('/api/0/test/pull-request/1') + output = self.app.get("/api/0/test/pull-request/1") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) data = self._clean_data(data) @@ -3328,20 +3430,16 @@ class PagureApiThresholdReachedTests(tests.Modeltests): """ Check the value of threshold_reach when the PR has one comment. """ # Check the PR with 1 comment: - headers = {'Authorization': 'token aaabbbcccddd'} - data = { - 'comment': 'This is a very interesting solution :thumbsup:', - } + headers = {"Authorization": "token aaabbbcccddd"} + data = {"comment": "This is a very interesting solution :thumbsup:"} output = self.app.post( - '/api/0/test/pull-request/1/comment', data=data, headers=headers) + "/api/0/test/pull-request/1/comment", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'Comment added'} - ) + self.assertDictEqual(data, {"message": "Comment added"}) - output = self.app.get('/api/0/test/pull-request/1') + output = self.app.get("/api/0/test/pull-request/1") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) data = self._clean_data(data) @@ -3353,33 +3451,25 @@ class PagureApiThresholdReachedTests(tests.Modeltests): but from the same person. """ # Add two comments from the same user: - headers = {'Authorization': 'token aaabbbcccddd'} - data = { - 'comment': 'This is a very interesting solution :thumbsup:', - } + headers = {"Authorization": "token aaabbbcccddd"} + data = {"comment": "This is a very interesting solution :thumbsup:"} output = self.app.post( - '/api/0/test/pull-request/1/comment', data=data, headers=headers) + "/api/0/test/pull-request/1/comment", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'Comment added'} - ) + self.assertDictEqual(data, {"message": "Comment added"}) - headers = {'Authorization': 'token aaabbbcccddd'} - data = { - 'comment': 'Indeed it is :thumbsup:', - } + headers = {"Authorization": "token aaabbbcccddd"} + data = {"comment": "Indeed it is :thumbsup:"} output = self.app.post( - '/api/0/test/pull-request/1/comment', data=data, headers=headers) + "/api/0/test/pull-request/1/comment", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'Comment added'} - ) + self.assertDictEqual(data, {"message": "Comment added"}) - output = self.app.get('/api/0/test/pull-request/1') + output = self.app.get("/api/0/test/pull-request/1") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) data = self._clean_data(data) @@ -3391,37 +3481,29 @@ class PagureApiThresholdReachedTests(tests.Modeltests): from two different persons. """ # Add two comments from two users: - headers = {'Authorization': 'token aaabbbcccddd'} - data = { - 'comment': 'This is a very interesting solution :thumbsup:', - } + headers = {"Authorization": "token aaabbbcccddd"} + data = {"comment": "This is a very interesting solution :thumbsup:"} output = self.app.post( - '/api/0/test/pull-request/1/comment', data=data, headers=headers) + "/api/0/test/pull-request/1/comment", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'Comment added'} - ) + self.assertDictEqual(data, {"message": "Comment added"}) - headers = {'Authorization': 'token aaabbbcccddd_foo'} - data = { - 'comment': 'Indeed it is :thumbsup:', - } + headers = {"Authorization": "token aaabbbcccddd_foo"} + data = {"comment": "Indeed it is :thumbsup:"} output = self.app.post( - '/api/0/test/pull-request/1/comment', data=data, headers=headers) + "/api/0/test/pull-request/1/comment", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'Comment added'} - ) + self.assertDictEqual(data, {"message": "Comment added"}) - output = self.app.get('/api/0/test/pull-request/1') + output = self.app.get("/api/0/test/pull-request/1") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) data = self._clean_data(data) - data['comments'] = [] # Let's not check the comments + data["comments"] = [] # Let's not check the comments self.expected_data["threshold_reached"] = True self.assertDictEqual(data, self.expected_data) @@ -3431,49 +3513,39 @@ class PagureApiThresholdReachedTests(tests.Modeltests): +1 to -1. """ # Add three comments from two users: - headers = {'Authorization': 'token aaabbbcccddd'} - data = { - 'comment': 'This is a very interesting solution :thumbsup:', - } + headers = {"Authorization": "token aaabbbcccddd"} + data = {"comment": "This is a very interesting solution :thumbsup:"} output = self.app.post( - '/api/0/test/pull-request/1/comment', data=data, headers=headers) + "/api/0/test/pull-request/1/comment", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'Comment added'} - ) + self.assertDictEqual(data, {"message": "Comment added"}) - headers = {'Authorization': 'token aaabbbcccddd_foo'} - data = { - 'comment': 'Indeed it is :thumbsup:', - } + headers = {"Authorization": "token aaabbbcccddd_foo"} + data = {"comment": "Indeed it is :thumbsup:"} output = self.app.post( - '/api/0/test/pull-request/1/comment', data=data, headers=headers) + "/api/0/test/pull-request/1/comment", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'Comment added'} - ) + self.assertDictEqual(data, {"message": "Comment added"}) data = { - 'comment': 'Nevermind the bug is elsewhere in fact :thumbsdown:', + "comment": "Nevermind the bug is elsewhere in fact :thumbsdown:" } output = self.app.post( - '/api/0/test/pull-request/1/comment', data=data, headers=headers) + "/api/0/test/pull-request/1/comment", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'Comment added'} - ) + self.assertDictEqual(data, {"message": "Comment added"}) - output = self.app.get('/api/0/test/pull-request/1') + output = self.app.get("/api/0/test/pull-request/1") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) data = self._clean_data(data) - data['comments'] = [] # Let's not check the comments + data["comments"] = [] # Let's not check the comments self.expected_data["threshold_reached"] = False self.assertDictEqual(data, self.expected_data) @@ -3483,52 +3555,40 @@ class PagureApiThresholdReachedTests(tests.Modeltests): -1 to +1 """ # Add three comments from two users: - headers = {'Authorization': 'token aaabbbcccddd'} - data = { - 'comment': 'This is a very interesting solution :thumbsup:', - } + headers = {"Authorization": "token aaabbbcccddd"} + data = {"comment": "This is a very interesting solution :thumbsup:"} output = self.app.post( - '/api/0/test/pull-request/1/comment', data=data, headers=headers) + "/api/0/test/pull-request/1/comment", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'Comment added'} - ) + self.assertDictEqual(data, {"message": "Comment added"}) - headers = {'Authorization': 'token aaabbbcccddd_foo'} - data = { - 'comment': 'I think the bug is elsewhere :thumbsdown:', - } + headers = {"Authorization": "token aaabbbcccddd_foo"} + data = {"comment": "I think the bug is elsewhere :thumbsdown:"} output = self.app.post( - '/api/0/test/pull-request/1/comment', data=data, headers=headers) + "/api/0/test/pull-request/1/comment", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'Comment added'} - ) + self.assertDictEqual(data, {"message": "Comment added"}) - data = { - 'comment': 'Nevermind it is here :thumbsup:', - } + data = {"comment": "Nevermind it is here :thumbsup:"} output = self.app.post( - '/api/0/test/pull-request/1/comment', data=data, headers=headers) + "/api/0/test/pull-request/1/comment", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'Comment added'} - ) + self.assertDictEqual(data, {"message": "Comment added"}) - output = self.app.get('/api/0/test/pull-request/1') + output = self.app.get("/api/0/test/pull-request/1") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) data = self._clean_data(data) - data['comments'] = [] # Let's not check the comments + data["comments"] = [] # Let's not check the comments self.expected_data["threshold_reached"] = True self.assertDictEqual(data, self.expected_data) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/test_pagure_flask_api_fork_assign.py b/tests/test_pagure_flask_api_fork_assign.py index eeb80c4..677523c 100644 --- a/tests/test_pagure_flask_api_fork_assign.py +++ b/tests/test_pagure_flask_api_fork_assign.py @@ -25,8 +25,9 @@ import munch from mock import patch, MagicMock from sqlalchemy.exc import SQLAlchemyError -sys.path.insert(0, os.path.join(os.path.dirname( - os.path.abspath(__file__)), '..')) +sys.path.insert( + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") +) import pagure.lib.query import tests @@ -37,40 +38,39 @@ class PagureFlaskApiForkAssigntests(tests.SimplePagureTest): maxDiff = None - @patch('pagure.lib.git.update_git', MagicMock(return_value=True)) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.git.update_git", MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def setUp(self): """ Set up the environnment, ran before every tests. """ super(PagureFlaskApiForkAssigntests, self).setUp() tests.create_projects(self.session) tests.add_content_git_repo( - os.path.join(self.path, "repos", "test.git")) + os.path.join(self.path, "repos", "test.git") + ) # Fork - project = pagure.lib.query.get_authorized_project( - self.session, 'test') + project = pagure.lib.query.get_authorized_project(self.session, "test") task = pagure.lib.query.fork_project( - session=self.session, - user='pingou', - repo=project, + session=self.session, user="pingou", repo=project ) self.session.commit() self.assertEqual( task.get(), - {'endpoint': 'ui_ns.view_repo', - 'repo': 'test', - 'namespace': None, - 'username': 'pingou'}) + { + "endpoint": "ui_ns.view_repo", + "repo": "test", + "namespace": None, + "username": "pingou", + }, + ) tests.add_readme_git_repo( - os.path.join(self.path, "repos", "forks", "pingou", "test.git")) - project = pagure.lib.query.get_authorized_project( - self.session, 'test') + os.path.join(self.path, "repos", "forks", "pingou", "test.git") + ) + project = pagure.lib.query.get_authorized_project(self.session, "test") fork = pagure.lib.query.get_authorized_project( - self.session, - 'test', - user='pingou', + self.session, "test", user="pingou" ) tests.create_tokens(self.session) @@ -79,64 +79,63 @@ class PagureFlaskApiForkAssigntests(tests.SimplePagureTest): req = pagure.lib.query.new_pull_request( session=self.session, repo_from=fork, - branch_from='master', + branch_from="master", repo_to=project, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") # Assert the PR is open self.session = pagure.lib.query.create_session(self.dbpath) - project = pagure.lib.query.get_authorized_project( - self.session, 'test') + project = pagure.lib.query.get_authorized_project(self.session, "test") self.assertEqual(len(project.requests), 1) self.assertEqual(project.requests[0].status, "Open") # Check how the PR renders in the API and the UI - output = self.app.get('/api/0/test/pull-request/1') + output = self.app.get("/api/0/test/pull-request/1") self.assertEqual(output.status_code, 200) - output = self.app.get('/test/pull-request/1') + output = self.app.get("/test/pull-request/1") self.assertEqual(output.status_code, 200) def test_api_assign_pr_invalid_project_namespace(self): """ Test api_pull_request_assign method when the project doesn't exist. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Valid token, wrong project output = self.app.post( - '/api/0/somenamespace/test3/pull-request/1/assign', headers=headers) + "/api/0/somenamespace/test3/pull-request/1/assign", headers=headers + ) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, - {'error': 'Invalid or expired token. Please visit ' - 'http://localhost.localdomain/settings#api-keys to get or renew your ' - 'API token.', - 'error_code': 'EINVALIDTOK'} - + { + "error": "Invalid or expired token. Please visit " + "http://localhost.localdomain/settings#api-keys to get or renew your " + "API token.", + "error_code": "EINVALIDTOK", + }, ) def test_api_assign_pr_invalid_project(self): """ Test api_pull_request_assign method when the project doesn't exist. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Invalid project - output = self.app.post('/api/0/foo/pull-request/1/assign', headers=headers) + output = self.app.post( + "/api/0/foo/pull-request/1/assign", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) def test_api_assign_pr_invalid_project_token(self): @@ -144,102 +143,96 @@ class PagureFlaskApiForkAssigntests(tests.SimplePagureTest): to the project. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Valid token, wrong project - output = self.app.post('/api/0/test2/pull-request/1/assign', headers=headers) + output = self.app.post( + "/api/0/test2/pull-request/1/assign", headers=headers + ) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(sorted(data.keys()), ['error', 'error_code']) - self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.value, data['error']) + self.assertEqual(sorted(data.keys()), ["error", "error_code"]) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.name, data['error_code']) + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) def test_api_assign_pr_invalid_pr(self): """ Test api_pull_request_assign method when asking for an invalid PR """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # No input - output = self.app.post('/api/0/test/pull-request/404/assign', headers=headers) + output = self.app.post( + "/api/0/test/pull-request/404/assign", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - {'error': 'Pull-Request not found', 'error_code': 'ENOREQ'} + data, {"error": "Pull-Request not found", "error_code": "ENOREQ"} ) def test_api_assign_pr_no_input(self): """ Test api_pull_request_assign method when no input is specified """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # No input - output = self.app.post('/api/0/test/pull-request/1/assign', headers=headers) + output = self.app.post( + "/api/0/test/pull-request/1/assign", headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'Nothing to change'} - ) + self.assertDictEqual(data, {"message": "Nothing to change"}) def test_api_assign_pr_assigned(self): """ Test api_pull_request_assign method when with valid input """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} - data = { - 'assignee': 'pingou', - } + data = {"assignee": "pingou"} # Valid request output = self.app.post( - '/api/0/test/pull-request/1/assign', data=data, headers=headers) + "/api/0/test/pull-request/1/assign", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'Request assigned'} - ) + self.assertDictEqual(data, {"message": "Request assigned"}) def test_api_assign_pr_unassigned(self): """ Test api_pull_request_assign method when unassigning """ self.test_api_assign_pr_assigned() - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = {} # Un-assign output = self.app.post( - '/api/0/test/pull-request/1/assign', data=data, headers=headers) + "/api/0/test/pull-request/1/assign", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'Request assignee reset'} - ) + self.assertDictEqual(data, {"message": "Request assignee reset"}) def test_api_assign_pr_unassigned_twice(self): """ Test api_pull_request_assign method when unassigning """ self.test_api_assign_pr_unassigned() - headers = {'Authorization': 'token aaabbbcccddd'} - data = {'assignee': None} + headers = {"Authorization": "token aaabbbcccddd"} + data = {"assignee": None} # Un-assign output = self.app.post( - '/api/0/test/pull-request/1/assign', data=data, headers=headers) + "/api/0/test/pull-request/1/assign", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'Nothing to change'} - ) + self.assertDictEqual(data, {"message": "Nothing to change"}) def test_api_assign_pr_unassigned_empty_string(self): """ Test api_pull_request_assign method when unassigning with an @@ -247,19 +240,17 @@ class PagureFlaskApiForkAssigntests(tests.SimplePagureTest): """ self.test_api_assign_pr_assigned() - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Un-assign - data = {'assignee': ''} + data = {"assignee": ""} output = self.app.post( - '/api/0/test/pull-request/1/assign', data=data, headers=headers) + "/api/0/test/pull-request/1/assign", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'Request assignee reset'} - ) + self.assertDictEqual(data, {"message": "Request assignee reset"}) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/test_pagure_flask_api_fork_update.py b/tests/test_pagure_flask_api_fork_update.py index a574443..d7c5d86 100644 --- a/tests/test_pagure_flask_api_fork_update.py +++ b/tests/test_pagure_flask_api_fork_update.py @@ -25,8 +25,9 @@ import munch from mock import patch, MagicMock from sqlalchemy.exc import SQLAlchemyError -sys.path.insert(0, os.path.join(os.path.dirname( - os.path.abspath(__file__)), '..')) +sys.path.insert( + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") +) import pagure.lib.query import tests @@ -37,40 +38,39 @@ class PagureFlaskApiForkUpdatetests(tests.SimplePagureTest): maxDiff = None - @patch('pagure.lib.git.update_git', MagicMock(return_value=True)) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.git.update_git", MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def setUp(self): """ Set up the environnment, ran before every tests. """ super(PagureFlaskApiForkUpdatetests, self).setUp() tests.create_projects(self.session) tests.add_content_git_repo( - os.path.join(self.path, "repos", "test.git")) + os.path.join(self.path, "repos", "test.git") + ) # Fork - project = pagure.lib.query.get_authorized_project( - self.session, 'test') + project = pagure.lib.query.get_authorized_project(self.session, "test") task = pagure.lib.query.fork_project( - session=self.session, - user='pingou', - repo=project, + session=self.session, user="pingou", repo=project ) self.session.commit() self.assertEqual( task.get(), - {'endpoint': 'ui_ns.view_repo', - 'repo': 'test', - 'namespace': None, - 'username': 'pingou'}) + { + "endpoint": "ui_ns.view_repo", + "repo": "test", + "namespace": None, + "username": "pingou", + }, + ) tests.add_readme_git_repo( - os.path.join(self.path, "repos", "forks", "pingou", "test.git")) - project = pagure.lib.query.get_authorized_project( - self.session, 'test') + os.path.join(self.path, "repos", "forks", "pingou", "test.git") + ) + project = pagure.lib.query.get_authorized_project(self.session, "test") fork = pagure.lib.query.get_authorized_project( - self.session, - 'test', - user='pingou', + self.session, "test", user="pingou" ) tests.create_tokens(self.session) @@ -79,64 +79,61 @@ class PagureFlaskApiForkUpdatetests(tests.SimplePagureTest): req = pagure.lib.query.new_pull_request( session=self.session, repo_from=fork, - branch_from='master', + branch_from="master", repo_to=project, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") # Assert the PR is open self.session = pagure.lib.query.create_session(self.dbpath) - project = pagure.lib.query.get_authorized_project( - self.session, 'test') + project = pagure.lib.query.get_authorized_project(self.session, "test") self.assertEqual(len(project.requests), 1) self.assertEqual(project.requests[0].status, "Open") # Check how the PR renders in the API and the UI - output = self.app.get('/api/0/test/pull-request/1') + output = self.app.get("/api/0/test/pull-request/1") self.assertEqual(output.status_code, 200) - output = self.app.get('/test/pull-request/1') + output = self.app.get("/test/pull-request/1") self.assertEqual(output.status_code, 200) def test_api_pull_request_update_invalid_project_namespace(self): """ Test api_pull_request_update method when the project doesn't exist. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Valid token, wrong project output = self.app.post( - '/api/0/somenamespace/test3/pull-request/1', headers=headers) + "/api/0/somenamespace/test3/pull-request/1", headers=headers + ) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, - {'error': 'Invalid or expired token. Please visit ' - 'http://localhost.localdomain/settings#api-keys to get or renew your ' - 'API token.', - 'error_code': 'EINVALIDTOK'} - + { + "error": "Invalid or expired token. Please visit " + "http://localhost.localdomain/settings#api-keys to get or renew your " + "API token.", + "error_code": "EINVALIDTOK", + }, ) def test_api_pull_request_update_invalid_project(self): """ Test api_pull_request_update method when the project doesn't exist. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Invalid project - output = self.app.post('/api/0/foo/pull-request/1', headers=headers) + output = self.app.post("/api/0/foo/pull-request/1", headers=headers) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) def test_api_pull_request_update_invalid_project_token(self): @@ -144,324 +141,360 @@ class PagureFlaskApiForkUpdatetests(tests.SimplePagureTest): to the project. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Valid token, wrong project - output = self.app.post('/api/0/test2/pull-request/1', headers=headers) + output = self.app.post("/api/0/test2/pull-request/1", headers=headers) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(sorted(data.keys()), ['error', 'error_code']) + self.assertEqual(sorted(data.keys()), ["error", "error_code"]) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.value, data['error']) - self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.name, data['error_code']) + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) def test_api_pull_request_update_invalid_pr(self): """ Test api_assign_pull_request method when asking for an invalid PR """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Invalid PR id - output = self.app.post('/api/0/test/pull-request/404', headers=headers) + output = self.app.post("/api/0/test/pull-request/404", headers=headers) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - {'error': 'Pull-Request not found', 'error_code': 'ENOREQ'} + data, {"error": "Pull-Request not found", "error_code": "ENOREQ"} ) def test_api_pull_request_update_no_input(self): """ Test api_assign_pull_request method when no input is specified """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # No input - output = self.app.post('/api/0/test/pull-request/1', headers=headers) + output = self.app.post("/api/0/test/pull-request/1", headers=headers) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - 'error': 'Invalid or incomplete input submitted', - 'error_code': 'EINVALIDREQ', - 'errors': {'title': ['This field is required.']} - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": {"title": ["This field is required."]}, + }, ) def test_api_pull_request_update_insufficient_input(self): """ Test api_assign_pull_request method when no input is specified """ - headers = {'Authorization': 'token aaabbbcccddd'} - data = {'initial_comment': 'will not work'} + headers = {"Authorization": "token aaabbbcccddd"} + data = {"initial_comment": "will not work"} # Missing the required title field - output = self.app.post('/api/0/test/pull-request/1', data=data, headers=headers) + output = self.app.post( + "/api/0/test/pull-request/1", data=data, headers=headers + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, - { - 'error': 'Invalid or incomplete input submitted', - 'error_code': 'EINVALIDREQ', - 'errors': {'title': ['This field is required.']} - } + { + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": {"title": ["This field is required."]}, + }, ) def test_api_pull_request_update_edited(self): """ Test api_assign_pull_request method when with valid input """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'title': 'edited test PR', - 'initial_comment': 'Edited initial comment', + "title": "edited test PR", + "initial_comment": "Edited initial comment", } # Valid request output = self.app.post( - '/api/0/test/pull-request/1', data=data, headers=headers) + "/api/0/test/pull-request/1", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) # Hard-code all the values that will change from a test to another # because either random or time-based - data['date_created'] = '1551276260' - data['last_updated'] = '1551276261' - data['updated_on'] = '1551276260' - data['commit_start'] = '5f5d609db65d447f77ba00e25afd17ba5053344b' - data['commit_stop'] = '5f5d609db65d447f77ba00e25afd17ba5053344b' - data['project']['date_created'] = '1551276259' - data['project']['date_modified'] = '1551276259' - data['repo_from']['date_created'] = '1551276259' - data['repo_from']['date_modified'] = '1551276259' - data['repo_from']['parent']['date_created'] = '1551276259' - data['repo_from']['parent']['date_modified'] = '1551276259' - data['uid'] = 'a2bddecc8ea548e88c22a0df77670092' + data["date_created"] = "1551276260" + data["last_updated"] = "1551276261" + data["updated_on"] = "1551276260" + data["commit_start"] = "5f5d609db65d447f77ba00e25afd17ba5053344b" + data["commit_stop"] = "5f5d609db65d447f77ba00e25afd17ba5053344b" + data["project"]["date_created"] = "1551276259" + data["project"]["date_modified"] = "1551276259" + data["repo_from"]["date_created"] = "1551276259" + data["repo_from"]["date_modified"] = "1551276259" + data["repo_from"]["parent"]["date_created"] = "1551276259" + data["repo_from"]["parent"]["date_modified"] = "1551276259" + data["uid"] = "a2bddecc8ea548e88c22a0df77670092" self.assertDictEqual( data, { - 'assignee': None, - 'branch': 'master', - 'branch_from': 'master', - 'cached_merge_status': 'unknown', - 'closed_at': None, - 'closed_by': None, - 'comments': [], - 'commit_start': '5f5d609db65d447f77ba00e25afd17ba5053344b', - 'commit_stop': '5f5d609db65d447f77ba00e25afd17ba5053344b', - 'date_created': '1551276260', - 'id': 1, - 'initial_comment': 'Edited initial comment', - 'last_updated': '1551276261', - 'project': {'access_groups': {'admin': [], 'commit': [], 'ticket': []}, - 'access_users': {'admin': [], - 'commit': [], - 'owner': ['pingou'], - 'ticket': []}, - 'close_status': ['Invalid', - 'Insufficient data', - 'Fixed', - 'Duplicate'], - 'custom_keys': [], - 'date_created': '1551276259', - 'date_modified': '1551276259', - 'description': 'test project #1', - 'fullname': 'test', - 'id': 1, - 'milestones': {}, - 'name': 'test', - 'namespace': None, - 'parent': None, - 'priorities': {}, - 'tags': [], - 'url_path': 'test', - 'user': {'fullname': 'PY C', 'name': 'pingou'}}, - 'remote_git': None, - 'repo_from': {'access_groups': {'admin': [], 'commit': [], 'ticket': []}, - 'access_users': {'admin': [], - 'commit': [], - 'owner': ['pingou'], - 'ticket': []}, - 'close_status': [], - 'custom_keys': [], - 'date_created': '1551276259', - 'date_modified': '1551276259', - 'description': 'test project #1', - 'fullname': 'forks/pingou/test', - 'id': 4, - 'milestones': {}, - 'name': 'test', - 'namespace': None, - 'parent': {'access_groups': {'admin': [], - 'commit': [], - 'ticket': []}, - 'access_users': {'admin': [], - 'commit': [], - 'owner': ['pingou'], - 'ticket': []}, - 'close_status': ['Invalid', - 'Insufficient data', - 'Fixed', - 'Duplicate'], - 'custom_keys': [], - 'date_created': '1551276259', - 'date_modified': '1551276259', - 'description': 'test project #1', - 'fullname': 'test', - 'id': 1, - 'milestones': {}, - 'name': 'test', - 'namespace': None, - 'parent': None, - 'priorities': {}, - 'tags': [], - 'url_path': 'test', - 'user': {'fullname': 'PY C', 'name': 'pingou'}}, - 'priorities': {}, - 'tags': [], - 'url_path': 'fork/pingou/test', - 'user': {'fullname': 'PY C', 'name': 'pingou'}}, - 'status': 'Open', - 'tags': [], - 'threshold_reached': None, - 'title': 'edited test PR', - 'uid': 'a2bddecc8ea548e88c22a0df77670092', - 'updated_on': '1551276260', - 'user': {'fullname': 'PY C', 'name': 'pingou'} - } + "assignee": None, + "branch": "master", + "branch_from": "master", + "cached_merge_status": "unknown", + "closed_at": None, + "closed_by": None, + "comments": [], + "commit_start": "5f5d609db65d447f77ba00e25afd17ba5053344b", + "commit_stop": "5f5d609db65d447f77ba00e25afd17ba5053344b", + "date_created": "1551276260", + "id": 1, + "initial_comment": "Edited initial comment", + "last_updated": "1551276261", + "project": { + "access_groups": {"admin": [], "commit": [], "ticket": []}, + "access_users": { + "admin": [], + "commit": [], + "owner": ["pingou"], + "ticket": [], + }, + "close_status": [ + "Invalid", + "Insufficient data", + "Fixed", + "Duplicate", + ], + "custom_keys": [], + "date_created": "1551276259", + "date_modified": "1551276259", + "description": "test project #1", + "fullname": "test", + "id": 1, + "milestones": {}, + "name": "test", + "namespace": None, + "parent": None, + "priorities": {}, + "tags": [], + "url_path": "test", + "user": {"fullname": "PY C", "name": "pingou"}, + }, + "remote_git": None, + "repo_from": { + "access_groups": {"admin": [], "commit": [], "ticket": []}, + "access_users": { + "admin": [], + "commit": [], + "owner": ["pingou"], + "ticket": [], + }, + "close_status": [], + "custom_keys": [], + "date_created": "1551276259", + "date_modified": "1551276259", + "description": "test project #1", + "fullname": "forks/pingou/test", + "id": 4, + "milestones": {}, + "name": "test", + "namespace": None, + "parent": { + "access_groups": { + "admin": [], + "commit": [], + "ticket": [], + }, + "access_users": { + "admin": [], + "commit": [], + "owner": ["pingou"], + "ticket": [], + }, + "close_status": [ + "Invalid", + "Insufficient data", + "Fixed", + "Duplicate", + ], + "custom_keys": [], + "date_created": "1551276259", + "date_modified": "1551276259", + "description": "test project #1", + "fullname": "test", + "id": 1, + "milestones": {}, + "name": "test", + "namespace": None, + "parent": None, + "priorities": {}, + "tags": [], + "url_path": "test", + "user": {"fullname": "PY C", "name": "pingou"}, + }, + "priorities": {}, + "tags": [], + "url_path": "fork/pingou/test", + "user": {"fullname": "PY C", "name": "pingou"}, + }, + "status": "Open", + "tags": [], + "threshold_reached": None, + "title": "edited test PR", + "uid": "a2bddecc8ea548e88c22a0df77670092", + "updated_on": "1551276260", + "user": {"fullname": "PY C", "name": "pingou"}, + }, ) def test_api_pull_request_update_edited_no_comment(self): """ Test api_assign_pull_request method when with valid input """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} - data = { - 'title': 'edited test PR', - } + data = {"title": "edited test PR"} # Valid request output = self.app.post( - '/api/0/test/pull-request/1', data=data, headers=headers) + "/api/0/test/pull-request/1", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) # Hard-code all the values that will change from a test to another # because either random or time-based - data['date_created'] = '1551276260' - data['last_updated'] = '1551276261' - data['updated_on'] = '1551276260' - data['commit_start'] = '5f5d609db65d447f77ba00e25afd17ba5053344b' - data['commit_stop'] = '5f5d609db65d447f77ba00e25afd17ba5053344b' - data['project']['date_created'] = '1551276259' - data['project']['date_modified'] = '1551276259' - data['repo_from']['date_created'] = '1551276259' - data['repo_from']['date_modified'] = '1551276259' - data['repo_from']['parent']['date_created'] = '1551276259' - data['repo_from']['parent']['date_modified'] = '1551276259' - data['uid'] = 'a2bddecc8ea548e88c22a0df77670092' + data["date_created"] = "1551276260" + data["last_updated"] = "1551276261" + data["updated_on"] = "1551276260" + data["commit_start"] = "5f5d609db65d447f77ba00e25afd17ba5053344b" + data["commit_stop"] = "5f5d609db65d447f77ba00e25afd17ba5053344b" + data["project"]["date_created"] = "1551276259" + data["project"]["date_modified"] = "1551276259" + data["repo_from"]["date_created"] = "1551276259" + data["repo_from"]["date_modified"] = "1551276259" + data["repo_from"]["parent"]["date_created"] = "1551276259" + data["repo_from"]["parent"]["date_modified"] = "1551276259" + data["uid"] = "a2bddecc8ea548e88c22a0df77670092" self.assertDictEqual( data, { - 'assignee': None, - 'branch': 'master', - 'branch_from': 'master', - 'cached_merge_status': 'unknown', - 'closed_at': None, - 'closed_by': None, - 'comments': [], - 'commit_start': '5f5d609db65d447f77ba00e25afd17ba5053344b', - 'commit_stop': '5f5d609db65d447f77ba00e25afd17ba5053344b', - 'date_created': '1551276260', - 'id': 1, - 'initial_comment': '', - 'last_updated': '1551276261', - 'project': {'access_groups': {'admin': [], 'commit': [], 'ticket': []}, - 'access_users': {'admin': [], - 'commit': [], - 'owner': ['pingou'], - 'ticket': []}, - 'close_status': ['Invalid', - 'Insufficient data', - 'Fixed', - 'Duplicate'], - 'custom_keys': [], - 'date_created': '1551276259', - 'date_modified': '1551276259', - 'description': 'test project #1', - 'fullname': 'test', - 'id': 1, - 'milestones': {}, - 'name': 'test', - 'namespace': None, - 'parent': None, - 'priorities': {}, - 'tags': [], - 'url_path': 'test', - 'user': {'fullname': 'PY C', 'name': 'pingou'}}, - 'remote_git': None, - 'repo_from': {'access_groups': {'admin': [], 'commit': [], 'ticket': []}, - 'access_users': {'admin': [], - 'commit': [], - 'owner': ['pingou'], - 'ticket': []}, - 'close_status': [], - 'custom_keys': [], - 'date_created': '1551276259', - 'date_modified': '1551276259', - 'description': 'test project #1', - 'fullname': 'forks/pingou/test', - 'id': 4, - 'milestones': {}, - 'name': 'test', - 'namespace': None, - 'parent': {'access_groups': {'admin': [], - 'commit': [], - 'ticket': []}, - 'access_users': {'admin': [], - 'commit': [], - 'owner': ['pingou'], - 'ticket': []}, - 'close_status': ['Invalid', - 'Insufficient data', - 'Fixed', - 'Duplicate'], - 'custom_keys': [], - 'date_created': '1551276259', - 'date_modified': '1551276259', - 'description': 'test project #1', - 'fullname': 'test', - 'id': 1, - 'milestones': {}, - 'name': 'test', - 'namespace': None, - 'parent': None, - 'priorities': {}, - 'tags': [], - 'url_path': 'test', - 'user': {'fullname': 'PY C', 'name': 'pingou'}}, - 'priorities': {}, - 'tags': [], - 'url_path': 'fork/pingou/test', - 'user': {'fullname': 'PY C', 'name': 'pingou'}}, - 'status': 'Open', - 'tags': [], - 'threshold_reached': None, - 'title': 'edited test PR', - 'uid': 'a2bddecc8ea548e88c22a0df77670092', - 'updated_on': '1551276260', - 'user': {'fullname': 'PY C', 'name': 'pingou'} - } + "assignee": None, + "branch": "master", + "branch_from": "master", + "cached_merge_status": "unknown", + "closed_at": None, + "closed_by": None, + "comments": [], + "commit_start": "5f5d609db65d447f77ba00e25afd17ba5053344b", + "commit_stop": "5f5d609db65d447f77ba00e25afd17ba5053344b", + "date_created": "1551276260", + "id": 1, + "initial_comment": "", + "last_updated": "1551276261", + "project": { + "access_groups": {"admin": [], "commit": [], "ticket": []}, + "access_users": { + "admin": [], + "commit": [], + "owner": ["pingou"], + "ticket": [], + }, + "close_status": [ + "Invalid", + "Insufficient data", + "Fixed", + "Duplicate", + ], + "custom_keys": [], + "date_created": "1551276259", + "date_modified": "1551276259", + "description": "test project #1", + "fullname": "test", + "id": 1, + "milestones": {}, + "name": "test", + "namespace": None, + "parent": None, + "priorities": {}, + "tags": [], + "url_path": "test", + "user": {"fullname": "PY C", "name": "pingou"}, + }, + "remote_git": None, + "repo_from": { + "access_groups": {"admin": [], "commit": [], "ticket": []}, + "access_users": { + "admin": [], + "commit": [], + "owner": ["pingou"], + "ticket": [], + }, + "close_status": [], + "custom_keys": [], + "date_created": "1551276259", + "date_modified": "1551276259", + "description": "test project #1", + "fullname": "forks/pingou/test", + "id": 4, + "milestones": {}, + "name": "test", + "namespace": None, + "parent": { + "access_groups": { + "admin": [], + "commit": [], + "ticket": [], + }, + "access_users": { + "admin": [], + "commit": [], + "owner": ["pingou"], + "ticket": [], + }, + "close_status": [ + "Invalid", + "Insufficient data", + "Fixed", + "Duplicate", + ], + "custom_keys": [], + "date_created": "1551276259", + "date_modified": "1551276259", + "description": "test project #1", + "fullname": "test", + "id": 1, + "milestones": {}, + "name": "test", + "namespace": None, + "parent": None, + "priorities": {}, + "tags": [], + "url_path": "test", + "user": {"fullname": "PY C", "name": "pingou"}, + }, + "priorities": {}, + "tags": [], + "url_path": "fork/pingou/test", + "user": {"fullname": "PY C", "name": "pingou"}, + }, + "status": "Open", + "tags": [], + "threshold_reached": None, + "title": "edited test PR", + "uid": "a2bddecc8ea548e88c22a0df77670092", + "updated_on": "1551276260", + "user": {"fullname": "PY C", "name": "pingou"}, + }, ) def test_api_pull_request_update_edited_linked(self): """ Test api_assign_pull_request method when with valid input """ - project = pagure.lib.query.get_authorized_project( - self.session, 'test') + project = pagure.lib.query.get_authorized_project(self.session, "test") self.assertEqual(len(project.requests), 1) self.assertEqual(len(project.requests[0].related_issues), 0) self.assertEqual(len(project.issues), 0) @@ -470,142 +503,160 @@ class PagureFlaskApiForkUpdatetests(tests.SimplePagureTest): msg = pagure.lib.query.new_issue( session=self.session, repo=project, - title='tést íssüé', - content='We should work on this', - user='pingou', + title="tést íssüé", + content="We should work on this", + user="pingou", ) self.session.commit() - self.assertEqual(msg.title, 'tést íssüé') + self.assertEqual(msg.title, "tést íssüé") - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'title': 'edited test PR', - 'initial_comment': 'Edited initial comment\n\n' - 'this PR fixes #2 \n\nThanks', + "title": "edited test PR", + "initial_comment": "Edited initial comment\n\n" + "this PR fixes #2 \n\nThanks", } # Valid request output = self.app.post( - '/api/0/test/pull-request/1', data=data, headers=headers) + "/api/0/test/pull-request/1", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) # Hard-code all the values that will change from a test to another # because either random or time-based - data['date_created'] = '1551276260' - data['last_updated'] = '1551276261' - data['updated_on'] = '1551276260' - data['commit_start'] = '5f5d609db65d447f77ba00e25afd17ba5053344b' - data['commit_stop'] = '5f5d609db65d447f77ba00e25afd17ba5053344b' - data['project']['date_created'] = '1551276259' - data['project']['date_modified'] = '1551276259' - data['repo_from']['date_created'] = '1551276259' - data['repo_from']['date_modified'] = '1551276259' - data['repo_from']['parent']['date_created'] = '1551276259' - data['repo_from']['parent']['date_modified'] = '1551276259' - data['uid'] = 'a2bddecc8ea548e88c22a0df77670092' + data["date_created"] = "1551276260" + data["last_updated"] = "1551276261" + data["updated_on"] = "1551276260" + data["commit_start"] = "5f5d609db65d447f77ba00e25afd17ba5053344b" + data["commit_stop"] = "5f5d609db65d447f77ba00e25afd17ba5053344b" + data["project"]["date_created"] = "1551276259" + data["project"]["date_modified"] = "1551276259" + data["repo_from"]["date_created"] = "1551276259" + data["repo_from"]["date_modified"] = "1551276259" + data["repo_from"]["parent"]["date_created"] = "1551276259" + data["repo_from"]["parent"]["date_modified"] = "1551276259" + data["uid"] = "a2bddecc8ea548e88c22a0df77670092" self.assertDictEqual( data, { - 'assignee': None, - 'branch': 'master', - 'branch_from': 'master', - 'cached_merge_status': 'unknown', - 'closed_at': None, - 'closed_by': None, - 'comments': [], - 'commit_start': '5f5d609db65d447f77ba00e25afd17ba5053344b', - 'commit_stop': '5f5d609db65d447f77ba00e25afd17ba5053344b', - 'date_created': '1551276260', - 'id': 1, - 'initial_comment': 'Edited initial comment\n\nthis PR ' - 'fixes #2 \n\nThanks', - 'last_updated': '1551276261', - 'project': {'access_groups': {'admin': [], 'commit': [], 'ticket': []}, - 'access_users': {'admin': [], - 'commit': [], - 'owner': ['pingou'], - 'ticket': []}, - 'close_status': ['Invalid', - 'Insufficient data', - 'Fixed', - 'Duplicate'], - 'custom_keys': [], - 'date_created': '1551276259', - 'date_modified': '1551276259', - 'description': 'test project #1', - 'fullname': 'test', - 'id': 1, - 'milestones': {}, - 'name': 'test', - 'namespace': None, - 'parent': None, - 'priorities': {}, - 'tags': [], - 'url_path': 'test', - 'user': {'fullname': 'PY C', 'name': 'pingou'}}, - 'remote_git': None, - 'repo_from': {'access_groups': {'admin': [], 'commit': [], 'ticket': []}, - 'access_users': {'admin': [], - 'commit': [], - 'owner': ['pingou'], - 'ticket': []}, - 'close_status': [], - 'custom_keys': [], - 'date_created': '1551276259', - 'date_modified': '1551276259', - 'description': 'test project #1', - 'fullname': 'forks/pingou/test', - 'id': 4, - 'milestones': {}, - 'name': 'test', - 'namespace': None, - 'parent': {'access_groups': {'admin': [], - 'commit': [], - 'ticket': []}, - 'access_users': {'admin': [], - 'commit': [], - 'owner': ['pingou'], - 'ticket': []}, - 'close_status': ['Invalid', - 'Insufficient data', - 'Fixed', - 'Duplicate'], - 'custom_keys': [], - 'date_created': '1551276259', - 'date_modified': '1551276259', - 'description': 'test project #1', - 'fullname': 'test', - 'id': 1, - 'milestones': {}, - 'name': 'test', - 'namespace': None, - 'parent': None, - 'priorities': {}, - 'tags': [], - 'url_path': 'test', - 'user': {'fullname': 'PY C', 'name': 'pingou'}}, - 'priorities': {}, - 'tags': [], - 'url_path': 'fork/pingou/test', - 'user': {'fullname': 'PY C', 'name': 'pingou'}}, - 'status': 'Open', - 'tags': [], - 'threshold_reached': None, - 'title': 'edited test PR', - 'uid': 'a2bddecc8ea548e88c22a0df77670092', - 'updated_on': '1551276260', - 'user': {'fullname': 'PY C', 'name': 'pingou'} - } + "assignee": None, + "branch": "master", + "branch_from": "master", + "cached_merge_status": "unknown", + "closed_at": None, + "closed_by": None, + "comments": [], + "commit_start": "5f5d609db65d447f77ba00e25afd17ba5053344b", + "commit_stop": "5f5d609db65d447f77ba00e25afd17ba5053344b", + "date_created": "1551276260", + "id": 1, + "initial_comment": "Edited initial comment\n\nthis PR " + "fixes #2 \n\nThanks", + "last_updated": "1551276261", + "project": { + "access_groups": {"admin": [], "commit": [], "ticket": []}, + "access_users": { + "admin": [], + "commit": [], + "owner": ["pingou"], + "ticket": [], + }, + "close_status": [ + "Invalid", + "Insufficient data", + "Fixed", + "Duplicate", + ], + "custom_keys": [], + "date_created": "1551276259", + "date_modified": "1551276259", + "description": "test project #1", + "fullname": "test", + "id": 1, + "milestones": {}, + "name": "test", + "namespace": None, + "parent": None, + "priorities": {}, + "tags": [], + "url_path": "test", + "user": {"fullname": "PY C", "name": "pingou"}, + }, + "remote_git": None, + "repo_from": { + "access_groups": {"admin": [], "commit": [], "ticket": []}, + "access_users": { + "admin": [], + "commit": [], + "owner": ["pingou"], + "ticket": [], + }, + "close_status": [], + "custom_keys": [], + "date_created": "1551276259", + "date_modified": "1551276259", + "description": "test project #1", + "fullname": "forks/pingou/test", + "id": 4, + "milestones": {}, + "name": "test", + "namespace": None, + "parent": { + "access_groups": { + "admin": [], + "commit": [], + "ticket": [], + }, + "access_users": { + "admin": [], + "commit": [], + "owner": ["pingou"], + "ticket": [], + }, + "close_status": [ + "Invalid", + "Insufficient data", + "Fixed", + "Duplicate", + ], + "custom_keys": [], + "date_created": "1551276259", + "date_modified": "1551276259", + "description": "test project #1", + "fullname": "test", + "id": 1, + "milestones": {}, + "name": "test", + "namespace": None, + "parent": None, + "priorities": {}, + "tags": [], + "url_path": "test", + "user": {"fullname": "PY C", "name": "pingou"}, + }, + "priorities": {}, + "tags": [], + "url_path": "fork/pingou/test", + "user": {"fullname": "PY C", "name": "pingou"}, + }, + "status": "Open", + "tags": [], + "threshold_reached": None, + "title": "edited test PR", + "uid": "a2bddecc8ea548e88c22a0df77670092", + "updated_on": "1551276260", + "user": {"fullname": "PY C", "name": "pingou"}, + }, ) - project = pagure.lib.query.get_authorized_project( - self.session, 'test') + project = pagure.lib.query.get_authorized_project(self.session, "test") self.assertEqual(len(project.requests), 1) self.assertEqual(len(project.requests[0].related_issues), 1) self.assertEqual(len(project.issues), 1) self.assertEqual(len(project.issues[0].related_prs), 1) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/test_pagure_flask_api_group.py b/tests/test_pagure_flask_api_group.py index 773d6a9..f8b83f0 100644 --- a/tests/test_pagure_flask_api_group.py +++ b/tests/test_pagure_flask_api_group.py @@ -16,8 +16,9 @@ import sys import os import json -sys.path.insert(0, os.path.join(os.path.dirname( - os.path.abspath(__file__)), '..')) +sys.path.insert( + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") +) import pagure.api import pagure.lib.query @@ -33,15 +34,15 @@ class PagureFlaskApiGroupTests(tests.SimplePagureTest): """ Set up the environnment, ran before every tests. """ super(PagureFlaskApiGroupTests, self).setUp() - pagure.config.config['REQUESTS_FOLDER'] = None + pagure.config.config["REQUESTS_FOLDER"] = None msg = pagure.lib.query.add_group( self.session, - group_name='some_group', - display_name='Some Group', + group_name="some_group", + display_name="Some Group", description=None, - group_type='bar', - user='pingou', + group_type="bar", + user="pingou", is_admin=False, blacklist=[], ) @@ -49,110 +50,101 @@ class PagureFlaskApiGroupTests(tests.SimplePagureTest): tests.create_projects(self.session) - project = pagure.lib.query._get_project(self.session, 'test2') + project = pagure.lib.query._get_project(self.session, "test2") msg = pagure.lib.query.add_group_to_project( session=self.session, project=project, - new_group='some_group', - user='pingou', + new_group="some_group", + user="pingou", ) self.session.commit() - self.assertEqual(msg, 'Group added') + self.assertEqual(msg, "Group added") def test_api_groups(self): """ Test the api_groups function. """ # Add a couple of groups so that we can list them item = pagure.lib.model.PagureGroup( - group_name='group1', - group_type='user', - display_name='User group', + group_name="group1", + group_type="user", + display_name="User group", user_id=1, # pingou ) self.session.add(item) item = pagure.lib.model.PagureGroup( - group_name='rel-eng', - group_type='user', - display_name='Release engineering group', + group_name="rel-eng", + group_type="user", + display_name="Release engineering group", user_id=1, # pingou ) self.session.add(item) self.session.commit() - output = self.app.get('/api/0/groups') + output = self.app.get("/api/0/groups") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(data['groups'], ['some_group', 'group1', 'rel-eng']) + self.assertEqual(data["groups"], ["some_group", "group1", "rel-eng"]) self.assertEqual( - sorted(data.keys()), - ['groups', 'pagination', 'total_groups']) - self.assertEqual(data['total_groups'], 3) + sorted(data.keys()), ["groups", "pagination", "total_groups"] + ) + self.assertEqual(data["total_groups"], 3) - output = self.app.get('/api/0/groups?pattern=re') + output = self.app.get("/api/0/groups?pattern=re") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(data['groups'], ['rel-eng']) + self.assertEqual(data["groups"], ["rel-eng"]) self.assertEqual( - sorted(data.keys()), - ['groups', 'pagination', 'total_groups']) - self.assertEqual(data['total_groups'], 1) + sorted(data.keys()), ["groups", "pagination", "total_groups"] + ) + self.assertEqual(data["total_groups"], 1) def test_api_groups_extended(self): """ Test the api_groups function. """ # Add a couple of groups so that we can list them item = pagure.lib.model.PagureGroup( - group_name='group1', - group_type='user', - display_name='User group', + group_name="group1", + group_type="user", + display_name="User group", user_id=1, # pingou ) self.session.add(item) item = pagure.lib.model.PagureGroup( - group_name='rel-eng', - group_type='user', - display_name='Release engineering group', + group_name="rel-eng", + group_type="user", + display_name="Release engineering group", user_id=1, # pingou ) self.session.add(item) self.session.commit() - output = self.app.get('/api/0/groups?extended=1') + output = self.app.get("/api/0/groups?extended=1") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." self.assertEqual( data, { "groups": [ - { - "description": None, - "name": "some_group" - }, - { - "description": None, - "name": "group1" - }, - { - "description": None, - "name": "rel-eng" - } + {"description": None, "name": "some_group"}, + {"description": None, "name": "group1"}, + {"description": None, "name": "rel-eng"}, ], - u'pagination': { - u'first': u'http://localhost...', - u'last': u'http://localhost...', - u'next': None, - u'page': 1, - u'pages': 1, - u'per_page': 20, - u'prev': None + "pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "page": 1, + "pages": 1, + "per_page": 20, + "prev": None, }, - "total_groups": 3 - } + "total_groups": 3, + }, ) def test_api_view_group_authenticated(self): @@ -162,8 +154,8 @@ class PagureFlaskApiGroupTests(tests.SimplePagureTest): """ tests.create_tokens(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} - output = self.app.get('/api/0/group/some_group', headers=headers) + headers = {"Authorization": "token aaabbbcccddd"} + output = self.app.get("/api/0/group/some_group", headers=headers) self.assertEqual(output.status_code, 200) exp = { "display_name": "Some Group", @@ -171,19 +163,16 @@ class PagureFlaskApiGroupTests(tests.SimplePagureTest): "creator": { "fullname": "PY C", "default_email": "bar@pingou.com", - "emails": [ - "bar@pingou.com", - "foo@pingou.com" - ], - "name": "pingou" + "emails": ["bar@pingou.com", "foo@pingou.com"], + "name": "pingou", }, "members": ["pingou"], "date_created": "1492020239", "group_type": "user", - "name": "some_group" + "name": "some_group", } data = json.loads(output.get_data(as_text=True)) - data['date_created'] = '1492020239' + data["date_created"] = "1492020239" self.assertDictEqual(data, exp) def test_api_view_group_unauthenticated(self): @@ -191,22 +180,19 @@ class PagureFlaskApiGroupTests(tests.SimplePagureTest): Test the api_view_group method of the flask api with an unauthenticated user. The tested group has one member. """ - output = self.app.get('/api/0/group/some_group') + output = self.app.get("/api/0/group/some_group") self.assertEqual(output.status_code, 200) exp = { "display_name": "Some Group", "description": None, - "creator": { - "fullname": "PY C", - "name": "pingou" - }, + "creator": {"fullname": "PY C", "name": "pingou"}, "members": ["pingou"], "date_created": "1492020239", "group_type": "user", - "name": "some_group" + "name": "some_group", } data = json.loads(output.get_data(as_text=True)) - data['date_created'] = '1492020239' + data["date_created"] = "1492020239" self.assertDictEqual(data, exp) def test_api_view_group_two_members_authenticated(self): @@ -215,24 +201,28 @@ class PagureFlaskApiGroupTests(tests.SimplePagureTest): authenticated user. The tested group has two members. """ user = pagure.lib.model.User( - user='mprahl', - fullname='Matt Prahl', - password='foo', - default_email='mprahl@redhat.com', + user="mprahl", + fullname="Matt Prahl", + password="foo", + default_email="mprahl@redhat.com", ) self.session.add(user) self.session.commit() - group = pagure.lib.query.search_groups(self.session, group_name='some_group') + group = pagure.lib.query.search_groups( + self.session, group_name="some_group" + ) result = pagure.lib.query.add_user_to_group( - self.session, user.username, group, user.username, True) + self.session, user.username, group, user.username, True + ) self.assertEqual( - result, 'User `mprahl` added to the group `some_group`.') + result, "User `mprahl` added to the group `some_group`." + ) self.session.commit() tests.create_tokens(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} - output = self.app.get('/api/0/group/some_group', headers=headers) + headers = {"Authorization": "token aaabbbcccddd"} + output = self.app.get("/api/0/group/some_group", headers=headers) self.assertEqual(output.status_code, 200) exp = { "display_name": "Some Group", @@ -240,20 +230,17 @@ class PagureFlaskApiGroupTests(tests.SimplePagureTest): "creator": { "fullname": "PY C", "default_email": "bar@pingou.com", - "emails": [ - "bar@pingou.com", - "foo@pingou.com" - ], - "name": "pingou" + "emails": ["bar@pingou.com", "foo@pingou.com"], + "name": "pingou", }, "members": ["pingou", "mprahl"], "date_created": "1492020239", "group_type": "user", - "name": "some_group" + "name": "some_group", } self.maxDiff = None data = json.loads(output.get_data(as_text=True)) - data['date_created'] = '1492020239' + data["date_created"] = "1492020239" self.assertDictEqual(data, exp) def test_api_view_group_no_group_error(self): @@ -264,8 +251,8 @@ class PagureFlaskApiGroupTests(tests.SimplePagureTest): output = self.app.get("/api/0/group/some_group3") self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(data['error'], 'Group not found') - self.assertEqual(data['error_code'], 'ENOGROUP') + self.assertEqual(data["error"], "Group not found") + self.assertEqual(data["error_code"], "ENOGROUP") def test_api_view_group_w_projects_and_acl(self): """ @@ -274,9 +261,10 @@ class PagureFlaskApiGroupTests(tests.SimplePagureTest): """ tests.create_tokens(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} output = self.app.get( - '/api/0/group/some_group?projects=1', headers=headers) + "/api/0/group/some_group?projects=1", headers=headers + ) self.assertEqual(output.status_code, 200) exp = { "display_name": "Some Group", @@ -284,11 +272,8 @@ class PagureFlaskApiGroupTests(tests.SimplePagureTest): "creator": { "fullname": "PY C", "default_email": "bar@pingou.com", - "emails": [ - "bar@pingou.com", - "foo@pingou.com" - ], - "name": "pingou" + "emails": ["bar@pingou.com", "foo@pingou.com"], + "name": "pingou", }, "members": ["pingou"], "date_created": "1492020239", @@ -297,25 +282,21 @@ class PagureFlaskApiGroupTests(tests.SimplePagureTest): "projects": [ { "access_groups": { - "admin": [ - "some_group" - ], + "admin": ["some_group"], "commit": [], - "ticket": [] + "ticket": [], }, "access_users": { "admin": [], "commit": [], - "owner": [ - "pingou" - ], - "ticket": [] + "owner": ["pingou"], + "ticket": [], }, "close_status": [ "Invalid", "Insufficient data", "Fixed", - "Duplicate" + "Duplicate", ], "custom_keys": [], "date_created": "1492020239", @@ -330,28 +311,26 @@ class PagureFlaskApiGroupTests(tests.SimplePagureTest): "priorities": {}, "tags": [], "url_path": "test2", - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, } - ] + ], } data = json.loads(output.get_data(as_text=True)) - data['date_created'] = '1492020239' + data["date_created"] = "1492020239" projects = [] - for p in data['projects']: - p['date_created'] = '1492020239' - p['date_modified'] = '1492020239' + for p in data["projects"]: + p["date_created"] = "1492020239" + p["date_modified"] = "1492020239" projects.append(p) - data['projects'] = projects + data["projects"] = projects self.assertDictEqual(data, exp) output2 = self.app.get( - '/api/0/group/some_group?projects=1&acl=admin', headers=headers) + "/api/0/group/some_group?projects=1&acl=admin", headers=headers + ) self.assertListEqual( - output.get_data(as_text=True).split('\n'), - output2.get_data(as_text=True).split('\n') + output.get_data(as_text=True).split("\n"), + output2.get_data(as_text=True).split("\n"), ) def test_api_view_group_w_projects_and_acl_commit(self): @@ -360,16 +339,12 @@ class PagureFlaskApiGroupTests(tests.SimplePagureTest): to the commit ACL """ - output = self.app.get( - '/api/0/group/some_group?projects=1&acl=commit') + output = self.app.get("/api/0/group/some_group?projects=1&acl=commit") self.assertEqual(output.status_code, 200) exp = { "display_name": "Some Group", "description": None, - "creator": { - "fullname": "PY C", - "name": "pingou" - }, + "creator": {"fullname": "PY C", "name": "pingou"}, "members": ["pingou"], "date_created": "1492020239", "group_type": "user", @@ -377,25 +352,21 @@ class PagureFlaskApiGroupTests(tests.SimplePagureTest): "projects": [ { "access_groups": { - "admin": [ - "some_group" - ], + "admin": ["some_group"], "commit": [], - "ticket": [] + "ticket": [], }, "access_users": { "admin": [], "commit": [], - "owner": [ - "pingou" - ], - "ticket": [] + "owner": ["pingou"], + "ticket": [], }, "close_status": [ "Invalid", "Insufficient data", "Fixed", - "Duplicate" + "Duplicate", ], "custom_keys": [], "date_created": "1492020239", @@ -410,21 +381,18 @@ class PagureFlaskApiGroupTests(tests.SimplePagureTest): "priorities": {}, "tags": [], "url_path": "test2", - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, } - ] + ], } data = json.loads(output.get_data(as_text=True)) - data['date_created'] = '1492020239' + data["date_created"] = "1492020239" projects = [] - for p in data['projects']: - p['date_created'] = '1492020239' - p['date_modified'] = '1492020239' + for p in data["projects"]: + p["date_created"] = "1492020239" + p["date_modified"] = "1492020239" projects.append(p) - data['projects'] = projects + data["projects"] = projects self.assertDictEqual(data, exp) def test_api_view_group_w_projects_and_acl_ticket(self): @@ -433,16 +401,12 @@ class PagureFlaskApiGroupTests(tests.SimplePagureTest): to the ticket ACL """ - output = self.app.get( - '/api/0/group/some_group?projects=1&acl=ticket') + output = self.app.get("/api/0/group/some_group?projects=1&acl=ticket") self.assertEqual(output.status_code, 200) exp = { "display_name": "Some Group", "description": None, - "creator": { - "fullname": "PY C", - "name": "pingou" - }, + "creator": {"fullname": "PY C", "name": "pingou"}, "members": ["pingou"], "date_created": "1492020239", "group_type": "user", @@ -450,25 +414,21 @@ class PagureFlaskApiGroupTests(tests.SimplePagureTest): "projects": [ { "access_groups": { - "admin": [ - "some_group" - ], + "admin": ["some_group"], "commit": [], - "ticket": [] + "ticket": [], }, "access_users": { "admin": [], "commit": [], - "owner": [ - "pingou" - ], - "ticket": [] + "owner": ["pingou"], + "ticket": [], }, "close_status": [ "Invalid", "Insufficient data", "Fixed", - "Duplicate" + "Duplicate", ], "custom_keys": [], "date_created": "1492020239", @@ -483,21 +443,18 @@ class PagureFlaskApiGroupTests(tests.SimplePagureTest): "priorities": {}, "tags": [], "url_path": "test2", - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, } - ] + ], } data = json.loads(output.get_data(as_text=True)) - data['date_created'] = '1492020239' + data["date_created"] = "1492020239" projects = [] - for p in data['projects']: - p['date_created'] = '1492020239' - p['date_modified'] = '1492020239' + for p in data["projects"]: + p["date_created"] = "1492020239" + p["date_modified"] = "1492020239" projects.append(p) - data['projects'] = projects + data["projects"] = projects self.assertDictEqual(data, exp) def test_api_view_group_w_projects_and_acl_admin_no_project(self): @@ -507,35 +464,31 @@ class PagureFlaskApiGroupTests(tests.SimplePagureTest): """ # Make the group having only commit access - project = pagure.lib.query._get_project(self.session, 'test2') + project = pagure.lib.query._get_project(self.session, "test2") msg = pagure.lib.query.add_group_to_project( session=self.session, project=project, - new_group='some_group', - user='pingou', - access='commit', + new_group="some_group", + user="pingou", + access="commit", ) self.session.commit() - self.assertEqual(msg, 'Group access updated') + self.assertEqual(msg, "Group access updated") - output = self.app.get( - '/api/0/group/some_group?projects=1&acl=admin') + output = self.app.get("/api/0/group/some_group?projects=1&acl=admin") self.assertEqual(output.status_code, 200) exp = { "display_name": "Some Group", "description": None, - "creator": { - "fullname": "PY C", - "name": "pingou" - }, + "creator": {"fullname": "PY C", "name": "pingou"}, "members": ["pingou"], "date_created": "1492020239", "group_type": "user", "name": "some_group", - "projects": [] + "projects": [], } data = json.loads(output.get_data(as_text=True)) - data['date_created'] = '1492020239' + data["date_created"] = "1492020239" self.assertDictEqual(data, exp) def test_api_view_group_w_projects_and_acl_commit_no_project(self): @@ -545,35 +498,31 @@ class PagureFlaskApiGroupTests(tests.SimplePagureTest): """ # Make the group having only ticket access - project = pagure.lib.query._get_project(self.session, 'test2') + project = pagure.lib.query._get_project(self.session, "test2") msg = pagure.lib.query.add_group_to_project( session=self.session, project=project, - new_group='some_group', - user='pingou', - access='ticket', + new_group="some_group", + user="pingou", + access="ticket", ) self.session.commit() - self.assertEqual(msg, 'Group access updated') + self.assertEqual(msg, "Group access updated") - output = self.app.get( - '/api/0/group/some_group?projects=1&acl=commit') + output = self.app.get("/api/0/group/some_group?projects=1&acl=commit") self.assertEqual(output.status_code, 200) exp = { "display_name": "Some Group", "description": None, - "creator": { - "fullname": "PY C", - "name": "pingou" - }, + "creator": {"fullname": "PY C", "name": "pingou"}, "members": ["pingou"], "date_created": "1492020239", "group_type": "user", "name": "some_group", - "projects": [] + "projects": [], } data = json.loads(output.get_data(as_text=True)) - data['date_created'] = '1492020239' + data["date_created"] = "1492020239" self.assertDictEqual(data, exp) def test_api_view_group_w_projects_and_acl_ticket_no_project(self): @@ -584,32 +533,28 @@ class PagureFlaskApiGroupTests(tests.SimplePagureTest): # Create a group not linked to any project item = pagure.lib.model.PagureGroup( - group_name='rel-eng', - group_type='user', - display_name='Release engineering group', + group_name="rel-eng", + group_type="user", + display_name="Release engineering group", user_id=1, # pingou ) self.session.add(item) self.session.commit() - output = self.app.get( - '/api/0/group/rel-eng?projects=1&acl=ticket') + output = self.app.get("/api/0/group/rel-eng?projects=1&acl=ticket") self.assertEqual(output.status_code, 200) exp = { "display_name": "Release engineering group", "description": None, - "creator": { - "fullname": "PY C", - "name": "pingou" - }, + "creator": {"fullname": "PY C", "name": "pingou"}, "members": [], "date_created": "1492020239", "group_type": "user", "name": "rel-eng", - "projects": [] + "projects": [], } data = json.loads(output.get_data(as_text=True)) - data['date_created'] = '1492020239' + data["date_created"] = "1492020239" self.assertDictEqual(data, exp) diff --git a/tests/test_pagure_flask_api_issue.py b/tests/test_pagure_flask_api_issue.py index 92c6440..52c204e 100644 --- a/tests/test_pagure_flask_api_issue.py +++ b/tests/test_pagure_flask_api_issue.py @@ -25,275 +25,249 @@ import munch from mock import patch, MagicMock from sqlalchemy.exc import SQLAlchemyError -sys.path.insert(0, os.path.join(os.path.dirname( - os.path.abspath(__file__)), '..')) +sys.path.insert( + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") +) import pagure.lib.query import tests FULL_ISSUE_LIST = [ - { - "assignee": None, - "blocks": [], - "close_status": None, - "closed_at": None, - "closed_by": None, - "comments": [], - "content": "We should work on this", - "custom_fields": [], - "date_created": "1431414800", - "depends": [], - "id": 2, - "last_updated": "1431414800", - "milestone": None, - "priority": None, - "private": True, - "status": "Closed", - "tags": [], - "title": "Test issue", - "user": { - "fullname": "PY C", - "name": "pingou" - } - }, - { - "assignee": {'fullname': 'foo bar', 'name': 'foo'}, - "blocks": [], - "close_status": None, - "closed_at": None, - "closed_by": None, - "comments": [], - "content": "This issue needs attention", - "custom_fields": [], - "date_created": "1431414800", - "depends": [], - "id": 8, - "last_updated": "1431414800", - "milestone": None, - "priority": None, - "private": True, - "status": "Open", - "tags": [], - "title": "test issue1", - "user": { - "fullname": "PY C", - "name": "pingou" - } - }, - { - "assignee": None, - "blocks": [], - "close_status": None, - "closed_at": None, - "closed_by": None, - "comments": [], - "content": "This issue needs attention", - "custom_fields": [], - "date_created": "1431414800", - "depends": [], - "id": 7, - "last_updated": "1431414800", - "milestone": None, - "priority": None, - "private": True, - "status": "Open", - "tags": [], - "title": "test issue", - "user": { - "fullname": "PY C", - "name": "pingou" - } - }, - { - "assignee": None, - "blocks": [], - "close_status": None, - "closed_at": None, - "closed_by": None, - "comments": [], - "content": "This issue needs attention", - "custom_fields": [], - "date_created": "1431414800", - "depends": [], - "id": 6, - "last_updated": "1431414800", - "milestone": None, - "priority": None, - "private": False, - "status": "Open", - "tags": [], - "title": "test issue", - "user": { - "fullname": "PY C", - "name": "pingou" - } - }, - { - "assignee": None, - "blocks": [], - "close_status": None, - "closed_at": None, - "closed_by": None, - "comments": [], - "content": "This issue needs attention", - "custom_fields": [], - "date_created": "1431414800", - "depends": [], - "id": 5, - "last_updated": "1431414800", - "milestone": None, - "priority": None, - "private": False, - "status": "Open", - "tags": [], - "title": "test issue", - "user": { - "fullname": "PY C", - "name": "pingou" - } - }, - { - "assignee": None, - "blocks": [], - "close_status": None, - "closed_at": None, - "closed_by": None, - "comments": [], - "content": "This issue needs attention", - "custom_fields": [], - "date_created": "1431414800", - "depends": [], - "id": 4, - "last_updated": "1431414800", - "milestone": None, - "priority": None, - "private": False, - "status": "Open", - "tags": [], - "title": "test issue", - "user": { - "fullname": "PY C", - "name": "pingou" - } - }, - { - "assignee": None, - "blocks": [], - "close_status": None, - "closed_at": None, - "closed_by": None, - "comments": [], - "content": "This issue needs attention", - "custom_fields": [], - "date_created": "1431414800", - "depends": [], - "id": 3, - "last_updated": "1431414800", - "milestone": None, - "priority": None, - "private": False, - "status": "Open", - "tags": [], - "title": "test issue", - "user": { - "fullname": "PY C", - "name": "pingou" - } - }, - { - "assignee": None, - "blocks": [], - "close_status": None, - "closed_at": None, - "closed_by": None, - "comments": [], - "content": "This issue needs attention", - "custom_fields": [], - "date_created": "1431414800", - "depends": [], - "id": 2, - "last_updated": "1431414800", - "milestone": "milestone-1.0", - "priority": None, - "private": False, - "status": "Open", - "tags": [], - "title": "test issue", - "user": { - "fullname": "PY C", - "name": "pingou" - } - }, - { - "assignee": None, - "blocks": [], - "close_status": None, - "closed_at": None, - "closed_by": None, - "comments": [], - "content": "This issue needs attention", - "custom_fields": [], - "date_created": "1431414800", - "depends": [], - "id": 1, - "last_updated": "1431414800", - "milestone": None, - "priority": None, - "private": False, - "status": "Open", - "tags": [], - "title": "test issue", - "user": { - "fullname": "PY C", - "name": "pingou" - } - } + { + "assignee": None, + "blocks": [], + "close_status": None, + "closed_at": None, + "closed_by": None, + "comments": [], + "content": "We should work on this", + "custom_fields": [], + "date_created": "1431414800", + "depends": [], + "id": 2, + "last_updated": "1431414800", + "milestone": None, + "priority": None, + "private": True, + "status": "Closed", + "tags": [], + "title": "Test issue", + "user": {"fullname": "PY C", "name": "pingou"}, + }, + { + "assignee": {"fullname": "foo bar", "name": "foo"}, + "blocks": [], + "close_status": None, + "closed_at": None, + "closed_by": None, + "comments": [], + "content": "This issue needs attention", + "custom_fields": [], + "date_created": "1431414800", + "depends": [], + "id": 8, + "last_updated": "1431414800", + "milestone": None, + "priority": None, + "private": True, + "status": "Open", + "tags": [], + "title": "test issue1", + "user": {"fullname": "PY C", "name": "pingou"}, + }, + { + "assignee": None, + "blocks": [], + "close_status": None, + "closed_at": None, + "closed_by": None, + "comments": [], + "content": "This issue needs attention", + "custom_fields": [], + "date_created": "1431414800", + "depends": [], + "id": 7, + "last_updated": "1431414800", + "milestone": None, + "priority": None, + "private": True, + "status": "Open", + "tags": [], + "title": "test issue", + "user": {"fullname": "PY C", "name": "pingou"}, + }, + { + "assignee": None, + "blocks": [], + "close_status": None, + "closed_at": None, + "closed_by": None, + "comments": [], + "content": "This issue needs attention", + "custom_fields": [], + "date_created": "1431414800", + "depends": [], + "id": 6, + "last_updated": "1431414800", + "milestone": None, + "priority": None, + "private": False, + "status": "Open", + "tags": [], + "title": "test issue", + "user": {"fullname": "PY C", "name": "pingou"}, + }, + { + "assignee": None, + "blocks": [], + "close_status": None, + "closed_at": None, + "closed_by": None, + "comments": [], + "content": "This issue needs attention", + "custom_fields": [], + "date_created": "1431414800", + "depends": [], + "id": 5, + "last_updated": "1431414800", + "milestone": None, + "priority": None, + "private": False, + "status": "Open", + "tags": [], + "title": "test issue", + "user": {"fullname": "PY C", "name": "pingou"}, + }, + { + "assignee": None, + "blocks": [], + "close_status": None, + "closed_at": None, + "closed_by": None, + "comments": [], + "content": "This issue needs attention", + "custom_fields": [], + "date_created": "1431414800", + "depends": [], + "id": 4, + "last_updated": "1431414800", + "milestone": None, + "priority": None, + "private": False, + "status": "Open", + "tags": [], + "title": "test issue", + "user": {"fullname": "PY C", "name": "pingou"}, + }, + { + "assignee": None, + "blocks": [], + "close_status": None, + "closed_at": None, + "closed_by": None, + "comments": [], + "content": "This issue needs attention", + "custom_fields": [], + "date_created": "1431414800", + "depends": [], + "id": 3, + "last_updated": "1431414800", + "milestone": None, + "priority": None, + "private": False, + "status": "Open", + "tags": [], + "title": "test issue", + "user": {"fullname": "PY C", "name": "pingou"}, + }, + { + "assignee": None, + "blocks": [], + "close_status": None, + "closed_at": None, + "closed_by": None, + "comments": [], + "content": "This issue needs attention", + "custom_fields": [], + "date_created": "1431414800", + "depends": [], + "id": 2, + "last_updated": "1431414800", + "milestone": "milestone-1.0", + "priority": None, + "private": False, + "status": "Open", + "tags": [], + "title": "test issue", + "user": {"fullname": "PY C", "name": "pingou"}, + }, + { + "assignee": None, + "blocks": [], + "close_status": None, + "closed_at": None, + "closed_by": None, + "comments": [], + "content": "This issue needs attention", + "custom_fields": [], + "date_created": "1431414800", + "depends": [], + "id": 1, + "last_updated": "1431414800", + "milestone": None, + "priority": None, + "private": False, + "status": "Open", + "tags": [], + "title": "test issue", + "user": {"fullname": "PY C", "name": "pingou"}, + }, ] LCL_ISSUES = [ - { - 'assignee': None, - 'blocks': [], - 'close_status': None, - 'closed_at': None, - "closed_by": None, - 'comments': [], - 'content': 'Description', - 'custom_fields': [], - 'date_created': '1431414800', - 'depends': [], - 'id': 2, - 'last_updated': '1431414800', - 'milestone': None, - 'priority': None, - 'private': False, - 'status': 'Open', - 'tags': [], - 'title': 'Issue #2', - 'user': {'fullname': 'PY C', 'name': 'pingou'} - }, - { - 'assignee': None, - 'blocks': [], - 'close_status': None, - 'closed_at': None, - "closed_by": None, - 'comments': [], - 'content': 'Description', - 'custom_fields': [], - 'date_created': '1431414800', - 'depends': [], - 'id': 1, - 'last_updated': '1431414800', - 'milestone': None, - 'priority': None, - 'private': False, - 'status': 'Open', - 'tags': [], - 'title': 'Issue #1', - 'user': {'fullname': 'PY C', 'name': 'pingou'} - } + { + "assignee": None, + "blocks": [], + "close_status": None, + "closed_at": None, + "closed_by": None, + "comments": [], + "content": "Description", + "custom_fields": [], + "date_created": "1431414800", + "depends": [], + "id": 2, + "last_updated": "1431414800", + "milestone": None, + "priority": None, + "private": False, + "status": "Open", + "tags": [], + "title": "Issue #2", + "user": {"fullname": "PY C", "name": "pingou"}, + }, + { + "assignee": None, + "blocks": [], + "close_status": None, + "closed_at": None, + "closed_by": None, + "comments": [], + "content": "Description", + "custom_fields": [], + "date_created": "1431414800", + "depends": [], + "id": 1, + "last_updated": "1431414800", + "milestone": None, + "priority": None, + "private": False, + "status": "Open", + "tags": [], + "title": "Issue #1", + "user": {"fullname": "PY C", "name": "pingou"}, + }, ] @@ -305,1266 +279,1223 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): def setUp(self): """ Set up the environnment, ran before every tests. """ super(PagureFlaskApiIssuetests, self).setUp() - pagure.config.config['TICKETS_FOLDER'] = None + pagure.config.config["TICKETS_FOLDER"] = None def test_api_new_issue_wrong_token(self): """ Test the api_new_issue method of the flask api. """ tests.create_projects(self.session) tests.create_projects_git( - os.path.join(self.path, 'tickets'), bare=True) + os.path.join(self.path, "tickets"), bare=True + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Valid token, wrong project - output = self.app.post('/api/0/test2/new_issue', headers=headers) + output = self.app.post("/api/0/test2/new_issue", headers=headers) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(sorted(data.keys()), ['error', 'error_code']) - self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.value, data['error']) + self.assertEqual(sorted(data.keys()), ["error", "error_code"]) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.name, data['error_code']) + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) - @patch.dict('pagure.config.config', {'ENABLE_TICKETS_NAMESPACE': ['foobar']}) + @patch.dict( + "pagure.config.config", {"ENABLE_TICKETS_NAMESPACE": ["foobar"]} + ) def test_api_new_issue_wrong_namespace(self): """ Test the api_new_issue method of the flask api. """ tests.create_projects(self.session) tests.create_projects_git( - os.path.join(self.path, 'tickets'), bare=True) + os.path.join(self.path, "tickets"), bare=True + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Valid token, wrong project output = self.app.post( - '/api/0/somenamespace/test3/new_issue', headers=headers) + "/api/0/somenamespace/test3/new_issue", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(sorted(data.keys()), ['error', 'error_code']) + self.assertEqual(sorted(data.keys()), ["error", "error_code"]) self.assertEqual( - pagure.api.APIERROR.ETRACKERDISABLED.value, data['error']) + pagure.api.APIERROR.ETRACKERDISABLED.value, data["error"] + ) self.assertEqual( - pagure.api.APIERROR.ETRACKERDISABLED.name, data['error_code']) + pagure.api.APIERROR.ETRACKERDISABLED.name, data["error_code"] + ) def test_api_new_issue_no_input(self): """ Test the api_new_issue method of the flask api. """ tests.create_projects(self.session) tests.create_projects_git( - os.path.join(self.path, 'tickets'), bare=True) + os.path.join(self.path, "tickets"), bare=True + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # No input - output = self.app.post('/api/0/test/new_issue', headers=headers) + output = self.app.post("/api/0/test/new_issue", headers=headers) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - "error": "Invalid or incomplete input submitted", - "error_code": "EINVALIDREQ", - "errors": { - "issue_content": ["This field is required."], - "title": ["This field is required."], - } - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": { + "issue_content": ["This field is required."], + "title": ["This field is required."], + }, + }, ) def test_api_new_issue_invalid_repo(self): """ Test the api_new_issue method of the flask api. """ tests.create_projects(self.session) tests.create_projects_git( - os.path.join(self.path, 'tickets'), bare=True) + os.path.join(self.path, "tickets"), bare=True + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} - data = { - 'title': 'test issue' - } + data = {"title": "test issue"} # Invalid repo output = self.app.post( - '/api/0/foo/new_issue', data=data, headers=headers) + "/api/0/foo/new_issue", data=data, headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) def test_api_new_issue_invalid_request(self): """ Test the api_new_issue method of the flask api. """ tests.create_projects(self.session) tests.create_projects_git( - os.path.join(self.path, 'tickets'), bare=True) + os.path.join(self.path, "tickets"), bare=True + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Incomplete request output = self.app.post( - '/api/0/test/new_issue', data={}, headers=headers) + "/api/0/test/new_issue", data={}, headers=headers + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - "error": "Invalid or incomplete input submitted", - "error_code": "EINVALIDREQ", - "errors": { - "issue_content": ["This field is required."], - "title": ["This field is required."] - } - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": { + "issue_content": ["This field is required."], + "title": ["This field is required."], + }, + }, ) def test_api_new_issue(self): """ Test the api_new_issue method of the flask api. """ tests.create_projects(self.session) tests.create_projects_git( - os.path.join(self.path, 'tickets'), bare=True) + os.path.join(self.path, "tickets"), bare=True + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'title': 'test issue', - 'issue_content': 'This issue needs attention', + "title": "test issue", + "issue_content": "This issue needs attention", } # Valid request output = self.app.post( - '/api/0/test/new_issue', data=data, headers=headers) + "/api/0/test/new_issue", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['issue']['date_created'] = '1431414800' - data['issue']['last_updated'] = '1431414800' + data["issue"]["date_created"] = "1431414800" + data["issue"]["last_updated"] = "1431414800" self.assertDictEqual( - data, - { - "issue": FULL_ISSUE_LIST[8], - "message": "Issue created" - } + data, {"issue": FULL_ISSUE_LIST[8], "message": "Issue created"} ) def test_api_new_issue_img(self): """ Test the api_new_issue method of the flask api. """ tests.create_projects(self.session) tests.create_projects_git( - os.path.join(self.path, 'tickets'), bare=True) + os.path.join(self.path, "tickets"), bare=True + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} - with open(os.path.join(tests.HERE, 'placebo.png'), 'rb') as stream: + with open(os.path.join(tests.HERE, "placebo.png"), "rb") as stream: data = { - 'title': 'test issue', - 'issue_content': 'This issue needs attention ', - 'filestream': stream, + "title": "test issue", + "issue_content": "This issue needs attention ", + "filestream": stream, } # Valid request output = self.app.post( - '/api/0/test/new_issue', data=data, headers=headers) + "/api/0/test/new_issue", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['issue']['date_created'] = '1431414800' - data['issue']['last_updated'] = '1431414800' + data["issue"]["date_created"] = "1431414800" + data["issue"]["last_updated"] = "1431414800" issue = copy.deepcopy(FULL_ISSUE_LIST[8]) - issue['id'] = 1 + issue["id"] = 1 self.assertIn( - 'pagure_tests_placebo.png)](/test/issue/raw/files/' - '8a06845923010b27bfd8e7e75acff7badc40d1021b4994e01f5e11ca' - '40bc3abe', data['issue']['content'] + "pagure_tests_placebo.png)](/test/issue/raw/files/" + "8a06845923010b27bfd8e7e75acff7badc40d1021b4994e01f5e11ca" + "40bc3abe", + data["issue"]["content"], ) - data['issue']['content'] = 'This issue needs attention' + data["issue"]["content"] = "This issue needs attention" self.assertDictEqual( - data, - { - "issue": issue, - "message": "Issue created" - } + data, {"issue": issue, "message": "Issue created"} ) def test_api_new_issue_invalid_milestone(self): """ Test the api_new_issue method of the flask api. """ tests.create_projects(self.session) tests.create_projects_git( - os.path.join(self.path, 'tickets'), bare=True) + os.path.join(self.path, "tickets"), bare=True + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Valid request but invalid milestone data = { - 'title': 'test issue', - 'issue_content': 'This issue needs attention', - 'milestone': ['milestone-1.0'], + "title": "test issue", + "issue_content": "This issue needs attention", + "milestone": ["milestone-1.0"], } output = self.app.post( - '/api/0/test/new_issue', data=data, headers=headers) + "/api/0/test/new_issue", data=data, headers=headers + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - "error": "Invalid or incomplete input submitted", - "error_code": "EINVALIDREQ", - "errors": { - "milestone": [ - "Not a valid choice" - ] - } - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": {"milestone": ["Not a valid choice"]}, + }, ) def test_api_new_issue_milestone(self): """ Test the api_new_issue method of the flask api. """ tests.create_projects(self.session) tests.create_projects_git( - os.path.join(self.path, 'tickets'), bare=True) + os.path.join(self.path, "tickets"), bare=True + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Set some milestones - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - repo.milestones = {'milestone-1.0': '', 'milestone-2.0': 'Tomorrow!'} + repo = pagure.lib.query.get_authorized_project(self.session, "test") + repo.milestones = {"milestone-1.0": "", "milestone-2.0": "Tomorrow!"} self.session.add(repo) self.session.commit() # Valid request with milestone data = { - 'title': 'test issue', - 'issue_content': 'This issue needs attention', - 'milestone': ['milestone-1.0'], + "title": "test issue", + "issue_content": "This issue needs attention", + "milestone": ["milestone-1.0"], } output = self.app.post( - '/api/0/test/new_issue', data=data, headers=headers) + "/api/0/test/new_issue", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['issue']['date_created'] = '1431414800' - data['issue']['last_updated'] = '1431414800' + data["issue"]["date_created"] = "1431414800" + data["issue"]["last_updated"] = "1431414800" issue = copy.deepcopy(FULL_ISSUE_LIST[7]) - issue['id'] = 1 + issue["id"] = 1 self.assertDictEqual( - data, - { - "issue": issue, - "message": "Issue created" - } + data, {"issue": issue, "message": "Issue created"} ) def test_api_new_issue_public(self): """ Test the api_new_issue method of the flask api. """ tests.create_projects(self.session) tests.create_projects_git( - os.path.join(self.path, 'tickets'), bare=True) + os.path.join(self.path, "tickets"), bare=True + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Valid request, with private='false' data = { - 'title': 'test issue', - 'issue_content': 'This issue needs attention', - 'private': 'false', + "title": "test issue", + "issue_content": "This issue needs attention", + "private": "false", } output = self.app.post( - '/api/0/test/new_issue', data=data, headers=headers) + "/api/0/test/new_issue", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['issue']['date_created'] = '1431414800' - data['issue']['last_updated'] = '1431414800' + data["issue"]["date_created"] = "1431414800" + data["issue"]["last_updated"] = "1431414800" issue = copy.deepcopy(FULL_ISSUE_LIST[6]) - issue['id'] = 1 + issue["id"] = 1 self.assertDictEqual( - data, - { - "issue": issue, - "message": "Issue created" - } + data, {"issue": issue, "message": "Issue created"} ) # Valid request, with private=False data = { - 'title': 'test issue', - 'issue_content': 'This issue needs attention', - 'private': False + "title": "test issue", + "issue_content": "This issue needs attention", + "private": False, } output = self.app.post( - '/api/0/test/new_issue', data=data, headers=headers) + "/api/0/test/new_issue", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['issue']['date_created'] = '1431414800' - data['issue']['last_updated'] = '1431414800' + data["issue"]["date_created"] = "1431414800" + data["issue"]["last_updated"] = "1431414800" issue = copy.deepcopy(FULL_ISSUE_LIST[5]) - issue['id'] = 2 + issue["id"] = 2 self.assertDictEqual( - data, - { - "issue": issue, - "message": "Issue created" - } + data, {"issue": issue, "message": "Issue created"} ) # Valid request, with private='False' data = { - 'title': 'test issue', - 'issue_content': 'This issue needs attention', - 'private': 'False' + "title": "test issue", + "issue_content": "This issue needs attention", + "private": "False", } output = self.app.post( - '/api/0/test/new_issue', data=data, headers=headers) + "/api/0/test/new_issue", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['issue']['date_created'] = '1431414800' - data['issue']['last_updated'] = '1431414800' + data["issue"]["date_created"] = "1431414800" + data["issue"]["last_updated"] = "1431414800" issue = copy.deepcopy(FULL_ISSUE_LIST[4]) - issue['id'] = 3 + issue["id"] = 3 self.assertDictEqual( - data, - { - "issue": issue, - "message": "Issue created" - } + data, {"issue": issue, "message": "Issue created"} ) # Valid request, with private=0 data = { - 'title': 'test issue', - 'issue_content': 'This issue needs attention', - 'private': 0 + "title": "test issue", + "issue_content": "This issue needs attention", + "private": 0, } output = self.app.post( - '/api/0/test/new_issue', data=data, headers=headers) + "/api/0/test/new_issue", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['issue']['date_created'] = '1431414800' - data['issue']['last_updated'] = '1431414800' + data["issue"]["date_created"] = "1431414800" + data["issue"]["last_updated"] = "1431414800" issue = copy.deepcopy(FULL_ISSUE_LIST[3]) - issue['id'] = 4 + issue["id"] = 4 self.assertDictEqual( - data, - { - "issue": issue, - "message": "Issue created" - } + data, {"issue": issue, "message": "Issue created"} ) def test_api_new_issue_private(self): """ Test the api_new_issue method of the flask api. """ tests.create_projects(self.session) tests.create_projects_git( - os.path.join(self.path, 'tickets'), bare=True) + os.path.join(self.path, "tickets"), bare=True + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Private issue: True data = { - 'title': 'test issue', - 'issue_content': 'This issue needs attention', - 'private': True, + "title": "test issue", + "issue_content": "This issue needs attention", + "private": True, } output = self.app.post( - '/api/0/test/new_issue', data=data, headers=headers) + "/api/0/test/new_issue", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['issue']['date_created'] = '1431414800' - data['issue']['last_updated'] = '1431414800' + data["issue"]["date_created"] = "1431414800" + data["issue"]["last_updated"] = "1431414800" issue = copy.deepcopy(FULL_ISSUE_LIST[2]) - issue['id'] = 1 + issue["id"] = 1 self.assertDictEqual( - data, - { - "issue": issue, - "message": "Issue created" - } + data, {"issue": issue, "message": "Issue created"} ) # Private issue: 1 data = { - 'title': 'test issue1', - 'issue_content': 'This issue needs attention', - 'private': 1, - 'assignee': 'foo' + "title": "test issue1", + "issue_content": "This issue needs attention", + "private": 1, + "assignee": "foo", } output = self.app.post( - '/api/0/test/new_issue', data=data, headers=headers) + "/api/0/test/new_issue", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['issue']['date_created'] = '1431414800' - data['issue']['last_updated'] = '1431414800' + data["issue"]["date_created"] = "1431414800" + data["issue"]["last_updated"] = "1431414800" exp = copy.deepcopy(FULL_ISSUE_LIST[1]) - exp['id'] = 2 + exp["id"] = 2 - self.assertDictEqual( - data, - { - "issue": exp, - "message": "Issue created" - } - ) + self.assertDictEqual(data, {"issue": exp, "message": "Issue created"}) - @patch('pagure.utils.check_api_acls', MagicMock(return_value=None)) + @patch("pagure.utils.check_api_acls", MagicMock(return_value=None)) def test_api_new_issue_raise_db_error(self): """ Test the api_new_issue method of the flask api. """ tests.create_projects(self.session) tests.create_projects_git( - os.path.join(self.path, 'tickets'), bare=True) + os.path.join(self.path, "tickets"), bare=True + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'title': 'test issue', - 'issue_content': 'This issue needs attention', + "title": "test issue", + "issue_content": "This issue needs attention", } - - with self._app.test_request_context('/') as ctx: + with self._app.test_request_context("/") as ctx: flask.g.session = self.session - flask.g.fas_user = tests.FakeUser(username='foo') + flask.g.fas_user = tests.FakeUser(username="foo") with patch( - 'flask.g.session.commit', - MagicMock(side_effect=SQLAlchemyError('DB error'))): + "flask.g.session.commit", + MagicMock(side_effect=SQLAlchemyError("DB error")), + ): output = self.app.post( - '/api/0/test/new_issue', data=data, headers=headers) + "/api/0/test/new_issue", data=data, headers=headers + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - u'error': u'An error occurred at the database ' - 'level and prevent the action from reaching ' - 'completion', - u'error_code': u'EDBERROR' - } + "error": "An error occurred at the database " + "level and prevent the action from reaching " + "completion", + "error_code": "EDBERROR", + }, ) def test_api_new_issue_user_token_no_input(self): """ Test the api_new_issue method of the flask api. """ tests.create_projects(self.session) tests.create_projects_git( - os.path.join(self.path, 'tickets'), bare=True) + os.path.join(self.path, "tickets"), bare=True + ) tests.create_tokens(self.session, project_id=None) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Valid token, invalid request - No input - output = self.app.post('/api/0/test2/new_issue', headers=headers) + output = self.app.post("/api/0/test2/new_issue", headers=headers) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - "error": "Invalid or incomplete input submitted", - "error_code": "EINVALIDREQ", - "errors": { - "issue_content": ["This field is required."], - "title": ["This field is required."], - } - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": { + "issue_content": ["This field is required."], + "title": ["This field is required."], + }, + }, ) def test_api_new_issue_user_token_invalid_user(self): """ Test the api_new_issue method of the flask api. """ tests.create_projects(self.session) tests.create_projects_git( - os.path.join(self.path, 'tickets'), bare=True) + os.path.join(self.path, "tickets"), bare=True + ) tests.create_tokens(self.session, project_id=None) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Another project, still an invalid request - No input - output = self.app.post('/api/0/test/new_issue', headers=headers) + output = self.app.post("/api/0/test/new_issue", headers=headers) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - "error": "Invalid or incomplete input submitted", - "error_code": "EINVALIDREQ", - "errors": { - "issue_content": ["This field is required."], - "title": ["This field is required."], - } - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": { + "issue_content": ["This field is required."], + "title": ["This field is required."], + }, + }, ) def test_api_new_issue_user_token_invalid_repo(self): """ Test the api_new_issue method of the flask api. """ tests.create_projects(self.session) tests.create_projects_git( - os.path.join(self.path, 'tickets'), bare=True) + os.path.join(self.path, "tickets"), bare=True + ) tests.create_tokens(self.session, project_id=None) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} - data = { - 'title': 'test issue' - } + headers = {"Authorization": "token aaabbbcccddd"} + data = {"title": "test issue"} # Invalid repo output = self.app.post( - '/api/0/foo/new_issue', data=data, headers=headers) + "/api/0/foo/new_issue", data=data, headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) def test_api_new_issue_user_token_invalid_request(self): """ Test the api_new_issue method of the flask api. """ tests.create_projects(self.session) tests.create_projects_git( - os.path.join(self.path, 'tickets'), bare=True) + os.path.join(self.path, "tickets"), bare=True + ) tests.create_tokens(self.session, project_id=None) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Incomplete request output = self.app.post( - '/api/0/test/new_issue', data={}, headers=headers) + "/api/0/test/new_issue", data={}, headers=headers + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - "error": "Invalid or incomplete input submitted", - "error_code": "EINVALIDREQ", - "errors": { - "issue_content": ["This field is required."], - "title": ["This field is required."] - } - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": { + "issue_content": ["This field is required."], + "title": ["This field is required."], + }, + }, ) def test_api_new_issue_user_token(self): """ Test the api_new_issue method of the flask api. """ tests.create_projects(self.session) tests.create_projects_git( - os.path.join(self.path, 'tickets'), bare=True) + os.path.join(self.path, "tickets"), bare=True + ) tests.create_tokens(self.session, project_id=None) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'title': 'test issue', - 'issue_content': 'This issue needs attention', + "title": "test issue", + "issue_content": "This issue needs attention", } # Valid request output = self.app.post( - '/api/0/test/new_issue', data=data, headers=headers) + "/api/0/test/new_issue", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['issue']['date_created'] = '1431414800' - data['issue']['last_updated'] = '1431414800' - + data["issue"]["date_created"] = "1431414800" + data["issue"]["last_updated"] = "1431414800" self.assertDictEqual( - data, - { - "issue": FULL_ISSUE_LIST[8], - "message": "Issue created" - } + data, {"issue": FULL_ISSUE_LIST[8], "message": "Issue created"} ) def test_api_new_issue_user_token_milestone(self): """ Test the api_new_issue method of the flask api. """ tests.create_projects(self.session) tests.create_projects_git( - os.path.join(self.path, 'tickets'), bare=True) + os.path.join(self.path, "tickets"), bare=True + ) tests.create_tokens(self.session, project_id=None) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Set some milestones - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - repo.milestones = {'milestone-1.0': '', 'milestone-2.0': 'Tomorrow!'} + repo = pagure.lib.query.get_authorized_project(self.session, "test") + repo.milestones = {"milestone-1.0": "", "milestone-2.0": "Tomorrow!"} self.session.add(repo) self.session.commit() # Valid request with milestone data = { - 'title': 'test issue', - 'issue_content': 'This issue needs attention', - 'milestone': ['milestone-1.0'], + "title": "test issue", + "issue_content": "This issue needs attention", + "milestone": ["milestone-1.0"], } output = self.app.post( - '/api/0/test/new_issue', data=data, headers=headers) + "/api/0/test/new_issue", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['issue']['date_created'] = '1431414800' - data['issue']['last_updated'] = '1431414800' + data["issue"]["date_created"] = "1431414800" + data["issue"]["last_updated"] = "1431414800" issue = copy.deepcopy(FULL_ISSUE_LIST[7]) - issue['id'] = 1 + issue["id"] = 1 self.assertDictEqual( - data, - { - "issue": issue, - "message": "Issue created" - } + data, {"issue": issue, "message": "Issue created"} ) def test_api_new_issue_user_token_public(self): """ Test the api_new_issue method of the flask api. """ tests.create_projects(self.session) tests.create_projects_git( - os.path.join(self.path, 'tickets'), bare=True) + os.path.join(self.path, "tickets"), bare=True + ) tests.create_tokens(self.session, project_id=None) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Valid request, with private='false' data = { - 'title': 'test issue', - 'issue_content': 'This issue needs attention', - 'private': 'false', + "title": "test issue", + "issue_content": "This issue needs attention", + "private": "false", } output = self.app.post( - '/api/0/test/new_issue', data=data, headers=headers) + "/api/0/test/new_issue", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['issue']['date_created'] = '1431414800' - data['issue']['last_updated'] = '1431414800' + data["issue"]["date_created"] = "1431414800" + data["issue"]["last_updated"] = "1431414800" issue = copy.deepcopy(FULL_ISSUE_LIST[6]) - issue['id'] = 1 + issue["id"] = 1 self.assertDictEqual( - data, - { - "issue": issue, - "message": "Issue created" - } + data, {"issue": issue, "message": "Issue created"} ) # Valid request, with private=False data = { - 'title': 'test issue', - 'issue_content': 'This issue needs attention', - 'private': False + "title": "test issue", + "issue_content": "This issue needs attention", + "private": False, } output = self.app.post( - '/api/0/test/new_issue', data=data, headers=headers) + "/api/0/test/new_issue", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['issue']['date_created'] = '1431414800' - data['issue']['last_updated'] = '1431414800' + data["issue"]["date_created"] = "1431414800" + data["issue"]["last_updated"] = "1431414800" issue = copy.deepcopy(FULL_ISSUE_LIST[5]) - issue['id'] = 2 + issue["id"] = 2 self.assertDictEqual( - data, - { - "issue": issue, - "message": "Issue created" - } + data, {"issue": issue, "message": "Issue created"} ) # Valid request, with private='False' data = { - 'title': 'test issue', - 'issue_content': 'This issue needs attention', - 'private': 'False' + "title": "test issue", + "issue_content": "This issue needs attention", + "private": "False", } output = self.app.post( - '/api/0/test/new_issue', data=data, headers=headers) + "/api/0/test/new_issue", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['issue']['date_created'] = '1431414800' - data['issue']['last_updated'] = '1431414800' + data["issue"]["date_created"] = "1431414800" + data["issue"]["last_updated"] = "1431414800" issue = copy.deepcopy(FULL_ISSUE_LIST[4]) - issue['id'] = 3 + issue["id"] = 3 self.assertDictEqual( - data, - { - "issue": issue, - "message": "Issue created" - } + data, {"issue": issue, "message": "Issue created"} ) # Valid request, with private=0 data = { - 'title': 'test issue', - 'issue_content': 'This issue needs attention', - 'private': 0 + "title": "test issue", + "issue_content": "This issue needs attention", + "private": 0, } output = self.app.post( - '/api/0/test/new_issue', data=data, headers=headers) + "/api/0/test/new_issue", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['issue']['date_created'] = '1431414800' - data['issue']['last_updated'] = '1431414800' + data["issue"]["date_created"] = "1431414800" + data["issue"]["last_updated"] = "1431414800" issue = copy.deepcopy(FULL_ISSUE_LIST[4]) - issue['id'] = 4 + issue["id"] = 4 self.assertDictEqual( - data, - { - "issue": issue, - "message": "Issue created" - } + data, {"issue": issue, "message": "Issue created"} ) def test_api_new_issue_user_token_private(self): """ Test the api_new_issue method of the flask api. """ tests.create_projects(self.session) tests.create_projects_git( - os.path.join(self.path, 'tickets'), bare=True) + os.path.join(self.path, "tickets"), bare=True + ) tests.create_tokens(self.session, project_id=None) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Private issue: True data = { - 'title': 'test issue', - 'issue_content': 'This issue needs attention', - 'private': True, + "title": "test issue", + "issue_content": "This issue needs attention", + "private": True, } output = self.app.post( - '/api/0/test/new_issue', data=data, headers=headers) + "/api/0/test/new_issue", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['issue']['date_created'] = '1431414800' - data['issue']['last_updated'] = '1431414800' + data["issue"]["date_created"] = "1431414800" + data["issue"]["last_updated"] = "1431414800" issue = copy.deepcopy(FULL_ISSUE_LIST[2]) - issue['id'] = 1 + issue["id"] = 1 self.assertDictEqual( - data, - { - "issue": issue, - "message": "Issue created" - } + data, {"issue": issue, "message": "Issue created"} ) # Private issue: 1 data = { - 'title': 'test issue1', - 'issue_content': 'This issue needs attention', - 'private': 1, - 'assignee': 'foo' + "title": "test issue1", + "issue_content": "This issue needs attention", + "private": 1, + "assignee": "foo", } output = self.app.post( - '/api/0/test/new_issue', data=data, headers=headers) + "/api/0/test/new_issue", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['issue']['date_created'] = '1431414800' - data['issue']['last_updated'] = '1431414800' + data["issue"]["date_created"] = "1431414800" + data["issue"]["last_updated"] = "1431414800" issue = copy.deepcopy(FULL_ISSUE_LIST[1]) - issue['id'] = 2 + issue["id"] = 2 self.assertDictEqual( - data, - { - "issue": issue, - "message": "Issue created" - } + data, {"issue": issue, "message": "Issue created"} ) # Private issue: 'true' data = { - 'title': 'test issue1', - 'issue_content': 'This issue needs attention', - 'private': 'true', + "title": "test issue1", + "issue_content": "This issue needs attention", + "private": "true", } output = self.app.post( - '/api/0/test/new_issue', data=data, headers=headers) + "/api/0/test/new_issue", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['issue']['date_created'] = '1431414800' - data['issue']['last_updated'] = '1431414800' + data["issue"]["date_created"] = "1431414800" + data["issue"]["last_updated"] = "1431414800" exp = copy.deepcopy(FULL_ISSUE_LIST[1]) - exp['id'] = 3 - exp['assignee'] = None + exp["id"] = 3 + exp["assignee"] = None - self.assertDictEqual( - data, - { - "issue": exp, - "message": "Issue created" - } - ) + self.assertDictEqual(data, {"issue": exp, "message": "Issue created"}) def test_api_view_issues(self): """ Test the api_view_issues method of the flask api. """ self.test_api_new_issue() # Invalid repo - output = self.app.get('/api/0/foo/issues') + output = self.app.get("/api/0/foo/issues") self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) # List all opened issues - output = self.app.get('/api/0/test/issues') + output = self.app.get("/api/0/test/issues") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - for idx in range(len(data['issues'])): - data['issues'][idx]['date_created'] = '1431414800' - data['issues'][idx]['last_updated'] = '1431414800' - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + for idx in range(len(data["issues"])): + data["issues"][idx]["date_created"] = "1431414800" + data["issues"][idx]["last_updated"] = "1431414800" + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." self.assertDictEqual( data, { - "args": { - "assignee": None, - "author": None, - 'milestones': [], - 'no_stones': None, - 'order': None, - 'priority': None, - "since": None, - "status": None, - "tags": [], - }, - "issues": [FULL_ISSUE_LIST[8]], - u'pagination': { - u'first': u'http://localhost...', - u'last': u'http://localhost...', - u'next': None, - u'page': 1, - u'pages': 1, - u'per_page': 20, - u'prev': None - }, - "total_issues": 1 - } + "args": { + "assignee": None, + "author": None, + "milestones": [], + "no_stones": None, + "order": None, + "priority": None, + "since": None, + "status": None, + "tags": [], + }, + "issues": [FULL_ISSUE_LIST[8]], + "pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "page": 1, + "pages": 1, + "per_page": 20, + "prev": None, + }, + "total_issues": 1, + }, ) # Create private issue - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue', - content='We should work on this', - user='pingou', + title="Test issue", + content="We should work on this", + user="pingou", private=True, - status="Closed" + status="Closed", ) self.session.commit() - self.assertEqual(msg.title, 'Test issue') + self.assertEqual(msg.title, "Test issue") # Access issues un-authenticated - output = self.app.get('/api/0/test/issues') + output = self.app.get("/api/0/test/issues") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - for idx in range(len(data['issues'])): - data['issues'][idx]['date_created'] = '1431414800' - data['issues'][idx]['last_updated'] = '1431414800' - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + for idx in range(len(data["issues"])): + data["issues"][idx]["date_created"] = "1431414800" + data["issues"][idx]["last_updated"] = "1431414800" + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." self.assertDictEqual( data, { - "args": { - "assignee": None, - "author": None, - 'milestones': [], - 'no_stones': None, - 'order': None, - 'priority': None, - "since": None, - "status": None, - "tags": [] - }, - "issues": [FULL_ISSUE_LIST[8]], - u'pagination': { - u'first': u'http://localhost...', - u'last': u'http://localhost...', - u'next': None, - u'page': 1, - u'pages': 1, - u'per_page': 20, - u'prev': None - }, - "total_issues": 1 - } + "args": { + "assignee": None, + "author": None, + "milestones": [], + "no_stones": None, + "order": None, + "priority": None, + "since": None, + "status": None, + "tags": [], + }, + "issues": [FULL_ISSUE_LIST[8]], + "pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "page": 1, + "pages": 1, + "per_page": 20, + "prev": None, + }, + "total_issues": 1, + }, ) - headers = {'Authorization': 'token aaabbbccc'} + headers = {"Authorization": "token aaabbbccc"} # Access issues authenticated but non-existing token - output = self.app.get('/api/0/test/issues', headers=headers) + output = self.app.get("/api/0/test/issues", headers=headers) self.assertEqual(output.status_code, 401) # Create a new token for another user item = pagure.lib.model.Token( - id='bar_token', + id="bar_token", user_id=2, project_id=1, - expiration=datetime.datetime.utcnow() + datetime.timedelta( - days=30) + expiration=datetime.datetime.utcnow() + + datetime.timedelta(days=30), ) self.session.add(item) self.session.commit() - headers = {'Authorization': 'token bar_token'} + headers = {"Authorization": "token bar_token"} # Access issues authenticated but wrong token - output = self.app.get('/api/0/test/issues', headers=headers) + output = self.app.get("/api/0/test/issues", headers=headers) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - for idx in range(len(data['issues'])): - data['issues'][idx]['date_created'] = '1431414800' - data['issues'][idx]['last_updated'] = '1431414800' - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + for idx in range(len(data["issues"])): + data["issues"][idx]["date_created"] = "1431414800" + data["issues"][idx]["last_updated"] = "1431414800" + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." self.assertDictEqual( data, { - "args": { - "assignee": None, - "author": None, - 'milestones': [], - 'no_stones': None, - 'order': None, - 'priority': None, - "since": None, - "status": None, - "tags": [] - }, - "issues": [FULL_ISSUE_LIST[8]], - u'pagination': { - u'first': u'http://localhost...', - u'last': u'http://localhost...', - u'next': None, - u'page': 1, - u'pages': 1, - u'per_page': 20, - u'prev': None - }, - "total_issues": 1 - } + "args": { + "assignee": None, + "author": None, + "milestones": [], + "no_stones": None, + "order": None, + "priority": None, + "since": None, + "status": None, + "tags": [], + }, + "issues": [FULL_ISSUE_LIST[8]], + "pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "page": 1, + "pages": 1, + "per_page": 20, + "prev": None, + }, + "total_issues": 1, + }, ) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Access issues authenticated correctly - output = self.app.get('/api/0/test/issues', headers=headers) + output = self.app.get("/api/0/test/issues", headers=headers) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - for idx in range(len(data['issues'])): - data['issues'][idx]['date_created'] = '1431414800' - data['issues'][idx]['last_updated'] = '1431414800' - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + for idx in range(len(data["issues"])): + data["issues"][idx]["date_created"] = "1431414800" + data["issues"][idx]["last_updated"] = "1431414800" + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." self.assertDictEqual( data, { - "args": { - "assignee": None, - "author": None, - 'milestones': [], - 'no_stones': None, - 'order': None, - 'priority': None, - "since": None, - "status": None, - "tags": [] - }, - "issues": [FULL_ISSUE_LIST[8]], - u'pagination': { - u'first': u'http://localhost...', - u'last': u'http://localhost...', - u'next': None, - u'page': 1, - u'pages': 1, - u'per_page': 20, - u'prev': None - }, - "total_issues": 1 - } + "args": { + "assignee": None, + "author": None, + "milestones": [], + "no_stones": None, + "order": None, + "priority": None, + "since": None, + "status": None, + "tags": [], + }, + "issues": [FULL_ISSUE_LIST[8]], + "pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "page": 1, + "pages": 1, + "per_page": 20, + "prev": None, + }, + "total_issues": 1, + }, ) - headers = {'Authorization': 'token aaabbbccc'} + headers = {"Authorization": "token aaabbbccc"} # Access issues authenticated but non-existing token - output = self.app.get('/api/0/test/issues', headers=headers) + output = self.app.get("/api/0/test/issues", headers=headers) self.assertEqual(output.status_code, 401) # Create a new token for another user item = pagure.lib.model.Token( - id='bar_token_foo', + id="bar_token_foo", user_id=2, project_id=1, - expiration=datetime.datetime.utcnow() + datetime.timedelta( - days=30) + expiration=datetime.datetime.utcnow() + + datetime.timedelta(days=30), ) self.session.add(item) self.session.commit() - headers = {'Authorization': 'token bar_token_foo'} + headers = {"Authorization": "token bar_token_foo"} # Access issues authenticated but wrong token - output = self.app.get('/api/0/test/issues', headers=headers) + output = self.app.get("/api/0/test/issues", headers=headers) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - for idx in range(len(data['issues'])): - data['issues'][idx]['date_created'] = '1431414800' - data['issues'][idx]['last_updated'] = '1431414800' - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + for idx in range(len(data["issues"])): + data["issues"][idx]["date_created"] = "1431414800" + data["issues"][idx]["last_updated"] = "1431414800" + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." self.assertDictEqual( data, { - "args": { - "assignee": None, - "author": None, - 'milestones': [], - 'no_stones': None, - 'order': None, - 'priority': None, - "since": None, - "status": None, - "tags": [] - }, - "issues": [FULL_ISSUE_LIST[8]], - u'pagination': { - u'first': u'http://localhost...', - u'last': u'http://localhost...', - u'next': None, - u'page': 1, - u'pages': 1, - u'per_page': 20, - u'prev': None - }, - "total_issues": 1 - } + "args": { + "assignee": None, + "author": None, + "milestones": [], + "no_stones": None, + "order": None, + "priority": None, + "since": None, + "status": None, + "tags": [], + }, + "issues": [FULL_ISSUE_LIST[8]], + "pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "page": 1, + "pages": 1, + "per_page": 20, + "prev": None, + }, + "total_issues": 1, + }, ) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Access issues authenticated correctly - output = self.app.get('/api/0/test/issues', headers=headers) + output = self.app.get("/api/0/test/issues", headers=headers) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - for idx in range(len(data['issues'])): - data['issues'][idx]['date_created'] = '1431414800' - data['issues'][idx]['last_updated'] = '1431414800' - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + for idx in range(len(data["issues"])): + data["issues"][idx]["date_created"] = "1431414800" + data["issues"][idx]["last_updated"] = "1431414800" + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." self.assertDictEqual( data, { - "args": { - "assignee": None, - "author": None, - 'milestones': [], - 'no_stones': None, - 'order': None, - 'priority': None, - "since": None, - "status": None, - "tags": [] - }, - "issues": [FULL_ISSUE_LIST[8]], - u'pagination': { - u'first': u'http://localhost...', - u'last': u'http://localhost...', - u'next': None, - u'page': 1, - u'pages': 1, - u'per_page': 20, - u'prev': None - }, - "total_issues": 1 - } + "args": { + "assignee": None, + "author": None, + "milestones": [], + "no_stones": None, + "order": None, + "priority": None, + "since": None, + "status": None, + "tags": [], + }, + "issues": [FULL_ISSUE_LIST[8]], + "pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "page": 1, + "pages": 1, + "per_page": 20, + "prev": None, + }, + "total_issues": 1, + }, ) # List closed issue - output = self.app.get('/api/0/test/issues?status=Closed', headers=headers) + output = self.app.get( + "/api/0/test/issues?status=Closed", headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['issues'][0]['date_created'] = '1431414800' - data['issues'][0]['last_updated'] = '1431414800' - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + data["issues"][0]["date_created"] = "1431414800" + data["issues"][0]["last_updated"] = "1431414800" + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." self.assertDictEqual( data, { - "args": { - "assignee": None, - "author": None, - "milestones": [], - "no_stones": None, - 'order': None, - "priority": None, - "since": None, - "status": "Closed", - "tags": [] - }, - "issues": [FULL_ISSUE_LIST[0]], - u'pagination': { - u'first': u'http://localhost...', - u'last': u'http://localhost...', - u'next': None, - u'page': 1, - u'pages': 1, - u'per_page': 20, - u'prev': None - }, - "total_issues": 1, - } + "args": { + "assignee": None, + "author": None, + "milestones": [], + "no_stones": None, + "order": None, + "priority": None, + "since": None, + "status": "Closed", + "tags": [], + }, + "issues": [FULL_ISSUE_LIST[0]], + "pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "page": 1, + "pages": 1, + "per_page": 20, + "prev": None, + }, + "total_issues": 1, + }, ) # List closed issue - output = self.app.get('/api/0/test/issues?status=Invalid', headers=headers) + output = self.app.get( + "/api/0/test/issues?status=Invalid", headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." self.assertDictEqual( data, { - "args": { - "assignee": None, - "author": None, - 'milestones': [], - 'no_stones': None, - 'order': None, - 'priority': None, - "since": None, - "status": "Invalid", - "tags": [] - }, - "issues": [], - u'pagination': { - u'first': u'http://localhost...', - u'last': u'http://localhost...', - u'next': None, - u'page': 1, - u'pages': 0, - u'per_page': 20, - u'prev': None - }, - "total_issues": 0, - } + "args": { + "assignee": None, + "author": None, + "milestones": [], + "no_stones": None, + "order": None, + "priority": None, + "since": None, + "status": "Invalid", + "tags": [], + }, + "issues": [], + "pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "page": 1, + "pages": 0, + "per_page": 20, + "prev": None, + }, + "total_issues": 0, + }, ) # List all issues - output = self.app.get('/api/0/test/issues?status=All', headers=headers) + output = self.app.get("/api/0/test/issues?status=All", headers=headers) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - for idx in range(len(data['issues'])): - data['issues'][idx]['last_updated'] = '1431414800' - data['issues'][idx]['date_created'] = '1431414800' - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + for idx in range(len(data["issues"])): + data["issues"][idx]["last_updated"] = "1431414800" + data["issues"][idx]["date_created"] = "1431414800" + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." self.assertDictEqual( data, { - "args": { - "assignee": None, - "author": None, - 'milestones': [], - 'no_stones': None, - 'order': None, - 'priority': None, - "since": None, - "status": "All", - "tags": [] - }, - "issues": [FULL_ISSUE_LIST[0], FULL_ISSUE_LIST[8]], - u'pagination': { - u'first': u'http://localhost...', - u'last': u'http://localhost...', - u'next': None, - u'page': 1, - u'pages': 1, - u'per_page': 20, - u'prev': None - }, - "total_issues": 2 - } + "args": { + "assignee": None, + "author": None, + "milestones": [], + "no_stones": None, + "order": None, + "priority": None, + "since": None, + "status": "All", + "tags": [], + }, + "issues": [FULL_ISSUE_LIST[0], FULL_ISSUE_LIST[8]], + "pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "page": 1, + "pages": 1, + "per_page": 20, + "prev": None, + }, + "total_issues": 2, + }, ) def test_api_view_issues_since_invalid_format(self): @@ -1572,15 +1503,12 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): self.test_api_new_issue() # Invalid repo - output = self.app.get('/api/0/test/issues?since=12-13') + output = self.app.get("/api/0/test/issues?since=12-13") self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, - { - u'error': u'Invalid datetime format', - u'error_code': u'EDATETIME' - } + {"error": "Invalid datetime format", "error_code": "EDATETIME"}, ) def test_api_view_issues_since_invalid_timestamp(self): @@ -1588,15 +1516,12 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): self.test_api_new_issue() # Invalid repo - output = self.app.get('/api/0/test/issues?since=100000000000000') + output = self.app.get("/api/0/test/issues?since=100000000000000") self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, - { - u'error': u'Invalid timestamp format', - u'error_code': u'ETIMESTAMP' - } + {"error": "Invalid timestamp format", "error_code": "ETIMESTAMP"}, ) def test_api_view_issues_reversed(self): @@ -1606,42 +1531,42 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): """ self.test_api_new_issue() - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # List issues in reverse order - output = self.app.get('/api/0/test/issues?order=asc', headers=headers) + output = self.app.get("/api/0/test/issues?order=asc", headers=headers) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - for idx in range(len(data['issues'])): - data['issues'][idx]['last_updated'] = '1431414800' - data['issues'][idx]['date_created'] = '1431414800' - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + for idx in range(len(data["issues"])): + data["issues"][idx]["last_updated"] = "1431414800" + data["issues"][idx]["date_created"] = "1431414800" + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." expected = { "args": { "assignee": None, "author": None, - 'milestones': [], - 'no_stones': None, - 'order': 'asc', - 'priority': None, + "milestones": [], + "no_stones": None, + "order": "asc", + "priority": None, "since": None, "status": None, - "tags": [] + "tags": [], }, "issues": [FULL_ISSUE_LIST[8]], - u'pagination': { - u'first': u'http://localhost...', - u'last': u'http://localhost...', - u'next': None, - u'page': 1, - u'pages': 1, - u'per_page': 20, - u'prev': None + "pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "page": 1, + "pages": 1, + "per_page": 20, + "prev": None, }, - "total_issues": 1 + "total_issues": 1, } self.assertDictEqual(data, expected) @@ -1651,21 +1576,22 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): """ tests.create_projects(self.session) tests.create_projects_git( - os.path.join(self.path, 'tickets'), bare=True) + os.path.join(self.path, "tickets"), bare=True + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") # Create 2 tickets but only 1 has a milestone start = arrow.utcnow().timestamp issue = pagure.lib.model.Issue( id=pagure.lib.query.get_next_id(self.session, repo.id), project_id=repo.id, - title='Issue #1', - content='Description', + title="Issue #1", + content="Description", user_id=1, # pingou - uid='issue#1', + uid="issue#1", private=False, ) self.session.add(issue) @@ -1674,94 +1600,94 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): issue = pagure.lib.model.Issue( id=pagure.lib.query.get_next_id(self.session, repo.id), project_id=repo.id, - title='Issue #2', - content='Description', + title="Issue #2", + content="Description", user_id=1, # pingou - uid='issue#2', + uid="issue#2", private=False, - milestone='v1.0', + milestone="v1.0", ) self.session.add(issue) self.session.commit() # List all opened issues - output = self.app.get('/api/0/test/issues') + output = self.app.get("/api/0/test/issues") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - for idx in range(len(data['issues'])): - data['issues'][idx]['date_created'] = '1431414800' - data['issues'][idx]['last_updated'] = '1431414800' - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + for idx in range(len(data["issues"])): + data["issues"][idx]["date_created"] = "1431414800" + data["issues"][idx]["last_updated"] = "1431414800" + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." lcl_issues = copy.deepcopy(LCL_ISSUES) - lcl_issues[0]['milestone'] = 'v1.0' + lcl_issues[0]["milestone"] = "v1.0" self.assertDictEqual( data, { - "args": { - "assignee": None, - "author": None, - 'milestones': [], - 'no_stones': None, - 'order': None, - 'priority': None, - "since": None, - "status": None, - "tags": [], - }, - "issues": lcl_issues, - u'pagination': { - u'first': u'http://localhost...', - u'last': u'http://localhost...', - u'next': None, - u'page': 1, - u'pages': 1, - u'per_page': 20, - u'prev': None - }, - "total_issues": 2 - } + "args": { + "assignee": None, + "author": None, + "milestones": [], + "no_stones": None, + "order": None, + "priority": None, + "since": None, + "status": None, + "tags": [], + }, + "issues": lcl_issues, + "pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "page": 1, + "pages": 1, + "per_page": 20, + "prev": None, + }, + "total_issues": 2, + }, ) # List all issues of the milestone v1.0 - output = self.app.get('/api/0/test/issues?milestones=v1.0') + output = self.app.get("/api/0/test/issues?milestones=v1.0") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - for idx in range(len(data['issues'])): - data['issues'][idx]['date_created'] = '1431414800' - data['issues'][idx]['last_updated'] = '1431414800' - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + for idx in range(len(data["issues"])): + data["issues"][idx]["date_created"] = "1431414800" + data["issues"][idx]["last_updated"] = "1431414800" + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." self.assertDictEqual( data, { - "args": { - "assignee": None, - "author": None, - 'milestones': ['v1.0'], - 'no_stones': None, - 'order': None, - 'priority': None, - "since": None, - "status": None, - "tags": [], - }, - "issues": [lcl_issues[0]], - u'pagination': { - u'first': u'http://localhost...', - u'last': u'http://localhost...', - u'next': None, - u'page': 1, - u'pages': 1, - u'per_page': 20, - u'prev': None - }, - "total_issues": 1 - } + "args": { + "assignee": None, + "author": None, + "milestones": ["v1.0"], + "no_stones": None, + "order": None, + "priority": None, + "since": None, + "status": None, + "tags": [], + }, + "issues": [lcl_issues[0]], + "pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "page": 1, + "pages": 1, + "per_page": 20, + "prev": None, + }, + "total_issues": 1, + }, ) def test_api_view_issues_priority(self): @@ -1770,21 +1696,22 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): """ tests.create_projects(self.session) tests.create_projects_git( - os.path.join(self.path, 'tickets'), bare=True) + os.path.join(self.path, "tickets"), bare=True + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") # Create 2 tickets but only 1 has a priority start = arrow.utcnow().timestamp issue = pagure.lib.model.Issue( id=pagure.lib.query.get_next_id(self.session, repo.id), project_id=repo.id, - title='Issue #1', - content='Description', + title="Issue #1", + content="Description", user_id=1, # pingou - uid='issue#1', + uid="issue#1", private=False, ) self.session.add(issue) @@ -1793,10 +1720,10 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): issue = pagure.lib.model.Issue( id=pagure.lib.query.get_next_id(self.session, repo.id), project_id=repo.id, - title='Issue #2', - content='Description', + title="Issue #2", + content="Description", user_id=1, # pingou - uid='issue#2', + uid="issue#2", private=False, priority=1, ) @@ -1804,126 +1731,126 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): self.session.commit() # Set some priorities to the project - repo.priorities = {'1': 'High', '2': 'Normal'} + repo.priorities = {"1": "High", "2": "Normal"} self.session.add(repo) self.session.commit() # List all opened issues - output = self.app.get('/api/0/test/issues') + output = self.app.get("/api/0/test/issues") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - for idx in range(len(data['issues'])): - data['issues'][idx]['date_created'] = '1431414800' - data['issues'][idx]['last_updated'] = '1431414800' - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + for idx in range(len(data["issues"])): + data["issues"][idx]["date_created"] = "1431414800" + data["issues"][idx]["last_updated"] = "1431414800" + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." lcl_issues = copy.deepcopy(LCL_ISSUES) - lcl_issues[0]['priority'] = 1 + lcl_issues[0]["priority"] = 1 self.assertDictEqual( data, { - "args": { - "assignee": None, - "author": None, - 'milestones': [], - 'no_stones': None, - 'order': None, - 'priority': None, - "since": None, - "status": None, - "tags": [], - }, - "issues": lcl_issues, - u'pagination': { - u'first': u'http://localhost...', - u'last': u'http://localhost...', - u'next': None, - u'page': 1, - u'pages': 1, - u'per_page': 20, - u'prev': None - }, - "total_issues": 2 - } + "args": { + "assignee": None, + "author": None, + "milestones": [], + "no_stones": None, + "order": None, + "priority": None, + "since": None, + "status": None, + "tags": [], + }, + "issues": lcl_issues, + "pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "page": 1, + "pages": 1, + "per_page": 20, + "prev": None, + }, + "total_issues": 2, + }, ) # List all issues of the priority high (ie: 1) - output = self.app.get('/api/0/test/issues?priority=high') + output = self.app.get("/api/0/test/issues?priority=high") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - for idx in range(len(data['issues'])): - data['issues'][idx]['date_created'] = '1431414800' - data['issues'][idx]['last_updated'] = '1431414800' - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + for idx in range(len(data["issues"])): + data["issues"][idx]["date_created"] = "1431414800" + data["issues"][idx]["last_updated"] = "1431414800" + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." self.assertDictEqual( data, { - "args": { - "assignee": None, - "author": None, - 'milestones': [], - 'no_stones': None, - 'order': None, - 'priority': 'high', - "since": None, - "status": None, - "tags": [], - }, - "issues": [lcl_issues[0]], - u'pagination': { - u'first': u'http://localhost...', - u'last': u'http://localhost...', - u'next': None, - u'page': 1, - u'pages': 1, - u'per_page': 20, - u'prev': None - }, - "total_issues": 1 - } + "args": { + "assignee": None, + "author": None, + "milestones": [], + "no_stones": None, + "order": None, + "priority": "high", + "since": None, + "status": None, + "tags": [], + }, + "issues": [lcl_issues[0]], + "pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "page": 1, + "pages": 1, + "per_page": 20, + "prev": None, + }, + "total_issues": 1, + }, ) - output = self.app.get('/api/0/test/issues?priority=1') + output = self.app.get("/api/0/test/issues?priority=1") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - for idx in range(len(data['issues'])): - data['issues'][idx]['date_created'] = '1431414800' - data['issues'][idx]['last_updated'] = '1431414800' - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + for idx in range(len(data["issues"])): + data["issues"][idx]["date_created"] = "1431414800" + data["issues"][idx]["last_updated"] = "1431414800" + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." self.assertDictEqual( data, { - "args": { - "assignee": None, - "author": None, - 'milestones': [], - 'no_stones': None, - 'order': None, - 'priority': '1', - "since": None, - "status": None, - "tags": [], - }, - "issues": [lcl_issues[0]], - u'pagination': { - u'first': u'http://localhost...', - u'last': u'http://localhost...', - u'next': None, - u'page': 1, - u'pages': 1, - u'per_page': 20, - u'prev': None - }, - "total_issues": 1 - } + "args": { + "assignee": None, + "author": None, + "milestones": [], + "no_stones": None, + "order": None, + "priority": "1", + "since": None, + "status": None, + "tags": [], + }, + "issues": [lcl_issues[0]], + "pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "page": 1, + "pages": 1, + "per_page": 20, + "prev": None, + }, + "total_issues": 1, + }, ) def test_api_view_issues_priority_invalid(self): @@ -1932,20 +1859,21 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): """ tests.create_projects(self.session) tests.create_projects_git( - os.path.join(self.path, 'tickets'), bare=True) + os.path.join(self.path, "tickets"), bare=True + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Try getting issues with an invalid priority - output = self.app.get('/api/0/test/issues?priority=foobar') + output = self.app.get("/api/0/test/issues?priority=foobar") self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - "error": "Invalid priority submitted", - "error_code": "EINVALIDPRIORITY" - } + "error": "Invalid priority submitted", + "error_code": "EINVALIDPRIORITY", + }, ) def test_api_view_issues_no_stones(self): @@ -1954,21 +1882,22 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): """ tests.create_projects(self.session) tests.create_projects_git( - os.path.join(self.path, 'tickets'), bare=True) + os.path.join(self.path, "tickets"), bare=True + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") # Create 2 tickets but only 1 has a milestone start = arrow.utcnow().timestamp issue = pagure.lib.model.Issue( id=pagure.lib.query.get_next_id(self.session, repo.id), project_id=repo.id, - title='Issue #1', - content='Description', + title="Issue #1", + content="Description", user_id=1, # pingou - uid='issue#1', + uid="issue#1", private=False, ) self.session.add(issue) @@ -1977,133 +1906,133 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): issue = pagure.lib.model.Issue( id=pagure.lib.query.get_next_id(self.session, repo.id), project_id=repo.id, - title='Issue #2', - content='Description', + title="Issue #2", + content="Description", user_id=1, # pingou - uid='issue#2', + uid="issue#2", private=False, - milestone='v1.0', + milestone="v1.0", ) self.session.add(issue) self.session.commit() # List all opened issues - output = self.app.get('/api/0/test/issues') + output = self.app.get("/api/0/test/issues") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - for idx in range(len(data['issues'])): - data['issues'][idx]['date_created'] = '1431414800' - data['issues'][idx]['last_updated'] = '1431414800' - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + for idx in range(len(data["issues"])): + data["issues"][idx]["date_created"] = "1431414800" + data["issues"][idx]["last_updated"] = "1431414800" + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." lcl_issues = copy.deepcopy(LCL_ISSUES) - lcl_issues[0]['milestone'] = 'v1.0' + lcl_issues[0]["milestone"] = "v1.0" self.assertDictEqual( data, { - "args": { - "assignee": None, - "author": None, - 'milestones': [], - 'no_stones': None, - 'order': None, - 'priority': None, - "since": None, - "status": None, - "tags": [], - }, - "issues": lcl_issues, - u'pagination': { - u'first': u'http://localhost...', - u'last': u'http://localhost...', - u'next': None, - u'page': 1, - u'pages': 1, - u'per_page': 20, - u'prev': None - }, - "total_issues": 2 - } + "args": { + "assignee": None, + "author": None, + "milestones": [], + "no_stones": None, + "order": None, + "priority": None, + "since": None, + "status": None, + "tags": [], + }, + "issues": lcl_issues, + "pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "page": 1, + "pages": 1, + "per_page": 20, + "prev": None, + }, + "total_issues": 2, + }, ) # List all issues with no milestone - output = self.app.get('/api/0/test/issues?no_stones=1') + output = self.app.get("/api/0/test/issues?no_stones=1") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - for idx in range(len(data['issues'])): - data['issues'][idx]['date_created'] = '1431414800' - data['issues'][idx]['last_updated'] = '1431414800' - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + for idx in range(len(data["issues"])): + data["issues"][idx]["date_created"] = "1431414800" + data["issues"][idx]["last_updated"] = "1431414800" + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." self.assertDictEqual( data, { - "args": { - "assignee": None, - "author": None, - 'milestones': [], - 'no_stones': True, - 'order': None, - 'priority': None, - "since": None, - "status": None, - "tags": [], - }, - "issues": [lcl_issues[1]], - u'pagination': { - u'first': u'http://localhost...', - u'last': u'http://localhost...', - u'next': None, - u'page': 1, - u'pages': 1, - u'per_page': 20, - u'prev': None - }, - "total_issues": 1 - } + "args": { + "assignee": None, + "author": None, + "milestones": [], + "no_stones": True, + "order": None, + "priority": None, + "since": None, + "status": None, + "tags": [], + }, + "issues": [lcl_issues[1]], + "pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "page": 1, + "pages": 1, + "per_page": 20, + "prev": None, + }, + "total_issues": 1, + }, ) # List all issues with a milestone - output = self.app.get('/api/0/test/issues?no_stones=0') + output = self.app.get("/api/0/test/issues?no_stones=0") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - for idx in range(len(data['issues'])): - data['issues'][idx]['date_created'] = '1431414800' - data['issues'][idx]['last_updated'] = '1431414800' - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + for idx in range(len(data["issues"])): + data["issues"][idx]["date_created"] = "1431414800" + data["issues"][idx]["last_updated"] = "1431414800" + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." self.assertDictEqual( data, { - "args": { - "assignee": None, - "author": None, - 'milestones': [], - 'no_stones': False, - 'order': None, - 'priority': None, - "since": None, - "status": None, - "tags": [], - }, - "issues": [lcl_issues[0]], - u'pagination': { - u'first': u'http://localhost...', - u'last': u'http://localhost...', - u'next': None, - u'page': 1, - u'pages': 1, - u'per_page': 20, - u'prev': None - }, - "total_issues": 1 - } + "args": { + "assignee": None, + "author": None, + "milestones": [], + "no_stones": False, + "order": None, + "priority": None, + "since": None, + "status": None, + "tags": [], + }, + "issues": [lcl_issues[0]], + "pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "page": 1, + "pages": 1, + "per_page": 20, + "prev": None, + }, + "total_issues": 1, + }, ) def test_api_view_issues_since(self): @@ -2111,21 +2040,22 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): tests.create_projects(self.session) tests.create_projects_git( - os.path.join(self.path, 'tickets'), bare=True) + os.path.join(self.path, "tickets"), bare=True + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") # Create 1st tickets start = arrow.utcnow().timestamp issue = pagure.lib.model.Issue( id=pagure.lib.query.get_next_id(self.session, repo.id), project_id=repo.id, - title='Issue #1', - content='Description', + title="Issue #1", + content="Description", user_id=1, # pingou - uid='issue#1', + uid="issue#1", private=False, ) self.session.add(issue) @@ -2138,10 +2068,10 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): issue = pagure.lib.model.Issue( id=pagure.lib.query.get_next_id(self.session, repo.id), project_id=repo.id, - title='Issue #2', - content='Description', + title="Issue #2", + content="Description", user_id=1, # pingou - uid='issue#2', + uid="issue#2", private=False, ) self.session.add(issue) @@ -2154,246 +2084,245 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): issue = pagure.lib.model.Issue( id=pagure.lib.query.get_next_id(self.session, repo.id), project_id=repo.id, - title='Issue #3', - content='Description', + title="Issue #3", + content="Description", user_id=1, # pingou - uid='issue#3', + uid="issue#3", private=True, ) self.session.add(issue) self.session.commit() # Invalid repo - output = self.app.get('/api/0/foo/issues') + output = self.app.get("/api/0/foo/issues") self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) # List all opened issues - output = self.app.get('/api/0/test/issues') + output = self.app.get("/api/0/test/issues") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - for idx in range(len(data['issues'])): - data['issues'][idx]['date_created'] = '1431414800' - data['issues'][idx]['last_updated'] = '1431414800' - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + for idx in range(len(data["issues"])): + data["issues"][idx]["date_created"] = "1431414800" + data["issues"][idx]["last_updated"] = "1431414800" + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." self.assertDictEqual( data, { - "args": { - "assignee": None, - "author": None, - 'milestones': [], - 'no_stones': None, - 'order': None, - 'priority': None, - "since": None, - "status": None, - "tags": [] - }, - "issues": LCL_ISSUES, - u'pagination': { - u'first': u'http://localhost...', - u'last': u'http://localhost...', - u'next': None, - u'page': 1, - u'pages': 1, - u'per_page': 20, - u'prev': None - }, - "total_issues": 2 - } + "args": { + "assignee": None, + "author": None, + "milestones": [], + "no_stones": None, + "order": None, + "priority": None, + "since": None, + "status": None, + "tags": [], + }, + "issues": LCL_ISSUES, + "pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "page": 1, + "pages": 1, + "per_page": 20, + "prev": None, + }, + "total_issues": 2, + }, ) time.sleep(1) late = arrow.utcnow().timestamp # List all opened issues from the start - output = self.app.get('/api/0/test/issues?since=%s' % start) + output = self.app.get("/api/0/test/issues?since=%s" % start) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - for idx in range(len(data['issues'])): - data['issues'][idx]['date_created'] = '1431414800' - data['issues'][idx]['last_updated'] = '1431414800' - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + for idx in range(len(data["issues"])): + data["issues"][idx]["date_created"] = "1431414800" + data["issues"][idx]["last_updated"] = "1431414800" + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." self.assertDictEqual( data, { - "args": { - "assignee": None, - "author": None, - 'milestones': [], - 'no_stones': None, - 'order': None, - 'priority': None, - "since": str(start), - "status": None, - "tags": [] - }, - "issues": LCL_ISSUES, - u'pagination': { - u'first': u'http://localhost...', - u'last': u'http://localhost...', - u'next': None, - u'page': 1, - u'pages': 1, - u'per_page': 20, - u'prev': None - }, - "total_issues": 2 - } + "args": { + "assignee": None, + "author": None, + "milestones": [], + "no_stones": None, + "order": None, + "priority": None, + "since": str(start), + "status": None, + "tags": [], + }, + "issues": LCL_ISSUES, + "pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "page": 1, + "pages": 1, + "per_page": 20, + "prev": None, + }, + "total_issues": 2, + }, ) # List all opened issues from the middle - output = self.app.get('/api/0/test/issues?since=%s' % middle) + output = self.app.get("/api/0/test/issues?since=%s" % middle) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - for idx in range(len(data['issues'])): - data['issues'][idx]['date_created'] = '1431414800' - data['issues'][idx]['last_updated'] = '1431414800' - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + for idx in range(len(data["issues"])): + data["issues"][idx]["date_created"] = "1431414800" + data["issues"][idx]["last_updated"] = "1431414800" + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." self.assertDictEqual( data, { - "args": { - "assignee": None, - "author": None, - 'milestones': [], - 'no_stones': None, - 'order': None, - 'priority': None, - "since": str(middle), - "status": None, - "tags": [] - }, - "issues": LCL_ISSUES[:1], - u'pagination': { - u'first': u'http://localhost...', - u'last': u'http://localhost...', - u'next': None, - u'page': 1, - u'pages': 1, - u'per_page': 20, - u'prev': None - }, - "total_issues": 1 - } + "args": { + "assignee": None, + "author": None, + "milestones": [], + "no_stones": None, + "order": None, + "priority": None, + "since": str(middle), + "status": None, + "tags": [], + }, + "issues": LCL_ISSUES[:1], + "pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "page": 1, + "pages": 1, + "per_page": 20, + "prev": None, + }, + "total_issues": 1, + }, ) # List all opened issues at the end - output = self.app.get('/api/0/test/issues?since=%s' % final) + output = self.app.get("/api/0/test/issues?since=%s" % final) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - for idx in range(len(data['issues'])): - data['issues'][idx]['date_created'] = '1431414800' - data['issues'][idx]['last_updated'] = '1431414800' - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + for idx in range(len(data["issues"])): + data["issues"][idx]["date_created"] = "1431414800" + data["issues"][idx]["last_updated"] = "1431414800" + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." self.assertDictEqual( data, { - "args": { - "assignee": None, - "author": None, - 'milestones': [], - 'no_stones': None, - 'order': None, - 'priority': None, - "since": str(final), - "status": None, - "tags": [] - }, - "issues": [], - u'pagination': { - u'first': u'http://localhost...', - u'last': u'http://localhost...', - u'next': None, - u'page': 1, - u'pages': 0, - u'per_page': 20, - u'prev': None - }, - "total_issues": 0 - } + "args": { + "assignee": None, + "author": None, + "milestones": [], + "no_stones": None, + "order": None, + "priority": None, + "since": str(final), + "status": None, + "tags": [], + }, + "issues": [], + "pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "page": 1, + "pages": 0, + "per_page": 20, + "prev": None, + }, + "total_issues": 0, + }, ) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Test since for a value before creation of issues output = self.app.get( - '/api/0/test/issues?since=%s' % final, headers=headers) + "/api/0/test/issues?since=%s" % final, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - for idx in range(len(data['issues'])): - data['issues'][idx]['last_updated'] = '1431414800' - data['issues'][idx]['date_created'] = '1431414800' - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + for idx in range(len(data["issues"])): + data["issues"][idx]["last_updated"] = "1431414800" + data["issues"][idx]["date_created"] = "1431414800" + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." self.assertDictEqual( data, { - "args": { - "assignee": None, - "author": None, - 'milestones': [], - 'no_stones': None, - 'order': None, - 'priority': None, - "since": str(final), - "status": None, - "tags": [] - }, - "issues": [{ - 'assignee': None, - 'blocks': [], - 'close_status': None, - 'closed_at': None, - 'closed_by': None, - 'comments': [], - 'content': 'Description', - 'custom_fields': [], - 'date_created': '1431414800', - 'depends': [], - 'id': 3, - 'last_updated': '1431414800', - 'milestone': None, - 'priority': None, - 'private': True, - 'status': 'Open', - 'tags': [], - 'title': 'Issue #3', - 'user': {'fullname': 'PY C', 'name': 'pingou'}} - ], - u'pagination': { - u'first': u'http://localhost...', - u'last': u'http://localhost...', - u'next': None, - u'page': 1, - u'pages': 1, - u'per_page': 20, - u'prev': None - }, - "total_issues": 1 - } + "args": { + "assignee": None, + "author": None, + "milestones": [], + "no_stones": None, + "order": None, + "priority": None, + "since": str(final), + "status": None, + "tags": [], + }, + "issues": [ + { + "assignee": None, + "blocks": [], + "close_status": None, + "closed_at": None, + "closed_by": None, + "comments": [], + "content": "Description", + "custom_fields": [], + "date_created": "1431414800", + "depends": [], + "id": 3, + "last_updated": "1431414800", + "milestone": None, + "priority": None, + "private": True, + "status": "Open", + "tags": [], + "title": "Issue #3", + "user": {"fullname": "PY C", "name": "pingou"}, + } + ], + "pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "page": 1, + "pages": 1, + "per_page": 20, + "prev": None, + }, + "total_issues": 1, + }, ) def test_api_view_issue(self): @@ -2401,407 +2330,389 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): self.test_api_new_issue() # Invalid repo - output = self.app.get('/api/0/foo/issue/1') + output = self.app.get("/api/0/foo/issue/1") self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) # Invalid issue for this repo - output = self.app.get('/api/0/test2/issue/1') + output = self.app.get("/api/0/test2/issue/1") self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Issue not found", - "error_code": "ENOISSUE", - } + data, {"error": "Issue not found", "error_code": "ENOISSUE"} ) # Valid issue - output = self.app.get('/api/0/test/issue/1') + output = self.app.get("/api/0/test/issue/1") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['date_created'] = '1431414800' - data['last_updated'] = '1431414800' + data["date_created"] = "1431414800" + data["last_updated"] = "1431414800" self.assertDictEqual( data, { - "assignee": None, - "blocks": [], - "comments": [], - "content": "This issue needs attention", - "custom_fields": [], - "date_created": "1431414800", - "close_status": None, - "closed_at": None, - "closed_by": None, - "depends": [], - "id": 1, - "last_updated": "1431414800", - "milestone": None, - "priority": None, - "private": False, - "status": "Open", - "tags": [], - "title": "test issue", - "user": { - "fullname": "PY C", - "name": "pingou" - } - } + "assignee": None, + "blocks": [], + "comments": [], + "content": "This issue needs attention", + "custom_fields": [], + "date_created": "1431414800", + "close_status": None, + "closed_at": None, + "closed_by": None, + "depends": [], + "id": 1, + "last_updated": "1431414800", + "milestone": None, + "priority": None, + "private": False, + "status": "Open", + "tags": [], + "title": "test issue", + "user": {"fullname": "PY C", "name": "pingou"}, + }, ) # Create private issue - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue', - content='We should work on this', - user='pingou', + title="Test issue", + content="We should work on this", + user="pingou", private=True, - issue_uid='aaabbbccc', + issue_uid="aaabbbccc", ) self.session.commit() - self.assertEqual(msg.title, 'Test issue') + self.assertEqual(msg.title, "Test issue") # Access private issue un-authenticated - output = self.app.get('/api/0/test/issue/2') + output = self.app.get("/api/0/test/issue/2") self.assertEqual(output.status_code, 403) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - "error": "You are not allowed to view this issue", - "error_code": "EISSUENOTALLOWED", - } + "error": "You are not allowed to view this issue", + "error_code": "EISSUENOTALLOWED", + }, ) - headers = {'Authorization': 'token aaabbbccc'} + headers = {"Authorization": "token aaabbbccc"} # Access private issue authenticated but non-existing token - output = self.app.get('/api/0/test/issue/2', headers=headers) + output = self.app.get("/api/0/test/issue/2", headers=headers) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(sorted(data.keys()), ['error', 'error_code', 'errors']) self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.value, data['error']) + sorted(data.keys()), ["error", "error_code", "errors"] + ) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.name, data['error_code']) - self.assertEqual(data['errors'], 'Invalid token') + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) + self.assertEqual(data["errors"], "Invalid token") # Create a new token for another user item = pagure.lib.model.Token( - id='bar_token', + id="bar_token", user_id=2, project_id=1, - expiration=datetime.datetime.utcnow() + datetime.timedelta( - days=30) + expiration=datetime.datetime.utcnow() + + datetime.timedelta(days=30), ) self.session.add(item) self.session.commit() - headers = {'Authorization': 'token bar_token'} + headers = {"Authorization": "token bar_token"} # Access private issue authenticated but wrong token - output = self.app.get('/api/0/test/issue/2', headers=headers) + output = self.app.get("/api/0/test/issue/2", headers=headers) self.assertEqual(output.status_code, 403) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - "error": "You are not allowed to view this issue", - "error_code": "EISSUENOTALLOWED", - } + "error": "You are not allowed to view this issue", + "error_code": "EISSUENOTALLOWED", + }, ) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Access private issue authenticated correctly - output = self.app.get('/api/0/test/issue/2', headers=headers) + output = self.app.get("/api/0/test/issue/2", headers=headers) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['date_created'] = '1431414800' - data['last_updated'] = '1431414800' + data["date_created"] = "1431414800" + data["last_updated"] = "1431414800" self.assertDictEqual( data, { - "assignee": None, - "blocks": [], - "comments": [], - "content": "We should work on this", - "custom_fields": [], - "date_created": "1431414800", - "close_status": None, - "closed_at": None, - "closed_by": None, - "depends": [], - "id": 2, - "last_updated": "1431414800", - "milestone": None, - "priority": None, - "private": True, - "status": "Open", - "tags": [], - "title": "Test issue", - "user": { - "fullname": "PY C", - "name": "pingou" - } - } + "assignee": None, + "blocks": [], + "comments": [], + "content": "We should work on this", + "custom_fields": [], + "date_created": "1431414800", + "close_status": None, + "closed_at": None, + "closed_by": None, + "depends": [], + "id": 2, + "last_updated": "1431414800", + "milestone": None, + "priority": None, + "private": True, + "status": "Open", + "tags": [], + "title": "Test issue", + "user": {"fullname": "PY C", "name": "pingou"}, + }, ) # Access private issue authenticated correctly using the issue's uid - output = self.app.get('/api/0/test/issue/aaabbbccc', headers=headers) + output = self.app.get("/api/0/test/issue/aaabbbccc", headers=headers) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['date_created'] = '1431414800' - data['last_updated'] = '1431414800' + data["date_created"] = "1431414800" + data["last_updated"] = "1431414800" self.assertDictEqual( data, { - "assignee": None, - "blocks": [], - "comments": [], - "content": "We should work on this", - "custom_fields": [], - "date_created": "1431414800", - "close_status": None, - "closed_at": None, - "closed_by": None, - "depends": [], - "id": 2, - "last_updated": "1431414800", - "milestone": None, - "priority": None, - "private": True, - "status": "Open", - "tags": [], - "title": "Test issue", - "user": { - "fullname": "PY C", - "name": "pingou" - } - } + "assignee": None, + "blocks": [], + "comments": [], + "content": "We should work on this", + "custom_fields": [], + "date_created": "1431414800", + "close_status": None, + "closed_at": None, + "closed_by": None, + "depends": [], + "id": 2, + "last_updated": "1431414800", + "milestone": None, + "priority": None, + "private": True, + "status": "Open", + "tags": [], + "title": "Test issue", + "user": {"fullname": "PY C", "name": "pingou"}, + }, ) def test_api_change_milestone_issue_invalid_project(self): """ Test the api_change_milestone_issue method of the flask api. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'tickets')) + tests.create_projects_git(os.path.join(self.path, "tickets")) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Set some milestones to the project - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - repo.milestones = {'v1.0': None, 'v2.0': 'Soon'} + repo = pagure.lib.query.get_authorized_project(self.session, "test") + repo.milestones = {"v1.0": None, "v2.0": "Soon"} self.session.add(repo) self.session.commit() - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Invalid project - output = self.app.post('/api/0/foo/issue/1/milestone', headers=headers) + output = self.app.post("/api/0/foo/issue/1/milestone", headers=headers) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) - @patch.dict('pagure.config.config', {'ENABLE_TICKETS_NAMESPACE': ['foobar']}) + @patch.dict( + "pagure.config.config", {"ENABLE_TICKETS_NAMESPACE": ["foobar"]} + ) def test_api_change_milestone_issue_wrong_namespace(self): """ Test the api_new_issue method of the flask api. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'tickets')) + tests.create_projects_git(os.path.join(self.path, "tickets")) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Set some milestones to the project repo = pagure.lib.query.get_authorized_project( - self.session, 'test3', namespace='somenamespace') - repo.milestones = {'v1.0': None, 'v2.0': 'Soon'} + self.session, "test3", namespace="somenamespace" + ) + repo.milestones = {"v1.0": None, "v2.0": "Soon"} self.session.add(repo) self.session.commit() # Create normal issue - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue #1', - content='We should work on this', - user='pingou', + title="Test issue #1", + content="We should work on this", + user="pingou", private=False, ) self.session.commit() - self.assertEqual(msg.title, 'Test issue #1') + self.assertEqual(msg.title, "Test issue #1") - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Valid token, wrong project output = self.app.post( - '/api/0/somenamespace/test3/issue/1/milestone', headers=headers) + "/api/0/somenamespace/test3/issue/1/milestone", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(sorted(data.keys()), ['error', 'error_code']) + self.assertEqual(sorted(data.keys()), ["error", "error_code"]) self.assertEqual( - pagure.api.APIERROR.ETRACKERDISABLED.value, data['error']) + pagure.api.APIERROR.ETRACKERDISABLED.value, data["error"] + ) self.assertEqual( - pagure.api.APIERROR.ETRACKERDISABLED.name, data['error_code']) + pagure.api.APIERROR.ETRACKERDISABLED.name, data["error_code"] + ) def test_api_change_milestone_issue_wrong_token(self): """ Test the api_change_milestone_issue method of the flask api. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'tickets')) + tests.create_projects_git(os.path.join(self.path, "tickets")) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Set some milestones to the project - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - repo.milestones = {'v1.0': None, 'v2.0': 'Soon'} + repo = pagure.lib.query.get_authorized_project(self.session, "test") + repo.milestones = {"v1.0": None, "v2.0": "Soon"} self.session.add(repo) self.session.commit() - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Valid token, wrong project - output = self.app.post('/api/0/test2/issue/1/milestone', headers=headers) + output = self.app.post( + "/api/0/test2/issue/1/milestone", headers=headers + ) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(sorted(data.keys()), ['error', 'error_code']) - self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.value, data['error']) + self.assertEqual(sorted(data.keys()), ["error", "error_code"]) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.name, data['error_code']) + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) def test_api_change_milestone_issue_no_issue(self): """ Test the api_change_milestone_issue method of the flask api. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'tickets')) + tests.create_projects_git(os.path.join(self.path, "tickets")) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Set some milestones to the project - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - repo.milestones = {'v1.0': None, 'v2.0': 'Soon'} + repo = pagure.lib.query.get_authorized_project(self.session, "test") + repo.milestones = {"v1.0": None, "v2.0": "Soon"} self.session.add(repo) self.session.commit() - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # No issue - output = self.app.post('/api/0/test/issue/1/milestone', headers=headers) + output = self.app.post( + "/api/0/test/issue/1/milestone", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Issue not found", - "error_code": "ENOISSUE", - } + data, {"error": "Issue not found", "error_code": "ENOISSUE"} ) def test_api_change_milestone_issue_no_milestone(self): """ Test the api_change_milestone_issue method of the flask api. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'tickets')) + tests.create_projects_git(os.path.join(self.path, "tickets")) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Set some milestones to the project - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - repo.milestones = {'v1.0': None, 'v2.0': 'Soon'} + repo = pagure.lib.query.get_authorized_project(self.session, "test") + repo.milestones = {"v1.0": None, "v2.0": "Soon"} self.session.add(repo) self.session.commit() - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Create normal issue - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue #1', - content='We should work on this', - user='pingou', + title="Test issue #1", + content="We should work on this", + user="pingou", private=False, ) self.session.commit() - self.assertEqual(msg.title, 'Test issue #1') + self.assertEqual(msg.title, "Test issue #1") # Check milestone before - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) self.assertEqual(issue.milestone, None) - data = { - 'milestone': '', - } + data = {"milestone": ""} # Valid request but no milestone specified output = self.app.post( - '/api/0/test/issue/1/milestone', data=data, headers=headers) + "/api/0/test/issue/1/milestone", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'No changes'} - ) + self.assertDictEqual(data, {"message": "No changes"}) # No change - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) self.assertEqual(issue.milestone, None) def test_api_change_milestone_issue_invalid_milestone(self): """ Test the api_change_milestone_issue method of the flask api. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'tickets')) + tests.create_projects_git(os.path.join(self.path, "tickets")) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Set some milestones to the project - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - repo.milestones = {'v1.0': None, 'v2.0': 'Soon'} + repo = pagure.lib.query.get_authorized_project(self.session, "test") + repo.milestones = {"v1.0": None, "v2.0": "Soon"} self.session.add(repo) self.session.commit() - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Create normal issue - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue #1', - content='We should work on this', - user='pingou', + title="Test issue #1", + content="We should work on this", + user="pingou", private=False, ) self.session.commit() - self.assertEqual(msg.title, 'Test issue #1') + self.assertEqual(msg.title, "Test issue #1") # Check milestone before - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) self.assertEqual(issue.milestone, None) - data = { - 'milestone': 'milestone-1-0', - } + data = {"milestone": "milestone-1-0"} # Invalid milestone specified output = self.app.post( - '/api/0/test/issue/1/milestone', data=data, headers=headers) + "/api/0/test/issue/1/milestone", data=data, headers=headers + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( @@ -2809,186 +2720,158 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): { "error": "Invalid or incomplete input submitted", "error_code": "EINVALIDREQ", - "errors": { - "milestone": [ - "Not a valid choice" - ] - } - } + "errors": {"milestone": ["Not a valid choice"]}, + }, ) def test_api_change_milestone_issue(self): """ Test the api_change_milestone_issue method of the flask api. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'tickets')) + tests.create_projects_git(os.path.join(self.path, "tickets")) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Set some milestones to the project - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - repo.milestones = {'v1.0': None, 'v2.0': 'Soon'} + repo = pagure.lib.query.get_authorized_project(self.session, "test") + repo.milestones = {"v1.0": None, "v2.0": "Soon"} self.session.add(repo) self.session.commit() - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Create normal issue - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue #1', - content='We should work on this', - user='pingou', + title="Test issue #1", + content="We should work on this", + user="pingou", private=False, ) self.session.commit() - self.assertEqual(msg.title, 'Test issue #1') + self.assertEqual(msg.title, "Test issue #1") # Check milestone before - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) self.assertEqual(issue.milestone, None) - data = { - 'milestone': 'v1.0', - } + data = {"milestone": "v1.0"} # Valid requests output = self.app.post( - '/api/0/test/issue/1/milestone', data=data, headers=headers) + "/api/0/test/issue/1/milestone", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "message": [ - "Issue set to the milestone: v1.0" - ] - } + data, {"message": ["Issue set to the milestone: v1.0"]} ) def test_api_change_milestone_issue_remove_milestone(self): """ Test the api_change_milestone_issue method of the flask api. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'tickets')) + tests.create_projects_git(os.path.join(self.path, "tickets")) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Set some milestones to the project - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - repo.milestones = {'v1.0': None, 'v2.0': 'Soon'} + repo = pagure.lib.query.get_authorized_project(self.session, "test") + repo.milestones = {"v1.0": None, "v2.0": "Soon"} self.session.add(repo) self.session.commit() - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Create normal issue - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue #1', - content='We should work on this', - user='pingou', + title="Test issue #1", + content="We should work on this", + user="pingou", private=False, ) self.session.commit() - self.assertEqual(msg.title, 'Test issue #1') + self.assertEqual(msg.title, "Test issue #1") # Check milestone before - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) self.assertEqual(issue.milestone, None) - data = { - 'milestone': 'v1.0', - } + data = {"milestone": "v1.0"} # Valid requests output = self.app.post( - '/api/0/test/issue/1/milestone', data=data, headers=headers) + "/api/0/test/issue/1/milestone", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "message": [ - "Issue set to the milestone: v1.0" - ] - } + data, {"message": ["Issue set to the milestone: v1.0"]} ) # remove milestone - data = { - 'milestone': '', - } + data = {"milestone": ""} # Valid requests output = self.app.post( - '/api/0/test/issue/1/milestone', data=data, headers=headers) + "/api/0/test/issue/1/milestone", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "message": [ - "Issue set to the milestone: None (was: v1.0)" - ] - } + data, {"message": ["Issue set to the milestone: None (was: v1.0)"]} ) # Change recorded - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) self.assertEqual(issue.milestone, None) def test_api_change_milestone_issue_remove_milestone2(self): """ Test the api_change_milestone_issue method of the flask api. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'tickets')) + tests.create_projects_git(os.path.join(self.path, "tickets")) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Set some milestones to the project - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - repo.milestones = {'v1.0': None, 'v2.0': 'Soon'} + repo = pagure.lib.query.get_authorized_project(self.session, "test") + repo.milestones = {"v1.0": None, "v2.0": "Soon"} self.session.add(repo) self.session.commit() - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Create normal issue - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue #1', - content='We should work on this', - user='pingou', + title="Test issue #1", + content="We should work on this", + user="pingou", private=False, ) self.session.commit() - self.assertEqual(msg.title, 'Test issue #1') + self.assertEqual(msg.title, "Test issue #1") # Check milestone before - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) self.assertEqual(issue.milestone, None) - data = { - 'milestone': 'v1.0', - } + data = {"milestone": "v1.0"} # Valid requests output = self.app.post( - '/api/0/test/issue/1/milestone', data=data, headers=headers) + "/api/0/test/issue/1/milestone", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "message": [ - "Issue set to the milestone: v1.0" - ] - } + data, {"message": ["Issue set to the milestone: v1.0"]} ) # remove milestone by using no milestone in JSON @@ -2996,364 +2879,359 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): # Valid requests output = self.app.post( - '/api/0/test/issue/1/milestone', data=data, headers=headers) + "/api/0/test/issue/1/milestone", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "message": [ - "Issue set to the milestone: None (was: v1.0)" - ] - } + data, {"message": ["Issue set to the milestone: None (was: v1.0)"]} ) # Change recorded - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) self.assertEqual(issue.milestone, None) def test_api_change_milestone_issue_unauthorized(self): """ Test the api_change_milestone_issue method of the flask api. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'tickets')) + tests.create_projects_git(os.path.join(self.path, "tickets")) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Set some milestones to the project - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - repo.milestones = {'v1.0': None, 'v2.0': 'Soon'} + repo = pagure.lib.query.get_authorized_project(self.session, "test") + repo.milestones = {"v1.0": None, "v2.0": "Soon"} self.session.add(repo) self.session.commit() - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Create normal issue - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue #1', - content='We should work on this', - user='pingou', + title="Test issue #1", + content="We should work on this", + user="pingou", private=False, ) self.session.commit() - self.assertEqual(msg.title, 'Test issue #1') + self.assertEqual(msg.title, "Test issue #1") - headers = {'Authorization': 'token pingou_foo'} - data = {'milestone': 'v1.0',} + headers = {"Authorization": "token pingou_foo"} + data = {"milestone": "v1.0"} # Un-authorized issue output = self.app.post( - '/api/0/foo/issue/1/milestone', data={}, headers=headers) + "/api/0/foo/issue/1/milestone", data={}, headers=headers + ) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(sorted(data.keys()), ['error', 'error_code', 'errors']) self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.value, data['error']) + sorted(data.keys()), ["error", "error_code", "errors"] + ) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.name, data['error_code']) - self.assertEqual(data['errors'], 'Invalid token') + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) + self.assertEqual(data["errors"], "Invalid token") - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) @patch( - 'pagure.lib.query.add_metadata_update_notif', - MagicMock(side_effect=pagure.exceptions.PagureException('error'))) + "pagure.lib.query.add_metadata_update_notif", + MagicMock(side_effect=pagure.exceptions.PagureException("error")), + ) def test_api_change_milestone_issue_raises_exception(self): """ Test the api_change_milestone_issue method of the flask api. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'tickets')) + tests.create_projects_git(os.path.join(self.path, "tickets")) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Set some milestones to the project - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - repo.milestones = {'v1.0': None, 'v2.0': 'Soon'} + repo = pagure.lib.query.get_authorized_project(self.session, "test") + repo.milestones = {"v1.0": None, "v2.0": "Soon"} self.session.add(repo) self.session.commit() - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Create normal issue - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue #1', - content='We should work on this', - user='pingou', + title="Test issue #1", + content="We should work on this", + user="pingou", private=False, ) self.session.commit() - self.assertEqual(msg.title, 'Test issue #1') + self.assertEqual(msg.title, "Test issue #1") - data = { - 'milestone': 'v1.0', - } + data = {"milestone": "v1.0"} # Valid requests output = self.app.post( - '/api/0/test/issue/1/milestone', data=data, headers=headers) + "/api/0/test/issue/1/milestone", data=data, headers=headers + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {u'error': u'error', u'error_code': u'ENOCODE'} - ) + self.assertDictEqual(data, {"error": "error", "error_code": "ENOCODE"}) - @patch('pagure.lib.git.update_git') - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.git.update_git") + @patch("pagure.lib.notify.send_email") def test_api_view_issue_comment(self, p_send_email, p_ugt): """ Test the api_view_issue_comment endpoint. """ p_send_email.return_value = True p_ugt.return_value = True tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'tickets')) + tests.create_projects_git(os.path.join(self.path, "tickets")) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Create normal issue in test - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue #1', - content='We should work on this', - user='pingou', + title="Test issue #1", + content="We should work on this", + user="pingou", private=False, - issue_uid='aaabbbccc1', + issue_uid="aaabbbccc1", ) self.session.commit() - self.assertEqual(msg.title, 'Test issue #1') - + self.assertEqual(msg.title, "Test issue #1") - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} - data = { - 'comment': 'This is a very interesting question', - } + data = {"comment": "This is a very interesting question"} # Valid request output = self.app.post( - '/api/0/test/issue/1/comment', data=data, headers=headers) + "/api/0/test/issue/1/comment", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( data, - {'message': 'Comment added', - 'avatar_url': 'https://seccdn.libravatar.org/avatar/...', - 'user': 'pingou'} + { + "message": "Comment added", + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + "user": "pingou", + }, ) # One comment added - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) self.assertEqual(len(issue.comments), 1) # View a comment that does not exist - output = self.app.get('/api/0/foo/issue/100/comment/2') + output = self.app.get("/api/0/foo/issue/100/comment/2") self.assertEqual(output.status_code, 404) # Issue exists but not the comment - output = self.app.get('/api/0/test/issue/1/comment/2') + output = self.app.get("/api/0/test/issue/1/comment/2") self.assertEqual(output.status_code, 404) # Issue and comment exists - output = self.app.get('/api/0/test/issue/1/comment/1') + output = self.app.get("/api/0/test/issue/1/comment/1") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['date_created'] = '1435821770' + data["date_created"] = "1435821770" data["comment_date"] = "2015-07-02 09:22" data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( data, { - "avatar_url": "https://seccdn.libravatar.org/avatar/...", - "comment": "This is a very interesting question", - "comment_date": "2015-07-02 09:22", - "date_created": "1435821770", - "edited_on": None, - "editor": None, - "notification": False, - "id": 1, - "parent": None, - "reactions": {}, - "user": { - "fullname": "PY C", - "name": "pingou" - } - } + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + "comment": "This is a very interesting question", + "comment_date": "2015-07-02 09:22", + "date_created": "1435821770", + "edited_on": None, + "editor": None, + "notification": False, + "id": 1, + "parent": None, + "reactions": {}, + "user": {"fullname": "PY C", "name": "pingou"}, + }, ) # Issue and comment exists, using UID - output = self.app.get('/api/0/test/issue/aaabbbccc1/comment/1') + output = self.app.get("/api/0/test/issue/aaabbbccc1/comment/1") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['date_created'] = '1435821770' + data["date_created"] = "1435821770" data["comment_date"] = "2015-07-02 09:22" data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( data, { - "avatar_url": "https://seccdn.libravatar.org/avatar/...", - "comment": "This is a very interesting question", - "comment_date": "2015-07-02 09:22", - "date_created": "1435821770", - "edited_on": None, - "editor": None, - "notification": False, - "id": 1, - "parent": None, - "reactions": {}, - "user": { - "fullname": "PY C", - "name": "pingou" - } - } + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + "comment": "This is a very interesting question", + "comment_date": "2015-07-02 09:22", + "date_created": "1435821770", + "edited_on": None, + "editor": None, + "notification": False, + "id": 1, + "parent": None, + "reactions": {}, + "user": {"fullname": "PY C", "name": "pingou"}, + }, ) - @patch('pagure.lib.git.update_git') - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.git.update_git") + @patch("pagure.lib.notify.send_email") def test_api_view_issue_comment_private(self, p_send_email, p_ugt): """ Test the api_view_issue_comment endpoint. """ p_send_email.return_value = True p_ugt.return_value = True tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'tickets')) + tests.create_projects_git(os.path.join(self.path, "tickets")) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Create normal issue in test - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue #1', - content='We should work on this', - user='foo', + title="Test issue #1", + content="We should work on this", + user="foo", private=True, - issue_uid='aaabbbccc1', + issue_uid="aaabbbccc1", ) self.session.commit() - self.assertEqual(msg.title, 'Test issue #1') + self.assertEqual(msg.title, "Test issue #1") # Create a token for another user item = pagure.lib.model.Token( - id='foo_token_2', + id="foo_token_2", user_id=2, project_id=1, expiration=datetime.datetime.utcnow() - + datetime.timedelta(days=30) + + datetime.timedelta(days=30), ) self.session.add(item) self.session.commit() - tests.create_tokens_acl(self.session, token_id='foo_token_2') + tests.create_tokens_acl(self.session, token_id="foo_token_2") # Add a comment to that issue - data = { - 'comment': 'This is a very interesting question', - } - headers = {'Authorization': 'token foo_token_2'} + data = {"comment": "This is a very interesting question"} + headers = {"Authorization": "token foo_token_2"} output = self.app.post( - '/api/0/test/issue/1/comment', data=data, headers=headers) + "/api/0/test/issue/1/comment", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( data, - {'message': 'Comment added', - 'avatar_url': 'https://seccdn.libravatar.org/avatar/...', - 'user': 'foo'} + { + "message": "Comment added", + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + "user": "foo", + }, ) # Private issue - no auth - output = self.app.get('/api/0/test/issue/1/comment/2') + output = self.app.get("/api/0/test/issue/1/comment/2") self.assertEqual(output.status_code, 403) # Private issue - Auth - Invalid token - headers = {'Authorization': 'token aaabbbcccdddee'} - output = self.app.get('/api/0/test/issue/1/comment/2', headers=headers) + headers = {"Authorization": "token aaabbbcccdddee"} + output = self.app.get("/api/0/test/issue/1/comment/2", headers=headers) self.assertEqual(output.status_code, 401) # Private issue - Auth - valid token - unknown comment - headers = {'Authorization': 'token foo_token_2'} - output = self.app.get('/api/0/test/issue/1/comment/3', headers=headers) + headers = {"Authorization": "token foo_token_2"} + output = self.app.get("/api/0/test/issue/1/comment/3", headers=headers) self.assertEqual(output.status_code, 404) # Private issue - Auth - valid token - known comment - headers = {'Authorization': 'token foo_token_2'} - output = self.app.get('/api/0/test/issue/1/comment/1', headers=headers) + headers = {"Authorization": "token foo_token_2"} + output = self.app.get("/api/0/test/issue/1/comment/1", headers=headers) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['date_created'] = '1435821770' + data["date_created"] = "1435821770" data["comment_date"] = "2015-07-02 09:22" data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( data, { - "avatar_url": "https://seccdn.libravatar.org/avatar/...", - "comment": "This is a very interesting question", - "comment_date": "2015-07-02 09:22", - "date_created": "1435821770", - "edited_on": None, - "editor": None, - "notification": False, - "id": 1, - "parent": None, - "reactions": {}, - "user": { - "fullname": "foo bar", - "name": "foo" - } - } + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + "comment": "This is a very interesting question", + "comment_date": "2015-07-02 09:22", + "date_created": "1435821770", + "edited_on": None, + "editor": None, + "notification": False, + "id": 1, + "parent": None, + "reactions": {}, + "user": {"fullname": "foo bar", "name": "foo"}, + }, ) - @patch.dict('pagure.config.config', {'ENABLE_TICKETS_NAMESPACE': ['foobar']}) + @patch.dict( + "pagure.config.config", {"ENABLE_TICKETS_NAMESPACE": ["foobar"]} + ) def test_api_assign_issue_wrong_namespace(self): """ Test the api_new_issue method of the flask api. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'tickets')) + tests.create_projects_git(os.path.join(self.path, "tickets")) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Set some milestones to the project repo = pagure.lib.query.get_authorized_project( - self.session, 'test3', namespace='somenamespace') - repo.milestones = {'v1.0': None, 'v2.0': 'Soon'} + self.session, "test3", namespace="somenamespace" + ) + repo.milestones = {"v1.0": None, "v2.0": "Soon"} self.session.add(repo) self.session.commit() # Create normal issue repo = pagure.lib.query.get_authorized_project( - self.session, 'test3', namespace='somenamespace') + self.session, "test3", namespace="somenamespace" + ) msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue #1', - content='We should work on this', - user='pingou', + title="Test issue #1", + content="We should work on this", + user="pingou", private=False, ) self.session.commit() - self.assertEqual(msg.title, 'Test issue #1') + self.assertEqual(msg.title, "Test issue #1") - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Valid token, wrong project output = self.app.post( - '/api/0/somenamespace/test3/issue/1/assign', headers=headers) + "/api/0/somenamespace/test3/issue/1/assign", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(sorted(data.keys()), ['error', 'error_code']) + self.assertEqual(sorted(data.keys()), ["error", "error_code"]) self.assertEqual( - pagure.api.APIERROR.ETRACKERDISABLED.value, data['error']) + pagure.api.APIERROR.ETRACKERDISABLED.value, data["error"] + ) self.assertEqual( - pagure.api.APIERROR.ETRACKERDISABLED.name, data['error_code']) + pagure.api.APIERROR.ETRACKERDISABLED.name, data["error_code"] + ) - @patch('pagure.lib.git.update_git') - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.git.update_git") + @patch("pagure.lib.notify.send_email") def test_api_assign_issue(self, p_send_email, p_ugt): """ Test the api_assign_issue method of the flask api. """ p_send_email.return_value = True @@ -3363,247 +3241,221 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Invalid project - output = self.app.post('/api/0/foo/issue/1/assign', headers=headers) + output = self.app.post("/api/0/foo/issue/1/assign", headers=headers) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) # Valid token, wrong project - output = self.app.post('/api/0/test2/issue/1/assign', headers=headers) + output = self.app.post("/api/0/test2/issue/1/assign", headers=headers) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(sorted(data.keys()), ['error', 'error_code']) + self.assertEqual(sorted(data.keys()), ["error", "error_code"]) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.value, data['error']) - self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.name, data['error_code']) + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) # No input - output = self.app.post('/api/0/test/issue/1/assign', headers=headers) + output = self.app.post("/api/0/test/issue/1/assign", headers=headers) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Issue not found", - "error_code": "ENOISSUE", - } + data, {"error": "Issue not found", "error_code": "ENOISSUE"} ) # Create normal issue - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue #1', - content='We should work on this', - user='pingou', + title="Test issue #1", + content="We should work on this", + user="pingou", private=False, - issue_uid='aaabbbccc1', + issue_uid="aaabbbccc1", ) self.session.commit() - self.assertEqual(msg.title, 'Test issue #1') + self.assertEqual(msg.title, "Test issue #1") # Check comments before - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) self.assertEqual(len(issue.comments), 0) # No change - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) - self.assertEqual(issue.status, 'Open') + self.assertEqual(issue.status, "Open") - data = { - 'assignee': 'pingou', - } + data = {"assignee": "pingou"} # Valid request output = self.app.post( - '/api/0/test/issue/1/assign', data=data, headers=headers) + "/api/0/test/issue/1/assign", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'Issue assigned to pingou'} - ) + self.assertDictEqual(data, {"message": "Issue assigned to pingou"}) # Un-assign output = self.app.post( - '/api/0/test/issue/1/assign', data=data, headers=headers) + "/api/0/test/issue/1/assign", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'Assignee reset'} - ) + self.assertDictEqual(data, {"message": "Assignee reset"}) # No change - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) self.assertEqual(issue.assignee, None) # Un-assign - data = {'assignee': None} + data = {"assignee": None} output = self.app.post( - '/api/0/test/issue/1/assign', data=data, headers=headers) + "/api/0/test/issue/1/assign", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'Nothing to change'} - ) - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + self.assertDictEqual(data, {"message": "Nothing to change"}) + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) self.assertEqual(issue.assignee, None) # Re-assign for the rest of the tests - data = {'assignee': 'pingou'} + data = {"assignee": "pingou"} output = self.app.post( - '/api/0/test/issue/1/assign', data=data, headers=headers) + "/api/0/test/issue/1/assign", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'Issue assigned to pingou'} - ) + self.assertDictEqual(data, {"message": "Issue assigned to pingou"}) # Un-assign - data = {'assignee': ''} + data = {"assignee": ""} output = self.app.post( - '/api/0/test/issue/1/assign', data=data, headers=headers) + "/api/0/test/issue/1/assign", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'Assignee reset'} - ) + self.assertDictEqual(data, {"message": "Assignee reset"}) # Re-assign for the rest of the tests - data = {'assignee': 'pingou'} + data = {"assignee": "pingou"} output = self.app.post( - '/api/0/test/issue/1/assign', data=data, headers=headers) + "/api/0/test/issue/1/assign", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'Issue assigned to pingou'} - ) + self.assertDictEqual(data, {"message": "Issue assigned to pingou"}) # One comment added self.session.commit() - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) - self.assertEqual(issue.assignee.user, 'pingou') + self.assertEqual(issue.assignee.user, "pingou") # Create another project item = pagure.lib.model.Project( user_id=2, # foo - name='foo', - description='test project #3', - hook_token='aaabbbdddeee', + name="foo", + description="test project #3", + hook_token="aaabbbdddeee", ) self.session.add(item) self.session.commit() # Create a token for pingou for this project item = pagure.lib.model.Token( - id='pingou_foo', + id="pingou_foo", user_id=1, project_id=4, - expiration=datetime.datetime.utcnow() + datetime.timedelta( - days=30) + expiration=datetime.datetime.utcnow() + + datetime.timedelta(days=30), ) self.session.add(item) self.session.commit() # Give `issue_change_status` to this token when `issue_comment` # is required - item = pagure.lib.model.TokenAcl( - token_id='pingou_foo', - acl_id=8, - ) + item = pagure.lib.model.TokenAcl(token_id="pingou_foo", acl_id=8) self.session.add(item) self.session.commit() - repo = pagure.lib.query.get_authorized_project(self.session, 'foo') + repo = pagure.lib.query.get_authorized_project(self.session, "foo") # Create private issue msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue', - content='We should work on this', - user='foo', + title="Test issue", + content="We should work on this", + user="foo", private=True, - issue_uid='aaabbbccc#2', + issue_uid="aaabbbccc#2", ) self.session.commit() - self.assertEqual(msg.title, 'Test issue') + self.assertEqual(msg.title, "Test issue") # Check before - repo = pagure.lib.query.get_authorized_project(self.session, 'foo') + repo = pagure.lib.query.get_authorized_project(self.session, "foo") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) self.assertEqual(len(issue.comments), 0) - data = { - 'assignee': 'pingou', - } - headers = {'Authorization': 'token pingou_foo'} + data = {"assignee": "pingou"} + headers = {"Authorization": "token pingou_foo"} # Valid request but un-authorized output = self.app.post( - '/api/0/foo/issue/1/assign', data=data, headers=headers) + "/api/0/foo/issue/1/assign", data=data, headers=headers + ) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(sorted(data.keys()), ['error', 'error_code', 'errors']) self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.value, data['error']) + sorted(data.keys()), ["error", "error_code", "errors"] + ) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.name, data['error_code']) + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) self.assertEqual( - data['errors'], 'Missing ACLs: issue_assign, issue_update') + data["errors"], "Missing ACLs: issue_assign, issue_update" + ) # No comment added - repo = pagure.lib.query.get_authorized_project(self.session, 'foo') + repo = pagure.lib.query.get_authorized_project(self.session, "foo") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) self.assertEqual(len(issue.comments), 0) # Create token for user foo item = pagure.lib.model.Token( - id='foo_token2', + id="foo_token2", user_id=2, project_id=4, - expiration=datetime.datetime.utcnow() + datetime.timedelta(days=30) + expiration=datetime.datetime.utcnow() + + datetime.timedelta(days=30), ) self.session.add(item) self.session.commit() - tests.create_tokens_acl(self.session, token_id='foo_token2') + tests.create_tokens_acl(self.session, token_id="foo_token2") - data = { - 'assignee': 'pingou', - } - headers = {'Authorization': 'token foo_token2'} + data = {"assignee": "pingou"} + headers = {"Authorization": "token foo_token2"} # Valid request and authorized output = self.app.post( - '/api/0/foo/issue/1/assign', data=data, headers=headers) + "/api/0/foo/issue/1/assign", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'Issue assigned to pingou'} - ) + self.assertDictEqual(data, {"message": "Issue assigned to pingou"}) - @patch('pagure.lib.git.update_git') - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.git.update_git") + @patch("pagure.lib.notify.send_email") def test_api_assign_issue_issuer(self, p_send_email, p_ugt): """ Test the api_assign_issue method of the flask api. """ p_send_email.return_value = True @@ -3613,72 +3465,67 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): tests.create_tokens(self.session, user_id=2) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Create normal issue - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue #1', - content='We should work on this', - user='pingou', + title="Test issue #1", + content="We should work on this", + user="pingou", private=False, - issue_uid='aaabbbccc1', - assignee='foo', + issue_uid="aaabbbccc1", + assignee="foo", ) self.session.commit() - self.assertEqual(msg.title, 'Test issue #1') + self.assertEqual(msg.title, "Test issue #1") # Check comments before - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) self.assertEqual(len(issue.comments), 0) # Un-assign - data = {'assignee': None} + data = {"assignee": None} output = self.app.post( - '/api/0/test/issue/1/assign', data={}, headers=headers) + "/api/0/test/issue/1/assign", data={}, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'Assignee reset'} - ) + self.assertDictEqual(data, {"message": "Assignee reset"}) # No longer allowed to self-assign since no access - data = { - 'assignee': 'foo', - } + data = {"assignee": "foo"} output = self.app.post( - '/api/0/test/issue/1/assign', data=data, headers=headers) + "/api/0/test/issue/1/assign", data=data, headers=headers + ) self.assertEqual(output.status_code, 403) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - 'error': 'You are not allowed to view this issue', - 'error_code': 'EISSUENOTALLOWED' - } + "error": "You are not allowed to view this issue", + "error_code": "EISSUENOTALLOWED", + }, ) - @patch('pagure.lib.git.update_git') - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.git.update_git") + @patch("pagure.lib.notify.send_email") def test_api_subscribe_issue(self, p_send_email, p_ugt): """ Test the api_subscribe_issue method of the flask api. """ p_send_email.return_value = True p_ugt.return_value = True item = pagure.lib.model.User( - user='bar', - fullname='bar foo', - password='foo', - default_email='bar@bar.com', + user="bar", + fullname="bar foo", + password="foo", + default_email="bar@bar.com", ) self.session.add(item) - item = pagure.lib.model.UserEmail( - user_id=3, - email='bar@bar.com') + item = pagure.lib.model.UserEmail(user_id=3, email="bar@bar.com") self.session.add(item) self.session.commit() @@ -3687,280 +3534,293 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): tests.create_tokens(self.session, user_id=3) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Invalid project - output = self.app.post( - '/api/0/foo/issue/1/subscribe', headers=headers) + output = self.app.post("/api/0/foo/issue/1/subscribe", headers=headers) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) # Valid token, wrong project output = self.app.post( - '/api/0/test2/issue/1/subscribe', headers=headers) + "/api/0/test2/issue/1/subscribe", headers=headers + ) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(sorted(data.keys()), ['error', 'error_code']) + self.assertEqual(sorted(data.keys()), ["error", "error_code"]) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.value, data['error']) - self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.name, data['error_code']) + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) # No input output = self.app.post( - '/api/0/test/issue/1/subscribe', headers=headers) + "/api/0/test/issue/1/subscribe", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Issue not found", - "error_code": "ENOISSUE", - } + data, {"error": "Issue not found", "error_code": "ENOISSUE"} ) # Create normal issue - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue #1', - content='We should work on this', - user='foo', + title="Test issue #1", + content="We should work on this", + user="foo", private=False, - issue_uid='aaabbbccc1', + issue_uid="aaabbbccc1", ) self.session.commit() - self.assertEqual(msg.title, 'Test issue #1') + self.assertEqual(msg.title, "Test issue #1") # Check subscribtion before - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) self.assertEqual( pagure.lib.query.get_watch_list(self.session, issue), - set(['pingou', 'foo'])) - + set(["pingou", "foo"]), + ) # Unsubscribe - no changes data = {} output = self.app.post( - '/api/0/test/issue/1/subscribe', data=data, headers=headers) + "/api/0/test/issue/1/subscribe", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( data, - {'message': 'You are no longer watching this issue', - 'avatar_url': 'https://seccdn.libravatar.org/avatar/...', - 'user': 'bar'} + { + "message": "You are no longer watching this issue", + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + "user": "bar", + }, ) data = {} output = self.app.post( - '/api/0/test/issue/1/subscribe', data=data, headers=headers) + "/api/0/test/issue/1/subscribe", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( data, - {'message': 'You are no longer watching this issue', - 'avatar_url': 'https://seccdn.libravatar.org/avatar/...', - 'user': 'bar'} + { + "message": "You are no longer watching this issue", + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + "user": "bar", + }, ) # No change - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) self.assertEqual( pagure.lib.query.get_watch_list(self.session, issue), - set(['pingou', 'foo'])) + set(["pingou", "foo"]), + ) # Subscribe - data = {'status': True} + data = {"status": True} output = self.app.post( - '/api/0/test/issue/1/subscribe', data=data, headers=headers) + "/api/0/test/issue/1/subscribe", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( data, - {'message': 'You are now watching this issue', - 'avatar_url': 'https://seccdn.libravatar.org/avatar/...', - 'user': 'bar'} + { + "message": "You are now watching this issue", + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + "user": "bar", + }, ) # Subscribe - no changes - data = {'status': True} + data = {"status": True} output = self.app.post( - '/api/0/test/issue/1/subscribe', data=data, headers=headers) + "/api/0/test/issue/1/subscribe", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( data, - {'message': 'You are now watching this issue', - 'avatar_url': 'https://seccdn.libravatar.org/avatar/...', - 'user': 'bar'} + { + "message": "You are now watching this issue", + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + "user": "bar", + }, ) - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) self.assertEqual( pagure.lib.query.get_watch_list(self.session, issue), - set(['pingou', 'foo', 'bar'])) + set(["pingou", "foo", "bar"]), + ) # Unsubscribe data = {} output = self.app.post( - '/api/0/test/issue/1/subscribe', data=data, headers=headers) + "/api/0/test/issue/1/subscribe", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( data, - {'message': 'You are no longer watching this issue', - 'avatar_url': 'https://seccdn.libravatar.org/avatar/...', - 'user': 'bar'} + { + "message": "You are no longer watching this issue", + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + "user": "bar", + }, ) - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) self.assertEqual( pagure.lib.query.get_watch_list(self.session, issue), - set(['pingou', 'foo'])) + set(["pingou", "foo"]), + ) def test_api_update_custom_field(self): """ Test the api_update_custom_field method of the flask api. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'tickets')) + tests.create_projects_git(os.path.join(self.path, "tickets")) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Invalid project output = self.app.post( - '/api/0/foo/issue/1/custom/bugzilla', headers=headers) + "/api/0/foo/issue/1/custom/bugzilla", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) # Valid token, wrong project output = self.app.post( - '/api/0/test2/issue/1/custom/bugzilla', headers=headers) + "/api/0/test2/issue/1/custom/bugzilla", headers=headers + ) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(sorted(data.keys()), ['error', 'error_code']) - self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.value, data['error']) + self.assertEqual(sorted(data.keys()), ["error", "error_code"]) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.name, data['error_code']) + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) # No issue output = self.app.post( - '/api/0/test/issue/1/custom/bugzilla', headers=headers) + "/api/0/test/issue/1/custom/bugzilla", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Issue not found", - "error_code": "ENOISSUE", - } + data, {"error": "Issue not found", "error_code": "ENOISSUE"} ) # Create normal issue - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue #1', - content='We should work on this', - user='pingou', + title="Test issue #1", + content="We should work on this", + user="pingou", private=False, ) self.session.commit() - self.assertEqual(msg.title, 'Test issue #1') + self.assertEqual(msg.title, "Test issue #1") # Project does not have this custom field output = self.app.post( - '/api/0/test/issue/1/custom/bugzilla', headers=headers) + "/api/0/test/issue/1/custom/bugzilla", headers=headers + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - "error": "Invalid custom field submitted", - "error_code": "EINVALIDISSUEFIELD", - } + "error": "Invalid custom field submitted", + "error_code": "EINVALIDISSUEFIELD", + }, ) # Check the behavior if the project disabled the issue tracker - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") settings = repo.settings - settings['issue_tracker'] = False + settings["issue_tracker"] = False repo.settings = settings self.session.add(repo) self.session.commit() output = self.app.post( - '/api/0/test/issue/1/custom/bugzilla', headers=headers) + "/api/0/test/issue/1/custom/bugzilla", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - "error": "Issue tracker disabled for this project", - "error_code": "ETRACKERDISABLED", - } + "error": "Issue tracker disabled for this project", + "error_code": "ETRACKERDISABLED", + }, ) - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") settings = repo.settings - settings['issue_tracker'] = True + settings["issue_tracker"] = True repo.settings = settings self.session.add(repo) self.session.commit() # Invalid API token - headers = {'Authorization': 'token foobar'} + headers = {"Authorization": "token foobar"} output = self.app.post( - '/api/0/test/issue/1/custom/bugzilla', headers=headers) + "/api/0/test/issue/1/custom/bugzilla", headers=headers + ) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(sorted(data.keys()), ['error', 'error_code', 'errors']) self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.value, data['error']) + sorted(data.keys()), ["error", "error_code", "errors"] + ) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.name, data['error_code']) - self.assertEqual(data['errors'], 'Invalid token') + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) + self.assertEqual(data["errors"], "Invalid token") - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Set some custom fields - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") msg = pagure.lib.query.set_custom_key_fields( - self.session, repo, - ['bugzilla', 'upstream', 'reviewstatus', 'duedate'], - ['link', 'boolean', 'list', 'date'], - ['', '', 'ack, nack , needs review', '2018-10-10'], - [None, None, None, None]) + self.session, + repo, + ["bugzilla", "upstream", "reviewstatus", "duedate"], + ["link", "boolean", "list", "date"], + ["", "", "ack, nack , needs review", "2018-10-10"], + [None, None, None, None], + ) self.session.commit() - self.assertEqual(msg, 'List of custom fields updated') + self.assertEqual(msg, "List of custom fields updated") # Check the project custom fields were correctly set for key in repo.issue_keys: @@ -3971,127 +3831,133 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): # Check that the reviewstatus list field still has its list if key.name == "reviewstatus": self.assertEqual( - sorted(key.data), ['ack', 'nack', 'needs review']) + sorted(key.data), ["ack", "nack", "needs review"] + ) # Check that the duedate date field still has its date if key.name == "duedate": - self.assertEqual(key.data, '2018-10-10') + self.assertEqual(key.data, "2018-10-10") # Check that not setting the value on a non-existing custom field # changes nothing output = self.app.post( - '/api/0/test/issue/1/custom/bugzilla', headers=headers) + "/api/0/test/issue/1/custom/bugzilla", headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - { - 'message': 'No changes' - } - ) + self.assertDictEqual(data, {"message": "No changes"}) - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) self.assertEqual(issue.other_fields, []) self.assertEqual(len(issue.other_fields), 0) # Invalid value output = self.app.post( - '/api/0/test/issue/1/custom/bugzilla', headers=headers, - data={'value': 'foobar'}) + "/api/0/test/issue/1/custom/bugzilla", + headers=headers, + data={"value": "foobar"}, + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - "error": "Invalid custom field submitted, the value is not " - "a link", - "error_code": "EINVALIDISSUEFIELD_LINK", - } + "error": "Invalid custom field submitted, the value is not " + "a link", + "error_code": "EINVALIDISSUEFIELD_LINK", + }, ) - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) self.assertEqual(issue.other_fields, []) self.assertEqual(len(issue.other_fields), 0) # All good output = self.app.post( - '/api/0/test/issue/1/custom/bugzilla', headers=headers, - data={'value': 'https://bugzilla.redhat.com/1234'}) + "/api/0/test/issue/1/custom/bugzilla", + headers=headers, + data={"value": "https://bugzilla.redhat.com/1234"}, + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - "message": "Custom field bugzilla adjusted to " + "message": "Custom field bugzilla adjusted to " "https://bugzilla.redhat.com/1234" - } + }, ) self.session.commit() - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) self.assertEqual(len(issue.other_fields), 1) - self.assertEqual(issue.other_fields[0].key.name, 'bugzilla') + self.assertEqual(issue.other_fields[0].key.name, "bugzilla") self.assertEqual( - issue.other_fields[0].value, - 'https://bugzilla.redhat.com/1234') + issue.other_fields[0].value, "https://bugzilla.redhat.com/1234" + ) # Reset the value output = self.app.post( - '/api/0/test/issue/1/custom/bugzilla', headers=headers, - data={'value': ''}) + "/api/0/test/issue/1/custom/bugzilla", + headers=headers, + data={"value": ""}, + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - "message": "Custom field bugzilla reset " - "(from https://bugzilla.redhat.com/1234)" - } + "message": "Custom field bugzilla reset " + "(from https://bugzilla.redhat.com/1234)" + }, ) self.session.commit() - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) self.assertEqual(len(issue.other_fields), 0) @patch( - 'pagure.lib.query.set_custom_key_value', - MagicMock(side_effect=pagure.exceptions.PagureException('error'))) + "pagure.lib.query.set_custom_key_value", + MagicMock(side_effect=pagure.exceptions.PagureException("error")), + ) def test_api_update_custom_field_raises_error(self): """ Test the api_update_custom_field method of the flask api. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'tickets')) + tests.create_projects_git(os.path.join(self.path, "tickets")) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Create normal issue - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue #1', - content='We should work on this', - user='pingou', + title="Test issue #1", + content="We should work on this", + user="pingou", private=False, ) self.session.commit() - self.assertEqual(msg.title, 'Test issue #1') + self.assertEqual(msg.title, "Test issue #1") # Set some custom fields - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") msg = pagure.lib.query.set_custom_key_fields( - self.session, repo, - ['bugzilla', 'upstream', 'reviewstatus'], - ['link', 'boolean', 'list'], - ['unused data for non-list type', '', 'ack, nack , needs review'], - [None, None, None]) + self.session, + repo, + ["bugzilla", "upstream", "reviewstatus"], + ["link", "boolean", "list"], + ["unused data for non-list type", "", "ack, nack , needs review"], + [None, None, None], + ) self.session.commit() - self.assertEqual(msg, 'List of custom fields updated') + self.assertEqual(msg, "List of custom fields updated") # Check the project custom fields were correctly set for key in repo.issue_keys: @@ -4102,47 +3968,47 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): # Check that the reviewstatus list field still has its list elif key.name == "reviewstatus": self.assertEqual( - sorted(key.data), ['ack', 'nack', 'needs review']) + sorted(key.data), ["ack", "nack", "needs review"] + ) # Should work but raises an exception output = self.app.post( - '/api/0/test/issue/1/custom/bugzilla', headers=headers, - data={'value': 'https://bugzilla.redhat.com/1234'}) + "/api/0/test/issue/1/custom/bugzilla", + headers=headers, + data={"value": "https://bugzilla.redhat.com/1234"}, + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {u'error': u'error', u'error_code': u'ENOCODE'} - ) + self.assertDictEqual(data, {"error": "error", "error_code": "ENOCODE"}) def test_api_view_issues_history_stats(self): """ Test the api_view_issues_history_stats method of the flask api. """ self.test_api_new_issue() # Create private issue - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue', - content='We should work on this', - user='pingou', + title="Test issue", + content="We should work on this", + user="pingou", private=True, - status="Closed" + status="Closed", ) self.session.commit() - self.assertEqual(msg.title, 'Test issue') + self.assertEqual(msg.title, "Test issue") - output = self.app.get('/api/0/test/issues/history/stats') + output = self.app.get("/api/0/test/issues/history/stats") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertEqual(len(data), 1) - self.assertEqual(len(data['stats']), 53) - last_key = sorted(data['stats'].keys())[-1] - self.assertEqual(data['stats'][last_key], 0) - for k in sorted(data['stats'].keys())[:-1]: - self.assertEqual(data['stats'][k], 0) + self.assertEqual(len(data["stats"]), 53) + last_key = sorted(data["stats"].keys())[-1] + self.assertEqual(data["stats"][last_key], 0) + for k in sorted(data["stats"].keys())[:-1]: + self.assertEqual(data["stats"][k], 0) def test_api_view_user_issues_pingou(self): """ Test the api_view_user_issues method of the flask api for pingou. @@ -4150,20 +4016,20 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): self.test_api_new_issue() # Create private issue - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue', - content='We should work on this', - user='pingou', + title="Test issue", + content="We should work on this", + user="pingou", private=True, - status="Closed" + status="Closed", ) self.session.commit() - self.assertEqual(msg.title, 'Test issue') + self.assertEqual(msg.title, "Test issue") - output = self.app.get('/api/0/user/pingou/issues') + output = self.app.get("/api/0/user/pingou/issues") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) args = { @@ -4182,16 +4048,16 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): "updated": None, } - self.assertEqual(data['args'], args) - self.assertEqual(data['issues_assigned'], []) - self.assertEqual(len(data['issues_created']), 1) - self.assertEqual(data['total_issues_assigned'], 0) - self.assertEqual(data['total_issues_created'], 1) - self.assertEqual(data['total_issues_assigned_pages'], 1) - self.assertEqual(data['total_issues_created_pages'], 1) + self.assertEqual(data["args"], args) + self.assertEqual(data["issues_assigned"], []) + self.assertEqual(len(data["issues_created"]), 1) + self.assertEqual(data["total_issues_assigned"], 0) + self.assertEqual(data["total_issues_created"], 1) + self.assertEqual(data["total_issues_assigned_pages"], 1) + self.assertEqual(data["total_issues_created_pages"], 1) # Restrict to a certain, fake milestone - output = self.app.get('/api/0/user/pingou/issues?milestones=v1.0') + output = self.app.get("/api/0/user/pingou/issues?milestones=v1.0") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) args = { @@ -4199,7 +4065,7 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): "author": True, "closed": None, "created": None, - "milestones": ['v1.0'], + "milestones": ["v1.0"], "no_stones": None, "order": None, "order_key": None, @@ -4210,16 +4076,16 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): "updated": None, } - self.assertEqual(data['args'], args) - self.assertEqual(data['issues_assigned'], []) - self.assertEqual(data['issues_created'], []) - self.assertEqual(data['total_issues_assigned'], 0) - self.assertEqual(data['total_issues_created'], 0) - self.assertEqual(data['total_issues_assigned_pages'], 1) - self.assertEqual(data['total_issues_created_pages'], 1) + self.assertEqual(data["args"], args) + self.assertEqual(data["issues_assigned"], []) + self.assertEqual(data["issues_created"], []) + self.assertEqual(data["total_issues_assigned"], 0) + self.assertEqual(data["total_issues_created"], 0) + self.assertEqual(data["total_issues_assigned_pages"], 1) + self.assertEqual(data["total_issues_created_pages"], 1) # Restrict to a certain status - output = self.app.get('/api/0/user/pingou/issues?status=closed') + output = self.app.get("/api/0/user/pingou/issues?status=closed") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) args = { @@ -4233,21 +4099,21 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): "order_key": None, "page": 1, "since": None, - "status": 'closed', + "status": "closed", "tags": [], "updated": None, } - self.assertEqual(data['args'], args) - self.assertEqual(data['issues_assigned'], []) - self.assertEqual(len(data['issues_created']), 1) - self.assertEqual(data['total_issues_assigned'], 0) - self.assertEqual(data['total_issues_created'], 1) - self.assertEqual(data['total_issues_assigned_pages'], 1) - self.assertEqual(data['total_issues_created_pages'], 1) + self.assertEqual(data["args"], args) + self.assertEqual(data["issues_assigned"], []) + self.assertEqual(len(data["issues_created"]), 1) + self.assertEqual(data["total_issues_assigned"], 0) + self.assertEqual(data["total_issues_created"], 1) + self.assertEqual(data["total_issues_assigned_pages"], 1) + self.assertEqual(data["total_issues_created_pages"], 1) # Restrict to a certain status - output = self.app.get('/api/0/user/pingou/issues?status=all') + output = self.app.get("/api/0/user/pingou/issues?status=all") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) args = { @@ -4261,18 +4127,18 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): "order_key": None, "page": 1, "since": None, - "status": 'all', + "status": "all", "tags": [], "updated": None, } - self.assertEqual(data['args'], args) - self.assertEqual(data['issues_assigned'], []) - self.assertEqual(len(data['issues_created']), 2) - self.assertEqual(data['total_issues_assigned'], 0) - self.assertEqual(data['total_issues_created'], 2) - self.assertEqual(data['total_issues_assigned_pages'], 1) - self.assertEqual(data['total_issues_created_pages'], 1) + self.assertEqual(data["args"], args) + self.assertEqual(data["issues_assigned"], []) + self.assertEqual(len(data["issues_created"]), 2) + self.assertEqual(data["total_issues_assigned"], 0) + self.assertEqual(data["total_issues_created"], 2) + self.assertEqual(data["total_issues_assigned_pages"], 1) + self.assertEqual(data["total_issues_created_pages"], 1) def test_api_view_user_issues_foo(self): """ Test the api_view_user_issues method of the flask api for foo. @@ -4280,20 +4146,20 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): self.test_api_new_issue() # Create private issue - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue', - content='We should work on this', - user='pingou', + title="Test issue", + content="We should work on this", + user="pingou", private=True, - status="Closed" + status="Closed", ) self.session.commit() - self.assertEqual(msg.title, 'Test issue') + self.assertEqual(msg.title, "Test issue") - output = self.app.get('/api/0/user/foo/issues') + output = self.app.get("/api/0/user/foo/issues") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) args = { @@ -4312,41 +4178,41 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): "updated": None, } - self.assertEqual(data['args'], args) - self.assertEqual(len(data['issues_assigned']), 0) - self.assertEqual(data['issues_created'], []) - self.assertEqual(data['total_issues_assigned'], 0) - self.assertEqual(data['total_issues_created'], 0) - self.assertEqual(data['total_issues_assigned_pages'], 1) - self.assertEqual(data['total_issues_created_pages'], 1) + self.assertEqual(data["args"], args) + self.assertEqual(len(data["issues_assigned"]), 0) + self.assertEqual(data["issues_created"], []) + self.assertEqual(data["total_issues_assigned"], 0) + self.assertEqual(data["total_issues_created"], 0) + self.assertEqual(data["total_issues_assigned_pages"], 1) + self.assertEqual(data["total_issues_created_pages"], 1) def test_api_view_user_issues_foo_invalid_page(self): """ Test the api_view_user_issues method of the flask api for foo. """ self.test_api_new_issue() - output = self.app.get('/api/0/user/foo/issues?page=0') + output = self.app.get("/api/0/user/foo/issues?page=0") self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertEqual( data, { - u'error': u'Invalid or incomplete input submitted', - u'error_code': u'EINVALIDREQ' - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + }, ) - output = self.app.get('/api/0/user/foo/issues?page=abc') + output = self.app.get("/api/0/user/foo/issues?page=abc") self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertEqual( data, { - u'error': u'Invalid or incomplete input submitted', - u'error_code': u'EINVALIDREQ' - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + }, ) def test_api_view_user_issues_foo_no_assignee(self): @@ -4354,7 +4220,7 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): """ self.test_api_new_issue() - output = self.app.get('/api/0/user/foo/issues?assignee=0') + output = self.app.get("/api/0/user/foo/issues?assignee=0") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) args = { @@ -4373,20 +4239,20 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): "updated": None, } - self.assertEqual(data['args'], args) - self.assertEqual(data['issues_assigned'], []) - self.assertEqual(data['issues_created'], []) - self.assertEqual(data['total_issues_assigned'], 0) - self.assertEqual(data['total_issues_created'], 0) - self.assertEqual(data['total_issues_assigned_pages'], 1) - self.assertEqual(data['total_issues_created_pages'], 1) + self.assertEqual(data["args"], args) + self.assertEqual(data["issues_assigned"], []) + self.assertEqual(data["issues_created"], []) + self.assertEqual(data["total_issues_assigned"], 0) + self.assertEqual(data["total_issues_created"], 0) + self.assertEqual(data["total_issues_assigned_pages"], 1) + self.assertEqual(data["total_issues_created_pages"], 1) def test_api_view_user_issues_pingou_no_author(self): """ Test the api_view_user_issues method of the flask api for pingou. """ self.test_api_new_issue() - output = self.app.get('/api/0/user/pingou/issues?author=0') + output = self.app.get("/api/0/user/pingou/issues?author=0") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) args = { @@ -4405,16 +4271,17 @@ class PagureFlaskApiIssuetests(tests.SimplePagureTest): "updated": None, } - self.assertEqual(data['args'], args) - self.assertEqual(data['issues_assigned'], []) - self.assertEqual(data['issues_created'], []) - self.assertEqual(data['total_issues_assigned'], 0) - self.assertEqual(data['total_issues_created'], 0) - self.assertEqual(data['total_issues_assigned_pages'], 1) - self.assertEqual(data['total_issues_created_pages'], 1) + self.assertEqual(data["args"], args) + self.assertEqual(data["issues_assigned"], []) + self.assertEqual(data["issues_created"], []) + self.assertEqual(data["total_issues_assigned"], 0) + self.assertEqual(data["total_issues_created"], 0) + self.assertEqual(data["total_issues_assigned_pages"], 1) + self.assertEqual(data["total_issues_created_pages"], 1) -if __name__ == '__main__': +if __name__ == "__main__": SUITE = unittest.TestLoader().loadTestsFromTestCase( - PagureFlaskApiIssuetests) + PagureFlaskApiIssuetests + ) unittest.TextTestRunner(verbosity=2).run(SUITE) diff --git a/tests/test_pagure_flask_api_issue_change_status.py b/tests/test_pagure_flask_api_issue_change_status.py index 80d544a..a15b337 100644 --- a/tests/test_pagure_flask_api_issue_change_status.py +++ b/tests/test_pagure_flask_api_issue_change_status.py @@ -21,8 +21,9 @@ import os import json from mock import patch, MagicMock -sys.path.insert(0, os.path.join(os.path.dirname( - os.path.abspath(__file__)), '..')) +sys.path.insert( + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") +) import pagure.lib.query import pagure.lib.model @@ -34,284 +35,267 @@ class PagureFlaskApiIssueChangeStatustests(tests.Modeltests): issue """ - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def setUp(self): """ Set up the environnment, ran before every tests. """ super(PagureFlaskApiIssueChangeStatustests, self).setUp() - pagure.config.config['TICKETS_FOLDER'] = None + pagure.config.config["TICKETS_FOLDER"] = None tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'tickets')) + tests.create_projects_git(os.path.join(self.path, "tickets")) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Create normal issue - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue #1', - content='We should work on this', - user='pingou', + title="Test issue #1", + content="We should work on this", + user="pingou", private=False, ) self.session.commit() - self.assertEqual(msg.title, 'Test issue #1') + self.assertEqual(msg.title, "Test issue #1") # Create private issue msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue #2', - content='We should work on this', - user='foo', + title="Test issue #2", + content="We should work on this", + user="foo", private=True, ) self.session.commit() - self.assertEqual(msg.title, 'Test issue #2') + self.assertEqual(msg.title, "Test issue #2") # Create project-less token for user foo item = pagure.lib.model.Token( - id='project-less-foo', + id="project-less-foo", user_id=2, project_id=None, expiration=datetime.datetime.utcnow() - + datetime.timedelta(days=30) + + datetime.timedelta(days=30), ) self.session.add(item) self.session.commit() - tests.create_tokens_acl(self.session, token_id='project-less-foo') + tests.create_tokens_acl(self.session, token_id="project-less-foo") # Create project-less token for user pingou item = pagure.lib.model.Token( - id='project-less-pingou', + id="project-less-pingou", user_id=1, project_id=None, expiration=datetime.datetime.utcnow() - + datetime.timedelta(days=30) + + datetime.timedelta(days=30), ) self.session.add(item) self.session.commit() - tests.create_tokens_acl(self.session, token_id='project-less-pingou') + tests.create_tokens_acl(self.session, token_id="project-less-pingou") def test_api_change_status_issue_invalid_project(self): """ Test the api_change_status_issue method of the flask api. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Invalid project - output = self.app.post( - '/api/0/foobar/issue/1/status', headers=headers) + output = self.app.post("/api/0/foobar/issue/1/status", headers=headers) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) def test_api_change_status_issue_token_not_for_project(self): """ Test the api_change_status_issue method of the flask api. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Valid token, wrong project - output = self.app.post('/api/0/test2/issue/1/status', headers=headers) + output = self.app.post("/api/0/test2/issue/1/status", headers=headers) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.name, - data['error_code']) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data['error']) + self.assertEqual( + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) def test_api_change_status_issue_invalid_issue(self): """ Test the api_change_status_issue method of the flask api. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # No issue - output = self.app.post('/api/0/test/issue/42/status', headers=headers) + output = self.app.post("/api/0/test/issue/42/status", headers=headers) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Issue not found", - "error_code": "ENOISSUE", - } + data, {"error": "Issue not found", "error_code": "ENOISSUE"} ) def test_api_change_status_issue_incomplete(self): """ Test the api_change_status_issue method of the flask api. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Check status before - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) - self.assertEqual(issue.status, 'Open') + self.assertEqual(issue.status, "Open") - data = { - 'title': 'test issue', - } + data = {"title": "test issue"} # Incomplete request output = self.app.post( - '/api/0/test/issue/1/status', data=data, headers=headers) + "/api/0/test/issue/1/status", data=data, headers=headers + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - "error": "Invalid or incomplete input submitted", - "error_code": "EINVALIDREQ", - "errors": {"status": ["Not a valid choice"]} - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": {"status": ["Not a valid choice"]}, + }, ) # No change - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) - self.assertEqual(issue.status, 'Open') + self.assertEqual(issue.status, "Open") def test_api_change_status_issue_no_change(self): """ Test the api_change_status_issue method of the flask api. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} - data = { - 'status': 'Open', - } + data = {"status": "Open"} # Valid request but no change output = self.app.post( - '/api/0/test/issue/1/status', data=data, headers=headers) + "/api/0/test/issue/1/status", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'No changes'} - ) + self.assertDictEqual(data, {"message": "No changes"}) # No change - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) - self.assertEqual(issue.status, 'Open') + self.assertEqual(issue.status, "Open") - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) @patch( - 'pagure.lib.query.edit_issue', - MagicMock(side_effect=pagure.exceptions.PagureException('error'))) + "pagure.lib.query.edit_issue", + MagicMock(side_effect=pagure.exceptions.PagureException("error")), + ) def test_api_change_status_issue_raise_error(self): """ Test the api_change_status_issue method of the flask api. """ - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") close_status = repo.close_status - close_status = ['Fixed', 'Upstream', 'Invalid'] + close_status = ["Fixed", "Upstream", "Invalid"] repo.close_status = close_status self.session.add(repo) self.session.commit() + headers = {"Authorization": "token aaabbbcccddd"} - headers = {'Authorization': 'token aaabbbcccddd'} - - data = { - 'status': 'Closed', - 'close_status': 'Fixed' - } + data = {"status": "Closed", "close_status": "Fixed"} # Valid request output = self.app.post( - '/api/0/test/issue/1/status', data=data, headers=headers) + "/api/0/test/issue/1/status", data=data, headers=headers + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {u'error': u'error', u'error_code': u'ENOCODE'} - ) + self.assertDictEqual(data, {"error": "error", "error_code": "ENOCODE"}) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_api_change_status_issue(self): """ Test the api_change_status_issue method of the flask api. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} - data = { - 'status': 'Fixed', - } + data = {"status": "Fixed"} # Valid request output = self.app.post( - '/api/0/test/issue/1/status', data=data, headers=headers) + "/api/0/test/issue/1/status", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, - {'message':[ - 'Issue status updated to: Closed (was: Open)', - 'Issue close_status updated to: Fixed' - ]} + { + "message": [ + "Issue status updated to: Closed (was: Open)", + "Issue close_status updated to: Fixed", + ] + }, ) - headers = {'Authorization': 'token pingou_foo'} + headers = {"Authorization": "token pingou_foo"} # Un-authorized issue output = self.app.post( - '/api/0/foo/issue/1/status', data=data, headers=headers) + "/api/0/foo/issue/1/status", data=data, headers=headers + ) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.name, - data['error_code']) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data['error']) + self.assertEqual( + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_api_change_status_issue_closed_status(self): """ Test the api_change_status_issue method of the flask api. """ - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") close_status = repo.close_status - close_status = ['Fixed', 'Upstream', 'Invalid'] + close_status = ["Fixed", "Upstream", "Invalid"] repo.close_status = close_status self.session.add(repo) self.session.commit() + headers = {"Authorization": "token aaabbbcccddd"} - headers = {'Authorization': 'token aaabbbcccddd'} - - data = { - 'status': 'Closed', - 'close_status': 'Fixed' - } + data = {"status": "Closed", "close_status": "Fixed"} # Valid request output = self.app.post( - '/api/0/test/issue/1/status', data=data, headers=headers) + "/api/0/test/issue/1/status", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, - {'message':[ - 'Issue status updated to: Closed (was: Open)', - 'Issue close_status updated to: Fixed' - ]} + { + "message": [ + "Issue status updated to: Closed (was: Open)", + "Issue close_status updated to: Fixed", + ] + }, ) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_api_change_status_issue_no_ticket_project_less(self): """ Test the api_change_status_issue method of the flask api. """ - headers = {'Authorization': 'token project-less-foo'} + headers = {"Authorization": "token project-less-foo"} - data = { - 'status': 'Fixed', - } + data = {"status": "Fixed"} # Valid request output = self.app.post( - '/api/0/test/issue/1/status', data=data, headers=headers) + "/api/0/test/issue/1/status", data=data, headers=headers + ) self.assertEqual(output.status_code, 403) data = json.loads(output.get_data(as_text=True)) @@ -319,23 +303,22 @@ class PagureFlaskApiIssueChangeStatustests(tests.Modeltests): data, { "error": "You are not allowed to view this issue", - "error_code": "EISSUENOTALLOWED" - } + "error_code": "EISSUENOTALLOWED", + }, ) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_api_change_status_issue_project_less(self): """ Test the api_change_status_issue method of the flask api. """ - headers = {'Authorization': 'token project-less-pingou'} + headers = {"Authorization": "token project-less-pingou"} - data = { - 'status': 'Fixed', - } + data = {"status": "Fixed"} # Valid request output = self.app.post( - '/api/0/test/issue/1/status', data=data, headers=headers) + "/api/0/test/issue/1/status", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) @@ -344,11 +327,11 @@ class PagureFlaskApiIssueChangeStatustests(tests.Modeltests): { "message": [ "Issue status updated to: Closed (was: Open)", - "Issue close_status updated to: Fixed" + "Issue close_status updated to: Fixed", ] - } + }, ) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/test_pagure_flask_api_issue_comment.py b/tests/test_pagure_flask_api_issue_comment.py index 4571d9f..6c8f007 100644 --- a/tests/test_pagure_flask_api_issue_comment.py +++ b/tests/test_pagure_flask_api_issue_comment.py @@ -19,8 +19,9 @@ import os import json from mock import patch, MagicMock -sys.path.insert(0, os.path.join(os.path.dirname( - os.path.abspath(__file__)), '..')) +sys.path.insert( + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") +) import pagure.lib.query # noqa: E402 import tests # noqa: E402 @@ -31,117 +32,109 @@ class PagureFlaskApiIssueCommenttests(tests.Modeltests): issue """ - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def setUp(self): """ Set up the environnment, ran before every tests. """ super(PagureFlaskApiIssueCommenttests, self).setUp() - pagure.config.config['TICKETS_FOLDER'] = None + pagure.config.config["TICKETS_FOLDER"] = None tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'tickets')) + tests.create_projects_git(os.path.join(self.path, "tickets")) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Create normal issue - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue #1', - content='We should work on this', - user='pingou', + title="Test issue #1", + content="We should work on this", + user="pingou", private=False, ) self.session.commit() - self.assertEqual(msg.title, 'Test issue #1') + self.assertEqual(msg.title, "Test issue #1") # Create private issue msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue #2', - content='We should work on this', - user='foo', + title="Test issue #2", + content="We should work on this", + user="foo", private=True, ) self.session.commit() - self.assertEqual(msg.title, 'Test issue #2') + self.assertEqual(msg.title, "Test issue #2") # Create project-less token for user foo item = pagure.lib.model.Token( - id='project-less-foo', + id="project-less-foo", user_id=2, project_id=None, expiration=datetime.datetime.utcnow() - + datetime.timedelta(days=30) + + datetime.timedelta(days=30), ) self.session.add(item) self.session.commit() - tests.create_tokens_acl(self.session, token_id='project-less-foo') + tests.create_tokens_acl(self.session, token_id="project-less-foo") def test_api_comment_issue_invalid_project(self): """ Test the api_comment_issue method of the flask api. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Invalid project - output = self.app.post('/api/0/foo/issue/1/comment', headers=headers) + output = self.app.post("/api/0/foo/issue/1/comment", headers=headers) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) def test_api_comment_issue_invalid_project_token(self): """ Test the api_comment_issue method of the flask api. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Valid token, wrong project - output = self.app.post('/api/0/test2/issue/1/comment', headers=headers) + output = self.app.post("/api/0/test2/issue/1/comment", headers=headers) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.name, - data['error_code']) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data['error']) + self.assertEqual( + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) def test_api_comment_issue_invalid_issue(self): """ Test the api_comment_issue method of the flask api. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Invalid issue - output = self.app.post('/api/0/test/issue/10/comment', headers=headers) + output = self.app.post("/api/0/test/issue/10/comment", headers=headers) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Issue not found", - "error_code": "ENOISSUE", - } + data, {"error": "Issue not found", "error_code": "ENOISSUE"} ) def test_api_comment_issue_incomplete_request(self): """ Test the api_comment_issue method of the flask api. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Check comments before - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) self.assertEqual(len(issue.comments), 0) - data = { - 'title': 'test issue', - } + data = {"title": "test issue"} # Incomplete request output = self.app.post( - '/api/0/test/issue/1/comment', data=data, headers=headers) + "/api/0/test/issue/1/comment", data=data, headers=headers + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( @@ -149,39 +142,40 @@ class PagureFlaskApiIssueCommenttests(tests.Modeltests): { "error": "Invalid or incomplete input submitted", "error_code": "EINVALIDREQ", - "errors": {"comment": ["This field is required."]} - } + "errors": {"comment": ["This field is required."]}, + }, ) # No change - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) - self.assertEqual(issue.status, 'Open') + self.assertEqual(issue.status, "Open") def test_api_comment_issue(self): """ Test the api_comment_issue method of the flask api. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} - data = { - 'comment': 'This is a very interesting question', - } + data = {"comment": "This is a very interesting question"} # Valid request output = self.app.post( - '/api/0/test/issue/1/comment', data=data, headers=headers) + "/api/0/test/issue/1/comment", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( data, - {'message': 'Comment added', - 'avatar_url': 'https://seccdn.libravatar.org/avatar/...', - 'user': 'pingou'} + { + "message": "Comment added", + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + "user": "pingou", + }, ) # One comment added - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) self.assertEqual(len(issue.comments), 1) @@ -189,128 +183,117 @@ class PagureFlaskApiIssueCommenttests(tests.Modeltests): """ Test the api_comment_issue method of the flask api. """ # Check before - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=2) self.assertEqual(len(issue.comments), 0) - data = { - 'comment': 'This is a very interesting question', - } - headers = {'Authorization': 'token pingou_foo'} + data = {"comment": "This is a very interesting question"} + headers = {"Authorization": "token pingou_foo"} # Valid request but un-authorized output = self.app.post( - '/api/0/test/issue/2/comment', data=data, headers=headers) + "/api/0/test/issue/2/comment", data=data, headers=headers + ) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.name, - data['error_code']) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data['error']) + self.assertEqual( + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) # No comment added - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=2) self.assertEqual(len(issue.comments), 0) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_api_comment_issue_private(self): """ Test the api_comment_issue method of the flask api. """ # Create token for user foo item = pagure.lib.model.Token( - id='foo_token2', + id="foo_token2", user_id=2, project_id=1, - expiration=datetime.datetime.utcnow() + datetime.timedelta(days=30) + expiration=datetime.datetime.utcnow() + + datetime.timedelta(days=30), ) self.session.add(item) self.session.commit() - tests.create_tokens_acl(self.session, token_id='foo_token2') + tests.create_tokens_acl(self.session, token_id="foo_token2") - data = { - 'comment': 'This is a very interesting question', - } - headers = {'Authorization': 'token foo_token2'} + data = {"comment": "This is a very interesting question"} + headers = {"Authorization": "token foo_token2"} # Valid request and authorized output = self.app.post( - '/api/0/test/issue/2/comment', data=data, headers=headers) + "/api/0/test/issue/2/comment", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( data, - {'message': 'Comment added', - 'avatar_url': 'https://seccdn.libravatar.org/avatar/...', - 'user': 'foo'} + { + "message": "Comment added", + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + "user": "foo", + }, ) def test_api_comment_issue_invalid_project_project_less(self): """ Test the api_comment_issue method of the flask api. """ - headers = {'Authorization': 'token project-less-foo'} + headers = {"Authorization": "token project-less-foo"} # Invalid project - output = self.app.post('/api/0/foo/issue/1/comment', headers=headers) + output = self.app.post("/api/0/foo/issue/1/comment", headers=headers) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) def test_api_comment_issue_invalid_project_token_project_less(self): """ Test the api_comment_issue method of the flask api. """ - headers = {'Authorization': 'token project-less-foo'} + headers = {"Authorization": "token project-less-foo"} # Valid token, no such issue, project-less token so different failure - output = self.app.post('/api/0/test2/issue/1/comment', headers=headers) + output = self.app.post("/api/0/test2/issue/1/comment", headers=headers) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Issue not found", - "error_code": "ENOISSUE", - } + data, {"error": "Issue not found", "error_code": "ENOISSUE"} ) def test_api_comment_issue_invalid_issue_project_less(self): """ Test the api_comment_issue method of the flask api. """ - headers = {'Authorization': 'token project-less-foo'} + headers = {"Authorization": "token project-less-foo"} # Invalid issue - output = self.app.post('/api/0/test/issue/10/comment', headers=headers) + output = self.app.post("/api/0/test/issue/10/comment", headers=headers) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Issue not found", - "error_code": "ENOISSUE", - } + data, {"error": "Issue not found", "error_code": "ENOISSUE"} ) def test_api_comment_issue_incomplete_request_project_less(self): """ Test the api_comment_issue method of the flask api. """ - headers = {'Authorization': 'token project-less-foo'} + headers = {"Authorization": "token project-less-foo"} # Check comments before - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) self.assertEqual(len(issue.comments), 0) - data = { - 'title': 'test issue', - } + data = {"title": "test issue"} # Incomplete request output = self.app.post( - '/api/0/test/issue/1/comment', data=data, headers=headers) + "/api/0/test/issue/1/comment", data=data, headers=headers + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( @@ -318,40 +301,41 @@ class PagureFlaskApiIssueCommenttests(tests.Modeltests): { "error": "Invalid or incomplete input submitted", "error_code": "EINVALIDREQ", - "errors": {"comment": ["This field is required."]} - } + "errors": {"comment": ["This field is required."]}, + }, ) # No change - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) - self.assertEqual(issue.status, 'Open') + self.assertEqual(issue.status, "Open") - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_api_comment_issue_project_less(self): """ Test the api_comment_issue method of the flask api. """ - headers = {'Authorization': 'token project-less-foo'} + headers = {"Authorization": "token project-less-foo"} - data = { - 'comment': 'This is a very interesting question', - } + data = {"comment": "This is a very interesting question"} # Valid request output = self.app.post( - '/api/0/test/issue/1/comment', data=data, headers=headers) + "/api/0/test/issue/1/comment", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( data, - {'message': 'Comment added', - 'avatar_url': 'https://seccdn.libravatar.org/avatar/...', - 'user': 'foo'} + { + "message": "Comment added", + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + "user": "foo", + }, ) # One comment added - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) self.assertEqual(len(issue.comments), 1) @@ -359,62 +343,64 @@ class PagureFlaskApiIssueCommenttests(tests.Modeltests): """ Test the api_comment_issue method of the flask api. """ # Check before - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=2) self.assertEqual(len(issue.comments), 0) - data = { - 'comment': 'This is a very interesting question', - } - headers = {'Authorization': 'token pingou_foo'} + data = {"comment": "This is a very interesting question"} + headers = {"Authorization": "token pingou_foo"} # Valid request but un-authorized output = self.app.post( - '/api/0/test/issue/2/comment', data=data, headers=headers) + "/api/0/test/issue/2/comment", data=data, headers=headers + ) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.name, - data['error_code']) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data['error']) + self.assertEqual( + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) # No comment added - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=2) self.assertEqual(len(issue.comments), 0) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_api_comment_issue_private_project_less(self): """ Test the api_comment_issue method of the flask api. """ # Create token for user foo item = pagure.lib.model.Token( - id='foo_token2', + id="foo_token2", user_id=2, project_id=None, - expiration=datetime.datetime.utcnow() + datetime.timedelta(days=30) + expiration=datetime.datetime.utcnow() + + datetime.timedelta(days=30), ) self.session.add(item) self.session.commit() - tests.create_tokens_acl(self.session, token_id='foo_token2') + tests.create_tokens_acl(self.session, token_id="foo_token2") - data = { - 'comment': 'This is a very interesting question', - } - headers = {'Authorization': 'token foo_token2'} + data = {"comment": "This is a very interesting question"} + headers = {"Authorization": "token foo_token2"} # Valid request and authorized output = self.app.post( - '/api/0/test/issue/2/comment', data=data, headers=headers) + "/api/0/test/issue/2/comment", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( data, - {'message': 'Comment added', - 'avatar_url': 'https://seccdn.libravatar.org/avatar/...', - 'user': 'foo'} + { + "message": "Comment added", + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + "user": "foo", + }, ) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/test_pagure_flask_api_issue_create.py b/tests/test_pagure_flask_api_issue_create.py index a65ace9..da633b2 100644 --- a/tests/test_pagure_flask_api_issue_create.py +++ b/tests/test_pagure_flask_api_issue_create.py @@ -18,8 +18,9 @@ import json from mock import patch, MagicMock -sys.path.insert(0, os.path.join(os.path.dirname( - os.path.abspath(__file__)), '..')) +sys.path.insert( + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") +) import pagure.lib.query # noqa: E402 import tests # noqa: E402 @@ -29,42 +30,41 @@ class PagureFlaskApiIssueCreatetests(tests.Modeltests): """ Tests for the flask API of pagure for creating an issue """ - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def setUp(self): """ Set up the environnment, ran before every tests. """ super(PagureFlaskApiIssueCreatetests, self).setUp() - pagure.config.config['TICKETS_FOLDER'] = None + pagure.config.config["TICKETS_FOLDER"] = None tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'tickets')) + tests.create_projects_git(os.path.join(self.path, "tickets")) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Create project-less token for user foo item = pagure.lib.model.Token( - id='project-less-foo', + id="project-less-foo", user_id=2, project_id=None, expiration=datetime.datetime.utcnow() - + datetime.timedelta(days=30) + + datetime.timedelta(days=30), ) self.session.add(item) self.session.commit() - tests.create_tokens_acl(self.session, token_id='project-less-foo') + tests.create_tokens_acl(self.session, token_id="project-less-foo") # Create project-specific token for user foo item = pagure.lib.model.Token( - id='project-specific-foo', + id="project-specific-foo", user_id=2, project_id=1, expiration=datetime.datetime.utcnow() - + datetime.timedelta(days=30) + + datetime.timedelta(days=30), ) self.session.add(item) self.session.commit() - tests.create_tokens_acl( - self.session, token_id='project-specific-foo') + tests.create_tokens_acl(self.session, token_id="project-specific-foo") def test_create_issue_own_project_no_data(self): """ Test creating a new ticket on a project for which you're the @@ -72,22 +72,22 @@ class PagureFlaskApiIssueCreatetests(tests.Modeltests): """ # pingou's token with all the ACLs - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Create an issue on /test/ where pingou is the main admin - output = self.app.post('/api/0/test/new_issue', headers=headers) + output = self.app.post("/api/0/test/new_issue", headers=headers) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertEqual( - pagure.api.APIERROR.EINVALIDREQ.name, data['error_code']) - self.assertEqual( - pagure.api.APIERROR.EINVALIDREQ.value, data['error']) + pagure.api.APIERROR.EINVALIDREQ.name, data["error_code"] + ) + self.assertEqual(pagure.api.APIERROR.EINVALIDREQ.value, data["error"]) self.assertEqual( - data['errors'], + data["errors"], { - 'issue_content': ['This field is required.'], - 'title': ['This field is required.'] - } + "issue_content": ["This field is required."], + "title": ["This field is required."], + }, ) def test_create_issue_own_project_incomplete_data(self): @@ -96,29 +96,23 @@ class PagureFlaskApiIssueCreatetests(tests.Modeltests): """ # pingou's token with all the ACLs - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # complete data set - data = { - 'title': 'test issue', - } + data = {"title": "test issue"} # Create an issue on /test/ where pingou is the main admin output = self.app.post( - '/api/0/test/new_issue', - headers=headers, - data=data) + "/api/0/test/new_issue", headers=headers, data=data + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertEqual( - pagure.api.APIERROR.EINVALIDREQ.name, data['error_code']) - self.assertEqual( - pagure.api.APIERROR.EINVALIDREQ.value, data['error']) + pagure.api.APIERROR.EINVALIDREQ.name, data["error_code"] + ) + self.assertEqual(pagure.api.APIERROR.EINVALIDREQ.value, data["error"]) self.assertEqual( - data['errors'], - { - 'issue_content': ['This field is required.'] - } + data["errors"], {"issue_content": ["This field is required."]} ) def test_create_issue_own_project(self): @@ -127,191 +121,178 @@ class PagureFlaskApiIssueCreatetests(tests.Modeltests): """ # pingou's token with all the ACLs - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # complete data set data = { - 'title': 'test issue', - 'issue_content': 'This issue needs attention', + "title": "test issue", + "issue_content": "This issue needs attention", } # Create an issue on /test/ where pingou is the main admin output = self.app.post( - '/api/0/test/new_issue', - headers=headers, - data=data) + "/api/0/test/new_issue", headers=headers, data=data + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['issue']['date_created'] = '1431414800' - data['issue']['last_updated'] = '1431414800' + data["issue"]["date_created"] = "1431414800" + data["issue"]["last_updated"] = "1431414800" self.assertEqual( data, { - "issue": { - "assignee": None, - "blocks": [], - "close_status": None, - "closed_at": None, - "closed_by": None, - "comments": [], - "content": "This issue needs attention", - "custom_fields": [], - "date_created": "1431414800", - "depends": [], - "id": 1, - "last_updated": "1431414800", - "milestone": None, - "priority": None, - "private": False, - "status": "Open", - "tags": [], - "title": "test issue", - "user": { - "fullname": "PY C", - "name": "pingou" - } - }, - "message": "Issue created" - } + "issue": { + "assignee": None, + "blocks": [], + "close_status": None, + "closed_at": None, + "closed_by": None, + "comments": [], + "content": "This issue needs attention", + "custom_fields": [], + "date_created": "1431414800", + "depends": [], + "id": 1, + "last_updated": "1431414800", + "milestone": None, + "priority": None, + "private": False, + "status": "Open", + "tags": [], + "title": "test issue", + "user": {"fullname": "PY C", "name": "pingou"}, + }, + "message": "Issue created", + }, ) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_create_issue_someone_else_project_project_less_token(self): """ Test creating a new ticket on a project with which you have nothing to do. """ # pingou's token with all the ACLs - headers = {'Authorization': 'token project-less-foo'} + headers = {"Authorization": "token project-less-foo"} # complete data set data = { - 'title': 'test issue', - 'issue_content': 'This issue needs attention', + "title": "test issue", + "issue_content": "This issue needs attention", } # Create an issue on /test/ where pingou is the main admin output = self.app.post( - '/api/0/test/new_issue', - headers=headers, - data=data) + "/api/0/test/new_issue", headers=headers, data=data + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['issue']['date_created'] = '1431414800' - data['issue']['last_updated'] = '1431414800' + data["issue"]["date_created"] = "1431414800" + data["issue"]["last_updated"] = "1431414800" self.assertEqual( data, { - "issue": { - "assignee": None, - "blocks": [], - "close_status": None, - "closed_at": None, - "closed_by": None, - "comments": [], - "content": "This issue needs attention", - "custom_fields": [], - "date_created": "1431414800", - "depends": [], - "id": 1, - "last_updated": "1431414800", - "milestone": None, - "priority": None, - "private": False, - "status": "Open", - "tags": [], - "title": "test issue", - "user": { - "fullname": "foo bar", - "name": "foo" - } - }, - "message": "Issue created" - } + "issue": { + "assignee": None, + "blocks": [], + "close_status": None, + "closed_at": None, + "closed_by": None, + "comments": [], + "content": "This issue needs attention", + "custom_fields": [], + "date_created": "1431414800", + "depends": [], + "id": 1, + "last_updated": "1431414800", + "milestone": None, + "priority": None, + "private": False, + "status": "Open", + "tags": [], + "title": "test issue", + "user": {"fullname": "foo bar", "name": "foo"}, + }, + "message": "Issue created", + }, ) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_create_issue_project_specific_token(self): """ Test creating a new ticket on a project with a regular project-specific token. """ # pingou's token with all the ACLs - headers = {'Authorization': 'token project-specific-foo'} + headers = {"Authorization": "token project-specific-foo"} # complete data set data = { - 'title': 'test issue', - 'issue_content': 'This issue needs attention', + "title": "test issue", + "issue_content": "This issue needs attention", } # Create an issue on /test/ where pingou is the main admin output = self.app.post( - '/api/0/test/new_issue', - headers=headers, - data=data) + "/api/0/test/new_issue", headers=headers, data=data + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['issue']['date_created'] = '1431414800' - data['issue']['last_updated'] = '1431414800' + data["issue"]["date_created"] = "1431414800" + data["issue"]["last_updated"] = "1431414800" self.assertEqual( data, { - "issue": { - "assignee": None, - "blocks": [], - "close_status": None, - "closed_at": None, - "closed_by": None, - "comments": [], - "content": "This issue needs attention", - "custom_fields": [], - "date_created": "1431414800", - "depends": [], - "id": 1, - "last_updated": "1431414800", - "milestone": None, - "priority": None, - "private": False, - "status": "Open", - "tags": [], - "title": "test issue", - "user": { - "fullname": "foo bar", - "name": "foo" - } - }, - "message": "Issue created" - } + "issue": { + "assignee": None, + "blocks": [], + "close_status": None, + "closed_at": None, + "closed_by": None, + "comments": [], + "content": "This issue needs attention", + "custom_fields": [], + "date_created": "1431414800", + "depends": [], + "id": 1, + "last_updated": "1431414800", + "milestone": None, + "priority": None, + "private": False, + "status": "Open", + "tags": [], + "title": "test issue", + "user": {"fullname": "foo bar", "name": "foo"}, + }, + "message": "Issue created", + }, ) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_create_issue_invalid_project_specific_token(self): """ Test creating a new ticket on a project with a regular project-specific token but for another project. """ # pingou's token with all the ACLs - headers = {'Authorization': 'token project-specific-foo'} + headers = {"Authorization": "token project-specific-foo"} # complete data set data = { - 'title': 'test issue', - 'issue_content': 'This issue needs attention', + "title": "test issue", + "issue_content": "This issue needs attention", } # Create an issue on /test/ where pingou is the main admin output = self.app.post( - '/api/0/test2/new_issue', - headers=headers, - data=data) + "/api/0/test2/new_issue", headers=headers, data=data + ) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.name, data['error_code']) - self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.value, data['error']) + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/test_pagure_flask_api_issue_custom_fields.py b/tests/test_pagure_flask_api_issue_custom_fields.py index dc2611b..a86892b 100644 --- a/tests/test_pagure_flask_api_issue_custom_fields.py +++ b/tests/test_pagure_flask_api_issue_custom_fields.py @@ -15,8 +15,9 @@ import json from mock import patch, MagicMock -sys.path.insert(0, os.path.join(os.path.dirname( - os.path.abspath(__file__)), '..')) +sys.path.insert( + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") +) import pagure.lib.query # noqa: E402 import tests # noqa: E402 @@ -30,21 +31,21 @@ class PagureFlaskApiCustomFieldIssuetests(tests.Modeltests): self.maxDiff = None super(PagureFlaskApiCustomFieldIssuetests, self).setUp() - pagure.config.config['TICKETS_FOLDER'] = None + pagure.config.config["TICKETS_FOLDER"] = None tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'tickets')) + tests.create_projects_git(os.path.join(self.path, "tickets")) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Create normal issue - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue #1', - content='We should work on this', - user='pingou', + title="Test issue #1", + content="We should work on this", + user="pingou", private=False, ) self.session.commit() @@ -54,12 +55,13 @@ class PagureFlaskApiCustomFieldIssuetests(tests.Modeltests): This test that a badly form request returns the correct error. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Request is not formated correctly (EMPTY) payload = {} output = self.app.post( - '/api/0/test/issue/1/custom', headers=headers, data=payload) + "/api/0/test/issue/1/custom", headers=headers, data=payload + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( @@ -67,7 +69,7 @@ class PagureFlaskApiCustomFieldIssuetests(tests.Modeltests): { "error": "Invalid or incomplete input submitted", "error_code": "EINVALIDREQ", - } + }, ) def test_api_update_custom_field_wrong_field(self): @@ -75,11 +77,12 @@ class PagureFlaskApiCustomFieldIssuetests(tests.Modeltests): This test that an invalid field retruns the correct error. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Project does not have this custom field - payload = {'foo': 'bar'} + payload = {"foo": "bar"} output = self.app.post( - '/api/0/test/issue/1/custom', headers=headers, data=payload) + "/api/0/test/issue/1/custom", headers=headers, data=payload + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( @@ -87,59 +90,77 @@ class PagureFlaskApiCustomFieldIssuetests(tests.Modeltests): { "error": "Invalid custom field submitted", "error_code": "EINVALIDISSUEFIELD", - } + }, ) @patch( - 'pagure.lib.query.set_custom_key_value', - MagicMock(side_effect=pagure.exceptions.PagureException('error'))) + "pagure.lib.query.set_custom_key_value", + MagicMock(side_effect=pagure.exceptions.PagureException("error")), + ) def test_api_update_custom_field_raise_error(self): """ Test the api_update_custom_field method of the flask api. This test the successful requests scenarii. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Set some custom fields - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") msg = pagure.lib.query.set_custom_key_fields( - self.session, repo, - ['bugzilla', 'upstream', 'reviewstatus'], - ['link', 'boolean', 'list'], - ['unused data for non-list type', '', 'ack', 'nack', 'needs review'], - [None, None, None]) + self.session, + repo, + ["bugzilla", "upstream", "reviewstatus"], + ["link", "boolean", "list"], + [ + "unused data for non-list type", + "", + "ack", + "nack", + "needs review", + ], + [None, None, None], + ) self.session.commit() - self.assertEqual(msg, 'List of custom fields updated') + self.assertEqual(msg, "List of custom fields updated") - payload = {'bugzilla': '', 'upstream': True} + payload = {"bugzilla": "", "upstream": True} output = self.app.post( - '/api/0/test/issue/1/custom', headers=headers, data=payload) + "/api/0/test/issue/1/custom", headers=headers, data=payload + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, {u'error': u'error', u'error_code': u'ENOCODE'}) + self.assertDictEqual(data, {"error": "error", "error_code": "ENOCODE"}) def test_api_update_custom_field(self): """ Test the api_update_custom_field method of the flask api. This test the successful requests scenarii. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Set some custom fields - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") msg = pagure.lib.query.set_custom_key_fields( - self.session, repo, - ['bugzilla', 'upstream', 'reviewstatus'], - ['link', 'boolean', 'list'], - ['unused data for non-list type', '', 'ack', 'nack', 'needs review'], - [None, None, None]) + self.session, + repo, + ["bugzilla", "upstream", "reviewstatus"], + ["link", "boolean", "list"], + [ + "unused data for non-list type", + "", + "ack", + "nack", + "needs review", + ], + [None, None, None], + ) self.session.commit() - self.assertEqual(msg, 'List of custom fields updated') + self.assertEqual(msg, "List of custom fields updated") - payload = {'bugzilla': '', 'upstream': True} + payload = {"bugzilla": "", "upstream": True} output = self.app.post( - '/api/0/test/issue/1/custom', headers=headers, data=payload) + "/api/0/test/issue/1/custom", headers=headers, data=payload + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) data["messages"].sort(key=lambda d: list(d.keys())[0]) @@ -150,20 +171,22 @@ class PagureFlaskApiCustomFieldIssuetests(tests.Modeltests): {"bugzilla": "No changes"}, {"upstream": "Custom field upstream adjusted to True"}, ] - } + }, ) self.session.commit() - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) self.assertEqual(len(issue.other_fields), 1) - payload = {'bugzilla': 'https://bugzilla.redhat.com/1234', - 'upstream': False, - 'reviewstatus': 'ack'} + payload = { + "bugzilla": "https://bugzilla.redhat.com/1234", + "upstream": False, + "reviewstatus": "ack", + } output = self.app.post( - '/api/0/test/issue/1/custom', headers=headers, - data=payload) + "/api/0/test/issue/1/custom", headers=headers, data=payload + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) data["messages"].sort(key=lambda d: list(d.keys())[0]) @@ -171,25 +194,30 @@ class PagureFlaskApiCustomFieldIssuetests(tests.Modeltests): data, { "messages": [ - {"bugzilla": "Custom field bugzilla adjusted to " - "https://bugzilla.redhat.com/1234"}, - {"reviewstatus": "Custom field reviewstatus adjusted to ack"}, - {"upstream": "Custom field upstream adjusted to False (was: True)"}, - + { + "bugzilla": "Custom field bugzilla adjusted to " + "https://bugzilla.redhat.com/1234" + }, + { + "reviewstatus": "Custom field reviewstatus adjusted to ack" + }, + { + "upstream": "Custom field upstream adjusted to False (was: True)" + }, ] - } + }, ) self.session.commit() - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) self.assertEqual(len(issue.other_fields), 3) # Reset the value - payload = {'bugzilla': '', 'upstream': '', 'reviewstatus': ''} + payload = {"bugzilla": "", "upstream": "", "reviewstatus": ""} output = self.app.post( - '/api/0/test/issue/1/custom', headers=headers, - data=payload) + "/api/0/test/issue/1/custom", headers=headers, data=payload + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) data["messages"].sort(key=lambda d: list(d.keys())[0]) @@ -197,14 +225,18 @@ class PagureFlaskApiCustomFieldIssuetests(tests.Modeltests): data, { "messages": [ - {"bugzilla": "Custom field bugzilla reset " - "(from https://bugzilla.redhat.com/1234)"}, - {"reviewstatus": "Custom field reviewstatus reset (from ack)"}, + { + "bugzilla": "Custom field bugzilla reset " + "(from https://bugzilla.redhat.com/1234)" + }, + { + "reviewstatus": "Custom field reviewstatus reset (from ack)" + }, {"upstream": "Custom field upstream reset (from False)"}, ] - } + }, ) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/test_pagure_flask_api_pr_flag.py b/tests/test_pagure_flask_api_pr_flag.py index 599e26c..d3a148b 100644 --- a/tests/test_pagure_flask_api_pr_flag.py +++ b/tests/test_pagure_flask_api_pr_flag.py @@ -17,8 +17,9 @@ import os import json from mock import patch, MagicMock -sys.path.insert(0, os.path.join(os.path.dirname( - os.path.abspath(__file__)), '..')) +sys.path.insert( + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") +) import pagure.config # noqa import pagure.lib.query # noqa @@ -30,148 +31,150 @@ class PagureFlaskApiPRFlagtests(tests.Modeltests): maxDiff = None - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def setUp(self): """ Set up the environnment, ran before every tests. """ super(PagureFlaskApiPRFlagtests, self).setUp() - pagure.config.config['REQUESTS_FOLDER'] = None + pagure.config.config["REQUESTS_FOLDER"] = None tests.create_projects(self.session) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Create a pull-request - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test" + ) req = pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") # Check flags before self.session.commit() request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual(len(request.flags), 0) def test_invalid_project(self): """ Test the flagging a PR on an invalid project. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Invalid project output = self.app.post( - '/api/0/foo/pull-request/1/flag', headers=headers) + "/api/0/foo/pull-request/1/flag", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) def test_incorrect_project(self): """ Test the flagging a PR on the wrong project. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Valid token, wrong project output = self.app.post( - '/api/0/test2/pull-request/1/flag', headers=headers) + "/api/0/test2/pull-request/1/flag", headers=headers + ) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.name, - data['error_code']) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data['error']) + self.assertEqual( + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) def test_pr_disabled(self): """ Test the flagging a PR when PRs are disabled. """ - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") settings = repo.settings - settings['pull_requests'] = False + settings["pull_requests"] = False repo.settings = settings self.session.add(repo) self.session.commit() - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # PRs disabled output = self.app.post( - '/api/0/test/pull-request/1/flag', headers=headers) + "/api/0/test/pull-request/1/flag", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - u'error': u'Pull-Request have been deactivated for this project', - u'error_code': u'EPULLREQUESTSDISABLED' - } + "error": "Pull-Request have been deactivated for this project", + "error_code": "EPULLREQUESTSDISABLED", + }, ) def test_no_pr(self): """ Test the flagging a PR when the PR doesn't exist. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # No PR output = self.app.post( - '/api/0/test/pull-request/10/flag', headers=headers) + "/api/0/test/pull-request/10/flag", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Pull-Request not found", - "error_code": "ENOREQ", - } + data, {"error": "Pull-Request not found", "error_code": "ENOREQ"} ) def test_no_input(self): """ Test the flagging an existing PR but with no data. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # No input output = self.app.post( - '/api/0/test/pull-request/1/flag', headers=headers) + "/api/0/test/pull-request/1/flag", headers=headers + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - 'error': 'Invalid or incomplete input submitted', - 'error_code': 'EINVALIDREQ', - 'errors': { - 'comment': ['This field is required.'], - 'url': ['This field is required.'], - 'username': ['This field is required.'] - } - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": { + "comment": ["This field is required."], + "url": ["This field is required."], + "username": ["This field is required."], + }, + }, ) def test_no_comment(self): """ Test the flagging an existing PR but with incomplete data. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'username': 'Jenkins', - 'percent': 100, - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'uid': 'jenkins_build_pagure_100+seed', + "username": "Jenkins", + "percent": 100, + "url": "http://jenkins.cloud.fedoraproject.org/", + "uid": "jenkins_build_pagure_100+seed", } # Incomplete request output = self.app.post( - '/api/0/test/pull-request/1/flag', data=data, headers=headers) + "/api/0/test/pull-request/1/flag", data=data, headers=headers + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( @@ -179,386 +182,408 @@ class PagureFlaskApiPRFlagtests(tests.Modeltests): { "error": "Invalid or incomplete input submitted", "error_code": "EINVALIDREQ", - "errors": {"comment": ["This field is required."]} - } + "errors": {"comment": ["This field is required."]}, + }, ) # No change self.session.commit() request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual(len(request.flags), 0) @patch( - 'pagure.lib.query.add_pull_request_flag', - MagicMock(side_effect=pagure.exceptions.PagureException('error'))) + "pagure.lib.query.add_pull_request_flag", + MagicMock(side_effect=pagure.exceptions.PagureException("error")), + ) def test_raise_exception(self): """ Test the flagging a PR when adding a flag raises an exception. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'username': 'Jenkins', - 'comment': 'Tests running', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'uid': 'jenkins_build_pagure_100+seed', + "username": "Jenkins", + "comment": "Tests running", + "url": "http://jenkins.cloud.fedoraproject.org/", + "uid": "jenkins_build_pagure_100+seed", } # Adding a flag raises an exception output = self.app.post( - '/api/0/test/pull-request/1/flag', headers=headers, data=data) + "/api/0/test/pull-request/1/flag", headers=headers, data=data + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, {u'error': u'error', u'error_code': u'ENOCODE'}) + self.assertDictEqual(data, {"error": "error", "error_code": "ENOCODE"}) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_flagging_a_pul_request_with_notification(self, mock_email): """ Test the flagging a PR. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Enable PR notifications - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") settings = repo.settings - settings['notify_on_pull-request_flag'] = True + settings["notify_on_pull-request_flag"] = True repo.settings = settings self.session.add(repo) self.session.commit() data = { - 'username': 'Jenkins', - 'comment': 'Tests running', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'uid': 'jenkins_build_pagure_100+seed', + "username": "Jenkins", + "comment": "Tests running", + "url": "http://jenkins.cloud.fedoraproject.org/", + "uid": "jenkins_build_pagure_100+seed", } # Valid request output = self.app.post( - '/api/0/test/pull-request/1/flag', data=data, headers=headers) + "/api/0/test/pull-request/1/flag", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['flag']['date_created'] = '1510742565' - data['flag']['date_updated'] = '1510742565' - pr_uid = data['flag']['pull_request_uid'] - data['flag']['pull_request_uid'] = '62b49f00d489452994de5010565fab81' + data["flag"]["date_created"] = "1510742565" + data["flag"]["date_updated"] = "1510742565" + pr_uid = data["flag"]["pull_request_uid"] + data["flag"]["pull_request_uid"] = "62b49f00d489452994de5010565fab81" data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( data, { - 'flag': { - 'comment': 'Tests running', - 'date_created': '1510742565', - 'date_updated': '1510742565', - 'percent': None, - 'pull_request_uid': '62b49f00d489452994de5010565fab81', - 'status': 'pending', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'user': { - 'default_email': 'bar@pingou.com', - 'emails': ['bar@pingou.com', 'foo@pingou.com'], - 'fullname': 'PY C', - 'name': 'pingou' + "flag": { + "comment": "Tests running", + "date_created": "1510742565", + "date_updated": "1510742565", + "percent": None, + "pull_request_uid": "62b49f00d489452994de5010565fab81", + "status": "pending", + "url": "http://jenkins.cloud.fedoraproject.org/", + "user": { + "default_email": "bar@pingou.com", + "emails": ["bar@pingou.com", "foo@pingou.com"], + "fullname": "PY C", + "name": "pingou", }, - 'username': 'Jenkins'}, - 'message': 'Flag added', - 'uid': 'jenkins_build_pagure_100+seed', - 'avatar_url': 'https://seccdn.libravatar.org/avatar/...', - 'user': 'pingou' - } + "username": "Jenkins", + }, + "message": "Flag added", + "uid": "jenkins_build_pagure_100+seed", + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + "user": "pingou", + }, ) # One flag added self.session.commit() request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual(len(request.flags), 1) - self.assertEqual(request.flags[0].comment, 'Tests running') + self.assertEqual(request.flags[0].comment, "Tests running") self.assertEqual(request.flags[0].percent, None) # Check the notification sent mock_email.assert_called_once_with( - '\nJenkins flagged the pull-request `test pull-request` ' - 'as pending: Tests running\n\n' - 'http://localhost.localdomain/test/pull-request/1\n', - 'PR #1 - Jenkins: pending', - 'bar@pingou.com', + "\nJenkins flagged the pull-request `test pull-request` " + "as pending: Tests running\n\n" + "http://localhost.localdomain/test/pull-request/1\n", + "PR #1 - Jenkins: pending", + "bar@pingou.com", assignee=None, - in_reply_to='test-pull-request-' + pr_uid, - mail_id='test-pull-request-' + pr_uid + '-1', - project_name='test', - reporter='pingou', - user_from='Jenkins' + in_reply_to="test-pull-request-" + pr_uid, + mail_id="test-pull-request-" + pr_uid + "-1", + project_name="test", + reporter="pingou", + user_from="Jenkins", ) def test_updating_flag(self): """ Test the updating the flag of a PR. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'username': 'Jenkins', - 'comment': 'Tests running', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'uid': 'jenkins_build_pagure_100+seed', + "username": "Jenkins", + "comment": "Tests running", + "url": "http://jenkins.cloud.fedoraproject.org/", + "uid": "jenkins_build_pagure_100+seed", } # Valid request output = self.app.post( - '/api/0/test/pull-request/1/flag', data=data, headers=headers) + "/api/0/test/pull-request/1/flag", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['flag']['date_created'] = '1510742565' - data['flag']['date_updated'] = '1510742565' - data['flag']['pull_request_uid'] = '62b49f00d489452994de5010565fab81' + data["flag"]["date_created"] = "1510742565" + data["flag"]["date_updated"] = "1510742565" + data["flag"]["pull_request_uid"] = "62b49f00d489452994de5010565fab81" data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( data, { - 'flag': { - 'comment': 'Tests running', - 'date_created': '1510742565', - 'date_updated': '1510742565', - 'percent': None, - 'pull_request_uid': '62b49f00d489452994de5010565fab81', - 'status': 'pending', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'user': { - 'default_email': 'bar@pingou.com', - 'emails': ['bar@pingou.com', 'foo@pingou.com'], - 'fullname': 'PY C', - 'name': 'pingou' + "flag": { + "comment": "Tests running", + "date_created": "1510742565", + "date_updated": "1510742565", + "percent": None, + "pull_request_uid": "62b49f00d489452994de5010565fab81", + "status": "pending", + "url": "http://jenkins.cloud.fedoraproject.org/", + "user": { + "default_email": "bar@pingou.com", + "emails": ["bar@pingou.com", "foo@pingou.com"], + "fullname": "PY C", + "name": "pingou", }, - 'username': 'Jenkins'}, - 'message': 'Flag added', - 'uid': 'jenkins_build_pagure_100+seed', - 'avatar_url': 'https://seccdn.libravatar.org/avatar/...', - 'user': 'pingou' - } + "username": "Jenkins", + }, + "message": "Flag added", + "uid": "jenkins_build_pagure_100+seed", + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + "user": "pingou", + }, ) # One flag added self.session.commit() request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual(len(request.flags), 1) - self.assertEqual(request.flags[0].comment, 'Tests running') + self.assertEqual(request.flags[0].comment, "Tests running") self.assertEqual(request.flags[0].percent, None) # Update flag - w/o providing the status data = { - 'username': 'Jenkins', - 'percent': 100, - 'comment': 'Tests passed', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'uid': 'jenkins_build_pagure_100+seed', + "username": "Jenkins", + "percent": 100, + "comment": "Tests passed", + "url": "http://jenkins.cloud.fedoraproject.org/", + "uid": "jenkins_build_pagure_100+seed", } output = self.app.post( - '/api/0/test/pull-request/1/flag', data=data, headers=headers) + "/api/0/test/pull-request/1/flag", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['flag']['date_created'] = '1510742565' - data['flag']['date_updated'] = '1510742565' - data['flag']['pull_request_uid'] = '62b49f00d489452994de5010565fab81' + data["flag"]["date_created"] = "1510742565" + data["flag"]["date_updated"] = "1510742565" + data["flag"]["pull_request_uid"] = "62b49f00d489452994de5010565fab81" data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( data, { - 'flag': { - 'comment': 'Tests passed', - 'date_created': '1510742565', - 'date_updated': '1510742565', - 'percent': 100, - 'pull_request_uid': '62b49f00d489452994de5010565fab81', - 'status': 'success', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'user': { - 'default_email': 'bar@pingou.com', - 'emails': ['bar@pingou.com', 'foo@pingou.com'], - 'fullname': 'PY C', - 'name': 'pingou' + "flag": { + "comment": "Tests passed", + "date_created": "1510742565", + "date_updated": "1510742565", + "percent": 100, + "pull_request_uid": "62b49f00d489452994de5010565fab81", + "status": "success", + "url": "http://jenkins.cloud.fedoraproject.org/", + "user": { + "default_email": "bar@pingou.com", + "emails": ["bar@pingou.com", "foo@pingou.com"], + "fullname": "PY C", + "name": "pingou", }, - 'username': 'Jenkins'}, - 'message': 'Flag updated', - 'uid': 'jenkins_build_pagure_100+seed', - 'avatar_url': 'https://seccdn.libravatar.org/avatar/...', - 'user': 'pingou' - } + "username": "Jenkins", + }, + "message": "Flag updated", + "uid": "jenkins_build_pagure_100+seed", + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + "user": "pingou", + }, ) # One flag added self.session.commit() request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual(len(request.flags), 1) - self.assertEqual(request.flags[0].comment, 'Tests passed') + self.assertEqual(request.flags[0].comment, "Tests passed") self.assertEqual(request.flags[0].percent, 100) def test_adding_two_flags(self): """ Test the adding two flags to a PR. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'username': 'Jenkins', - 'comment': 'Tests passed', - 'status': 'success', - 'percent': '100', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'uid': 'jenkins_build_pagure_100+seed', + "username": "Jenkins", + "comment": "Tests passed", + "status": "success", + "percent": "100", + "url": "http://jenkins.cloud.fedoraproject.org/", + "uid": "jenkins_build_pagure_100+seed", } # Valid request output = self.app.post( - '/api/0/test/pull-request/1/flag', data=data, headers=headers) + "/api/0/test/pull-request/1/flag", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['flag']['date_created'] = '1510742565' - data['flag']['date_updated'] = '1510742565' - data['flag']['pull_request_uid'] = '62b49f00d489452994de5010565fab81' + data["flag"]["date_created"] = "1510742565" + data["flag"]["date_updated"] = "1510742565" + data["flag"]["pull_request_uid"] = "62b49f00d489452994de5010565fab81" data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( data, { - 'flag': { - 'comment': 'Tests passed', - 'date_created': '1510742565', - 'date_updated': '1510742565', - 'percent': 100, - 'pull_request_uid': '62b49f00d489452994de5010565fab81', - 'status': 'success', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'user': { - 'default_email': 'bar@pingou.com', - 'emails': ['bar@pingou.com', 'foo@pingou.com'], - 'fullname': 'PY C', - 'name': 'pingou' + "flag": { + "comment": "Tests passed", + "date_created": "1510742565", + "date_updated": "1510742565", + "percent": 100, + "pull_request_uid": "62b49f00d489452994de5010565fab81", + "status": "success", + "url": "http://jenkins.cloud.fedoraproject.org/", + "user": { + "default_email": "bar@pingou.com", + "emails": ["bar@pingou.com", "foo@pingou.com"], + "fullname": "PY C", + "name": "pingou", }, - 'username': 'Jenkins'}, - 'message': 'Flag added', - 'uid': 'jenkins_build_pagure_100+seed', - 'avatar_url': 'https://seccdn.libravatar.org/avatar/...', - 'user': 'pingou' - } + "username": "Jenkins", + }, + "message": "Flag added", + "uid": "jenkins_build_pagure_100+seed", + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + "user": "pingou", + }, ) # One flag added self.session.commit() request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual(len(request.flags), 1) - self.assertEqual(request.flags[0].comment, 'Tests passed') + self.assertEqual(request.flags[0].comment, "Tests passed") self.assertEqual(request.flags[0].percent, 100) data = { - 'username': 'Jenkins', - 'comment': 'Tests running again', - 'url': 'http://jenkins.cloud.fedoraproject.org/', + "username": "Jenkins", + "comment": "Tests running again", + "url": "http://jenkins.cloud.fedoraproject.org/", } # Valid request output = self.app.post( - '/api/0/test/pull-request/1/flag', data=data, headers=headers) + "/api/0/test/pull-request/1/flag", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['flag']['date_created'] = '1510742565' - data['flag']['date_updated'] = '1510742565' - data['flag']['pull_request_uid'] = '62b49f00d489452994de5010565fab81' - self.assertNotEqual( - data['uid'], 'jenkins_build_pagure_100+seed') - data['uid'] = 'jenkins_build_pagure_100+seed' + data["flag"]["date_created"] = "1510742565" + data["flag"]["date_updated"] = "1510742565" + data["flag"]["pull_request_uid"] = "62b49f00d489452994de5010565fab81" + self.assertNotEqual(data["uid"], "jenkins_build_pagure_100+seed") + data["uid"] = "jenkins_build_pagure_100+seed" data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( data, { - 'flag': { - 'comment': 'Tests running again', - 'date_created': '1510742565', - 'date_updated': '1510742565', - 'percent': None, - 'pull_request_uid': '62b49f00d489452994de5010565fab81', - 'status': 'pending', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'user': { - 'default_email': 'bar@pingou.com', - 'emails': ['bar@pingou.com', 'foo@pingou.com'], - 'fullname': 'PY C', - 'name': 'pingou' + "flag": { + "comment": "Tests running again", + "date_created": "1510742565", + "date_updated": "1510742565", + "percent": None, + "pull_request_uid": "62b49f00d489452994de5010565fab81", + "status": "pending", + "url": "http://jenkins.cloud.fedoraproject.org/", + "user": { + "default_email": "bar@pingou.com", + "emails": ["bar@pingou.com", "foo@pingou.com"], + "fullname": "PY C", + "name": "pingou", }, - 'username': 'Jenkins'}, - 'message': 'Flag added', - 'uid': 'jenkins_build_pagure_100+seed', - 'avatar_url': 'https://seccdn.libravatar.org/avatar/...', - 'user': 'pingou' - } + "username": "Jenkins", + }, + "message": "Flag added", + "uid": "jenkins_build_pagure_100+seed", + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + "user": "pingou", + }, ) # Two flag added self.session.commit() request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual(len(request.flags), 2) - self.assertEqual(request.flags[0].comment, 'Tests running again') + self.assertEqual(request.flags[0].comment, "Tests running again") self.assertEqual(request.flags[0].percent, None) - self.assertEqual(request.flags[1].comment, 'Tests passed') + self.assertEqual(request.flags[1].comment, "Tests passed") self.assertEqual(request.flags[1].percent, 100) - @patch.dict('pagure.config.config', - { - 'FLAG_STATUSES_LABELS': - { - 'pend!': 'label-info', - 'succeed!': 'label-success', - 'fail!': 'label-danger', - 'what?': 'label-warning', - }, - 'FLAG_PENDING': 'pend!', - 'FLAG_SUCCESS': 'succeed!', - 'FLAG_FAILURE': 'fail!', - }) + @patch.dict( + "pagure.config.config", + { + "FLAG_STATUSES_LABELS": { + "pend!": "label-info", + "succeed!": "label-success", + "fail!": "label-danger", + "what?": "label-warning", + }, + "FLAG_PENDING": "pend!", + "FLAG_SUCCESS": "succeed!", + "FLAG_FAILURE": "fail!", + }, + ) def test_flagging_a_pull_request_while_having_custom_statuses(self): """ Test flagging a PR while having custom statuses. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # No status and no percent => should use FLAG_PENDING send_data = { - 'username': 'Jenkins', - 'comment': 'Tests running', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'uid': 'jenkins_build_pagure_100+seed', + "username": "Jenkins", + "comment": "Tests running", + "url": "http://jenkins.cloud.fedoraproject.org/", + "uid": "jenkins_build_pagure_100+seed", } output = self.app.post( - '/api/0/test/pull-request/1/flag', data=send_data, headers=headers) + "/api/0/test/pull-request/1/flag", data=send_data, headers=headers + ) data = json.loads(output.get_data(as_text=True)) self.assertEqual(output.status_code, 200) - self.assertEqual(data['flag']['status'], 'pend!') + self.assertEqual(data["flag"]["status"], "pend!") # No status and 50 % => should use FLAG_SUCCESS - send_data['percent'] = 50 + send_data["percent"] = 50 output = self.app.post( - '/api/0/test/pull-request/1/flag', data=send_data, headers=headers) + "/api/0/test/pull-request/1/flag", data=send_data, headers=headers + ) data = json.loads(output.get_data(as_text=True)) self.assertEqual(output.status_code, 200) - self.assertEqual(data['flag']['status'], 'succeed!') + self.assertEqual(data["flag"]["status"], "succeed!") # No status and 0 % => should use FLAG_FAILURE - send_data['percent'] = 0 + send_data["percent"] = 0 output = self.app.post( - '/api/0/test/pull-request/1/flag', data=send_data, headers=headers) + "/api/0/test/pull-request/1/flag", data=send_data, headers=headers + ) data = json.loads(output.get_data(as_text=True)) self.assertEqual(output.status_code, 200) - self.assertEqual(data['flag']['status'], 'fail!') + self.assertEqual(data["flag"]["status"], "fail!") # Explicitly set status - send_data['status'] = 'what?' + send_data["status"] = "what?" output = self.app.post( - '/api/0/test/pull-request/1/flag', data=send_data, headers=headers) + "/api/0/test/pull-request/1/flag", data=send_data, headers=headers + ) data = json.loads(output.get_data(as_text=True)) self.assertEqual(output.status_code, 200) - self.assertEqual(data['flag']['status'], 'what?') + self.assertEqual(data["flag"]["status"], "what?") # Explicitly set wrong status - send_data['status'] = 'nooo.....' + send_data["status"] = "nooo....." output = self.app.post( - '/api/0/test/pull-request/1/flag', data=send_data, headers=headers) + "/api/0/test/pull-request/1/flag", data=send_data, headers=headers + ) data = json.loads(output.get_data(as_text=True)) self.assertEqual(output.status_code, 400) self.assertDictEqual( @@ -566,8 +591,8 @@ class PagureFlaskApiPRFlagtests(tests.Modeltests): { "error": "Invalid or incomplete input submitted", "error_code": "EINVALIDREQ", - "errors": {"status": ["Not a valid choice"]} - } + "errors": {"status": ["Not a valid choice"]}, + }, ) @@ -578,109 +603,108 @@ class PagureFlaskApiPRFlagUserTokentests(tests.Modeltests): maxDiff = None - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def setUp(self): """ Set up the environnment, ran before every tests. """ super(PagureFlaskApiPRFlagUserTokentests, self).setUp() - pagure.config.config['REQUESTS_FOLDER'] = None + pagure.config.config["REQUESTS_FOLDER"] = None tests.create_projects(self.session) tests.create_tokens(self.session, project_id=None) tests.create_tokens_acl(self.session) # Create a pull-request - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test" + ) req = pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") # Check flags before self.session.commit() request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual(len(request.flags), 0) def test_no_pr(self): """ Test flagging a non-existing PR. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Invalid project output = self.app.post( - '/api/0/foo/pull-request/1/flag', headers=headers) + "/api/0/foo/pull-request/1/flag", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) def test_no_pr_other_project(self): """ Test flagging a non-existing PR on a different project. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Valid token, wrong project output = self.app.post( - '/api/0/test2/pull-request/1/flag', headers=headers) + "/api/0/test2/pull-request/1/flag", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Pull-Request not found", - "error_code": "ENOREQ", - } + data, {"error": "Pull-Request not found", "error_code": "ENOREQ"} ) def test_no_input(self): """ Test flagging an existing PR but without submitting any data. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # No input output = self.app.post( - '/api/0/test/pull-request/1/flag', headers=headers) + "/api/0/test/pull-request/1/flag", headers=headers + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - 'error': 'Invalid or incomplete input submitted', - 'error_code': 'EINVALIDREQ', - 'errors': { - 'comment': ['This field is required.'], - 'url': ['This field is required.'], - 'username': ['This field is required.'] - } - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": { + "comment": ["This field is required."], + "url": ["This field is required."], + "username": ["This field is required."], + }, + }, ) def test_no_comment(self): """ Test flagging an existing PR but without all the required info. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'username': 'Jenkins', - 'percent': 100, - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'uid': 'jenkins_build_pagure_100+seed', + "username": "Jenkins", + "percent": 100, + "url": "http://jenkins.cloud.fedoraproject.org/", + "uid": "jenkins_build_pagure_100+seed", } # Incomplete request output = self.app.post( - '/api/0/test/pull-request/1/flag', data=data, headers=headers) + "/api/0/test/pull-request/1/flag", data=data, headers=headers + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( @@ -688,32 +712,34 @@ class PagureFlaskApiPRFlagUserTokentests(tests.Modeltests): { "error": "Invalid or incomplete input submitted", "error_code": "EINVALIDREQ", - "errors": {"comment": ["This field is required."]} - } + "errors": {"comment": ["This field is required."]}, + }, ) # No change self.session.commit() request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual(len(request.flags), 0) def test_invalid_status(self): """ Test flagging an existing PR but with an invalid status. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'username': 'Jenkins', - 'status': 'failed', - 'comment': 'Failed to run the tests', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'uid': 'jenkins_build_pagure_100+seed', + "username": "Jenkins", + "status": "failed", + "comment": "Failed to run the tests", + "url": "http://jenkins.cloud.fedoraproject.org/", + "uid": "jenkins_build_pagure_100+seed", } # Invalid status submitted output = self.app.post( - '/api/0/test/pull-request/1/flag', data=data, headers=headers) + "/api/0/test/pull-request/1/flag", data=data, headers=headers + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( @@ -721,72 +747,76 @@ class PagureFlaskApiPRFlagUserTokentests(tests.Modeltests): { "error": "Invalid or incomplete input submitted", "error_code": "EINVALIDREQ", - "errors": {"status": ["Not a valid choice"]} - } + "errors": {"status": ["Not a valid choice"]}, + }, ) # No change self.session.commit() request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual(len(request.flags), 0) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_flag_pr_no_status(self, mock_email): """ Test flagging an existing PR without providing a status. Also check that no notifications have been sent. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'username': 'Jenkins', - 'percent': 0, - 'comment': 'Tests failed', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'uid': 'jenkins_build_pagure_100+seed', + "username": "Jenkins", + "percent": 0, + "comment": "Tests failed", + "url": "http://jenkins.cloud.fedoraproject.org/", + "uid": "jenkins_build_pagure_100+seed", } # Valid request - w/o providing the status output = self.app.post( - '/api/0/test/pull-request/1/flag', data=data, headers=headers) + "/api/0/test/pull-request/1/flag", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['flag']['date_created'] = '1510742565' - data['flag']['date_updated'] = '1510742565' - data['flag']['pull_request_uid'] = '62b49f00d489452994de5010565fab81' + data["flag"]["date_created"] = "1510742565" + data["flag"]["date_updated"] = "1510742565" + data["flag"]["pull_request_uid"] = "62b49f00d489452994de5010565fab81" data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( data, { - 'flag': { - 'comment': 'Tests failed', - 'date_created': '1510742565', - 'date_updated': '1510742565', - 'percent': 0, - 'pull_request_uid': '62b49f00d489452994de5010565fab81', - 'status': 'failure', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'user': { - 'default_email': 'bar@pingou.com', - 'emails': ['bar@pingou.com', 'foo@pingou.com'], - 'fullname': 'PY C', - 'name': 'pingou' + "flag": { + "comment": "Tests failed", + "date_created": "1510742565", + "date_updated": "1510742565", + "percent": 0, + "pull_request_uid": "62b49f00d489452994de5010565fab81", + "status": "failure", + "url": "http://jenkins.cloud.fedoraproject.org/", + "user": { + "default_email": "bar@pingou.com", + "emails": ["bar@pingou.com", "foo@pingou.com"], + "fullname": "PY C", + "name": "pingou", }, - 'username': 'Jenkins'}, - 'message': 'Flag added', - 'uid': 'jenkins_build_pagure_100+seed', - 'avatar_url': 'https://seccdn.libravatar.org/avatar/...', - 'user': 'pingou' - } + "username": "Jenkins", + }, + "message": "Flag added", + "uid": "jenkins_build_pagure_100+seed", + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + "user": "pingou", + }, ) # One flag added self.session.commit() request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual(len(request.flags), 1) - self.assertEqual(request.flags[0].comment, 'Tests failed') + self.assertEqual(request.flags[0].comment, "Tests failed") self.assertEqual(request.flags[0].percent, 0) # no notifications sent @@ -795,262 +825,262 @@ class PagureFlaskApiPRFlagUserTokentests(tests.Modeltests): def test_editing_flag(self): """ Test flagging an existing PR without providing a status. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'username': 'Jenkins', - 'status': 'failure', - 'comment': 'Tests failed', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'uid': 'jenkins_build_pagure_100+seed', + "username": "Jenkins", + "status": "failure", + "comment": "Tests failed", + "url": "http://jenkins.cloud.fedoraproject.org/", + "uid": "jenkins_build_pagure_100+seed", } # Valid request - w/o providing the status output = self.app.post( - '/api/0/test/pull-request/1/flag', data=data, headers=headers) + "/api/0/test/pull-request/1/flag", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['flag']['date_created'] = '1510742565' - data['flag']['date_updated'] = '1510742565' - data['flag']['pull_request_uid'] = '62b49f00d489452994de5010565fab81' + data["flag"]["date_created"] = "1510742565" + data["flag"]["date_updated"] = "1510742565" + data["flag"]["pull_request_uid"] = "62b49f00d489452994de5010565fab81" data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( data, { - 'flag': { - 'comment': 'Tests failed', - 'date_created': '1510742565', - 'date_updated': '1510742565', - 'percent': None, - 'pull_request_uid': '62b49f00d489452994de5010565fab81', - 'status': 'failure', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'user': { - 'default_email': 'bar@pingou.com', - 'emails': ['bar@pingou.com', 'foo@pingou.com'], - 'fullname': 'PY C', - 'name': 'pingou' + "flag": { + "comment": "Tests failed", + "date_created": "1510742565", + "date_updated": "1510742565", + "percent": None, + "pull_request_uid": "62b49f00d489452994de5010565fab81", + "status": "failure", + "url": "http://jenkins.cloud.fedoraproject.org/", + "user": { + "default_email": "bar@pingou.com", + "emails": ["bar@pingou.com", "foo@pingou.com"], + "fullname": "PY C", + "name": "pingou", }, - 'username': 'Jenkins'}, - 'message': 'Flag added', - 'uid': 'jenkins_build_pagure_100+seed', - 'avatar_url': 'https://seccdn.libravatar.org/avatar/...', - 'user': 'pingou' - } + "username": "Jenkins", + }, + "message": "Flag added", + "uid": "jenkins_build_pagure_100+seed", + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + "user": "pingou", + }, ) # One flag added self.session.commit() request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual(len(request.flags), 1) - self.assertEqual(request.flags[0].comment, 'Tests failed') + self.assertEqual(request.flags[0].comment, "Tests failed") self.assertEqual(request.flags[0].percent, None) # Update flag data = { - 'username': 'Jenkins', - 'percent': 100, - 'comment': 'Tests passed', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'uid': 'jenkins_build_pagure_100+seed', - 'status': 'success', + "username": "Jenkins", + "percent": 100, + "comment": "Tests passed", + "url": "http://jenkins.cloud.fedoraproject.org/", + "uid": "jenkins_build_pagure_100+seed", + "status": "success", } output = self.app.post( - '/api/0/test/pull-request/1/flag', data=data, headers=headers) + "/api/0/test/pull-request/1/flag", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['flag']['date_created'] = '1510742565' - data['flag']['date_updated'] = '1510742565' - data['flag']['pull_request_uid'] = '62b49f00d489452994de5010565fab81' + data["flag"]["date_created"] = "1510742565" + data["flag"]["date_updated"] = "1510742565" + data["flag"]["pull_request_uid"] = "62b49f00d489452994de5010565fab81" data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( data, { - 'flag': { - 'comment': 'Tests passed', - 'date_created': '1510742565', - 'date_updated': '1510742565', - 'percent': 100, - 'pull_request_uid': '62b49f00d489452994de5010565fab81', - 'status': 'success', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'user': { - 'default_email': 'bar@pingou.com', - 'emails': ['bar@pingou.com', 'foo@pingou.com'], - 'fullname': 'PY C', - 'name': 'pingou' + "flag": { + "comment": "Tests passed", + "date_created": "1510742565", + "date_updated": "1510742565", + "percent": 100, + "pull_request_uid": "62b49f00d489452994de5010565fab81", + "status": "success", + "url": "http://jenkins.cloud.fedoraproject.org/", + "user": { + "default_email": "bar@pingou.com", + "emails": ["bar@pingou.com", "foo@pingou.com"], + "fullname": "PY C", + "name": "pingou", }, - 'username': 'Jenkins'}, - 'message': 'Flag updated', - 'uid': 'jenkins_build_pagure_100+seed', - 'avatar_url': 'https://seccdn.libravatar.org/avatar/...', - 'user': 'pingou' - } + "username": "Jenkins", + }, + "message": "Flag updated", + "uid": "jenkins_build_pagure_100+seed", + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + "user": "pingou", + }, ) # Still only one flag self.session.commit() request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual(len(request.flags), 1) - self.assertEqual(request.flags[0].comment, 'Tests passed') + self.assertEqual(request.flags[0].comment, "Tests passed") self.assertEqual(request.flags[0].percent, 100) - class PagureFlaskApiGetPRFlagtests(tests.Modeltests): """ Tests for the flask API of pagure for retrieving pull-requests flags """ maxDiff = None - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def setUp(self): """ Set up the environnment, ran before every tests. """ super(PagureFlaskApiGetPRFlagtests, self).setUp() - pagure.config.config['REQUESTS_FOLDER'] = None + pagure.config.config["REQUESTS_FOLDER"] = None tests.create_projects(self.session) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Create a pull-request - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test" + ) req = pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") # Check flags before self.session.commit() request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual(len(request.flags), 0) def test_invalid_project(self): """ Test the retrieving the flags of a PR on an invalid project. """ # Invalid project - output = self.app.get('/api/0/foo/pull-request/1/flag') + output = self.app.get("/api/0/foo/pull-request/1/flag") self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) def test_pr_disabled(self): """ Test the retrieving the flags of a PR when PRs are disabled. """ - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") settings = repo.settings - settings['pull_requests'] = False + settings["pull_requests"] = False repo.settings = settings self.session.add(repo) self.session.commit() # PRs disabled - output = self.app.get('/api/0/test/pull-request/1/flag') + output = self.app.get("/api/0/test/pull-request/1/flag") self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - u'error': u'Pull-Request have been deactivated for this project', - u'error_code': u'EPULLREQUESTSDISABLED' - } + "error": "Pull-Request have been deactivated for this project", + "error_code": "EPULLREQUESTSDISABLED", + }, ) def test_no_pr(self): """ Test the retrieving the flags of a PR when the PR doesn't exist. """ # No PR - output = self.app.get('/api/0/test/pull-request/10/flag') + output = self.app.get("/api/0/test/pull-request/10/flag") self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Pull-Request not found", - "error_code": "ENOREQ", - } + data, {"error": "Pull-Request not found", "error_code": "ENOREQ"} ) def test_no_flag(self): """ Test the retrieving the flags of a PR when the PR has no flags. """ # No flag - output = self.app.get('/api/0/test/pull-request/1/flag') + output = self.app.get("/api/0/test/pull-request/1/flag") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {"flags": []} - ) + self.assertDictEqual(data, {"flags": []}) def test_get_flag(self): """ Test the retrieving the flags of a PR when the PR has one flag. """ # Add a flag to the PR request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) msg = pagure.lib.query.add_pull_request_flag( session=self.session, request=request, username="jenkins", percent=None, comment="Build passes", - status='success', + status="success", url="http://jenkins.cloud.fedoraproject.org", uid="jenkins_build_pagure_34", - user='foo', - token='aaabbbcccddd', + user="foo", + token="aaabbbcccddd", ) - self.assertEqual(msg, ('Flag added', 'jenkins_build_pagure_34')) + self.assertEqual(msg, ("Flag added", "jenkins_build_pagure_34")) self.session.commit() self.assertEqual(len(request.flags), 1) - self.assertEqual(request.flags[0].token_id, 'aaabbbcccddd') + self.assertEqual(request.flags[0].token_id, "aaabbbcccddd") # 1 flag - output = self.app.get('/api/0/test/pull-request/1/flag') + output = self.app.get("/api/0/test/pull-request/1/flag") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['flags'][0]['date_created'] = '1541413645' - data['flags'][0]['date_updated'] = '1541413645' - data['flags'][0]['pull_request_uid'] = '72a61033c2fc464aa9ef514c057aa62c' + data["flags"][0]["date_created"] = "1541413645" + data["flags"][0]["date_updated"] = "1541413645" + data["flags"][0][ + "pull_request_uid" + ] = "72a61033c2fc464aa9ef514c057aa62c" self.assertDictEqual( data, { - 'flags': [ - { - 'comment': 'Build passes', - 'date_created': '1541413645', - 'date_updated': '1541413645', - 'percent': None, - 'pull_request_uid': '72a61033c2fc464aa9ef514c057aa62c', - 'status': 'success', - 'url': 'http://jenkins.cloud.fedoraproject.org', - 'user': {'fullname': 'foo bar', 'name': 'foo'}, - 'username': 'jenkins' - } - ] - } + "flags": [ + { + "comment": "Build passes", + "date_created": "1541413645", + "date_updated": "1541413645", + "percent": None, + "pull_request_uid": "72a61033c2fc464aa9ef514c057aa62c", + "status": "success", + "url": "http://jenkins.cloud.fedoraproject.org", + "user": {"fullname": "foo bar", "name": "foo"}, + "username": "jenkins", + } + ] + }, ) def test_get_flags(self): @@ -1058,20 +1088,21 @@ class PagureFlaskApiGetPRFlagtests(tests.Modeltests): # Add two flags to the PR request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) msg = pagure.lib.query.add_pull_request_flag( session=self.session, request=request, username="jenkins", percent=None, comment="Build passes", - status='success', + status="success", url="http://jenkins.cloud.fedoraproject.org", uid="jenkins_build_pagure_34", - user='foo', - token='aaabbbcccddd', + user="foo", + token="aaabbbcccddd", ) - self.assertEqual(msg, ('Flag added', 'jenkins_build_pagure_34')) + self.assertEqual(msg, ("Flag added", "jenkins_build_pagure_34")) self.session.commit() msg = pagure.lib.query.add_pull_request_flag( @@ -1080,59 +1111,63 @@ class PagureFlaskApiGetPRFlagtests(tests.Modeltests): username="travis", percent=None, comment="Build pending", - status='pending', + status="pending", url="http://travis.io", uid="travis_build_pagure_34", - user='foo', - token='aaabbbcccddd', + user="foo", + token="aaabbbcccddd", ) - self.assertEqual(msg, ('Flag added', 'travis_build_pagure_34')) + self.assertEqual(msg, ("Flag added", "travis_build_pagure_34")) self.session.commit() self.assertEqual(len(request.flags), 2) - self.assertEqual(request.flags[1].token_id, 'aaabbbcccddd') - self.assertEqual(request.flags[0].token_id, 'aaabbbcccddd') + self.assertEqual(request.flags[1].token_id, "aaabbbcccddd") + self.assertEqual(request.flags[0].token_id, "aaabbbcccddd") # 1 flag - output = self.app.get('/api/0/test/pull-request/1/flag') + output = self.app.get("/api/0/test/pull-request/1/flag") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['flags'][0]['date_created'] = '1541413645' - data['flags'][0]['date_updated'] = '1541413645' - data['flags'][0]['pull_request_uid'] = '72a61033c2fc464aa9ef514c057aa62c' - data['flags'][1]['date_created'] = '1541413645' - data['flags'][1]['date_updated'] = '1541413645' - data['flags'][1]['pull_request_uid'] = '72a61033c2fc464aa9ef514c057aa62c' + data["flags"][0]["date_created"] = "1541413645" + data["flags"][0]["date_updated"] = "1541413645" + data["flags"][0][ + "pull_request_uid" + ] = "72a61033c2fc464aa9ef514c057aa62c" + data["flags"][1]["date_created"] = "1541413645" + data["flags"][1]["date_updated"] = "1541413645" + data["flags"][1][ + "pull_request_uid" + ] = "72a61033c2fc464aa9ef514c057aa62c" self.assertDictEqual( data, { - 'flags': [ - { - 'comment': 'Build pending', - 'date_created': '1541413645', - 'date_updated': '1541413645', - 'percent': None, - 'pull_request_uid': '72a61033c2fc464aa9ef514c057aa62c', - 'status': 'pending', - 'url': 'http://travis.io', - 'user': {'fullname': 'foo bar', 'name': 'foo'}, - 'username': 'travis' - }, - { - 'comment': 'Build passes', - 'date_created': '1541413645', - 'date_updated': '1541413645', - 'percent': None, - 'pull_request_uid': '72a61033c2fc464aa9ef514c057aa62c', - 'status': 'success', - 'url': 'http://jenkins.cloud.fedoraproject.org', - 'user': {'fullname': 'foo bar', 'name': 'foo'}, - 'username': 'jenkins' - } - ] - } - ) - - -if __name__ == '__main__': + "flags": [ + { + "comment": "Build pending", + "date_created": "1541413645", + "date_updated": "1541413645", + "percent": None, + "pull_request_uid": "72a61033c2fc464aa9ef514c057aa62c", + "status": "pending", + "url": "http://travis.io", + "user": {"fullname": "foo bar", "name": "foo"}, + "username": "travis", + }, + { + "comment": "Build passes", + "date_created": "1541413645", + "date_updated": "1541413645", + "percent": None, + "pull_request_uid": "72a61033c2fc464aa9ef514c057aa62c", + "status": "success", + "url": "http://jenkins.cloud.fedoraproject.org", + "user": {"fullname": "foo bar", "name": "foo"}, + "username": "jenkins", + }, + ] + }, + ) + + +if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/test_pagure_flask_api_project.py b/tests/test_pagure_flask_api_project.py index 187be7b..2dde3df 100644 --- a/tests/test_pagure_flask_api_project.py +++ b/tests/test_pagure_flask_api_project.py @@ -23,8 +23,9 @@ import pygit2 from celery.result import EagerResult from mock import patch, Mock -sys.path.insert(0, os.path.join(os.path.dirname( - os.path.abspath(__file__)), '..')) +sys.path.insert( + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") +) import pagure.flask_app import pagure.lib.query @@ -38,9 +39,10 @@ class PagureFlaskApiProjecttests(tests.Modeltests): def setUp(self): super(PagureFlaskApiProjecttests, self).setUp() self.gga_patcher = patch( - 'pagure.lib.tasks.generate_gitolite_acls.delay') + "pagure.lib.tasks.generate_gitolite_acls.delay" + ) self.mock_gen_acls = self.gga_patcher.start() - task_result = EagerResult('abc-1234', True, "SUCCESS") + task_result = EagerResult("abc-1234", True, "SUCCESS") self.mock_gen_acls.return_value = task_result def tearDown(self): @@ -52,65 +54,65 @@ class PagureFlaskApiProjecttests(tests.Modeltests): tests.create_projects(self.session) # Create a git repo to play with - gitrepo = os.path.join(self.path, 'repos', 'test.git') + gitrepo = os.path.join(self.path, "repos", "test.git") repo = pygit2.init_repository(gitrepo, bare=True) - newpath = tempfile.mkdtemp(prefix='pagure-fork-test') - repopath = os.path.join(newpath, 'test') + newpath = tempfile.mkdtemp(prefix="pagure-fork-test") + repopath = os.path.join(newpath, "test") clone_repo = pygit2.clone_repository(gitrepo, repopath) # Create a file in that git repo - with open(os.path.join(repopath, 'sources'), 'w') as stream: - stream.write('foo\n bar') - clone_repo.index.add('sources') + with open(os.path.join(repopath, "sources"), "w") as stream: + stream.write("foo\n bar") + clone_repo.index.add("sources") clone_repo.index.write() # Commits the files added tree = clone_repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") clone_repo.create_commit( - 'refs/heads/master', # the name of the reference to update + "refs/heads/master", # the name of the reference to update author, committer, - 'Add sources file for testing', + "Add sources file for testing", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [] + [], ) - refname = 'refs/heads/master:refs/heads/master' + refname = "refs/heads/master:refs/heads/master" ori_remote = clone_repo.remotes[0] PagureRepo.push(ori_remote, refname) # Tag our first commit - first_commit = repo.revparse_single('HEAD') - tagger = pygit2.Signature('Alice Doe', 'adoe@example.com', 12347, 0) + first_commit = repo.revparse_single("HEAD") + tagger = pygit2.Signature("Alice Doe", "adoe@example.com", 12347, 0) repo.create_tag( - "0.0.1", first_commit.oid.hex, pygit2.GIT_OBJ_COMMIT, tagger, - "Release 0.0.1") + "0.0.1", + first_commit.oid.hex, + pygit2.GIT_OBJ_COMMIT, + tagger, + "Release 0.0.1", + ) # Check tags - output = self.app.get('/api/0/test/git/tags') + output = self.app.get("/api/0/test/git/tags") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'tags': ['0.0.1'], 'total_tags': 1} - ) + self.assertDictEqual(data, {"tags": ["0.0.1"], "total_tags": 1}) # Check tags with commits - output = self.app.get('/api/0/test/git/tags?with_commits=True') + output = self.app.get("/api/0/test/git/tags?with_commits=True") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['tags']['0.0.1'] = 'bb8fa2aa199da08d6085e1c9badc3d83d188d38c' + data["tags"]["0.0.1"] = "bb8fa2aa199da08d6085e1c9badc3d83d188d38c" self.assertDictEqual( data, { - 'tags': {'0.0.1': 'bb8fa2aa199da08d6085e1c9badc3d83d188d38c'}, - 'total_tags': 1} + "tags": {"0.0.1": "bb8fa2aa199da08d6085e1c9badc3d83d188d38c"}, + "total_tags": 1, + }, ) shutil.rmtree(newpath) @@ -119,19 +121,19 @@ class PagureFlaskApiProjecttests(tests.Modeltests): """ Test the api_git_branches method of the flask api. """ # Create a git repo to add branches to tests.create_projects(self.session) - repo_path = os.path.join(self.path, 'repos', 'test.git') + repo_path = os.path.join(self.path, "repos", "test.git") tests.add_content_git_repo(repo_path) - new_repo_path = tempfile.mkdtemp(prefix='pagure-api-git-branches-test') + new_repo_path = tempfile.mkdtemp(prefix="pagure-api-git-branches-test") clone_repo = pygit2.clone_repository(repo_path, new_repo_path) # Create two other branches based on master - for branch in ['pats-win-49', 'pats-win-51']: + for branch in ["pats-win-49", "pats-win-51"]: clone_repo.create_branch(branch, clone_repo.head.peel()) - refname = 'refs/heads/{0}:refs/heads/{0}'.format(branch) + refname = "refs/heads/{0}:refs/heads/{0}".format(branch) PagureRepo.push(clone_repo.remotes[0], refname) # Check that the branches show up on the API - output = self.app.get('/api/0/test/git/branches') + output = self.app.get("/api/0/test/git/branches") # Delete the cloned git repo after the API call shutil.rmtree(new_repo_path) @@ -141,9 +143,9 @@ class PagureFlaskApiProjecttests(tests.Modeltests): self.assertDictEqual( data, { - 'branches': ['master', 'pats-win-49', 'pats-win-51'], - 'total_branches': 3 - } + "branches": ["master", "pats-win-49", "pats-win-51"], + "total_branches": 3, + }, ) def test_api_git_branches_empty_repo(self): @@ -152,41 +154,35 @@ class PagureFlaskApiProjecttests(tests.Modeltests): """ # Create a git repo without any branches tests.create_projects(self.session) - repo_base_path = os.path.join(self.path, 'repos') + repo_base_path = os.path.join(self.path, "repos") tests.create_projects_git(repo_base_path) # Check that no branches show up on the API - output = self.app.get('/api/0/test/git/branches') + output = self.app.get("/api/0/test/git/branches") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - { - 'branches': [], - 'total_branches': 0 - } - ) + self.assertDictEqual(data, {"branches": [], "total_branches": 0}) def test_api_git_branches_no_repo(self): """ Test the api_git_branches method of the flask api when there is no repo on a project. """ tests.create_projects(self.session) - output = self.app.get('/api/0/test/git/branches') + output = self.app.get("/api/0/test/git/branches") self.assertEqual(output.status_code, 404) def test_api_git_urls(self): """ Test the api_project_git_urls method of the flask api. """ tests.create_projects(self.session) - output = self.app.get('/api/0/test/git/urls') + output = self.app.get("/api/0/test/git/urls") self.assertEqual(output.status_code, 200) expected_rv = { - 'urls': { - 'git': 'git://localhost.localdomain/test.git', - 'ssh': 'ssh://git@localhost.localdomain/test.git' + "urls": { + "git": "git://localhost.localdomain/test.git", + "ssh": "ssh://git@localhost.localdomain/test.git", }, - 'total_urls': 2 + "total_urls": 2, } data = json.loads(output.get_data(as_text=True)) self.assertDictEqual(data, expected_rv) @@ -195,58 +191,58 @@ class PagureFlaskApiProjecttests(tests.Modeltests): """ Test the api_project_git_urls method of the flask api when there is no project. """ - output = self.app.get('/api/0/test1234/git/urls') + output = self.app.get("/api/0/test1234/git/urls") self.assertEqual(output.status_code, 404) expected_rv = { - 'error': 'Project not found', - 'error_code': 'ENOPROJECT' + "error": "Project not found", + "error_code": "ENOPROJECT", } data = json.loads(output.get_data(as_text=True)) self.assertDictEqual(data, expected_rv) - @patch.dict('pagure.config.config', {'PRIVATE_PROJECTS': True}) + @patch.dict("pagure.config.config", {"PRIVATE_PROJECTS": True}) def test_api_git_urls_private_project(self): """ Test the api_project_git_urls method of the flask api when the project is private. """ tests.create_projects(self.session) tests.create_tokens(self.session) - tests.create_tokens_acl(self.session, 'aaabbbcccddd') - headers = {'Authorization': 'token aaabbbcccddd'} + tests.create_tokens_acl(self.session, "aaabbbcccddd") + headers = {"Authorization": "token aaabbbcccddd"} - test_project = pagure.lib.query._get_project(self.session, 'test') + test_project = pagure.lib.query._get_project(self.session, "test") test_project.private = True self.session.add(test_project) self.session.commit() - output = self.app.get('/api/0/test/git/urls', headers=headers) + output = self.app.get("/api/0/test/git/urls", headers=headers) self.assertEqual(output.status_code, 200) expected_rv = { - 'urls': { - 'git': 'git://localhost.localdomain/test.git', - 'ssh': 'ssh://git@localhost.localdomain/test.git' + "urls": { + "git": "git://localhost.localdomain/test.git", + "ssh": "ssh://git@localhost.localdomain/test.git", }, - 'total_urls': 2 + "total_urls": 2, } data = json.loads(output.get_data(as_text=True)) self.assertDictEqual(data, expected_rv) - @patch.dict('pagure.config.config', {'PRIVATE_PROJECTS': True}) + @patch.dict("pagure.config.config", {"PRIVATE_PROJECTS": True}) def test_api_git_urls_private_project_no_login(self): """ Test the api_project_git_urls method of the flask api when the project is private and the user is not logged in. """ tests.create_projects(self.session) - test_project = pagure.lib.query._get_project(self.session, 'test') + test_project = pagure.lib.query._get_project(self.session, "test") test_project.private = True self.session.add(test_project) self.session.commit() - output = self.app.get('/api/0/test/git/urls') + output = self.app.get("/api/0/test/git/urls") self.assertEqual(output.status_code, 404) expected_rv = { - 'error': 'Project not found', - 'error_code': 'ENOPROJECT' + "error": "Project not found", + "error_code": "ENOPROJECT", } data = json.loads(output.get_data(as_text=True)) self.assertDictEqual(data, expected_rv) @@ -255,65 +251,56 @@ class PagureFlaskApiProjecttests(tests.Modeltests): """ Test the api_projects method of the flask api. """ tests.create_projects(self.session) - output = self.app.get('/api/0/projects?pattern=test') + output = self.app.get("/api/0/projects?pattern=test") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['projects'][0]['date_created'] = "1436527638" - data['projects'][0]['date_modified'] = "1436527638" - del data['pagination'] + data["projects"][0]["date_created"] = "1436527638" + data["projects"][0]["date_modified"] = "1436527638" + del data["pagination"] expected_data = { - "args": { - "fork": None, - "namespace": None, - "owner": None, - "page": 1, - "pattern": "test", - "per_page": 20, - "short": False, - "tags": [], - "username": None - }, - "projects": [ - { - "access_groups": { - "admin": [], - "commit": [], - "ticket": [] - }, - "access_users": { - "admin": [], - "commit": [], - "owner": [ - "pingou" - ], - "ticket": [] - }, - "close_status": [ - "Invalid", - "Insufficient data", - "Fixed", - "Duplicate" - ], - "custom_keys": [], - "date_created": "1436527638", - "date_modified": "1436527638", - "description": "test project #1", - "fullname": "test", - "url_path": "test", - "id": 1, - "milestones": {}, - "name": "test", - "namespace": None, - "parent": None, - "priorities": {}, - "tags": [], - "user": { - "fullname": "PY C", - "name": "pingou" - } - } - ], - "total_projects": 1 + "args": { + "fork": None, + "namespace": None, + "owner": None, + "page": 1, + "pattern": "test", + "per_page": 20, + "short": False, + "tags": [], + "username": None, + }, + "projects": [ + { + "access_groups": {"admin": [], "commit": [], "ticket": []}, + "access_users": { + "admin": [], + "commit": [], + "owner": ["pingou"], + "ticket": [], + }, + "close_status": [ + "Invalid", + "Insufficient data", + "Fixed", + "Duplicate", + ], + "custom_keys": [], + "date_created": "1436527638", + "date_modified": "1436527638", + "description": "test project #1", + "fullname": "test", + "url_path": "test", + "id": 1, + "milestones": {}, + "name": "test", + "namespace": None, + "parent": None, + "priorities": {}, + "tags": [], + "user": {"fullname": "PY C", "name": "pingou"}, + } + ], + "total_projects": 1, } self.assertDictEqual(data, expected_data) @@ -321,43 +308,43 @@ class PagureFlaskApiProjecttests(tests.Modeltests): """ Test the api_projects method of the flask api. """ tests.create_projects(self.session) - output = self.app.get('/api/0/projects?pattern=te*&short=1') + output = self.app.get("/api/0/projects?pattern=te*&short=1") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - del data['pagination'] + del data["pagination"] expected_data = { - "args": { - "fork": None, - "namespace": None, - "owner": None, - "page": 1, - "pattern": "te*", - "per_page": 20, - "short": True, - "tags": [], - "username": None - }, - "projects": [ - { - "description": "test project #1", - "fullname": "test", - "name": "test", - "namespace": None - }, - { - "description": "test project #2", - "fullname": "test2", - "name": "test2", - "namespace": None + "args": { + "fork": None, + "namespace": None, + "owner": None, + "page": 1, + "pattern": "te*", + "per_page": 20, + "short": True, + "tags": [], + "username": None, }, - { - "description": "namespaced test project", - "fullname": "somenamespace/test3", - "name": "test3", - "namespace": "somenamespace" - } - ], - "total_projects": 3 + "projects": [ + { + "description": "test project #1", + "fullname": "test", + "name": "test", + "namespace": None, + }, + { + "description": "test project #2", + "fullname": "test2", + "name": "test2", + "namespace": None, + }, + { + "description": "namespaced test project", + "fullname": "somenamespace/test3", + "name": "test3", + "namespace": "somenamespace", + }, + ], + "total_projects": 3, } self.maxDiff = None self.assertDictEqual(data, expected_data) @@ -366,24 +353,24 @@ class PagureFlaskApiProjecttests(tests.Modeltests): """ Test the api_projects method of the flask api. """ tests.create_projects(self.session) - output = self.app.get('/api/0/projects?owner=foo') + output = self.app.get("/api/0/projects?owner=foo") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - del data['pagination'] + del data["pagination"] expected_data = { - "args": { - "fork": None, - "namespace": None, - "owner": "foo", - "page": 1, - "pattern": None, - "per_page": 20, - "short": False, - "tags": [], - "username": None - }, - "projects": [], - "total_projects": 0 + "args": { + "fork": None, + "namespace": None, + "owner": "foo", + "page": 1, + "pattern": None, + "per_page": 20, + "short": False, + "tags": [], + "username": None, + }, + "projects": [], + "total_projects": 0, } self.maxDiff = None self.assertDictEqual(data, expected_data) @@ -392,43 +379,43 @@ class PagureFlaskApiProjecttests(tests.Modeltests): """ Test the api_projects method of the flask api. """ tests.create_projects(self.session) - output = self.app.get('/api/0/projects?owner=!foo&short=1') + output = self.app.get("/api/0/projects?owner=!foo&short=1") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - del data['pagination'] + del data["pagination"] expected_data = { - "args": { - "fork": None, - "namespace": None, - "owner": "!foo", - "page": 1, - "pattern": None, - "per_page": 20, - "short": True, - "tags": [], - "username": None - }, - "projects": [ - { - "description": "test project #1", - "fullname": "test", - "name": "test", - "namespace": None - }, - { - "description": "test project #2", - "fullname": "test2", - "name": "test2", - "namespace": None + "args": { + "fork": None, + "namespace": None, + "owner": "!foo", + "page": 1, + "pattern": None, + "per_page": 20, + "short": True, + "tags": [], + "username": None, }, - { - "description": "namespaced test project", - "fullname": "somenamespace/test3", - "name": "test3", - "namespace": "somenamespace" - } - ], - "total_projects": 3 + "projects": [ + { + "description": "test project #1", + "fullname": "test", + "name": "test", + "namespace": None, + }, + { + "description": "test project #2", + "fullname": "test2", + "name": "test2", + "namespace": None, + }, + { + "description": "namespaced test project", + "fullname": "somenamespace/test3", + "name": "test3", + "namespace": "somenamespace", + }, + ], + "total_projects": 3, } self.maxDiff = None self.assertDictEqual(data, expected_data) @@ -438,25 +425,26 @@ class PagureFlaskApiProjecttests(tests.Modeltests): tests.create_projects(self.session) # Check before adding - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") self.assertEqual(repo.tags, []) # Adding a tag output = pagure.lib.query.update_tags( - self.session, repo, 'infra', 'pingou') - self.assertEqual(output, ['Project tagged with: infra']) + self.session, repo, "infra", "pingou" + ) + self.assertEqual(output, ["Project tagged with: infra"]) # Check after adding - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") self.assertEqual(len(repo.tags), 1) - self.assertEqual(repo.tags_text, ['infra']) + self.assertEqual(repo.tags_text, ["infra"]) # Check the API - output = self.app.get('/api/0/projects?tags=inf') + output = self.app.get("/api/0/projects?tags=inf") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) null = None - del data['pagination'] + del data["pagination"] self.assertDictEqual( data, { @@ -471,16 +459,16 @@ class PagureFlaskApiProjecttests(tests.Modeltests): "per_page": 20, "short": False, "tags": ["inf"], - "username": None + "username": None, }, - } + }, ) - output = self.app.get('/api/0/projects?tags=infra') + output = self.app.get("/api/0/projects?tags=infra") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['projects'][0]['date_created'] = "1436527638" - data['projects'][0]['date_modified'] = "1436527638" - del data['pagination'] + data["projects"][0]["date_created"] = "1436527638" + data["projects"][0]["date_modified"] = "1436527638" + del data["pagination"] expected_data = { "args": { "fork": None, @@ -491,56 +479,53 @@ class PagureFlaskApiProjecttests(tests.Modeltests): "per_page": 20, "short": False, "tags": ["infra"], - "username": None + "username": None, }, - "projects": [{ - "access_groups": { - "admin": [], - "commit": [], - "ticket": []}, - "access_users": { - "admin": [], - "commit": [], - "owner": ["pingou"], - "ticket": []}, - "close_status": [ - "Invalid", - "Insufficient data", - "Fixed", - "Duplicate" - ], - "custom_keys": [], - "date_created": "1436527638", - "date_modified": "1436527638", - "description": "test project #1", - "fullname": "test", - "url_path": "test", - "id": 1, - "milestones": {}, - "name": "test", - "namespace": None, - "parent": None, - "priorities": {}, - "tags": ["infra"], - "user": { - "fullname": "PY C", - "name": "pingou" + "projects": [ + { + "access_groups": {"admin": [], "commit": [], "ticket": []}, + "access_users": { + "admin": [], + "commit": [], + "owner": ["pingou"], + "ticket": [], + }, + "close_status": [ + "Invalid", + "Insufficient data", + "Fixed", + "Duplicate", + ], + "custom_keys": [], + "date_created": "1436527638", + "date_modified": "1436527638", + "description": "test project #1", + "fullname": "test", + "url_path": "test", + "id": 1, + "milestones": {}, + "name": "test", + "namespace": None, + "parent": None, + "priorities": {}, + "tags": ["infra"], + "user": {"fullname": "PY C", "name": "pingou"}, } - }], - "total_projects": 1 + ], + "total_projects": 1, } self.assertDictEqual(data, expected_data) - output = self.app.get('/api/0/projects?owner=pingou') + output = self.app.get("/api/0/projects?owner=pingou") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['projects'][0]['date_created'] = "1436527638" - data['projects'][0]['date_modified'] = "1436527638" - data['projects'][1]['date_created'] = "1436527638" - data['projects'][1]['date_modified'] = "1436527638" - data['projects'][2]['date_created'] = "1436527638" - data['projects'][2]['date_modified'] = "1436527638" - del data['pagination'] + data["projects"][0]["date_created"] = "1436527638" + data["projects"][0]["date_modified"] = "1436527638" + data["projects"][1]["date_created"] = "1436527638" + data["projects"][1]["date_modified"] = "1436527638" + data["projects"][2]["date_created"] = "1436527638" + data["projects"][2]["date_modified"] = "1436527638" + del data["pagination"] expected_data = { "args": { "fork": None, @@ -551,26 +536,22 @@ class PagureFlaskApiProjecttests(tests.Modeltests): "per_page": 20, "short": False, "tags": [], - "username": None + "username": None, }, "projects": [ { - "access_groups": { - "admin": [], - "commit": [], - "ticket": [] - }, + "access_groups": {"admin": [], "commit": [], "ticket": []}, "access_users": { "admin": [], "commit": [], "owner": ["pingou"], - "ticket": [] + "ticket": [], }, "close_status": [ "Invalid", "Insufficient data", "Fixed", - "Duplicate" + "Duplicate", ], "custom_keys": [], "date_created": "1436527638", @@ -585,28 +566,21 @@ class PagureFlaskApiProjecttests(tests.Modeltests): "parent": None, "priorities": {}, "tags": ["infra"], - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, }, { - "access_groups": { - "admin": [], - "commit": [], - "ticket": [] - }, + "access_groups": {"admin": [], "commit": [], "ticket": []}, "access_users": { "admin": [], "commit": [], "owner": ["pingou"], - "ticket": [] + "ticket": [], }, "close_status": [ "Invalid", "Insufficient data", "Fixed", - "Duplicate" + "Duplicate", ], "custom_keys": [], "date_created": "1436527638", @@ -621,28 +595,21 @@ class PagureFlaskApiProjecttests(tests.Modeltests): "parent": None, "priorities": {}, "tags": [], - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, }, { - "access_groups": { - "admin": [], - "commit": [], - "ticket": [] - }, + "access_groups": {"admin": [], "commit": [], "ticket": []}, "access_users": { "admin": [], "commit": [], "owner": ["pingou"], - "ticket": [] + "ticket": [], }, "close_status": [ "Invalid", "Insufficient data", "Fixed", - "Duplicate" + "Duplicate", ], "custom_keys": [], "date_created": "1436527638", @@ -657,26 +624,23 @@ class PagureFlaskApiProjecttests(tests.Modeltests): "parent": None, "priorities": {}, "tags": [], - "user": { - "fullname": "PY C", - "name": "pingou" - } - } + "user": {"fullname": "PY C", "name": "pingou"}, + }, ], - "total_projects": 3 + "total_projects": 3, } self.assertDictEqual(data, expected_data) - output = self.app.get('/api/0/projects?username=pingou') + output = self.app.get("/api/0/projects?username=pingou") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['projects'][0]['date_created'] = "1436527638" - data['projects'][0]['date_modified'] = "1436527638" - data['projects'][1]['date_created'] = "1436527638" - data['projects'][1]['date_modified'] = "1436527638" - data['projects'][2]['date_created'] = "1436527638" - data['projects'][2]['date_modified'] = "1436527638" - del data['pagination'] + data["projects"][0]["date_created"] = "1436527638" + data["projects"][0]["date_modified"] = "1436527638" + data["projects"][1]["date_created"] = "1436527638" + data["projects"][1]["date_modified"] = "1436527638" + data["projects"][2]["date_created"] = "1436527638" + data["projects"][2]["date_modified"] = "1436527638" + del data["pagination"] expected_data = { "args": { "fork": None, @@ -687,25 +651,22 @@ class PagureFlaskApiProjecttests(tests.Modeltests): "per_page": 20, "short": False, "tags": [], - "username": "pingou" + "username": "pingou", }, "projects": [ { - "access_groups": { - "admin": [], - "commit": [], - "ticket": []}, + "access_groups": {"admin": [], "commit": [], "ticket": []}, "access_users": { "admin": [], "commit": [], "owner": ["pingou"], - "ticket": [] + "ticket": [], }, "close_status": [ "Invalid", "Insufficient data", "Fixed", - "Duplicate" + "Duplicate", ], "custom_keys": [], "date_created": "1436527638", @@ -720,28 +681,21 @@ class PagureFlaskApiProjecttests(tests.Modeltests): "parent": None, "priorities": {}, "tags": ["infra"], - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, }, { - "access_groups": { - "admin": [], - "commit": [], - "ticket": [] - }, + "access_groups": {"admin": [], "commit": [], "ticket": []}, "access_users": { "admin": [], "commit": [], "owner": ["pingou"], - "ticket": [] + "ticket": [], }, "close_status": [ "Invalid", "Insufficient data", "Fixed", - "Duplicate" + "Duplicate", ], "custom_keys": [], "date_created": "1436527638", @@ -756,26 +710,21 @@ class PagureFlaskApiProjecttests(tests.Modeltests): "parent": None, "priorities": {}, "tags": [], - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, }, { - "access_groups": { - "admin": [], - "commit": [], - "ticket": []}, + "access_groups": {"admin": [], "commit": [], "ticket": []}, "access_users": { "admin": [], "commit": [], "owner": ["pingou"], - "ticket": []}, + "ticket": [], + }, "close_status": [ "Invalid", "Insufficient data", "Fixed", - "Duplicate" + "Duplicate", ], "custom_keys": [], "date_created": "1436527638", @@ -790,22 +739,19 @@ class PagureFlaskApiProjecttests(tests.Modeltests): "parent": None, "priorities": {}, "tags": [], - "user": { - "fullname": "PY C", - "name": "pingou" - } - } + "user": {"fullname": "PY C", "name": "pingou"}, + }, ], - "total_projects": 3 + "total_projects": 3, } self.assertDictEqual(data, expected_data) - output = self.app.get('/api/0/projects?username=pingou&tags=infra') + output = self.app.get("/api/0/projects?username=pingou&tags=infra") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['projects'][0]['date_created'] = "1436527638" - data['projects'][0]['date_modified'] = "1436527638" - del data['pagination'] + data["projects"][0]["date_created"] = "1436527638" + data["projects"][0]["date_modified"] = "1436527638" + del data["pagination"] expected_data = { "args": { "fork": None, @@ -818,50 +764,47 @@ class PagureFlaskApiProjecttests(tests.Modeltests): "tags": ["infra"], "username": "pingou", }, - "projects": [{ - "access_groups": { - "admin": [], - "commit": [], - "ticket": [] - }, - "access_users": { - "admin": [], - "commit": [], - "owner": ["pingou"], - "ticket": []}, - "close_status": [ - "Invalid", - "Insufficient data", - "Fixed", - "Duplicate"], - "custom_keys": [], - "date_created": "1436527638", - "date_modified": "1436527638", - "description": "test project #1", - "fullname": "test", - "url_path": "test", - "id": 1, - "milestones": {}, - "name": "test", - "namespace": None, - "parent": None, - "priorities": {}, - "tags": ["infra"], - "user": { - "fullname": "PY C", - "name": "pingou" + "projects": [ + { + "access_groups": {"admin": [], "commit": [], "ticket": []}, + "access_users": { + "admin": [], + "commit": [], + "owner": ["pingou"], + "ticket": [], + }, + "close_status": [ + "Invalid", + "Insufficient data", + "Fixed", + "Duplicate", + ], + "custom_keys": [], + "date_created": "1436527638", + "date_modified": "1436527638", + "description": "test project #1", + "fullname": "test", + "url_path": "test", + "id": 1, + "milestones": {}, + "name": "test", + "namespace": None, + "parent": None, + "priorities": {}, + "tags": ["infra"], + "user": {"fullname": "PY C", "name": "pingou"}, } - }], - "total_projects": 1 + ], + "total_projects": 1, } self.assertDictEqual(data, expected_data) - output = self.app.get('/api/0/projects?namespace=somenamespace') + output = self.app.get("/api/0/projects?namespace=somenamespace") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['projects'][0]['date_created'] = "1436527638" - data['projects'][0]['date_modified'] = "1436527638" - del data['pagination'] + data["projects"][0]["date_created"] = "1436527638" + data["projects"][0]["date_modified"] = "1436527638" + del data["pagination"] expected_data = { "args": { "fork": None, @@ -872,24 +815,22 @@ class PagureFlaskApiProjecttests(tests.Modeltests): "pattern": None, "short": False, "tags": [], - "username": None + "username": None, }, "projects": [ { - "access_groups": { - "admin": [], - "commit": [], - "ticket": []}, + "access_groups": {"admin": [], "commit": [], "ticket": []}, "access_users": { "admin": [], "commit": [], "owner": ["pingou"], - "ticket": []}, + "ticket": [], + }, "close_status": [ "Invalid", "Insufficient data", "Fixed", - "Duplicate" + "Duplicate", ], "custom_keys": [], "date_created": "1436527638", @@ -904,13 +845,10 @@ class PagureFlaskApiProjecttests(tests.Modeltests): "parent": None, "priorities": {}, "tags": [], - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, } ], - "total_projects": 1 + "total_projects": 1, } self.assertDictEqual(data, expected_data) @@ -919,52 +857,49 @@ class PagureFlaskApiProjecttests(tests.Modeltests): tests.create_projects(self.session) # Check before adding - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") self.assertEqual(repo.tags, []) # Adding a tag output = pagure.lib.query.update_tags( - self.session, repo, 'infra', 'pingou') - self.assertEqual(output, ['Project tagged with: infra']) + self.session, repo, "infra", "pingou" + ) + self.assertEqual(output, ["Project tagged with: infra"]) # Check after adding - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") self.assertEqual(len(repo.tags), 1) - self.assertEqual(repo.tags_text, ['infra']) + self.assertEqual(repo.tags_text, ["infra"]) # Check the API # Non-existing project - output = self.app.get('/api/0/random') + output = self.app.get("/api/0/random") self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - {'error_code': 'ENOPROJECT', 'error': 'Project not found'} + data, {"error_code": "ENOPROJECT", "error": "Project not found"} ) # Existing project - output = self.app.get('/api/0/test') + output = self.app.get("/api/0/test") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['date_created'] = "1436527638" - data['date_modified'] = "1436527638" - expected_data ={ - "access_groups": { - "admin": [], - "commit": [], - "ticket": [] - }, + data["date_created"] = "1436527638" + data["date_modified"] = "1436527638" + expected_data = { + "access_groups": {"admin": [], "commit": [], "ticket": []}, "access_users": { "admin": [], "commit": [], "owner": ["pingou"], - "ticket": []}, + "ticket": [], + }, "close_status": [ "Invalid", "Insufficient data", "Fixed", - "Duplicate" + "Duplicate", ], "custom_keys": [], "date_created": "1436527638", @@ -979,80 +914,80 @@ class PagureFlaskApiProjecttests(tests.Modeltests): "parent": None, "priorities": {}, "tags": ["infra"], - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, } self.assertDictEqual(data, expected_data) def test_api_project_group(self): """ Test the api_project method of the flask api. """ tests.create_projects(self.session) - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") # Adding a tag output = pagure.lib.query.update_tags( - self.session, repo, 'infra', 'pingou') - self.assertEqual(output, ['Project tagged with: infra']) + self.session, repo, "infra", "pingou" + ) + self.assertEqual(output, ["Project tagged with: infra"]) # Check after adding - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") self.assertEqual(len(repo.tags), 1) - self.assertEqual(repo.tags_text, ['infra']) + self.assertEqual(repo.tags_text, ["infra"]) # Add a group to the project msg = pagure.lib.query.add_group( self.session, - group_name='some_group', - display_name='Some Group', + group_name="some_group", + display_name="Some Group", description=None, - group_type='bar', - user='foo', + group_type="bar", + user="foo", is_admin=False, blacklist=[], ) self.session.commit() - project = pagure.lib.query.get_authorized_project(self.session, 'test') + project = pagure.lib.query.get_authorized_project(self.session, "test") group = pagure.lib.query.search_groups( - self.session, group_name='some_group') + self.session, group_name="some_group" + ) pagure.lib.query.add_group_to_project( self.session, project, - new_group='some_group', - user='pingou', - access='commit', + new_group="some_group", + user="pingou", + access="commit", create=False, - is_admin=True + is_admin=True, ) self.session.commit() # Check the API # Existing project - output = self.app.get('/api/0/test?expand_group=1') + output = self.app.get("/api/0/test?expand_group=1") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['date_created'] = "1436527638" - data['date_modified'] = "1436527638" - expected_data ={ + data["date_created"] = "1436527638" + data["date_modified"] = "1436527638" + expected_data = { "access_groups": { "admin": [], "commit": ["some_group"], - "ticket": [] + "ticket": [], }, "access_users": { "admin": [], "commit": [], "owner": ["pingou"], - "ticket": []}, + "ticket": [], + }, "close_status": [ "Invalid", "Insufficient data", "Fixed", - "Duplicate" + "Duplicate", ], "custom_keys": [], "date_created": "1436527638", @@ -1060,11 +995,7 @@ class PagureFlaskApiProjecttests(tests.Modeltests): "description": "test project #1", "fullname": "test", "url_path": "test", - "group_details": { - "some_group": [ - "foo" - ] - }, + "group_details": {"some_group": ["foo"]}, "id": 1, "milestones": {}, "name": "test", @@ -1072,10 +1003,7 @@ class PagureFlaskApiProjecttests(tests.Modeltests): "parent": None, "priorities": {}, "tags": ["infra"], - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, } self.assertDictEqual(data, expected_data) @@ -1084,42 +1012,40 @@ class PagureFlaskApiProjecttests(tests.Modeltests): group details while there are none associated. """ tests.create_projects(self.session) - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") # Adding a tag output = pagure.lib.query.update_tags( - self.session, repo, 'infra', 'pingou') - self.assertEqual(output, ['Project tagged with: infra']) + self.session, repo, "infra", "pingou" + ) + self.assertEqual(output, ["Project tagged with: infra"]) # Check after adding - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") self.assertEqual(len(repo.tags), 1) - self.assertEqual(repo.tags_text, ['infra']) + self.assertEqual(repo.tags_text, ["infra"]) # Check the API # Existing project - output = self.app.get('/api/0/test?expand_group=0') + output = self.app.get("/api/0/test?expand_group=0") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['date_created'] = "1436527638" - data['date_modified'] = "1436527638" - expected_data ={ - "access_groups": { - "admin": [], - "commit": [], - "ticket": [] - }, + data["date_created"] = "1436527638" + data["date_modified"] = "1436527638" + expected_data = { + "access_groups": {"admin": [], "commit": [], "ticket": []}, "access_users": { "admin": [], "commit": [], "owner": ["pingou"], - "ticket": []}, + "ticket": [], + }, "close_status": [ "Invalid", "Insufficient data", "Fixed", - "Duplicate" + "Duplicate", ], "custom_keys": [], "date_created": "1436527638", @@ -1134,10 +1060,7 @@ class PagureFlaskApiProjecttests(tests.Modeltests): "parent": None, "priorities": {}, "tags": ["infra"], - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, } self.assertDictEqual(data, expected_data) @@ -1145,12 +1068,12 @@ class PagureFlaskApiProjecttests(tests.Modeltests): """ Test the api_projects method of the flask api with pagination. """ tests.create_projects(self.session) - output = self.app.get('/api/0/projects?page=1') + output = self.app.get("/api/0/projects?page=1") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) for i in range(3): - data['projects'][i]['date_created'] = "1436527638" - data['projects'][i]['date_modified'] = "1436527638" + data["projects"][i]["date_created"] = "1436527638" + data["projects"][i]["date_modified"] = "1436527638" expected_data = { "args": { "fork": None, @@ -1161,32 +1084,29 @@ class PagureFlaskApiProjecttests(tests.Modeltests): "pattern": None, "short": False, "tags": [], - "username": None + "username": None, }, "pagination": { "next": None, "page": 1, "pages": 1, "per_page": 20, - "prev": None + "prev": None, }, "projects": [ { - "access_groups": { - "admin": [], - "commit": [], - "ticket": []}, + "access_groups": {"admin": [], "commit": [], "ticket": []}, "access_users": { "admin": [], "commit": [], "owner": ["pingou"], - "ticket": [] + "ticket": [], }, "close_status": [ "Invalid", "Insufficient data", "Fixed", - "Duplicate" + "Duplicate", ], "custom_keys": [], "date_created": "1436527638", @@ -1201,28 +1121,21 @@ class PagureFlaskApiProjecttests(tests.Modeltests): "parent": None, "priorities": {}, "tags": [], - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, }, { - "access_groups": { - "admin": [], - "commit": [], - "ticket": [] - }, + "access_groups": {"admin": [], "commit": [], "ticket": []}, "access_users": { "admin": [], "commit": [], "owner": ["pingou"], - "ticket": [] + "ticket": [], }, "close_status": [ "Invalid", "Insufficient data", "Fixed", - "Duplicate" + "Duplicate", ], "custom_keys": [], "date_created": "1436527638", @@ -1237,26 +1150,21 @@ class PagureFlaskApiProjecttests(tests.Modeltests): "parent": None, "priorities": {}, "tags": [], - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, }, { - "access_groups": { - "admin": [], - "commit": [], - "ticket": []}, + "access_groups": {"admin": [], "commit": [], "ticket": []}, "access_users": { "admin": [], "commit": [], "owner": ["pingou"], - "ticket": []}, + "ticket": [], + }, "close_status": [ "Invalid", "Insufficient data", "Fixed", - "Duplicate" + "Duplicate", ], "custom_keys": [], "date_created": "1436527638", @@ -1271,13 +1179,10 @@ class PagureFlaskApiProjecttests(tests.Modeltests): "parent": None, "priorities": {}, "tags": [], - "user": { - "fullname": "PY C", - "name": "pingou" - } - } + "user": {"fullname": "PY C", "name": "pingou"}, + }, ], - "total_projects": 3 + "total_projects": 3, } # Test URLs self.assertURLEqual( @@ -1295,11 +1200,11 @@ class PagureFlaskApiProjecttests(tests.Modeltests): the `per_page` argument set. """ tests.create_projects(self.session) - output = self.app.get('/api/0/projects?page=2&per_page=2') + output = self.app.get("/api/0/projects?page=2&per_page=2") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['projects'][0]['date_created'] = "1436527638" - data['projects'][0]['date_modified'] = "1436527638" + data["projects"][0]["date_created"] = "1436527638" + data["projects"][0]["date_modified"] = "1436527638" expected_data = { "args": { "fork": None, @@ -1310,32 +1215,23 @@ class PagureFlaskApiProjecttests(tests.Modeltests): "pattern": None, "short": False, "tags": [], - "username": None - }, - "pagination": { - "next": None, - "page": 2, - "pages": 2, - "per_page": 2, + "username": None, }, + "pagination": {"next": None, "page": 2, "pages": 2, "per_page": 2}, "projects": [ { - "access_groups": { - "admin": [], - "commit": [], - "ticket": [] - }, + "access_groups": {"admin": [], "commit": [], "ticket": []}, "access_users": { "admin": [], "commit": [], "owner": ["pingou"], - "ticket": [] + "ticket": [], }, "close_status": [ "Invalid", "Insufficient data", "Fixed", - "Duplicate" + "Duplicate", ], "custom_keys": [], "date_created": "1436527638", @@ -1350,13 +1246,10 @@ class PagureFlaskApiProjecttests(tests.Modeltests): "parent": None, "priorities": {}, "tags": [], - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, } ], - "total_projects": 3 + "total_projects": 3, } self.assertURLEqual( data["pagination"].pop("first"), @@ -1377,7 +1270,7 @@ class PagureFlaskApiProjecttests(tests.Modeltests): value is entered. """ tests.create_projects(self.session) - output = self.app.get('/api/0/projects?page=-3') + output = self.app.get("/api/0/projects?page=-3") self.assertEqual(output.status_code, 400) def test_api_projects_pagination_invalid_page_str(self): @@ -1385,7 +1278,7 @@ class PagureFlaskApiProjecttests(tests.Modeltests): for the page value is entered. """ tests.create_projects(self.session) - output = self.app.get('/api/0/projects?page=abcd') + output = self.app.get("/api/0/projects?page=abcd") self.assertEqual(output.status_code, 400) def test_api_projects_pagination_invalid_per_page_too_low(self): @@ -1393,29 +1286,31 @@ class PagureFlaskApiProjecttests(tests.Modeltests): value is below 1. """ tests.create_projects(self.session) - output = self.app.get('/api/0/projects?page=1&per_page=0') + output = self.app.get("/api/0/projects?page=1&per_page=0") self.assertEqual(output.status_code, 400) error = json.loads(output.get_data(as_text=True)) self.assertEqual( - error['error'], 'The per_page value must be between 1 and 100') + error["error"], "The per_page value must be between 1 and 100" + ) def test_api_projects_pagination_invalid_per_page_too_high(self): """ Test the api_projects method of the flask api when a per_page value is above 100. """ tests.create_projects(self.session) - output = self.app.get('/api/0/projects?page=1&per_page=101') + output = self.app.get("/api/0/projects?page=1&per_page=101") self.assertEqual(output.status_code, 400) error = json.loads(output.get_data(as_text=True)) self.assertEqual( - error['error'], 'The per_page value must be between 1 and 100') + error["error"], "The per_page value must be between 1 and 100" + ) def test_api_projects_pagination_invalid_per_page_str(self): """ Test the api_projects method of the flask api when an invalid type for the per_page value is entered. """ tests.create_projects(self.session) - output = self.app.get('/api/0/projects?page=1&per_page=abcd') + output = self.app.get("/api/0/projects?page=1&per_page=abcd") self.assertEqual(output.status_code, 400) def test_api_projects_pagination_beyond_last_page(self): @@ -1423,7 +1318,7 @@ class PagureFlaskApiProjecttests(tests.Modeltests): that is larger than the last page is entered. """ tests.create_projects(self.session) - output = self.app.get('/api/0/projects?page=99999') + output = self.app.get("/api/0/projects?page=99999") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertURLEqual( @@ -1441,26 +1336,26 @@ class PagureFlaskApiProjecttests(tests.Modeltests): self.assertEqual( data, { - "args": { - "fork": None, - "namespace": None, - "owner": None, - "page": 99999, - "pattern": None, - "per_page": 20, - "short": False, - "tags": [], - "username": None - }, - "pagination": { - "next": None, - "page": 99999, - "pages": 1, - "per_page": 20, - }, - "projects": [], - "total_projects": 3 - } + "args": { + "fork": None, + "namespace": None, + "owner": None, + "page": 99999, + "pattern": None, + "per_page": 20, + "short": False, + "tags": [], + "username": None, + }, + "pagination": { + "next": None, + "page": 99999, + "pages": 1, + "per_page": 20, + }, + "projects": [], + "total_projects": 3, + }, ) def test_api_modify_project_main_admin(self): @@ -1468,35 +1363,29 @@ class PagureFlaskApiProjecttests(tests.Modeltests): request is to change the main_admin of the project. """ tests.create_projects(self.session) tests.create_tokens(self.session, project_id=None) - tests.create_tokens_acl(self.session, 'aaabbbcccddd', 'modify_project') - headers = {'Authorization': 'token aaabbbcccddd'} + tests.create_tokens_acl(self.session, "aaabbbcccddd", "modify_project") + headers = {"Authorization": "token aaabbbcccddd"} output = self.app.patch( - '/api/0/test', headers=headers, - data={'main_admin': 'foo'}) + "/api/0/test", headers=headers, data={"main_admin": "foo"} + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['date_created'] = '1496338274' - data['date_modified'] = '1496338274' + data["date_created"] = "1496338274" + data["date_modified"] = "1496338274" expected_output = { - "access_groups": { - "admin": [], - "commit": [], - "ticket": [] - }, + "access_groups": {"admin": [], "commit": [], "ticket": []}, "access_users": { "admin": [], "commit": [], - "owner": [ - "foo" - ], - "ticket": [] + "owner": ["foo"], + "ticket": [], }, "close_status": [ "Invalid", "Insufficient data", "Fixed", - "Duplicate" + "Duplicate", ], "custom_keys": [], "date_created": "1496338274", @@ -1513,12 +1402,10 @@ class PagureFlaskApiProjecttests(tests.Modeltests): "tags": [], "user": { "default_email": "foo@bar.com", - "emails": [ - "foo@bar.com" - ], + "emails": ["foo@bar.com"], "fullname": "foo bar", - "name": "foo" - } + "name": "foo", + }, } self.assertEqual(data, expected_output) @@ -1528,37 +1415,31 @@ class PagureFlaskApiProjecttests(tests.Modeltests): is true. """ tests.create_projects(self.session) tests.create_tokens(self.session, project_id=None) - tests.create_tokens_acl(self.session, 'aaabbbcccddd', 'modify_project') - headers = {'Authorization': 'token aaabbbcccddd'} + tests.create_tokens_acl(self.session, "aaabbbcccddd", "modify_project") + headers = {"Authorization": "token aaabbbcccddd"} output = self.app.patch( - '/api/0/test', headers=headers, - data={'main_admin': 'foo', 'retain_access': True}) + "/api/0/test", + headers=headers, + data={"main_admin": "foo", "retain_access": True}, + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['date_created'] = '1496338274' - data['date_modified'] = '1496338274' + data["date_created"] = "1496338274" + data["date_modified"] = "1496338274" expected_output = { - "access_groups": { - "admin": [], - "commit": [], - "ticket": [] - }, + "access_groups": {"admin": [], "commit": [], "ticket": []}, "access_users": { - "admin": [ - "pingou" - ], + "admin": ["pingou"], "commit": [], - "owner": [ - "foo" - ], - "ticket": [] + "owner": ["foo"], + "ticket": [], }, "close_status": [ "Invalid", "Insufficient data", "Fixed", - "Duplicate" + "Duplicate", ], "custom_keys": [], "date_created": "1496338274", @@ -1575,12 +1456,10 @@ class PagureFlaskApiProjecttests(tests.Modeltests): "tags": [], "user": { "default_email": "foo@bar.com", - "emails": [ - "foo@bar.com" - ], + "emails": ["foo@bar.com"], "fullname": "foo bar", - "name": "foo" - } + "name": "foo", + }, } self.assertEqual(data, expected_output) @@ -1590,46 +1469,41 @@ class PagureFlaskApiProjecttests(tests.Modeltests): is true and the user becoming the main_admin already has access. """ tests.create_projects(self.session) tests.create_tokens(self.session, project_id=None) - tests.create_tokens_acl(self.session, 'aaabbbcccddd', 'modify_project') - headers = {'Authorization': 'token aaabbbcccddd'} + tests.create_tokens_acl(self.session, "aaabbbcccddd", "modify_project") + headers = {"Authorization": "token aaabbbcccddd"} - project = pagure.lib.query._get_project(self.session, 'test') + project = pagure.lib.query._get_project(self.session, "test") pagure.lib.query.add_user_to_project( - self.session, project, - new_user='foo', - user='pingou', - access='commit' + self.session, + project, + new_user="foo", + user="pingou", + access="commit", ) self.session.commit() output = self.app.patch( - '/api/0/test', headers=headers, - data={'main_admin': 'foo', 'retain_access': True}) + "/api/0/test", + headers=headers, + data={"main_admin": "foo", "retain_access": True}, + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['date_created'] = '1496338274' - data['date_modified'] = '1496338274' + data["date_created"] = "1496338274" + data["date_modified"] = "1496338274" expected_output = { - "access_groups": { - "admin": [], - "commit": [], - "ticket": [] - }, + "access_groups": {"admin": [], "commit": [], "ticket": []}, "access_users": { - "admin": [ - "pingou" - ], + "admin": ["pingou"], "commit": [], - "owner": [ - "foo" - ], - "ticket": [] + "owner": ["foo"], + "ticket": [], }, "close_status": [ "Invalid", "Insufficient data", "Fixed", - "Duplicate" + "Duplicate", ], "custom_keys": [], "date_created": "1496338274", @@ -1646,12 +1520,10 @@ class PagureFlaskApiProjecttests(tests.Modeltests): "tags": [], "user": { "default_email": "foo@bar.com", - "emails": [ - "foo@bar.com" - ], + "emails": ["foo@bar.com"], "fullname": "foo bar", - "name": "foo" - } + "name": "foo", + }, } self.assertEqual(data, expected_output) @@ -1660,36 +1532,34 @@ class PagureFlaskApiProjecttests(tests.Modeltests): request is to change the main_admin of the project using JSON. """ tests.create_projects(self.session) tests.create_tokens(self.session, project_id=None) - tests.create_tokens_acl(self.session, 'aaabbbcccddd', 'modify_project') - headers = {'Authorization': 'token aaabbbcccddd', - 'Content-Type': 'application/json'} + tests.create_tokens_acl(self.session, "aaabbbcccddd", "modify_project") + headers = { + "Authorization": "token aaabbbcccddd", + "Content-Type": "application/json", + } output = self.app.patch( - '/api/0/test', headers=headers, - data=json.dumps({'main_admin': 'foo'})) + "/api/0/test", + headers=headers, + data=json.dumps({"main_admin": "foo"}), + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['date_created'] = '1496338274' - data['date_modified'] = '1496338274' + data["date_created"] = "1496338274" + data["date_modified"] = "1496338274" expected_output = { - "access_groups": { - "admin": [], - "commit": [], - "ticket": [] - }, + "access_groups": {"admin": [], "commit": [], "ticket": []}, "access_users": { "admin": [], "commit": [], - "owner": [ - "foo" - ], - "ticket": [] + "owner": ["foo"], + "ticket": [], }, "close_status": [ "Invalid", "Insufficient data", "Fixed", - "Duplicate" + "Duplicate", ], "custom_keys": [], "date_created": "1496338274", @@ -1706,57 +1576,48 @@ class PagureFlaskApiProjecttests(tests.Modeltests): "tags": [], "user": { "default_email": "foo@bar.com", - "emails": [ - "foo@bar.com" - ], + "emails": ["foo@bar.com"], "fullname": "foo bar", - "name": "foo" - } + "name": "foo", + }, } self.assertEqual(data, expected_output) - @patch.dict('pagure.config.config', {'PAGURE_ADMIN_USERS': 'foo'}) + @patch.dict("pagure.config.config", {"PAGURE_ADMIN_USERS": "foo"}) def test_api_modify_project_main_admin_as_site_admin(self): """ Test the api_modify_project method of the flask api when the request is to change the main_admin of the project and the user is a Pagure site admin. """ tests.create_projects(self.session) tests.create_tokens(self.session, user_id=2, project_id=None) - tests.create_tokens_acl(self.session, 'aaabbbcccddd', 'modify_project') - headers = {'Authorization': 'token aaabbbcccddd'} + tests.create_tokens_acl(self.session, "aaabbbcccddd", "modify_project") + headers = {"Authorization": "token aaabbbcccddd"} # date before: - project = pagure.lib.query.get_authorized_project( - self.session, 'test') + project = pagure.lib.query.get_authorized_project(self.session, "test") date_before = project.date_modified self.assertIsNotNone(date_before) output = self.app.patch( - '/api/0/test', headers=headers, - data={'main_admin': 'foo'}) + "/api/0/test", headers=headers, data={"main_admin": "foo"} + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['date_created'] = '1496338274' - data['date_modified'] = '1496338274' + data["date_created"] = "1496338274" + data["date_modified"] = "1496338274" expected_output = { - "access_groups": { - "admin": [], - "commit": [], - "ticket": [] - }, + "access_groups": {"admin": [], "commit": [], "ticket": []}, "access_users": { "admin": [], "commit": [], - "owner": [ - "foo" - ], - "ticket": [] + "owner": ["foo"], + "ticket": [], }, "close_status": [ "Invalid", "Insufficient data", "Fixed", - "Duplicate" + "Duplicate", ], "custom_keys": [], "date_created": "1496338274", @@ -1773,19 +1634,16 @@ class PagureFlaskApiProjecttests(tests.Modeltests): "tags": [], "user": { "default_email": "foo@bar.com", - "emails": [ - "foo@bar.com" - ], + "emails": ["foo@bar.com"], "fullname": "foo bar", - "name": "foo" - } + "name": "foo", + }, } self.assertEqual(data, expected_output) # date after: self.session = pagure.lib.query.create_session(self.dbpath) - project = pagure.lib.query.get_authorized_project( - self.session, 'test') + project = pagure.lib.query.get_authorized_project(self.session, "test") self.assertNotEqual(date_before, project.date_modified) def test_api_modify_project_main_admin_not_main_admin(self): @@ -1795,27 +1653,27 @@ class PagureFlaskApiProjecttests(tests.Modeltests): """ tests.create_projects(self.session) project_user = pagure.lib.query.model.ProjectUser( - project_id=1, - user_id=2, - access='admin', + project_id=1, user_id=2, access="admin" ) self.session.add(project_user) self.session.commit() tests.create_tokens(self.session, project_id=None, user_id=2) - tests.create_tokens_acl(self.session, 'aaabbbcccddd', 'modify_project') - headers = {'Authorization': 'token aaabbbcccddd'} + tests.create_tokens_acl(self.session, "aaabbbcccddd", "modify_project") + headers = {"Authorization": "token aaabbbcccddd"} output = self.app.patch( - '/api/0/test', headers=headers, - data={'main_admin': 'foo'}) + "/api/0/test", headers=headers, data={"main_admin": "foo"} + ) self.assertEqual(output.status_code, 401) expected_error = { - 'error': ('Only the main admin can set the main admin of a ' - 'project'), - 'error_code': 'ENOTMAINADMIN' + "error": ( + "Only the main admin can set the main admin of a " "project" + ), + "error_code": "ENOTMAINADMIN", } self.assertEqual( - json.loads(output.get_data(as_text=True)), expected_error) + json.loads(output.get_data(as_text=True)), expected_error + ) def test_api_modify_project_not_admin(self): """ Test the api_modify_project method of the flask api when the @@ -1823,19 +1681,20 @@ class PagureFlaskApiProjecttests(tests.Modeltests): """ tests.create_projects(self.session) tests.create_tokens(self.session, project_id=None, user_id=2) - tests.create_tokens_acl(self.session, 'aaabbbcccddd', 'modify_project') - headers = {'Authorization': 'token aaabbbcccddd'} + tests.create_tokens_acl(self.session, "aaabbbcccddd", "modify_project") + headers = {"Authorization": "token aaabbbcccddd"} output = self.app.patch( - '/api/0/test', headers=headers, - data={'main_admin': 'foo'}) + "/api/0/test", headers=headers, data={"main_admin": "foo"} + ) self.assertEqual(output.status_code, 401) expected_error = { - 'error': 'You are not allowed to modify this project', - 'error_code': 'EMODIFYPROJECTNOTALLOWED' + "error": "You are not allowed to modify this project", + "error_code": "EMODIFYPROJECTNOTALLOWED", } self.assertEqual( - json.loads(output.get_data(as_text=True)), expected_error) + json.loads(output.get_data(as_text=True)), expected_error + ) def test_api_modify_project_invalid_request(self): """ Test the api_modify_project method of the flask api when the @@ -1843,19 +1702,18 @@ class PagureFlaskApiProjecttests(tests.Modeltests): """ tests.create_projects(self.session) tests.create_tokens(self.session, project_id=None) - tests.create_tokens_acl(self.session, 'aaabbbcccddd', 'modify_project') - headers = {'Authorization': 'token aaabbbcccddd'} + tests.create_tokens_acl(self.session, "aaabbbcccddd", "modify_project") + headers = {"Authorization": "token aaabbbcccddd"} - output = self.app.patch( - '/api/0/test', headers=headers, - data='invalid') + output = self.app.patch("/api/0/test", headers=headers, data="invalid") self.assertEqual(output.status_code, 400) expected_error = { - 'error': 'Invalid or incomplete input submitted', - 'error_code': 'EINVALIDREQ' + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", } self.assertEqual( - json.loads(output.get_data(as_text=True)), expected_error) + json.loads(output.get_data(as_text=True)), expected_error + ) def test_api_modify_project_invalid_keys(self): """ Test the api_modify_project method of the flask api when the @@ -1863,19 +1721,20 @@ class PagureFlaskApiProjecttests(tests.Modeltests): """ tests.create_projects(self.session) tests.create_tokens(self.session, project_id=None) - tests.create_tokens_acl(self.session, 'aaabbbcccddd', 'modify_project') - headers = {'Authorization': 'token aaabbbcccddd'} + tests.create_tokens_acl(self.session, "aaabbbcccddd", "modify_project") + headers = {"Authorization": "token aaabbbcccddd"} output = self.app.patch( - '/api/0/test', headers=headers, - data={'invalid': 'invalid'}) + "/api/0/test", headers=headers, data={"invalid": "invalid"} + ) self.assertEqual(output.status_code, 400) expected_error = { - 'error': 'Invalid or incomplete input submitted', - 'error_code': 'EINVALIDREQ' + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", } self.assertEqual( - json.loads(output.get_data(as_text=True)), expected_error) + json.loads(output.get_data(as_text=True)), expected_error + ) def test_api_modify_project_invalid_new_main_admin(self): """ Test the api_modify_project method of the flask api when the @@ -1884,567 +1743,546 @@ class PagureFlaskApiProjecttests(tests.Modeltests): """ tests.create_projects(self.session) tests.create_tokens(self.session, project_id=None) - tests.create_tokens_acl(self.session, 'aaabbbcccddd', 'modify_project') - headers = {'Authorization': 'token aaabbbcccddd'} + tests.create_tokens_acl(self.session, "aaabbbcccddd", "modify_project") + headers = {"Authorization": "token aaabbbcccddd"} output = self.app.patch( - '/api/0/test', headers=headers, - data={'main_admin': 'tbrady'}) + "/api/0/test", headers=headers, data={"main_admin": "tbrady"} + ) self.assertEqual(output.status_code, 400) expected_error = { - 'error': 'No such user found', - 'error_code': 'ENOUSER' + "error": "No such user found", + "error_code": "ENOUSER", } self.assertEqual( - json.loads(output.get_data(as_text=True)), expected_error) + json.loads(output.get_data(as_text=True)), expected_error + ) def test_api_project_watchers(self): """ Test the api_project_watchers method of the flask api. """ tests.create_projects(self.session) # The user is not logged in and the owner is watching issues implicitly - output = self.app.get('/api/0/test/watchers') + output = self.app.get("/api/0/test/watchers") self.assertEqual(output.status_code, 200) expected_data = { "total_watchers": 1, - "watchers": { - "pingou": [ - "issues" - ] - } + "watchers": {"pingou": ["issues"]}, } - self.assertDictEqual(json.loads(output.get_data(as_text=True)), expected_data) + self.assertDictEqual( + json.loads(output.get_data(as_text=True)), expected_data + ) - user = tests.FakeUser(username='pingou') + user = tests.FakeUser(username="pingou") with tests.user_set(self.app.application, user): # Non-existing project - output = self.app.get('/api/0/random/watchers') + output = self.app.get("/api/0/random/watchers") self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, - {'error_code': 'ENOPROJECT', 'error': 'Project not found'} + {"error_code": "ENOPROJECT", "error": "Project not found"}, ) # The owner is watching issues implicitly - output = self.app.get('/api/0/test/watchers') + output = self.app.get("/api/0/test/watchers") self.assertEqual(output.status_code, 200) expected_data = { "total_watchers": 1, - "watchers": { - "pingou": [ - "issues" - ] - } + "watchers": {"pingou": ["issues"]}, } - self.assertDictEqual(json.loads(output.get_data(as_text=True)), expected_data) + self.assertDictEqual( + json.loads(output.get_data(as_text=True)), expected_data + ) - project = pagure.lib.query.get_authorized_project(self.session, 'test') + project = pagure.lib.query.get_authorized_project( + self.session, "test" + ) # The owner is watching issues and commits explicitly pagure.lib.query.update_watch_status( - self.session, project, 'pingou', '3') + self.session, project, "pingou", "3" + ) self.session.commit() - output = self.app.get('/api/0/test/watchers') + output = self.app.get("/api/0/test/watchers") self.assertEqual(output.status_code, 200) expected_data = { "total_watchers": 1, - "watchers": { - "pingou": [ - "issues", - "commits" - ] - } + "watchers": {"pingou": ["issues", "commits"]}, } - self.assertDictEqual(json.loads(output.get_data(as_text=True)), expected_data) + self.assertDictEqual( + json.loads(output.get_data(as_text=True)), expected_data + ) # The owner is watching issues explicitly pagure.lib.query.update_watch_status( - self.session, project, 'pingou', '1') + self.session, project, "pingou", "1" + ) self.session.commit() - output = self.app.get('/api/0/test/watchers') + output = self.app.get("/api/0/test/watchers") self.assertEqual(output.status_code, 200) expected_data = { "total_watchers": 1, - "watchers": { - "pingou": [ - "issues" - ] - } + "watchers": {"pingou": ["issues"]}, } - self.assertDictEqual(json.loads(output.get_data(as_text=True)), expected_data) + self.assertDictEqual( + json.loads(output.get_data(as_text=True)), expected_data + ) # The owner is watching commits explicitly pagure.lib.query.update_watch_status( - self.session, project, 'pingou', '2') + self.session, project, "pingou", "2" + ) self.session.commit() - output = self.app.get('/api/0/test/watchers') + output = self.app.get("/api/0/test/watchers") self.assertEqual(output.status_code, 200) expected_data = { "total_watchers": 1, - "watchers": { - "pingou": [ - "commits" - ] - } + "watchers": {"pingou": ["commits"]}, } - self.assertDictEqual(json.loads(output.get_data(as_text=True)), expected_data) + self.assertDictEqual( + json.loads(output.get_data(as_text=True)), expected_data + ) # The owner is watching commits explicitly and foo is watching # issues implicitly project_user = pagure.lib.model.ProjectUser( - project_id=project.id, - user_id=2, - access='commit', + project_id=project.id, user_id=2, access="commit" ) pagure.lib.query.update_watch_status( - self.session, project, 'pingou', '2') + self.session, project, "pingou", "2" + ) self.session.add(project_user) self.session.commit() - output = self.app.get('/api/0/test/watchers') + output = self.app.get("/api/0/test/watchers") self.assertEqual(output.status_code, 200) expected_data = { "total_watchers": 2, - "watchers": { - "foo": ["issues"], - "pingou": ["commits"] - } + "watchers": {"foo": ["issues"], "pingou": ["commits"]}, } - self.assertDictEqual(json.loads(output.get_data(as_text=True)), expected_data) + self.assertDictEqual( + json.loads(output.get_data(as_text=True)), expected_data + ) # The owner and foo are watching issues implicitly pagure.lib.query.update_watch_status( - self.session, project, 'pingou', '-1') + self.session, project, "pingou", "-1" + ) self.session.commit() - output = self.app.get('/api/0/test/watchers') + output = self.app.get("/api/0/test/watchers") self.assertEqual(output.status_code, 200) expected_data = { "total_watchers": 2, - "watchers": { - "foo": ["issues"], - "pingou": ["issues"] - } + "watchers": {"foo": ["issues"], "pingou": ["issues"]}, } - self.assertDictEqual(json.loads(output.get_data(as_text=True)), expected_data) + self.assertDictEqual( + json.loads(output.get_data(as_text=True)), expected_data + ) # The owner and foo through group membership are watching issues # implicitly pagure.lib.query.update_watch_status( - self.session, project, 'pingou', '-1') - project_membership = self.session.query( - pagure.lib.model.ProjectUser).filter_by( - user_id=2, project_id=project.id).one() + self.session, project, "pingou", "-1" + ) + project_membership = ( + self.session.query(pagure.lib.model.ProjectUser) + .filter_by(user_id=2, project_id=project.id) + .one() + ) self.session.delete(project_membership) self.session.commit() msg = pagure.lib.query.add_group( self.session, - group_name='some_group', - display_name='Some Group', + group_name="some_group", + display_name="Some Group", description=None, - group_type='bar', - user='pingou', + group_type="bar", + user="pingou", is_admin=False, blacklist=[], ) self.session.commit() - project = pagure.lib.query.get_authorized_project(self.session, 'test') + project = pagure.lib.query.get_authorized_project( + self.session, "test" + ) group = pagure.lib.query.search_groups( - self.session, group_name='some_group') + self.session, group_name="some_group" + ) pagure.lib.query.add_user_to_group( - self.session, 'foo', group, 'pingou', False) + self.session, "foo", group, "pingou", False + ) pagure.lib.query.add_group_to_project( self.session, project, - new_group='some_group', - user='pingou', - access='commit', + new_group="some_group", + user="pingou", + access="commit", create=False, - is_admin=True + is_admin=True, ) self.session.commit() - output = self.app.get('/api/0/test/watchers') + output = self.app.get("/api/0/test/watchers") self.assertEqual(output.status_code, 200) expected_data = { "total_watchers": 2, - "watchers": { - "@some_group": ["issues"], - "pingou": ["issues"] - } + "watchers": {"@some_group": ["issues"], "pingou": ["issues"]}, } - self.assertDictEqual(json.loads(output.get_data(as_text=True)), expected_data) + self.assertDictEqual( + json.loads(output.get_data(as_text=True)), expected_data + ) # The owner is watching issues implicitly and foo will be watching # commits explicitly but is in a group with commit access pagure.lib.query.update_watch_status( - self.session, project, 'pingou', '-1') + self.session, project, "pingou", "-1" + ) pagure.lib.query.update_watch_status( - self.session, project, 'foo', '2') + self.session, project, "foo", "2" + ) self.session.commit() - output = self.app.get('/api/0/test/watchers') + output = self.app.get("/api/0/test/watchers") self.assertEqual(output.status_code, 200) expected_data = { "total_watchers": 3, "watchers": { "@some_group": ["issues"], "foo": ["commits"], - "pingou": ["issues"] - } + "pingou": ["issues"], + }, } - self.assertDictEqual(json.loads(output.get_data(as_text=True)), expected_data) + self.assertDictEqual( + json.loads(output.get_data(as_text=True)), expected_data + ) def test_api_new_project(self): """ Test the api_new_project method of the flask api. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'tickets')) + tests.create_projects_git(os.path.join(self.path, "tickets")) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token foo_token'} + headers = {"Authorization": "token foo_token"} # Invalid token - output = self.app.post('/api/0/new', headers=headers) + output = self.app.post("/api/0/new", headers=headers) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(sorted(data.keys()), [ - 'error', 'error_code', "errors"]) self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.value, data['error']) - self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.name, data['error_code']) + sorted(data.keys()), ["error", "error_code", "errors"] + ) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) self.assertEqual( - data['errors'], "Missing ACLs: create_project") + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) + self.assertEqual(data["errors"], "Missing ACLs: create_project") - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # No input - output = self.app.post('/api/0/new', headers=headers) + output = self.app.post("/api/0/new", headers=headers) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - "error": "Invalid or incomplete input submitted", - "error_code": "EINVALIDREQ", - "errors": { - "name": ["This field is required."], - "description": ["This field is required."] - } - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": { + "name": ["This field is required."], + "description": ["This field is required."], + }, + }, ) - data = { - 'name': 'test', - } + data = {"name": "test"} # Incomplete request - output = self.app.post( - '/api/0/new', data=data, headers=headers) + output = self.app.post("/api/0/new", data=data, headers=headers) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - "error": "Invalid or incomplete input submitted", - "error_code": "EINVALIDREQ", - "errors": {"description": ["This field is required."]} - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": {"description": ["This field is required."]}, + }, ) - data = { - 'name': 'test', - 'description': 'Just a small test project', - } + data = {"name": "test", "description": "Just a small test project"} # Valid request but repo already exists - output = self.app.post( - '/api/0/new/', data=data, headers=headers) + output = self.app.post("/api/0/new/", data=data, headers=headers) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - "error": "It is not possible to create the repo \"test\"", - "error_code": "ENOCODE" - } + "error": 'It is not possible to create the repo "test"', + "error_code": "ENOCODE", + }, ) data = { - 'name': 'api1', - 'description': 'Mighty mighty description', - 'avatar_email': 123 + "name": "api1", + "description": "Mighty mighty description", + "avatar_email": 123, } # invalid avatar_email - number - output = self.app.post( - '/api/0/new/', data=data, headers=headers) + output = self.app.post("/api/0/new/", data=data, headers=headers) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual(data, - {"error": "Invalid or incomplete input submitted", - "error_code": "EINVALIDREQ", - "errors": - {"avatar_email": ['avatar_email must be an email']} - } + self.assertDictEqual( + data, + { + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": {"avatar_email": ["avatar_email must be an email"]}, + }, ) data = { - 'name': 'api1', - 'description': 'Mighty mighty description', - 'avatar_email': [1,2,3] + "name": "api1", + "description": "Mighty mighty description", + "avatar_email": [1, 2, 3], } # invalid avatar_email - list - output = self.app.post( - '/api/0/new/', data=data, headers=headers) + output = self.app.post("/api/0/new/", data=data, headers=headers) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual(data, - {"error": "Invalid or incomplete input submitted", - "error_code": "EINVALIDREQ", - "errors": - {"avatar_email": ['avatar_email must be an email']} - } + self.assertDictEqual( + data, + { + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": {"avatar_email": ["avatar_email must be an email"]}, + }, ) data = { - 'name': 'api1', - 'description': 'Mighty mighty description', - 'avatar_email': True + "name": "api1", + "description": "Mighty mighty description", + "avatar_email": True, } # invalid avatar_email - boolean - output = self.app.post( - '/api/0/new/', data=data, headers=headers) + output = self.app.post("/api/0/new/", data=data, headers=headers) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual(data, - {"error": "Invalid or incomplete input submitted", - "error_code": "EINVALIDREQ", - "errors": - {"avatar_email": ['avatar_email must be an email']} - } + self.assertDictEqual( + data, + { + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": {"avatar_email": ["avatar_email must be an email"]}, + }, ) data = { - 'name': 'api1', - 'description': 'Mighty mighty description', - 'avatar_email': 'mighty@email.com' + "name": "api1", + "description": "Mighty mighty description", + "avatar_email": "mighty@email.com", } # valid avatar_email - output = self.app.post( - '/api/0/new/', data=data, headers=headers) + output = self.app.post("/api/0/new/", data=data, headers=headers) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'Project "api1" created'}) + self.assertDictEqual(data, {"message": 'Project "api1" created'}) data = { - 'name': 'test_42', - 'description': 'Just another small test project', + "name": "test_42", + "description": "Just another small test project", } # Valid request - output = self.app.post( - '/api/0/new/', data=data, headers=headers) + output = self.app.post("/api/0/new/", data=data, headers=headers) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'Project "test_42" created'} - ) - - @patch.dict('pagure.config.config', {'PAGURE_ADMIN_USERS': ['pingou'], - 'ALLOW_ADMIN_IGNORE_EXISTING_REPOS': True}) + self.assertDictEqual(data, {"message": 'Project "test_42" created'}) + + @patch.dict( + "pagure.config.config", + { + "PAGURE_ADMIN_USERS": ["pingou"], + "ALLOW_ADMIN_IGNORE_EXISTING_REPOS": True, + }, + ) def test_adopt_repos(self): """ Test the new_project endpoint with existing git repo. """ # Before projects = pagure.lib.query.search_projects(self.session) self.assertEqual(len(projects), 0) - tests.create_projects_git(os.path.join(self.path, 'repos'), bare=True) - tests.add_content_git_repo(os.path.join(self.path, 'repos', 'test.git')) + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) + tests.add_content_git_repo( + os.path.join(self.path, "repos", "test.git") + ) item = pagure.lib.model.Token( - id='aaabbbcccddd', + id="aaabbbcccddd", user_id=1, project_id=None, - expiration=datetime.datetime.utcnow() + datetime.timedelta(days=10) + expiration=datetime.datetime.utcnow() + + datetime.timedelta(days=10), ) self.session.add(item) self.session.commit() tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} - user = tests.FakeUser(username='pingou') + user = tests.FakeUser(username="pingou") with tests.user_set(self.app.application, user): - input_data = { - 'name': 'test', - 'description': 'Project #1', - } + input_data = {"name": "test", "description": "Project #1"} # Valid request output = self.app.post( - '/api/0/new/', data=input_data, headers=headers) + "/api/0/new/", data=input_data, headers=headers + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - 'error': 'The main repo test.git already exists', - 'error_code': 'ENOCODE' - } + "error": "The main repo test.git already exists", + "error_code": "ENOCODE", + }, ) - input_data['ignore_existing_repos'] = 'y' + input_data["ignore_existing_repos"] = "y" # Valid request output = self.app.post( - '/api/0/new/', data=input_data, headers=headers) + "/api/0/new/", data=input_data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'Project "test" created'} - ) + self.assertDictEqual(data, {"message": 'Project "test" created'}) - @patch.dict('pagure.config.config', {'PRIVATE_PROJECTS': True}) + @patch.dict("pagure.config.config", {"PRIVATE_PROJECTS": True}) def test_api_new_project_private(self): """ Test the api_new_project method of the flask api to create a private project. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'tickets')) + tests.create_projects_git(os.path.join(self.path, "tickets")) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'name': 'test', - 'description': 'Just a small test project', - 'private': True, + "name": "test", + "description": "Just a small test project", + "private": True, } # Valid request - output = self.app.post( - '/api/0/new/', data=data, headers=headers) + output = self.app.post("/api/0/new/", data=data, headers=headers) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - {'message': 'Project "pingou/test" created'} + data, {"message": 'Project "pingou/test" created'} ) def test_api_new_project_user_token(self): """ Test the api_new_project method of the flask api. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'tickets')) + tests.create_projects_git(os.path.join(self.path, "tickets")) tests.create_tokens(self.session, project_id=None) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token foo_token'} + headers = {"Authorization": "token foo_token"} # Invalid token - output = self.app.post('/api/0/new', headers=headers) + output = self.app.post("/api/0/new", headers=headers) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(sorted(data.keys()), [ - 'error', 'error_code', "errors"]) - self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.value, data['error']) self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.name, data['error_code']) + sorted(data.keys()), ["error", "error_code", "errors"] + ) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) self.assertEqual( - data['errors'], "Missing ACLs: create_project") + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) + self.assertEqual(data["errors"], "Missing ACLs: create_project") - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # No input - output = self.app.post('/api/0/new', headers=headers) + output = self.app.post("/api/0/new", headers=headers) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - "error": "Invalid or incomplete input submitted", - "error_code": "EINVALIDREQ", - "errors": { - "name": ["This field is required."], - "description": ["This field is required."] - } - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": { + "name": ["This field is required."], + "description": ["This field is required."], + }, + }, ) - data = { - 'name': 'test', - } + data = {"name": "test"} # Incomplete request - output = self.app.post( - '/api/0/new', data=data, headers=headers) + output = self.app.post("/api/0/new", data=data, headers=headers) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - "error": "Invalid or incomplete input submitted", - "error_code": "EINVALIDREQ", - "errors": {"description": ["This field is required."]} - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": {"description": ["This field is required."]}, + }, ) - data = { - 'name': 'test', - 'description': 'Just a small test project', - } + data = {"name": "test", "description": "Just a small test project"} # Valid request but repo already exists - output = self.app.post( - '/api/0/new/', data=data, headers=headers) + output = self.app.post("/api/0/new/", data=data, headers=headers) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - "error": "It is not possible to create the repo \"test\"", - "error_code": "ENOCODE" - } + "error": 'It is not possible to create the repo "test"', + "error_code": "ENOCODE", + }, ) data = { - 'name': 'test_42', - 'description': 'Just another small test project', + "name": "test_42", + "description": "Just another small test project", } # Valid request - output = self.app.post( - '/api/0/new/', data=data, headers=headers) + output = self.app.post("/api/0/new/", data=data, headers=headers) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'Project "test_42" created'} - ) + self.assertDictEqual(data, {"message": 'Project "test_42" created'}) # Project with a namespace - pagure.config.config['ALLOWED_PREFIX'] = ['rpms'] + pagure.config.config["ALLOWED_PREFIX"] = ["rpms"] data = { - 'name': 'test_42', - 'namespace': 'pingou', - 'description': 'Just another small test project', + "name": "test_42", + "namespace": "pingou", + "description": "Just another small test project", } # Invalid namespace - output = self.app.post( - '/api/0/new/', data=data, headers=headers) + output = self.app.post("/api/0/new/", data=data, headers=headers) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( @@ -2452,324 +2290,270 @@ class PagureFlaskApiProjecttests(tests.Modeltests): { "error": "Invalid or incomplete input submitted", "error_code": "EINVALIDREQ", - "errors": { - "namespace": [ - "Not a valid choice" - ] - } - } + "errors": {"namespace": ["Not a valid choice"]}, + }, ) data = { - 'name': 'test_42', - 'namespace': 'rpms', - 'description': 'Just another small test project', + "name": "test_42", + "namespace": "rpms", + "description": "Just another small test project", } # All good - output = self.app.post( - '/api/0/new/', data=data, headers=headers) + output = self.app.post("/api/0/new/", data=data, headers=headers) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - {'message': 'Project "rpms/test_42" created'} + data, {"message": 'Project "rpms/test_42" created'} ) - @patch.dict('pagure.config.config', {'USER_NAMESPACE': True}) + @patch.dict("pagure.config.config", {"USER_NAMESPACE": True}) def test_api_new_project_user_ns(self): """ Test the api_new_project method of the flask api. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'tickets')) + tests.create_projects_git(os.path.join(self.path, "tickets")) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Create a project with the user namespace feature on data = { - 'name': 'testproject', - 'description': 'Just another small test project', + "name": "testproject", + "description": "Just another small test project", } # Valid request - output = self.app.post( - '/api/0/new/', data=data, headers=headers) + output = self.app.post("/api/0/new/", data=data, headers=headers) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - {'message': 'Project "pingou/testproject" created'} + data, {"message": 'Project "pingou/testproject" created'} ) # Create a project with a namespace and the user namespace feature on data = { - 'name': 'testproject2', - 'namespace': 'testns', - 'description': 'Just another small test project', + "name": "testproject2", + "namespace": "testns", + "description": "Just another small test project", } # Valid request - with patch.dict('pagure.config.config', {'ALLOWED_PREFIX': ['testns']}): - output = self.app.post( - '/api/0/new/', data=data, headers=headers) + with patch.dict( + "pagure.config.config", {"ALLOWED_PREFIX": ["testns"]} + ): + output = self.app.post("/api/0/new/", data=data, headers=headers) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - {'message': 'Project "testns/testproject2" created'} + data, {"message": 'Project "testns/testproject2" created'} ) def test_api_fork_project(self): """ Test the api_fork_project method of the flask api. """ tests.create_projects(self.session) - for folder in ['docs', 'tickets', 'requests', 'repos']: + for folder in ["docs", "tickets", "requests", "repos"]: tests.create_projects_git( - os.path.join(self.path, folder), bare=True) + os.path.join(self.path, folder), bare=True + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token foo_token'} + headers = {"Authorization": "token foo_token"} # Invalid token - output = self.app.post('/api/0/fork', headers=headers) + output = self.app.post("/api/0/fork", headers=headers) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(sorted(data.keys()), [ - 'error', 'error_code', "errors"]) - self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.value, data['error']) self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.name, data['error_code']) + sorted(data.keys()), ["error", "error_code", "errors"] + ) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) self.assertEqual( - data['errors'], "Missing ACLs: fork_project") + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) + self.assertEqual(data["errors"], "Missing ACLs: fork_project") - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # No input - output = self.app.post('/api/0/fork', headers=headers) + output = self.app.post("/api/0/fork", headers=headers) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - "error": "Invalid or incomplete input submitted", - "error_code": "EINVALIDREQ", - "errors": {"repo": ["This field is required."]} - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": {"repo": ["This field is required."]}, + }, ) - data = { - 'name': 'test', - } + data = {"name": "test"} # Incomplete request - output = self.app.post( - '/api/0/fork', data=data, headers=headers) + output = self.app.post("/api/0/fork", data=data, headers=headers) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - "error": "Invalid or incomplete input submitted", - "error_code": "EINVALIDREQ", - "errors": {"repo": ["This field is required."]} - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": {"repo": ["This field is required."]}, + }, ) - data = { - 'repo': 'test', - } + data = {"repo": "test"} # Valid request - output = self.app.post( - '/api/0/fork/', data=data, headers=headers) + output = self.app.post("/api/0/fork/", data=data, headers=headers) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "message": "Repo \"test\" cloned to \"pingou/test\"" - } + data, {"message": 'Repo "test" cloned to "pingou/test"'} ) - data = { - 'repo': 'test', - } + data = {"repo": "test"} # project already forked - output = self.app.post( - '/api/0/fork/', data=data, headers=headers) + output = self.app.post("/api/0/fork/", data=data, headers=headers) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - "error": "Repo \"forks/pingou/test\" already exists", - "error_code": "ENOCODE" - } + "error": 'Repo "forks/pingou/test" already exists', + "error_code": "ENOCODE", + }, ) - data = { - 'repo': 'test', - 'username': 'pingou', - } + data = {"repo": "test", "username": "pingou"} # Fork already exists - output = self.app.post( - '/api/0/fork/', data=data, headers=headers) + output = self.app.post("/api/0/fork/", data=data, headers=headers) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - "error": "Repo \"forks/pingou/test\" already exists", - "error_code": "ENOCODE" - } + "error": 'Repo "forks/pingou/test" already exists', + "error_code": "ENOCODE", + }, ) - data = { - 'repo': 'test', - 'namespace': 'pingou', - } + data = {"repo": "test", "namespace": "pingou"} # Repo does not exists - output = self.app.post( - '/api/0/fork/', data=data, headers=headers) + output = self.app.post("/api/0/fork/", data=data, headers=headers) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT" - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) def test_api_fork_project_user_token(self): """ Test the api_fork_project method of the flask api. """ tests.create_projects(self.session) - for folder in ['docs', 'tickets', 'requests', 'repos']: + for folder in ["docs", "tickets", "requests", "repos"]: tests.create_projects_git( - os.path.join(self.path, folder), bare=True) + os.path.join(self.path, folder), bare=True + ) tests.create_tokens(self.session, project_id=None) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token foo_token'} + headers = {"Authorization": "token foo_token"} # Invalid token - output = self.app.post('/api/0/fork', headers=headers) + output = self.app.post("/api/0/fork", headers=headers) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(sorted(data.keys()), [ - 'error', 'error_code', "errors"]) - self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.value, data['error']) self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.name, data['error_code']) + sorted(data.keys()), ["error", "error_code", "errors"] + ) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) self.assertEqual( - data['errors'], "Missing ACLs: fork_project") + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) + self.assertEqual(data["errors"], "Missing ACLs: fork_project") - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # No input - output = self.app.post('/api/0/fork', headers=headers) + output = self.app.post("/api/0/fork", headers=headers) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - "error": "Invalid or incomplete input submitted", - "error_code": "EINVALIDREQ", - "errors": {"repo": ["This field is required."]} - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": {"repo": ["This field is required."]}, + }, ) - data = { - 'name': 'test', - } + data = {"name": "test"} # Incomplete request - output = self.app.post( - '/api/0/fork', data=data, headers=headers) + output = self.app.post("/api/0/fork", data=data, headers=headers) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - "error": "Invalid or incomplete input submitted", - "error_code": "EINVALIDREQ", - "errors": {"repo": ["This field is required."]} - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": {"repo": ["This field is required."]}, + }, ) - data = { - 'repo': 'test', - } + data = {"repo": "test"} # Valid request - output = self.app.post( - '/api/0/fork/', data=data, headers=headers) + output = self.app.post("/api/0/fork/", data=data, headers=headers) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "message": "Repo \"test\" cloned to \"pingou/test\"" - } + data, {"message": 'Repo "test" cloned to "pingou/test"'} ) - data = { - 'repo': 'test', - } + data = {"repo": "test"} # project already forked - output = self.app.post( - '/api/0/fork/', data=data, headers=headers) + output = self.app.post("/api/0/fork/", data=data, headers=headers) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - "error": "Repo \"forks/pingou/test\" already exists", - "error_code": "ENOCODE" - } + "error": 'Repo "forks/pingou/test" already exists', + "error_code": "ENOCODE", + }, ) - data = { - 'repo': 'test', - 'username': 'pingou', - } + data = {"repo": "test", "username": "pingou"} # Fork already exists - output = self.app.post( - '/api/0/fork/', data=data, headers=headers) + output = self.app.post("/api/0/fork/", data=data, headers=headers) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - "error": "Repo \"forks/pingou/test\" already exists", - "error_code": "ENOCODE" - } + "error": 'Repo "forks/pingou/test" already exists', + "error_code": "ENOCODE", + }, ) - data = { - 'repo': 'test', - 'namespace': 'pingou', - } + data = {"repo": "test", "namespace": "pingou"} # Repo does not exists - output = self.app.post( - '/api/0/fork/', data=data, headers=headers) + output = self.app.post("/api/0/fork/", data=data, headers=headers) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT" - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) def test_api_generate_acls(self): @@ -2777,46 +2561,56 @@ class PagureFlaskApiProjecttests(tests.Modeltests): tests.create_projects(self.session) tests.create_tokens(self.session, project_id=None) tests.create_tokens_acl( - self.session, 'aaabbbcccddd', 'generate_acls_project') - headers = {'Authorization': 'token aaabbbcccddd'} + self.session, "aaabbbcccddd", "generate_acls_project" + ) + headers = {"Authorization": "token aaabbbcccddd"} - user = pagure.lib.query.get_user(self.session, 'pingou') + user = pagure.lib.query.get_user(self.session, "pingou") output = self.app.post( - '/api/0/test/git/generateacls', headers=headers, - data={'wait': False}) + "/api/0/test/git/generateacls", + headers=headers, + data={"wait": False}, + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) expected_output = { - 'message': 'Project ACL generation queued', - 'taskid': 'abc-1234' + "message": "Project ACL generation queued", + "taskid": "abc-1234", } self.assertEqual(data, expected_output) self.mock_gen_acls.assert_called_once_with( - name='test', namespace=None, user=None, group=None) + name="test", namespace=None, user=None, group=None + ) def test_api_generate_acls_json(self): """ Test the api_generate_acls method of the flask api using JSON """ tests.create_projects(self.session) tests.create_tokens(self.session, project_id=None) tests.create_tokens_acl( - self.session, 'aaabbbcccddd', 'generate_acls_project') - headers = {'Authorization': 'token aaabbbcccddd', - 'Content-Type': 'application/json'} + self.session, "aaabbbcccddd", "generate_acls_project" + ) + headers = { + "Authorization": "token aaabbbcccddd", + "Content-Type": "application/json", + } - user = pagure.lib.query.get_user(self.session, 'pingou') + user = pagure.lib.query.get_user(self.session, "pingou") output = self.app.post( - '/api/0/test/git/generateacls', headers=headers, - data=json.dumps({'wait': False})) + "/api/0/test/git/generateacls", + headers=headers, + data=json.dumps({"wait": False}), + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) expected_output = { - 'message': 'Project ACL generation queued', - 'taskid': 'abc-1234' + "message": "Project ACL generation queued", + "taskid": "abc-1234", } self.assertEqual(data, expected_output) self.mock_gen_acls.assert_called_once_with( - name='test', namespace=None, user=None, group=None) + name="test", namespace=None, user=None, group=None + ) def test_api_generate_acls_wait_true(self): """ Test the api_generate_acls method of the flask api when wait is @@ -2824,25 +2618,27 @@ class PagureFlaskApiProjecttests(tests.Modeltests): tests.create_projects(self.session) tests.create_tokens(self.session, project_id=None) tests.create_tokens_acl( - self.session, 'aaabbbcccddd', 'generate_acls_project') - headers = {'Authorization': 'token aaabbbcccddd'} + self.session, "aaabbbcccddd", "generate_acls_project" + ) + headers = {"Authorization": "token aaabbbcccddd"} task_result = Mock() - task_result.id = 'abc-1234' + task_result.id = "abc-1234" self.mock_gen_acls.return_value = task_result - user = pagure.lib.query.get_user(self.session, 'pingou') + user = pagure.lib.query.get_user(self.session, "pingou") output = self.app.post( - '/api/0/test/git/generateacls', headers=headers, - data={'wait': True}) + "/api/0/test/git/generateacls", + headers=headers, + data={"wait": True}, + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - expected_output = { - 'message': 'Project ACLs generated', - } + expected_output = {"message": "Project ACLs generated"} self.assertEqual(data, expected_output) self.mock_gen_acls.assert_called_once_with( - name='test', namespace=None, user=None, group=None) + name="test", namespace=None, user=None, group=None + ) self.assertTrue(task_result.get.called) def test_api_generate_acls_no_project(self): @@ -2851,138 +2647,135 @@ class PagureFlaskApiProjecttests(tests.Modeltests): tests.create_projects(self.session) tests.create_tokens(self.session, project_id=None) tests.create_tokens_acl( - self.session, 'aaabbbcccddd', 'generate_acls_project') - headers = {'Authorization': 'token aaabbbcccddd'} + self.session, "aaabbbcccddd", "generate_acls_project" + ) + headers = {"Authorization": "token aaabbbcccddd"} - user = pagure.lib.query.get_user(self.session, 'pingou') + user = pagure.lib.query.get_user(self.session, "pingou") output = self.app.post( - '/api/0/test12345123/git/generateacls', headers=headers, - data={'wait': False}) + "/api/0/test12345123/git/generateacls", + headers=headers, + data={"wait": False}, + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) expected_output = { - 'error_code': 'ENOPROJECT', - 'error': 'Project not found' + "error_code": "ENOPROJECT", + "error": "Project not found", } self.assertEqual(data, expected_output) def test_api_new_git_branch(self): """ Test the api_new_branch method of the flask api """ tests.create_projects(self.session) - repo_path = os.path.join(self.path, 'repos') + repo_path = os.path.join(self.path, "repos") tests.create_projects_git(repo_path, bare=True) - tests.add_content_git_repo(os.path.join(repo_path, 'test.git')) + tests.add_content_git_repo(os.path.join(repo_path, "test.git")) tests.create_tokens(self.session, project_id=None) - tests.create_tokens_acl( - self.session, 'aaabbbcccddd', 'create_branch') - headers = {'Authorization': 'token aaabbbcccddd'} - args = {'branch': 'test123'} - output = self.app.post('/api/0/test/git/branch', headers=headers, - data=args) + tests.create_tokens_acl(self.session, "aaabbbcccddd", "create_branch") + headers = {"Authorization": "token aaabbbcccddd"} + args = {"branch": "test123"} + output = self.app.post( + "/api/0/test/git/branch", headers=headers, data=args + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - expected_output = { - 'message': 'Project branch was created', - } + expected_output = {"message": "Project branch was created"} self.assertEqual(data, expected_output) - git_path = os.path.join(self.path, 'repos', 'test.git') + git_path = os.path.join(self.path, "repos", "test.git") repo_obj = pygit2.Repository(git_path) - self.assertIn('test123', repo_obj.listall_branches()) + self.assertIn("test123", repo_obj.listall_branches()) def test_api_new_git_branch_json(self): """ Test the api_new_branch method of the flask api """ tests.create_projects(self.session) - repo_path = os.path.join(self.path, 'repos') + repo_path = os.path.join(self.path, "repos") tests.create_projects_git(repo_path, bare=True) - tests.add_content_git_repo(os.path.join(repo_path, 'test.git')) + tests.add_content_git_repo(os.path.join(repo_path, "test.git")) tests.create_tokens(self.session, project_id=None) - tests.create_tokens_acl( - self.session, 'aaabbbcccddd', 'create_branch') - headers = {'Authorization': 'token aaabbbcccddd', - 'Content-Type': 'application/json'} - args = {'branch': 'test123'} - output = self.app.post('/api/0/test/git/branch', headers=headers, - data=json.dumps(args)) + tests.create_tokens_acl(self.session, "aaabbbcccddd", "create_branch") + headers = { + "Authorization": "token aaabbbcccddd", + "Content-Type": "application/json", + } + args = {"branch": "test123"} + output = self.app.post( + "/api/0/test/git/branch", headers=headers, data=json.dumps(args) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - expected_output = { - 'message': 'Project branch was created', - } + expected_output = {"message": "Project branch was created"} self.assertEqual(data, expected_output) - git_path = os.path.join(self.path, 'repos', 'test.git') + git_path = os.path.join(self.path, "repos", "test.git") repo_obj = pygit2.Repository(git_path) - self.assertIn('test123', repo_obj.listall_branches()) + self.assertIn("test123", repo_obj.listall_branches()) def test_api_new_git_branch_from_branch(self): """ Test the api_new_branch method of the flask api """ tests.create_projects(self.session) - repo_path = os.path.join(self.path, 'repos') + repo_path = os.path.join(self.path, "repos") tests.create_projects_git(repo_path, bare=True) - tests.add_content_git_repo(os.path.join(repo_path, 'test.git')) + tests.add_content_git_repo(os.path.join(repo_path, "test.git")) tests.create_tokens(self.session, project_id=None) - tests.create_tokens_acl( - self.session, 'aaabbbcccddd', 'create_branch') - git_path = os.path.join(self.path, 'repos', 'test.git') + tests.create_tokens_acl(self.session, "aaabbbcccddd", "create_branch") + git_path = os.path.join(self.path, "repos", "test.git") repo_obj = pygit2.Repository(git_path) - parent = pagure.lib.git.get_branch_ref(repo_obj, 'master').peel() - repo_obj.create_branch('dev123', parent) - headers = {'Authorization': 'token aaabbbcccddd'} - args = {'branch': 'test123', 'from_branch': 'dev123'} - output = self.app.post('/api/0/test/git/branch', headers=headers, - data=args) + parent = pagure.lib.git.get_branch_ref(repo_obj, "master").peel() + repo_obj.create_branch("dev123", parent) + headers = {"Authorization": "token aaabbbcccddd"} + args = {"branch": "test123", "from_branch": "dev123"} + output = self.app.post( + "/api/0/test/git/branch", headers=headers, data=args + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - expected_output = { - 'message': 'Project branch was created', - } + expected_output = {"message": "Project branch was created"} self.assertEqual(data, expected_output) - self.assertIn('test123', repo_obj.listall_branches()) + self.assertIn("test123", repo_obj.listall_branches()) def test_api_new_git_branch_already_exists(self): """ Test the api_new_branch method of the flask api when branch already exists """ tests.create_projects(self.session) - repo_path = os.path.join(self.path, 'repos') + repo_path = os.path.join(self.path, "repos") tests.create_projects_git(repo_path, bare=True) - tests.add_content_git_repo(os.path.join(repo_path, 'test.git')) + tests.add_content_git_repo(os.path.join(repo_path, "test.git")) tests.create_tokens(self.session, project_id=None) - tests.create_tokens_acl( - self.session, 'aaabbbcccddd', 'create_branch') - headers = {'Authorization': 'token aaabbbcccddd'} - args = {'branch': 'master'} - output = self.app.post('/api/0/test/git/branch', headers=headers, - data=args) + tests.create_tokens_acl(self.session, "aaabbbcccddd", "create_branch") + headers = {"Authorization": "token aaabbbcccddd"} + args = {"branch": "master"} + output = self.app.post( + "/api/0/test/git/branch", headers=headers, data=args + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) expected_output = { - 'error': 'The branch "master" already exists', - 'error_code': 'ENOCODE' + "error": 'The branch "master" already exists', + "error_code": "ENOCODE", } self.assertEqual(data, expected_output) def test_api_new_git_branch_from_commit(self): """ Test the api_new_branch method of the flask api """ tests.create_projects(self.session) - repos_path = os.path.join(self.path, 'repos') + repos_path = os.path.join(self.path, "repos") tests.create_projects_git(repos_path, bare=True) - git_path = os.path.join(repos_path, 'test.git') + git_path = os.path.join(repos_path, "test.git") tests.add_content_git_repo(git_path) tests.create_tokens(self.session, project_id=None) - tests.create_tokens_acl( - self.session, 'aaabbbcccddd', 'create_branch') + tests.create_tokens_acl(self.session, "aaabbbcccddd", "create_branch") repo_obj = pygit2.Repository(git_path) - from_commit = repo_obj.revparse_single('HEAD').oid.hex - headers = {'Authorization': 'token aaabbbcccddd'} - args = {'branch': 'test123', 'from_commit': from_commit} - output = self.app.post('/api/0/test/git/branch', headers=headers, - data=args) + from_commit = repo_obj.revparse_single("HEAD").oid.hex + headers = {"Authorization": "token aaabbbcccddd"} + args = {"branch": "test123", "from_commit": from_commit} + output = self.app.post( + "/api/0/test/git/branch", headers=headers, data=args + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - expected_output = { - 'message': 'Project branch was created', - } + expected_output = {"message": "Project branch was created"} self.assertEqual(data, expected_output) - self.assertIn('test123', repo_obj.listall_branches()) + self.assertIn("test123", repo_obj.listall_branches()) class PagureFlaskApiProjectFlagtests(tests.Modeltests): @@ -2994,407 +2787,413 @@ class PagureFlaskApiProjectFlagtests(tests.Modeltests): super(PagureFlaskApiProjectFlagtests, self).setUp() tests.create_projects(self.session) - repo_path = os.path.join(self.path, 'repos') - self.git_path = os.path.join(repo_path, 'test.git') + repo_path = os.path.join(self.path, "repos") + self.git_path = os.path.join(repo_path, "test.git") tests.create_projects_git(repo_path, bare=True) tests.add_content_git_repo(self.git_path) tests.create_tokens(self.session, project_id=None) - tests.create_tokens_acl( - self.session, 'aaabbbcccddd', 'commit_flag') + tests.create_tokens_acl(self.session, "aaabbbcccddd", "commit_flag") def test_flag_commit_missing_status(self): """ Test flagging a commit with missing precentage. """ repo_obj = pygit2.Repository(self.git_path) - commit = repo_obj.revparse_single('HEAD') + commit = repo_obj.revparse_single("HEAD") - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'username': 'Jenkins', - 'comment': 'Tests passed', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'uid': 'jenkins_build_pagure_100+seed', + "username": "Jenkins", + "comment": "Tests passed", + "url": "http://jenkins.cloud.fedoraproject.org/", + "uid": "jenkins_build_pagure_100+seed", } output = self.app.post( - '/api/0/test/c/%s/flag' % commit.oid.hex, - headers=headers, data=data) + "/api/0/test/c/%s/flag" % commit.oid.hex, + headers=headers, + data=data, + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) expected_output = { - "error": "Invalid or incomplete input submitted", - "error_code": "EINVALIDREQ", - "errors": { - "status": [ - "Not a valid choice" - ] - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": {"status": ["Not a valid choice"]}, } self.assertEqual(data, expected_output) def test_flag_commit_missing_username(self): """ Test flagging a commit with missing username. """ repo_obj = pygit2.Repository(self.git_path) - commit = repo_obj.revparse_single('HEAD') + commit = repo_obj.revparse_single("HEAD") - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'percent': 100, - 'comment': 'Tests passed', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'uid': 'jenkins_build_pagure_100+seed', - 'status': 'success', + "percent": 100, + "comment": "Tests passed", + "url": "http://jenkins.cloud.fedoraproject.org/", + "uid": "jenkins_build_pagure_100+seed", + "status": "success", } output = self.app.post( - '/api/0/test/c/%s/flag' % commit.oid.hex, - headers=headers, data=data) + "/api/0/test/c/%s/flag" % commit.oid.hex, + headers=headers, + data=data, + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) expected_output = { - "error": "Invalid or incomplete input submitted", - "error_code": "EINVALIDREQ", - "errors": { - "username": [ - "This field is required." - ] - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": {"username": ["This field is required."]}, } self.assertEqual(data, expected_output) def test_flag_commit_missing_comment(self): """ Test flagging a commit with missing comment. """ repo_obj = pygit2.Repository(self.git_path) - commit = repo_obj.revparse_single('HEAD') + commit = repo_obj.revparse_single("HEAD") - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'username': 'Jenkins', - 'percent': 100, - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'uid': 'jenkins_build_pagure_100+seed', - 'status': 'success', + "username": "Jenkins", + "percent": 100, + "url": "http://jenkins.cloud.fedoraproject.org/", + "uid": "jenkins_build_pagure_100+seed", + "status": "success", } output = self.app.post( - '/api/0/test/c/%s/flag' % commit.oid.hex, - headers=headers, data=data) + "/api/0/test/c/%s/flag" % commit.oid.hex, + headers=headers, + data=data, + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) expected_output = { - "error": "Invalid or incomplete input submitted", - "error_code": "EINVALIDREQ", - "errors": { - "comment": [ - "This field is required." - ] - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": {"comment": ["This field is required."]}, } self.assertEqual(data, expected_output) def test_flag_commit_missing_url(self): """ Test flagging a commit with missing url. """ repo_obj = pygit2.Repository(self.git_path) - commit = repo_obj.revparse_single('HEAD') + commit = repo_obj.revparse_single("HEAD") - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'username': 'Jenkins', - 'percent': 100, - 'comment': 'Tests passed', - 'uid': 'jenkins_build_pagure_100+seed', - 'status': 'success', + "username": "Jenkins", + "percent": 100, + "comment": "Tests passed", + "uid": "jenkins_build_pagure_100+seed", + "status": "success", } output = self.app.post( - '/api/0/test/c/%s/flag' % commit.oid.hex, - headers=headers, data=data) + "/api/0/test/c/%s/flag" % commit.oid.hex, + headers=headers, + data=data, + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) expected_output = { - "error": "Invalid or incomplete input submitted", - "error_code": "EINVALIDREQ", - "errors": { - "url": [ - "This field is required." - ] - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": {"url": ["This field is required."]}, } self.assertEqual(data, expected_output) def test_flag_commit_invalid_token(self): """ Test flagging a commit with missing info. """ repo_obj = pygit2.Repository(self.git_path) - commit = repo_obj.revparse_single('HEAD') + commit = repo_obj.revparse_single("HEAD") - headers = {'Authorization': 'token 123'} + headers = {"Authorization": "token 123"} data = { - 'username': 'Jenkins', - 'percent': 100, - 'comment': 'Tests passed', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'uid': 'jenkins_build_pagure_100+seed', + "username": "Jenkins", + "percent": 100, + "comment": "Tests passed", + "url": "http://jenkins.cloud.fedoraproject.org/", + "uid": "jenkins_build_pagure_100+seed", } output = self.app.post( - '/api/0/test/c/%s/flag' % commit.oid.hex, - headers=headers, data=data) + "/api/0/test/c/%s/flag" % commit.oid.hex, + headers=headers, + data=data, + ) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(sorted(data.keys()), [ - 'error', 'error_code', "errors"]) - self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.value, data['error']) self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.name, data['error_code']) + sorted(data.keys()), ["error", "error_code", "errors"] + ) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) self.assertEqual( - data['errors'], "Invalid token") + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) + self.assertEqual(data["errors"], "Invalid token") def test_flag_commit_invalid_status(self): """ Test flagging a commit with an invalid status. """ repo_obj = pygit2.Repository(self.git_path) - commit = repo_obj.revparse_single('HEAD') + commit = repo_obj.revparse_single("HEAD") - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'username': 'Jenkins', - 'percent': 100, - 'comment': 'Tests passed', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'status': 'foobar', + "username": "Jenkins", + "percent": 100, + "comment": "Tests passed", + "url": "http://jenkins.cloud.fedoraproject.org/", + "status": "foobar", } output = self.app.post( - '/api/0/test/c/%s/flag' % commit.oid.hex, - headers=headers, data=data) + "/api/0/test/c/%s/flag" % commit.oid.hex, + headers=headers, + data=data, + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertEqual( data, { - 'errors': {'status': ['Not a valid choice']}, - 'error_code': 'EINVALIDREQ', - 'error': 'Invalid or incomplete input submitted' - } + "errors": {"status": ["Not a valid choice"]}, + "error_code": "EINVALIDREQ", + "error": "Invalid or incomplete input submitted", + }, ) def test_flag_commit_with_uid(self): """ Test flagging a commit with provided uid. """ repo_obj = pygit2.Repository(self.git_path) - commit = repo_obj.revparse_single('HEAD') + commit = repo_obj.revparse_single("HEAD") - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'username': 'Jenkins', - 'percent': 100, - 'comment': 'Tests passed', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'uid': 'jenkins_build_pagure_100+seed', - 'status': 'success', + "username": "Jenkins", + "percent": 100, + "comment": "Tests passed", + "url": "http://jenkins.cloud.fedoraproject.org/", + "uid": "jenkins_build_pagure_100+seed", + "status": "success", } output = self.app.post( - '/api/0/test/c/%s/flag' % commit.oid.hex, - headers=headers, data=data) + "/api/0/test/c/%s/flag" % commit.oid.hex, + headers=headers, + data=data, + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['flag']['date_created'] = '1510742565' - data['flag']['date_updated'] = '1510742565' - data['flag']['commit_hash'] = '62b49f00d489452994de5010565fab81' + data["flag"]["date_created"] = "1510742565" + data["flag"]["date_updated"] = "1510742565" + data["flag"]["commit_hash"] = "62b49f00d489452994de5010565fab81" expected_output = { - 'flag': { - 'comment': 'Tests passed', - 'commit_hash': '62b49f00d489452994de5010565fab81', - 'date_created': '1510742565', - 'date_updated': '1510742565', - 'percent': 100, - 'status': 'success', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'user': { - 'default_email': 'bar@pingou.com', - 'emails': ['bar@pingou.com', 'foo@pingou.com'], - 'fullname': 'PY C', - 'name': 'pingou'}, - 'username': 'Jenkins' + "flag": { + "comment": "Tests passed", + "commit_hash": "62b49f00d489452994de5010565fab81", + "date_created": "1510742565", + "date_updated": "1510742565", + "percent": 100, + "status": "success", + "url": "http://jenkins.cloud.fedoraproject.org/", + "user": { + "default_email": "bar@pingou.com", + "emails": ["bar@pingou.com", "foo@pingou.com"], + "fullname": "PY C", + "name": "pingou", + }, + "username": "Jenkins", }, - 'message': 'Flag added', - 'uid': 'jenkins_build_pagure_100+seed' + "message": "Flag added", + "uid": "jenkins_build_pagure_100+seed", } self.assertEqual(data, expected_output) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_flag_commit_without_uid(self, mock_email): """ Test flagging a commit with missing info. Also ensure notifications aren't sent when they are not asked for. """ repo_obj = pygit2.Repository(self.git_path) - commit = repo_obj.revparse_single('HEAD') + commit = repo_obj.revparse_single("HEAD") - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'username': 'Jenkins', - 'percent': 100, - 'comment': 'Tests passed', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'status': 'success', + "username": "Jenkins", + "percent": 100, + "comment": "Tests passed", + "url": "http://jenkins.cloud.fedoraproject.org/", + "status": "success", } output = self.app.post( - '/api/0/test/c/%s/flag' % commit.oid.hex, - headers=headers, data=data) + "/api/0/test/c/%s/flag" % commit.oid.hex, + headers=headers, + data=data, + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertNotEqual( - data['uid'], - 'jenkins_build_pagure_100+seed' - ) - data['flag']['date_created'] = '1510742565' - data['flag']['date_updated'] = '1510742565' - data['uid'] = 'b1de8f80defd4a81afe2e09f39678087' + self.assertNotEqual(data["uid"], "jenkins_build_pagure_100+seed") + data["flag"]["date_created"] = "1510742565" + data["flag"]["date_updated"] = "1510742565" + data["uid"] = "b1de8f80defd4a81afe2e09f39678087" expected_output = { - 'flag': { - 'comment': 'Tests passed', - 'commit_hash': commit.oid.hex, - 'date_created': '1510742565', - 'date_updated': '1510742565', - 'percent': 100, - 'status': 'success', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'user': { - 'default_email': 'bar@pingou.com', - 'emails': ['bar@pingou.com', 'foo@pingou.com'], - 'fullname': 'PY C', - 'name': 'pingou'}, - 'username': 'Jenkins' + "flag": { + "comment": "Tests passed", + "commit_hash": commit.oid.hex, + "date_created": "1510742565", + "date_updated": "1510742565", + "percent": 100, + "status": "success", + "url": "http://jenkins.cloud.fedoraproject.org/", + "user": { + "default_email": "bar@pingou.com", + "emails": ["bar@pingou.com", "foo@pingou.com"], + "fullname": "PY C", + "name": "pingou", + }, + "username": "Jenkins", }, - 'message': 'Flag added', - 'uid': 'b1de8f80defd4a81afe2e09f39678087' + "message": "Flag added", + "uid": "b1de8f80defd4a81afe2e09f39678087", } self.assertEqual(data, expected_output) mock_email.assert_not_called() - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_flag_commit_with_notification(self, mock_email): """ Test flagging a commit with notification enabled. """ # Enable commit notifications - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") settings = repo.settings - settings['notify_on_commit_flag'] = True + settings["notify_on_commit_flag"] = True repo.settings = settings self.session.add(repo) self.session.commit() repo_obj = pygit2.Repository(self.git_path) - commit = repo_obj.revparse_single('HEAD') + commit = repo_obj.revparse_single("HEAD") - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} data = { - 'username': 'Jenkins', - 'percent': 100, - 'comment': 'Tests passed', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'status': 'success', + "username": "Jenkins", + "percent": 100, + "comment": "Tests passed", + "url": "http://jenkins.cloud.fedoraproject.org/", + "status": "success", } output = self.app.post( - '/api/0/test/c/%s/flag' % commit.oid.hex, - headers=headers, data=data) + "/api/0/test/c/%s/flag" % commit.oid.hex, + headers=headers, + data=data, + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertNotEqual( - data['uid'], - 'jenkins_build_pagure_100+seed' - ) - data['flag']['date_created'] = '1510742565' - data['flag']['date_updated'] = '1510742565' - data['uid'] = 'b1de8f80defd4a81afe2e09f39678087' + self.assertNotEqual(data["uid"], "jenkins_build_pagure_100+seed") + data["flag"]["date_created"] = "1510742565" + data["flag"]["date_updated"] = "1510742565" + data["uid"] = "b1de8f80defd4a81afe2e09f39678087" expected_output = { - 'flag': { - 'comment': 'Tests passed', - 'commit_hash': commit.oid.hex, - 'date_created': '1510742565', - 'date_updated': '1510742565', - 'percent': 100, - 'status': 'success', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'user': { - 'default_email': 'bar@pingou.com', - 'emails': ['bar@pingou.com', 'foo@pingou.com'], - 'fullname': 'PY C', - 'name': 'pingou'}, - 'username': 'Jenkins' + "flag": { + "comment": "Tests passed", + "commit_hash": commit.oid.hex, + "date_created": "1510742565", + "date_updated": "1510742565", + "percent": 100, + "status": "success", + "url": "http://jenkins.cloud.fedoraproject.org/", + "user": { + "default_email": "bar@pingou.com", + "emails": ["bar@pingou.com", "foo@pingou.com"], + "fullname": "PY C", + "name": "pingou", + }, + "username": "Jenkins", }, - 'message': 'Flag added', - 'uid': 'b1de8f80defd4a81afe2e09f39678087' + "message": "Flag added", + "uid": "b1de8f80defd4a81afe2e09f39678087", } self.assertEqual(data, expected_output) mock_email.assert_called_once_with( - '\nJenkins flagged the commit ' - '`' + commit.oid.hex + '` as success: ' - 'Tests passed\n\n' - 'http://localhost.localdomain/test/c/' + commit.oid.hex + '\n', - 'Commit #' + commit.oid.hex + ' - Jenkins: success', - 'bar@pingou.com', - in_reply_to='test-project-1', - mail_id='test-commit-1-1', - project_name='test', - user_from='Jenkins' - ) - - @patch.dict('pagure.config.config', - { - 'FLAG_STATUSES_LABELS': - { - 'pend!': 'label-info', - 'succeed!': 'label-success', - 'fail!': 'label-danger', - 'what?': 'label-warning', - }, - 'FLAG_PENDING': 'pend!', - 'FLAG_SUCCESS': 'succeed!', - 'FLAG_FAILURE': 'fail!', - }) + "\nJenkins flagged the commit " + "`" + commit.oid.hex + "` as success: " + "Tests passed\n\n" + "http://localhost.localdomain/test/c/" + commit.oid.hex + "\n", + "Commit #" + commit.oid.hex + " - Jenkins: success", + "bar@pingou.com", + in_reply_to="test-project-1", + mail_id="test-commit-1-1", + project_name="test", + user_from="Jenkins", + ) + + @patch.dict( + "pagure.config.config", + { + "FLAG_STATUSES_LABELS": { + "pend!": "label-info", + "succeed!": "label-success", + "fail!": "label-danger", + "what?": "label-warning", + }, + "FLAG_PENDING": "pend!", + "FLAG_SUCCESS": "succeed!", + "FLAG_FAILURE": "fail!", + }, + ) def test_flag_commit_with_custom_flags(self): """ Test flagging when custom flags are set up """ repo_obj = pygit2.Repository(self.git_path) - commit = repo_obj.revparse_single('HEAD') + commit = repo_obj.revparse_single("HEAD") - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} send_data = { - 'username': 'Jenkins', - 'percent': 100, - 'comment': 'Tests passed', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'status': 'succeed!', + "username": "Jenkins", + "percent": 100, + "comment": "Tests passed", + "url": "http://jenkins.cloud.fedoraproject.org/", + "status": "succeed!", } output = self.app.post( - '/api/0/test/c/%s/flag' % commit.oid.hex, - headers=headers, data=send_data) + "/api/0/test/c/%s/flag" % commit.oid.hex, + headers=headers, + data=send_data, + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(data['flag']['status'], 'succeed!') + self.assertEqual(data["flag"]["status"], "succeed!") # Try invalid flag status - send_data['status'] = 'nooooo....' + send_data["status"] = "nooooo...." output = self.app.post( - '/api/0/test/c/%s/flag' % commit.oid.hex, - headers=headers, data=send_data) + "/api/0/test/c/%s/flag" % commit.oid.hex, + headers=headers, + data=send_data, + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertEqual( data, { - 'errors': {'status': ['Not a valid choice']}, - 'error_code': 'EINVALIDREQ', - 'error': 'Invalid or incomplete input submitted' - } + "errors": {"status": ["Not a valid choice"]}, + "error_code": "EINVALIDREQ", + "error": "Invalid or incomplete input submitted", + }, ) def test_commit_flags(self): """ Test retrieving commit flags. """ - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") repo_obj = pygit2.Repository(self.git_path) - commit = repo_obj.revparse_single('HEAD') + commit = repo_obj.revparse_single("HEAD") # test with no flags - output = self.app.get('/api/0/test/c/%s/flag' % commit.oid.hex) - self.assertEqual(json.loads(output.get_data(as_text=True)), {'total_flags': 0, 'flags': []}) + output = self.app.get("/api/0/test/c/%s/flag" % commit.oid.hex) + self.assertEqual( + json.loads(output.get_data(as_text=True)), + {"total_flags": 0, "flags": []}, + ) self.assertEqual(output.status_code, 200) # add some flags and retrieve them @@ -3402,70 +3201,64 @@ class PagureFlaskApiProjectFlagtests(tests.Modeltests): session=self.session, repo=repo, commit_hash=commit.oid.hex, - username='simple-koji-ci', - status='pending', + username="simple-koji-ci", + status="pending", percent=None, - comment='Build is running', - url='https://koji.fp.o/koji...', - uid='uid', - user='foo', - token='aaabbbcccddd' + comment="Build is running", + url="https://koji.fp.o/koji...", + uid="uid", + user="foo", + token="aaabbbcccddd", ) pagure.lib.query.add_commit_flag( session=self.session, repo=repo, commit_hash=commit.oid.hex, - username='complex-koji-ci', - status='success', + username="complex-koji-ci", + status="success", percent=None, - comment='Build succeeded', - url='https://koji.fp.o/koji...', - uid='uid2', - user='foo', - token='aaabbbcccddd' + comment="Build succeeded", + url="https://koji.fp.o/koji...", + uid="uid2", + user="foo", + token="aaabbbcccddd", ) self.session.commit() - output = self.app.get('/api/0/test/c/%s/flag' % commit.oid.hex) + output = self.app.get("/api/0/test/c/%s/flag" % commit.oid.hex) data = json.loads(output.get_data(as_text=True)) - for f in data['flags']: - f['date_created'] = '1510742565' - f['date_updated'] = '1510742565' - f['commit_hash'] = '62b49f00d489452994de5010565fab81' + for f in data["flags"]: + f["date_created"] = "1510742565" + f["date_updated"] = "1510742565" + f["commit_hash"] = "62b49f00d489452994de5010565fab81" expected_output = { "flags": [ - { - "comment": "Build is running", - "commit_hash": "62b49f00d489452994de5010565fab81", - "date_created": "1510742565", - 'date_updated': '1510742565', - "percent": None, - "status": "pending", - "url": "https://koji.fp.o/koji...", - "user": { - "fullname": "foo bar", - "name": "foo" + { + "comment": "Build is running", + "commit_hash": "62b49f00d489452994de5010565fab81", + "date_created": "1510742565", + "date_updated": "1510742565", + "percent": None, + "status": "pending", + "url": "https://koji.fp.o/koji...", + "user": {"fullname": "foo bar", "name": "foo"}, + "username": "simple-koji-ci", }, - "username": "simple-koji-ci" - }, - { - "comment": "Build succeeded", - "commit_hash": "62b49f00d489452994de5010565fab81", - "date_created": "1510742565", - 'date_updated': '1510742565', - "percent": None, - "status": "success", - "url": "https://koji.fp.o/koji...", - "user": { - "fullname": "foo bar", - "name": "foo" + { + "comment": "Build succeeded", + "commit_hash": "62b49f00d489452994de5010565fab81", + "date_created": "1510742565", + "date_updated": "1510742565", + "percent": None, + "status": "success", + "url": "https://koji.fp.o/koji...", + "user": {"fullname": "foo bar", "name": "foo"}, + "username": "complex-koji-ci", }, - "username": "complex-koji-ci" - } ], - "total_flags": 2 + "total_flags": 2, } self.assertEqual(data, expected_output) @@ -3482,75 +3275,61 @@ class PagureFlaskApiProjectModifyAclTests(tests.Modeltests): super(PagureFlaskApiProjectModifyAclTests, self).setUp() tests.create_projects(self.session) tests.create_tokens(self.session, project_id=None) - tests.create_tokens_acl( - self.session, 'aaabbbcccddd', 'modify_project') + tests.create_tokens_acl(self.session, "aaabbbcccddd", "modify_project") - project = pagure.lib.query._get_project(self.session, 'test') + project = pagure.lib.query._get_project(self.session, "test") self.assertEquals( - project.access_users, - {u'admin': [], u'commit': [], u'ticket': []} + project.access_users, {"admin": [], "commit": [], "ticket": []} ) def test_api_modify_acls_no_project(self): """ Test the api_modify_acls method of the flask api when the project doesn't exist """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} - data = { - 'user_type': 'user', - 'name': 'bar', - 'acl': 'commit' - } + data = {"user_type": "user", "name": "bar", "acl": "commit"} output = self.app.post( - '/api/0/test12345123/git/modifyacls', - headers=headers, data=data) + "/api/0/test12345123/git/modifyacls", headers=headers, data=data + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) expected_output = { - 'error_code': 'ENOPROJECT', - 'error': 'Project not found' + "error_code": "ENOPROJECT", + "error": "Project not found", } self.assertEqual(data, expected_output) def test_api_modify_acls_no_user(self): """ Test the api_modify_acls method of the flask api when the user doesn't exist """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} - data = { - 'user_type': 'user', - 'name': 'nosuchuser', - 'acl': 'commit' - } + data = {"user_type": "user", "name": "nosuchuser", "acl": "commit"} output = self.app.post( - '/api/0/test/git/modifyacls', - headers=headers, data=data) + "/api/0/test/git/modifyacls", headers=headers, data=data + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) expected_output = { - 'error': 'No such user found', - 'error_code': u'ENOUSER' + "error": "No such user found", + "error_code": "ENOUSER", } self.assertEqual(data, expected_output) def test_api_modify_acls_no_group(self): """ Test the api_modify_acls method of the flask api when the group doesn't exist """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} - data = { - 'user_type': 'group', - 'name': 'nosuchgroup', - 'acl': 'commit' - } + data = {"user_type": "group", "name": "nosuchgroup", "acl": "commit"} output = self.app.post( - '/api/0/test/git/modifyacls', - headers=headers, data=data) + "/api/0/test/git/modifyacls", headers=headers, data=data + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) expected_output = { - 'error': 'Group not found', - 'error_code': 'ENOGROUP' + "error": "Group not found", + "error_code": "ENOGROUP", } self.assertEqual(data, expected_output) @@ -3558,214 +3337,194 @@ class PagureFlaskApiProjectModifyAclTests(tests.Modeltests): """ Test the api_modify_acls method of the flask api when the user doesn't have permissions """ item = pagure.lib.model.Token( - id='foo_token2', + id="foo_token2", user_id=2, project_id=None, expiration=datetime.datetime.utcnow() - + datetime.timedelta(days=30) + + datetime.timedelta(days=30), ) self.session.add(item) self.session.commit() - tests.create_tokens_acl( - self.session, 'foo_token2', 'modify_project') + tests.create_tokens_acl(self.session, "foo_token2", "modify_project") - headers = {'Authorization': 'token foo_token2'} + headers = {"Authorization": "token foo_token2"} - data = { - 'user_type': 'user', - 'name': 'foo', - 'acl': 'commit' - } + data = {"user_type": "user", "name": "foo", "acl": "commit"} output = self.app.post( - '/api/0/test/git/modifyacls', - headers=headers, data=data) + "/api/0/test/git/modifyacls", headers=headers, data=data + ) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) expected_output = { - 'error': 'You are not allowed to modify this project', - 'error_code': 'EMODIFYPROJECTNOTALLOWED' + "error": "You are not allowed to modify this project", + "error_code": "EMODIFYPROJECTNOTALLOWED", } self.assertEqual(data, expected_output) def test_api_modify_acls_neither_user_nor_group(self): """ Test the api_modify_acls method of the flask api when neither user nor group was set """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} - data = { - 'acl': 'commit' - } + data = {"acl": "commit"} output = self.app.post( - '/api/0/test/git/modifyacls', - headers=headers, data=data) + "/api/0/test/git/modifyacls", headers=headers, data=data + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) expected_output = { - 'error': 'Invalid or incomplete input submitted', - 'error_code': 'EINVALIDREQ', - 'errors': {'name': ['This field is required.'], - 'user_type': ['Not a valid choice']} + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": { + "name": ["This field is required."], + "user_type": ["Not a valid choice"], + }, } self.assertEqual(data, expected_output) def test_api_modify_acls_invalid_acl(self): """ Test the api_modify_acls method of the flask api when the ACL doesn't exist. Must be one of ticket, commit or admin. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} - data = { - 'user_type': 'user', - 'name': 'bar', - 'acl': 'invalidacl' - } + data = {"user_type": "user", "name": "bar", "acl": "invalidacl"} output = self.app.post( - '/api/0/test/git/modifyacls', - headers=headers, data=data) + "/api/0/test/git/modifyacls", headers=headers, data=data + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) expected_output = { - 'error': 'Invalid or incomplete input submitted', - 'error_code': 'EINVALIDREQ', - 'errors': { - 'acl': ['Not a valid choice'] - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": {"acl": ["Not a valid choice"]}, } self.assertEqual(data, expected_output) def test_api_modify_acls_user(self): """ Test the api_modify_acls method of the flask api for setting an ACL for a user. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} - data = { - 'user_type': 'user', - 'name': 'foo', - 'acl': 'commit' - } + data = {"user_type": "user", "name": "foo", "acl": "commit"} output = self.app.post( - '/api/0/test/git/modifyacls', - headers=headers, data=data) + "/api/0/test/git/modifyacls", headers=headers, data=data + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['date_created'] = '1510742565' - data['date_modified'] = '1510742566' + data["date_created"] = "1510742565" + data["date_modified"] = "1510742566" expected_output = { - 'access_groups': {'admin': [], 'commit': [], 'ticket': []}, - 'access_users': {'admin': [], - 'commit': ['foo'], - 'owner': ['pingou'], - 'ticket': []}, - 'close_status': - ['Invalid', 'Insufficient data', 'Fixed', 'Duplicate'], - 'custom_keys': [], - 'date_created': '1510742565', - 'date_modified': '1510742566', - 'description': 'test project #1', - 'fullname': 'test', - 'id': 1, - 'milestones': {}, - 'name': 'test', - 'namespace': None, - 'parent': None, - 'priorities': {}, - 'tags': [], - 'url_path': 'test', - 'user': {'fullname': 'PY C', 'name': 'pingou'} + "access_groups": {"admin": [], "commit": [], "ticket": []}, + "access_users": { + "admin": [], + "commit": ["foo"], + "owner": ["pingou"], + "ticket": [], + }, + "close_status": [ + "Invalid", + "Insufficient data", + "Fixed", + "Duplicate", + ], + "custom_keys": [], + "date_created": "1510742565", + "date_modified": "1510742566", + "description": "test project #1", + "fullname": "test", + "id": 1, + "milestones": {}, + "name": "test", + "namespace": None, + "parent": None, + "priorities": {}, + "tags": [], + "url_path": "test", + "user": {"fullname": "PY C", "name": "pingou"}, } self.assertEqual(data, expected_output) def test_api_modify_acls_group(self): """ Test the api_modify_acls method of the flask api for setting an ACL for a group. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Create a group msg = pagure.lib.query.add_group( self.session, - group_name='baz', - display_name='baz group', + group_name="baz", + display_name="baz group", description=None, - group_type='bar', - user='foo', + group_type="bar", + user="foo", is_admin=False, blacklist=[], ) self.session.commit() - self.assertEqual(msg, 'User `foo` added to the group `baz`.') + self.assertEqual(msg, "User `foo` added to the group `baz`.") - data = { - 'user_type': 'group', - 'name': 'baz', - 'acl': 'ticket' - } + data = {"user_type": "group", "name": "baz", "acl": "ticket"} output = self.app.post( - '/api/0/test/git/modifyacls', - headers=headers, data=data) + "/api/0/test/git/modifyacls", headers=headers, data=data + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['date_created'] = '1510742565' - data['date_modified'] = '1510742566' + data["date_created"] = "1510742565" + data["date_modified"] = "1510742566" expected_output = { - 'access_groups': { - 'admin': [], - 'commit': [], - 'ticket': ['baz'] - }, - 'access_users': { - 'admin': [], - 'commit': [], - 'owner': ['pingou'], - 'ticket': [] + "access_groups": {"admin": [], "commit": [], "ticket": ["baz"]}, + "access_users": { + "admin": [], + "commit": [], + "owner": ["pingou"], + "ticket": [], }, - 'close_status': [ - 'Invalid', - 'Insufficient data', - 'Fixed', - 'Duplicate' + "close_status": [ + "Invalid", + "Insufficient data", + "Fixed", + "Duplicate", ], - 'custom_keys': [], - 'date_created': '1510742565', - 'date_modified': '1510742566', - 'description': 'test project #1', - 'fullname': 'test', - 'id': 1, - 'milestones': {}, - 'name': 'test', - 'namespace': None, - 'parent': None, - 'priorities': {}, - 'tags': [], - 'url_path': 'test', - 'user': {'fullname': 'PY C', 'name': 'pingou'} + "custom_keys": [], + "date_created": "1510742565", + "date_modified": "1510742566", + "description": "test project #1", + "fullname": "test", + "id": 1, + "milestones": {}, + "name": "test", + "namespace": None, + "parent": None, + "priorities": {}, + "tags": [], + "url_path": "test", + "user": {"fullname": "PY C", "name": "pingou"}, } self.assertEqual(data, expected_output) def test_api_modify_acls_no_acl(self): """ Test the api_modify_acls method of the flask api when no ACL are specified. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} - project = pagure.lib.query._get_project(self.session, 'test') + project = pagure.lib.query._get_project(self.session, "test") self.assertEquals( - project.access_users, - {u'admin': [], u'commit': [], u'ticket': []} + project.access_users, {"admin": [], "commit": [], "ticket": []} ) - data = { - 'user_type': 'user', - 'name': 'foo', - } + data = {"user_type": "user", "name": "foo"} output = self.app.post( - '/api/0/test/git/modifyacls', headers=headers, data=data) + "/api/0/test/git/modifyacls", headers=headers, data=data + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) expected_output = { - "error": "Invalid or incomplete input submitted", - "error_code": "EINVALIDREQ", - "errors": "User does not have any access on the repo" + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": "User does not have any access on the repo", } self.assertEqual(data, expected_output) @@ -3774,20 +3533,18 @@ class PagureFlaskApiProjectModifyAclTests(tests.Modeltests): """ Test the api_modify_acls method of the flask api when no ACL are specified, so the user tries to remove their own access but the user is the project owner. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} - data = { - 'user_type': 'user', - 'name': 'pingou', - } + data = {"user_type": "user", "name": "pingou"} output = self.app.post( - '/api/0/test/git/modifyacls', headers=headers, data=data) + "/api/0/test/git/modifyacls", headers=headers, data=data + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) expected_output = { - "error": "Invalid or incomplete input submitted", - "error_code": "EINVALIDREQ", - "errors": "User does not have any access on the repo" + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + "errors": "User does not have any access on the repo", } self.assertEqual(data, expected_output) @@ -3800,85 +3557,75 @@ class PagureFlaskApiProjectModifyAclTests(tests.Modeltests): self.test_api_modify_acls_user() # Ensure `foo` was properly added: - project = pagure.lib.query._get_project(self.session, 'test') - user_foo = pagure.lib.query.search_user(self.session, username='foo') + project = pagure.lib.query._get_project(self.session, "test") + user_foo = pagure.lib.query.search_user(self.session, username="foo") self.assertEquals( project.access_users, - {u'admin': [], u'commit': [user_foo], u'ticket': []} + {"admin": [], "commit": [user_foo], "ticket": []}, ) # Create an API token for `foo` for the project `test` item = pagure.lib.model.Token( - id='foo_test_token', + id="foo_test_token", user_id=2, # foo project_id=1, # test - expiration=datetime.datetime.utcnow() + datetime.timedelta(days=10) + expiration=datetime.datetime.utcnow() + + datetime.timedelta(days=10), ) self.session.add(item) self.session.commit() tests.create_tokens_acl( - self.session, 'foo_test_token', 'modify_project') + self.session, "foo_test_token", "modify_project" + ) - headers = {'Authorization': 'token foo_test_token'} + headers = {"Authorization": "token foo_test_token"} - data = { - 'user_type': 'user', - 'name': 'foo', - } + data = {"user_type": "user", "name": "foo"} output = self.app.post( - '/api/0/test/git/modifyacls', headers=headers, data=data) + "/api/0/test/git/modifyacls", headers=headers, data=data + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['date_created'] = '1510742565' - data['date_modified'] = '1510742566' + data["date_created"] = "1510742565" + data["date_modified"] = "1510742566" expected_output = { - "access_groups": { - "admin": [], - "commit": [], - "ticket": [] - }, - "access_users": { - "admin": [], - "commit": [], - "owner": [ - "pingou" + "access_groups": {"admin": [], "commit": [], "ticket": []}, + "access_users": { + "admin": [], + "commit": [], + "owner": ["pingou"], + "ticket": [], + }, + "close_status": [ + "Invalid", + "Insufficient data", + "Fixed", + "Duplicate", ], - "ticket": [] - }, - "close_status": [ - "Invalid", - "Insufficient data", - "Fixed", - "Duplicate" - ], - "custom_keys": [], - "date_created": "1510742565", - "date_modified": "1510742566", - "description": "test project #1", - "fullname": "test", - "id": 1, - "milestones": {}, - "name": "test", - "namespace": None, - "parent": None, - "priorities": {}, - "tags": [], - "url_path": "test", - "user": { - "fullname": "PY C", - "name": "pingou" - } + "custom_keys": [], + "date_created": "1510742565", + "date_modified": "1510742566", + "description": "test project #1", + "fullname": "test", + "id": 1, + "milestones": {}, + "name": "test", + "namespace": None, + "parent": None, + "priorities": {}, + "tags": [], + "url_path": "test", + "user": {"fullname": "PY C", "name": "pingou"}, } self.assertEqual(data, expected_output) # Ensure `foo` was properly removed self.session = pagure.lib.query.create_session(self.dbpath) - project = pagure.lib.query._get_project(self.session, 'test') + project = pagure.lib.query._get_project(self.session, "test") self.assertEquals( - project.access_users, - {u'admin': [], u'commit': [], u'ticket': []} + project.access_users, {"admin": [], "commit": [], "ticket": []} ) def test_api_modify_acls_remove_someone_else_acl(self): @@ -3888,72 +3635,60 @@ class PagureFlaskApiProjectModifyAclTests(tests.Modeltests): self.test_api_modify_acls_user() # Ensure `foo` was properly added: - project = pagure.lib.query._get_project(self.session, 'test') - user_foo = pagure.lib.query.search_user(self.session, username='foo') + project = pagure.lib.query._get_project(self.session, "test") + user_foo = pagure.lib.query.search_user(self.session, username="foo") self.assertEquals( project.access_users, - {u'admin': [], u'commit': [user_foo], u'ticket': []} + {"admin": [], "commit": [user_foo], "ticket": []}, ) - headers = {'Authorization': 'token aaabbbcccddd'} - data = { - 'user_type': 'user', - 'name': 'foo', - } + headers = {"Authorization": "token aaabbbcccddd"} + data = {"user_type": "user", "name": "foo"} output = self.app.post( - '/api/0/test/git/modifyacls', headers=headers, data=data) + "/api/0/test/git/modifyacls", headers=headers, data=data + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['date_created'] = '1510742565' - data['date_modified'] = '1510742566' + data["date_created"] = "1510742565" + data["date_modified"] = "1510742566" expected_output = { - "access_groups": { - "admin": [], - "commit": [], - "ticket": [] - }, - "access_users": { - "admin": [], - "commit": [], - "owner": [ - "pingou" + "access_groups": {"admin": [], "commit": [], "ticket": []}, + "access_users": { + "admin": [], + "commit": [], + "owner": ["pingou"], + "ticket": [], + }, + "close_status": [ + "Invalid", + "Insufficient data", + "Fixed", + "Duplicate", ], - "ticket": [] - }, - "close_status": [ - "Invalid", - "Insufficient data", - "Fixed", - "Duplicate" - ], - "custom_keys": [], - "date_created": "1510742565", - "date_modified": "1510742566", - "description": "test project #1", - "fullname": "test", - "id": 1, - "milestones": {}, - "name": "test", - "namespace": None, - "parent": None, - "priorities": {}, - "tags": [], - "url_path": "test", - "user": { - "fullname": "PY C", - "name": "pingou" - } + "custom_keys": [], + "date_created": "1510742565", + "date_modified": "1510742566", + "description": "test project #1", + "fullname": "test", + "id": 1, + "milestones": {}, + "name": "test", + "namespace": None, + "parent": None, + "priorities": {}, + "tags": [], + "url_path": "test", + "user": {"fullname": "PY C", "name": "pingou"}, } self.assertEqual(data, expected_output) # Ensure `foo` was properly removed self.session = pagure.lib.query.create_session(self.dbpath) - project = pagure.lib.query._get_project(self.session, 'test') + project = pagure.lib.query._get_project(self.session, "test") self.assertEquals( - project.access_users, - {u'admin': [], u'commit': [], u'ticket': []} + project.access_users, {"admin": [], "commit": [], "ticket": []} ) @@ -3968,160 +3703,155 @@ class PagureFlaskApiProjectOptionsTests(tests.Modeltests): super(PagureFlaskApiProjectOptionsTests, self).setUp() tests.create_projects(self.session) tests.create_tokens(self.session, project_id=None) - tests.create_tokens_acl( - self.session, 'aaabbbcccddd', 'modify_project') + tests.create_tokens_acl(self.session, "aaabbbcccddd", "modify_project") - project = pagure.lib.query._get_project(self.session, 'test') + project = pagure.lib.query._get_project(self.session, "test") self.assertEquals( - project.access_users, - {u'admin': [], u'commit': [], u'ticket': []} + project.access_users, {"admin": [], "commit": [], "ticket": []} ) def test_api_get_project_options_wrong_project(self): """ Test accessing api_get_project_options w/o auth header. """ - headers = {'Authorization': 'token aaabbbcccddd'} - output = self.app.get('/api/0/unknown/options', headers=headers) + headers = {"Authorization": "token aaabbbcccddd"} + output = self.app.get("/api/0/unknown/options", headers=headers) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertEqual( - data, - {u'error': u'Project not found', u'error_code': u'ENOPROJECT'} + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) def test_api_get_project_options_wo_header(self): """ Test accessing api_get_project_options w/o auth header. """ - output = self.app.get('/api/0/test/options') + output = self.app.get("/api/0/test/options") self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) self.assertEqual( data, { - u'error': u'Invalid or expired token. Please visit ' - 'http://localhost.localdomain/settings#api-keys to get ' - 'or renew your API token.', - u'error_code': u'EINVALIDTOK', - u'errors': u'Invalid token', - } + "error": "Invalid or expired token. Please visit " + "http://localhost.localdomain/settings#api-keys to get " + "or renew your API token.", + "error_code": "EINVALIDTOK", + "errors": "Invalid token", + }, ) def test_api_get_project_options_w_header(self): """ Test accessing api_get_project_options w/ auth header. """ - headers = {'Authorization': 'token aaabbbcccddd'} - output = self.app.get('/api/0/test/options', headers=headers) + headers = {"Authorization": "token aaabbbcccddd"} + output = self.app.get("/api/0/test/options", headers=headers) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertEqual( data, { - "settings": { - "Enforce_signed-off_commits_in_pull-request": False, - "Minimum_score_to_merge_pull-request": -1, - "Only_assignee_can_merge_pull-request": False, - "Web-hooks": None, - "always_merge": False, - "disable_non_fast-forward_merges": False, - "fedmsg_notifications": True, - "issue_tracker": True, - "issue_tracker_read_only": False, - "issues_default_to_private": False, - "mqtt_notifications": True, - "notify_on_commit_flag": False, - "notify_on_pull-request_flag": False, - "open_metadata_access_to_all": False, - "project_documentation": False, - "pull_request_access_only": False, - "pull_requests": True, - "stomp_notifications": True - }, - "status": "ok" - } + "settings": { + "Enforce_signed-off_commits_in_pull-request": False, + "Minimum_score_to_merge_pull-request": -1, + "Only_assignee_can_merge_pull-request": False, + "Web-hooks": None, + "always_merge": False, + "disable_non_fast-forward_merges": False, + "fedmsg_notifications": True, + "issue_tracker": True, + "issue_tracker_read_only": False, + "issues_default_to_private": False, + "mqtt_notifications": True, + "notify_on_commit_flag": False, + "notify_on_pull-request_flag": False, + "open_metadata_access_to_all": False, + "project_documentation": False, + "pull_request_access_only": False, + "pull_requests": True, + "stomp_notifications": True, + }, + "status": "ok", + }, ) def test_api_modify_project_options_wrong_project(self): """ Test accessing api_modify_project_options w/ an invalid project. """ - headers = {'Authorization': 'token aaabbbcccddd'} - output = self.app.post('/api/0/unknown/options/update', headers=headers) + headers = {"Authorization": "token aaabbbcccddd"} + output = self.app.post( + "/api/0/unknown/options/update", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertEqual( - data, - {u'error': u'Project not found', u'error_code': u'ENOPROJECT'} + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) def test_api_modify_project_options_wo_header(self): """ Test accessing api_modify_project_options w/o auth header. """ - output = self.app.post('/api/0/test/options/update') + output = self.app.post("/api/0/test/options/update") self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) self.assertEqual( data, { - u'error': u'Invalid or expired token. Please visit ' - 'http://localhost.localdomain/settings#api-keys to get ' - 'or renew your API token.', - u'error_code': u'EINVALIDTOK', - u'errors': u'Invalid token', - } + "error": "Invalid or expired token. Please visit " + "http://localhost.localdomain/settings#api-keys to get " + "or renew your API token.", + "error_code": "EINVALIDTOK", + "errors": "Invalid token", + }, ) def test_api_modify_project_options_no_data(self): """ Test accessing api_modify_project_options w/ auth header. """ # check before - headers = {'Authorization': 'token aaabbbcccddd'} - output = self.app.get('/api/0/test/options', headers=headers) + headers = {"Authorization": "token aaabbbcccddd"} + output = self.app.get("/api/0/test/options", headers=headers) self.assertEqual(output.status_code, 200) before = json.loads(output.get_data(as_text=True)) self.assertEqual( before, { - "settings": { - "Enforce_signed-off_commits_in_pull-request": False, - "Minimum_score_to_merge_pull-request": -1, - "Only_assignee_can_merge_pull-request": False, - "Web-hooks": None, - "always_merge": False, - "disable_non_fast-forward_merges": False, - "fedmsg_notifications": True, - "issue_tracker": True, - "issue_tracker_read_only": False, - "issues_default_to_private": False, - "mqtt_notifications": True, - "notify_on_commit_flag": False, - "notify_on_pull-request_flag": False, - "open_metadata_access_to_all": False, - "project_documentation": False, - "pull_request_access_only": False, - "pull_requests": True, - "stomp_notifications": True - }, - "status": "ok" - } + "settings": { + "Enforce_signed-off_commits_in_pull-request": False, + "Minimum_score_to_merge_pull-request": -1, + "Only_assignee_can_merge_pull-request": False, + "Web-hooks": None, + "always_merge": False, + "disable_non_fast-forward_merges": False, + "fedmsg_notifications": True, + "issue_tracker": True, + "issue_tracker_read_only": False, + "issues_default_to_private": False, + "mqtt_notifications": True, + "notify_on_commit_flag": False, + "notify_on_pull-request_flag": False, + "open_metadata_access_to_all": False, + "project_documentation": False, + "pull_request_access_only": False, + "pull_requests": True, + "stomp_notifications": True, + }, + "status": "ok", + }, ) # Do not update anything data = {} output = self.app.post( - '/api/0/test/options/update', headers=headers, data=data) + "/api/0/test/options/update", headers=headers, data=data + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertEqual( - data, - { - u'message': u'No settings to change', - u'status': u'ok' - } + data, {"message": "No settings to change", "status": "ok"} ) # check after - headers = {'Authorization': 'token aaabbbcccddd'} - output = self.app.get('/api/0/test/options', headers=headers) + headers = {"Authorization": "token aaabbbcccddd"} + output = self.app.get("/api/0/test/options", headers=headers) self.assertEqual(output.status_code, 200) after = json.loads(output.get_data(as_text=True)) self.assertEqual(after, before) @@ -4130,60 +3860,62 @@ class PagureFlaskApiProjectOptionsTests(tests.Modeltests): """ Test accessing api_modify_project_options w/ auth header. """ # check before - headers = {'Authorization': 'token aaabbbcccddd'} - output = self.app.get('/api/0/test/options', headers=headers) + headers = {"Authorization": "token aaabbbcccddd"} + output = self.app.get("/api/0/test/options", headers=headers) self.assertEqual(output.status_code, 200) before = json.loads(output.get_data(as_text=True)) self.assertEqual( before, { - "settings": { - "Enforce_signed-off_commits_in_pull-request": False, - "Minimum_score_to_merge_pull-request": -1, - "Only_assignee_can_merge_pull-request": False, - "Web-hooks": None, - "always_merge": False, - "disable_non_fast-forward_merges": False, - "fedmsg_notifications": True, - "issue_tracker": True, - "issue_tracker_read_only": False, - "issues_default_to_private": False, - "mqtt_notifications": True, - "notify_on_commit_flag": False, - "notify_on_pull-request_flag": False, - "open_metadata_access_to_all": False, - "project_documentation": False, - "pull_request_access_only": False, - "pull_requests": True, - "stomp_notifications": True - }, - "status": "ok" - } + "settings": { + "Enforce_signed-off_commits_in_pull-request": False, + "Minimum_score_to_merge_pull-request": -1, + "Only_assignee_can_merge_pull-request": False, + "Web-hooks": None, + "always_merge": False, + "disable_non_fast-forward_merges": False, + "fedmsg_notifications": True, + "issue_tracker": True, + "issue_tracker_read_only": False, + "issues_default_to_private": False, + "mqtt_notifications": True, + "notify_on_commit_flag": False, + "notify_on_pull-request_flag": False, + "open_metadata_access_to_all": False, + "project_documentation": False, + "pull_request_access_only": False, + "pull_requests": True, + "stomp_notifications": True, + }, + "status": "ok", + }, ) # Update: `issues_default_to_private`. data = {"issues_default_to_private": True} output = self.app.post( - '/api/0/test/options/update', headers=headers, data=data) + "/api/0/test/options/update", headers=headers, data=data + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertEqual( data, { - u'message': u'Edited successfully settings of repo: test', - u'status': u'ok' - } + "message": "Edited successfully settings of repo: test", + "status": "ok", + }, ) # check after - headers = {'Authorization': 'token aaabbbcccddd'} - output = self.app.get('/api/0/test/options', headers=headers) + headers = {"Authorization": "token aaabbbcccddd"} + output = self.app.get("/api/0/test/options", headers=headers) self.assertEqual(output.status_code, 200) after = json.loads(output.get_data(as_text=True)) self.assertNotEqual(before, after) before["settings"]["issues_default_to_private"] = True self.assertEqual(after, before) + class PagureFlaskApiProjectCreateAPITokenTests(tests.Modeltests): """ Tests for the flask API of pagure for creating user project API token """ @@ -4195,88 +3927,78 @@ class PagureFlaskApiProjectCreateAPITokenTests(tests.Modeltests): super(PagureFlaskApiProjectCreateAPITokenTests, self).setUp() tests.create_projects(self.session) tests.create_tokens(self.session, project_id=None) - tests.create_tokens_acl( - self.session, 'aaabbbcccddd', 'modify_project') + tests.create_tokens_acl(self.session, "aaabbbcccddd", "modify_project") def test_api_createapitoken_as_owner(self): """ Test accessing api_project_create_token as owner. """ - headers = {'Authorization': 'token aaabbbcccddd'} - project = pagure.lib.query._get_project(self.session, 'test') - tdescription = 'my new token' + headers = {"Authorization": "token aaabbbcccddd"} + project = pagure.lib.query._get_project(self.session, "test") + tdescription = "my new token" # Call the api with pingou user token and verify content data = { - 'description': tdescription, - 'acls': ['pull_request_merge', 'pull_request_comment'] + "description": tdescription, + "acls": ["pull_request_merge", "pull_request_comment"], } - output = self.app.post('/api/0/test/token/new', - headers=headers, data=data) + output = self.app.post( + "/api/0/test/token/new", headers=headers, data=data + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) tid = pagure.lib.query.search_token( - self.session, None, description=tdescription)[0].id + self.session, None, description=tdescription + )[0].id self.assertEqual( - data, - {"token": { - "description": tdescription, - "id": tid - } - } + data, {"token": {"description": tdescription, "id": tid}} ) # Create a second token but with faulty acl # Call the api with pingou user token and error code - data = { - 'description': tdescription, - 'acl': ['foo', 'bar'] - } - output = self.app.post('/api/0/test/token/new', - headers=headers, data=data) + data = {"description": tdescription, "acl": ["foo", "bar"]} + output = self.app.post( + "/api/0/test/token/new", headers=headers, data=data + ) self.assertEqual(output.status_code, 400) def test_api_createapitoken_as_admin(self): """ Test accessing api_project_create_token as admin. """ - project = pagure.lib.query._get_project(self.session, 'test') + project = pagure.lib.query._get_project(self.session, "test") # Set the foo user as test project admin pagure.lib.query.add_user_to_project( - self.session, project, - new_user='foo', - user='pingou', - access='admin' + self.session, + project, + new_user="foo", + user="pingou", + access="admin", ) self.session.commit() # Create modify_project token for foo user token = pagure.lib.query.add_token_to_user( - self.session, - project=None, - acls=['modify_project'], - username='foo') + self.session, project=None, acls=["modify_project"], username="foo" + ) # Call the connector with foo user token and verify content - headers = {'Authorization': 'token %s' % token.id} - tdescription = 'my new token' + headers = {"Authorization": "token %s" % token.id} + tdescription = "my new token" # Call the api with pingou user token and verify content data = { - 'description': tdescription, - 'acls': ['pull_request_merge', 'pull_request_comment'] + "description": tdescription, + "acls": ["pull_request_merge", "pull_request_comment"], } - output = self.app.post('/api/0/test/token/new', - headers=headers, data=data) + output = self.app.post( + "/api/0/test/token/new", headers=headers, data=data + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) tid = pagure.lib.query.search_token( - self.session, None, user='foo', description=tdescription)[0].id + self.session, None, user="foo", description=tdescription + )[0].id self.assertEqual( - data, - {"token": { - "description": tdescription, - "id": tid - } - } + data, {"token": {"description": tdescription, "id": tid}} ) def test_api_createapitoken_as_unauthorized(self): @@ -4284,37 +4006,38 @@ class PagureFlaskApiProjectCreateAPITokenTests(tests.Modeltests): but with unauthorized token ACL. """ - project = pagure.lib.query._get_project(self.session, 'test') + project = pagure.lib.query._get_project(self.session, "test") # Set the foo user as test project admin pagure.lib.query.add_user_to_project( - self.session, project, - new_user='foo', - user='pingou', - access='admin' + self.session, + project, + new_user="foo", + user="pingou", + access="admin", ) self.session.commit() # Create modify_project token for foo user pagure.lib.query.add_token_to_user( - self.session, - project=None, - acls=['create_branch'], - username='foo') + self.session, project=None, acls=["create_branch"], username="foo" + ) mtoken = pagure.lib.query.search_token( - self.session, ['create_branch'], user='foo')[0] + self.session, ["create_branch"], user="foo" + )[0] # Call the connector with foo user token and verify content - headers = {'Authorization': 'token %s' % mtoken.id} - tdescription = 'my new token' + headers = {"Authorization": "token %s" % mtoken.id} + tdescription = "my new token" # Call the api with pingou user token and verify content data = { - 'description': tdescription, - 'acls': ['pull_request_merge', 'pull_request_comment'] + "description": tdescription, + "acls": ["pull_request_merge", "pull_request_comment"], } - output = self.app.post('/api/0/test/token/new', - headers=headers, data=data) + output = self.app.post( + "/api/0/test/token/new", headers=headers, data=data + ) self.assertEqual(output.status_code, 401) def test_api_createapitoken_as_unauthorized_2(self): @@ -4322,37 +4045,38 @@ class PagureFlaskApiProjectCreateAPITokenTests(tests.Modeltests): with unauthorized token ACL. """ - project = pagure.lib.query._get_project(self.session, 'test') + project = pagure.lib.query._get_project(self.session, "test") # Set the foo user as test project admin pagure.lib.query.add_user_to_project( - self.session, project, - new_user='foo', - user='pingou', - access='commit' + self.session, + project, + new_user="foo", + user="pingou", + access="commit", ) self.session.commit() # Create modify_project token for foo user pagure.lib.query.add_token_to_user( - self.session, - project=None, - acls=['modify_project'], - username='foo') + self.session, project=None, acls=["modify_project"], username="foo" + ) mtoken = pagure.lib.query.search_token( - self.session, ['modify_project'], user='foo')[0] + self.session, ["modify_project"], user="foo" + )[0] # Call the connector with foo user token and verify content - headers = {'Authorization': 'token %s' % mtoken.id} - tdescription = 'my new token' + headers = {"Authorization": "token %s" % mtoken.id} + tdescription = "my new token" # Call the api with pingou user token and verify content data = { - 'description': tdescription, - 'acls': ['pull_request_merge', 'pull_request_comment'] + "description": tdescription, + "acls": ["pull_request_merge", "pull_request_comment"], } - output = self.app.post('/api/0/test/token/new', - headers=headers, data=data) + output = self.app.post( + "/api/0/test/token/new", headers=headers, data=data + ) self.assertEqual(output.status_code, 401) @@ -4367,92 +4091,104 @@ class PagureFlaskApiProjectConnectorTests(tests.Modeltests): super(PagureFlaskApiProjectConnectorTests, self).setUp() tests.create_projects(self.session) tests.create_tokens(self.session, project_id=None) - tests.create_tokens_acl( - self.session, 'aaabbbcccddd', 'modify_project') - + tests.create_tokens_acl(self.session, "aaabbbcccddd", "modify_project") def test_api_get_project_connector_as_owner(self): """ Test accessing api_get_project_connector as project owner. """ - project = pagure.lib.query._get_project(self.session, 'test') + project = pagure.lib.query._get_project(self.session, "test") # Create witness project Token for pingou user pagure.lib.query.add_token_to_user( self.session, project=project, - acls=['pull_request_merge'], - username='pingou') + acls=["pull_request_merge"], + username="pingou", + ) ctokens = pagure.lib.query.search_token( - self.session, ['pull_request_merge'], user='pingou') + self.session, ["pull_request_merge"], user="pingou" + ) self.assertEqual(len(ctokens), 1) # Call the connector with pingou user token and verify content - headers = {'Authorization': 'token aaabbbcccddd'} - output = self.app.get('/api/0/test/connector', headers=headers) + headers = {"Authorization": "token aaabbbcccddd"} + output = self.app.get("/api/0/test/connector", headers=headers) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertEqual( data, - {"connector": { - "hook_token": project.hook_token, - "api_tokens": [ - {'description': t.description, - 'id': t.id, - 'expired': False} for t in ctokens] + { + "connector": { + "hook_token": project.hook_token, + "api_tokens": [ + { + "description": t.description, + "id": t.id, + "expired": False, + } + for t in ctokens + ], + }, + "status": "ok", }, - "status": "ok" - } ) def test_api_get_project_connector_as_admin(self): """ Test accessing api_get_project_connector as project admin """ - project = pagure.lib.query._get_project(self.session, 'test') + project = pagure.lib.query._get_project(self.session, "test") # Set the foo user as test project admin pagure.lib.query.add_user_to_project( - self.session, project, - new_user='foo', - user='pingou', - access='admin' + self.session, + project, + new_user="foo", + user="pingou", + access="admin", ) self.session.commit() # Create modify_project token for foo user pagure.lib.query.add_token_to_user( - self.session, - project=None, - acls=['modify_project'], - username='foo') + self.session, project=None, acls=["modify_project"], username="foo" + ) mtoken = pagure.lib.query.search_token( - self.session, ['modify_project'], user='foo')[0] + self.session, ["modify_project"], user="foo" + )[0] # Create witness project Token for foo user pagure.lib.query.add_token_to_user( self.session, project=project, - acls=['pull_request_merge'], - username='foo') + acls=["pull_request_merge"], + username="foo", + ) ctokens = pagure.lib.query.search_token( - self.session, ['pull_request_merge'], user='foo') + self.session, ["pull_request_merge"], user="foo" + ) self.assertEqual(len(ctokens), 1) # Call the connector with foo user token and verify content - headers = {'Authorization': 'token %s' % mtoken.id} - output = self.app.get('/api/0/test/connector', headers=headers) + headers = {"Authorization": "token %s" % mtoken.id} + output = self.app.get("/api/0/test/connector", headers=headers) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertEqual( data, - {"connector": { - "hook_token": project.hook_token, - "api_tokens": [ - {'description': t.description, - 'id': t.id, - 'expired': False} for t in ctokens] + { + "connector": { + "hook_token": project.hook_token, + "api_tokens": [ + { + "description": t.description, + "id": t.id, + "expired": False, + } + for t in ctokens + ], + }, + "status": "ok", }, - "status": "ok" - } ) def test_api_get_project_connector_as_unauthorized(self): @@ -4460,29 +4196,29 @@ class PagureFlaskApiProjectConnectorTests(tests.Modeltests): but with unauthorized token ACL """ - project = pagure.lib.query._get_project(self.session, 'test') + project = pagure.lib.query._get_project(self.session, "test") # Set the foo user as test project admin pagure.lib.query.add_user_to_project( - self.session, project, - new_user='foo', - user='pingou', - access='admin' + self.session, + project, + new_user="foo", + user="pingou", + access="admin", ) self.session.commit() # Create modify_project token for foo user pagure.lib.query.add_token_to_user( - self.session, - project=None, - acls=['create_project'], - username='foo') + self.session, project=None, acls=["create_project"], username="foo" + ) mtoken = pagure.lib.query.search_token( - self.session, ['create_project'], user='foo')[0] + self.session, ["create_project"], user="foo" + )[0] # Call the connector with foo user token and verify unauthorized - headers = {'Authorization': 'token %s' % mtoken.id} - output = self.app.get('/api/0/test/connector', headers=headers) + headers = {"Authorization": "token %s" % mtoken.id} + output = self.app.get("/api/0/test/connector", headers=headers) self.assertEqual(output.status_code, 401) def test_api_get_project_connector_as_unauthorized_2(self): @@ -4490,30 +4226,31 @@ class PagureFlaskApiProjectConnectorTests(tests.Modeltests): but with unauthorized token ACL """ - project = pagure.lib.query._get_project(self.session, 'test') + project = pagure.lib.query._get_project(self.session, "test") # Set the foo user as test project admin pagure.lib.query.add_user_to_project( - self.session, project, - new_user='foo', - user='pingou', - access='commit' + self.session, + project, + new_user="foo", + user="pingou", + access="commit", ) self.session.commit() # Create modify_project token for foo user pagure.lib.query.add_token_to_user( - self.session, - project=None, - acls=['modify_project'], - username='foo') + self.session, project=None, acls=["modify_project"], username="foo" + ) mtoken = pagure.lib.query.search_token( - self.session, ['modify_project'], user='foo')[0] + self.session, ["modify_project"], user="foo" + )[0] # Call the connector with foo user token and verify unauthorized - headers = {'Authorization': 'token %s' % mtoken.id} - output = self.app.get('/api/0/test/connector', headers=headers) + headers = {"Authorization": "token %s" % mtoken.id} + output = self.app.get("/api/0/test/connector", headers=headers) self.assertEqual(output.status_code, 401) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/test_pagure_flask_api_project_blockuser.py b/tests/test_pagure_flask_api_project_blockuser.py index dfed55c..1d763b8 100644 --- a/tests/test_pagure_flask_api_project_blockuser.py +++ b/tests/test_pagure_flask_api_project_blockuser.py @@ -45,8 +45,7 @@ class PagureFlaskApiProjectBlockuserTests(tests.SimplePagureTest): super(PagureFlaskApiProjectBlockuserTests, self).setUp() tests.create_projects(self.session) - tests.create_projects_git( - os.path.join(self.path, 'repos'), bare=True) + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) @@ -65,7 +64,9 @@ class PagureFlaskApiProjectBlockuserTests(tests.SimplePagureTest): self.assertEqual(project.block_users, []) self.blocked_users = [] - project = pagure.lib.query.get_authorized_project(self.session, "test2") + project = pagure.lib.query.get_authorized_project( + self.session, "test2" + ) project.block_users = ["foo"] self.session.add(project) self.session.commit() @@ -225,9 +226,9 @@ class PagureFlaskApiProjectBlockuserTests(tests.SimplePagureTest): self.assertDictEqual( data, { - "error":"You have been blocked from this project", - "error_code":"EUBLOCKED" - } + "error": "You have been blocked from this project", + "error_code": "EUBLOCKED", + }, ) def test_ui_new_issue_user_blocked(self): @@ -237,27 +238,25 @@ class PagureFlaskApiProjectBlockuserTests(tests.SimplePagureTest): user = tests.FakeUser(username="foo") with tests.user_set(self.app.application, user): - output = self.app.get('/test2/new_issue') + output = self.app.get("/test2/new_issue") self.assertEqual(output.status_code, 200) - self.assertIn( - 'New Issue', - output.get_data(as_text=True)) + self.assertIn("New Issue", output.get_data(as_text=True)) csrf_token = self.get_csrf(output=output) data = { - 'title': 'Test issue', - 'issue_content': 'We really should improve on this issue', - 'status': 'Open', - 'csrf_token': csrf_token, + "title": "Test issue", + "issue_content": "We really should improve on this issue", + "status": "Open", + "csrf_token": csrf_token, } - output = self.app.post('/test2/new_issue', data=data) + output = self.app.post("/test2/new_issue", data=data) self.assertEqual(output.status_code, 403) output_text = output.get_data(as_text=True) self.assertIn( - '

You have been blocked from this project

', - output_text) + "

You have been blocked from this project

", output_text + ) if __name__ == "__main__": diff --git a/tests/test_pagure_flask_api_project_update_watch.py b/tests/test_pagure_flask_api_project_update_watch.py index 2486b60..e4c5989 100644 --- a/tests/test_pagure_flask_api_project_update_watch.py +++ b/tests/test_pagure_flask_api_project_update_watch.py @@ -21,8 +21,9 @@ import os import json from mock import patch, MagicMock -sys.path.insert(0, os.path.join(os.path.dirname( - os.path.abspath(__file__)), '..')) +sys.path.insert( + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") +) import pagure.lib.query import tests @@ -33,262 +34,244 @@ class PagureFlaskApiProjectUpdateWatchTests(tests.Modeltests): a project via the API """ - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def setUp(self): """ Set up the environnment, ran before every tests. """ super(PagureFlaskApiProjectUpdateWatchTests, self).setUp() tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'tickets')) + tests.create_projects_git(os.path.join(self.path, "tickets")) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Create normal issue - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue #1', - content='We should work on this', - user='pingou', + title="Test issue #1", + content="We should work on this", + user="pingou", private=False, ) self.session.commit() - self.assertEqual(msg.title, 'Test issue #1') + self.assertEqual(msg.title, "Test issue #1") # Create project-less token for user foo item = pagure.lib.model.Token( - id='project-less-foo', + id="project-less-foo", user_id=1, project_id=None, expiration=datetime.datetime.utcnow() - + datetime.timedelta(days=30) + + datetime.timedelta(days=30), ) self.session.add(item) self.session.commit() - tests.create_tokens_acl(self.session, token_id='project-less-foo') + tests.create_tokens_acl(self.session, token_id="project-less-foo") def test_api_update_project_watchers_invalid_project(self): """ Test the api_update_project_watchers method of the flask api. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Invalid project output = self.app.post( - '/api/0/foobar/watchers/update', headers=headers) + "/api/0/foobar/watchers/update", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) def test_api_change_status_issue_token_not_for_project(self): """ Test the api_update_project_watchers method of the flask api. """ - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Valid token, wrong project - output = self.app.post( - '/api/0/test2/watchers/update', headers=headers) + output = self.app.post("/api/0/test2/watchers/update", headers=headers) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.name, - data['error_code']) - self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data['error']) + self.assertEqual( + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) def test_api_update_project_watchers_no_user_watching(self): """ Test the api_update_project_watchers method of the flask api. """ - headers = {'Authorization': 'token aaabbbcccddd'} - data = { - 'status': '42', - } + headers = {"Authorization": "token aaabbbcccddd"} + data = {"status": "42"} output = self.app.post( - '/api/0/test/watchers/update', headers=headers, data=data) + "/api/0/test/watchers/update", headers=headers, data=data + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - u'error': u'Invalid or incomplete input submitted', - u'error_code': u'EINVALIDREQ' - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + }, ) def test_api_update_project_watchers_no_watch_status(self): """ Test the api_update_project_watchers method of the flask api. """ - headers = {'Authorization': 'token aaabbbcccddd'} - data = { - 'watcher': 'pingou', - } + headers = {"Authorization": "token aaabbbcccddd"} + data = {"watcher": "pingou"} output = self.app.post( - '/api/0/test/watchers/update', headers=headers, data=data) + "/api/0/test/watchers/update", headers=headers, data=data + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - u'error': u'The watch value of "None" is invalid', - u'error_code': u'ENOCODE' - } + "error": 'The watch value of "None" is invalid', + "error_code": "ENOCODE", + }, ) def test_api_update_project_watchers_invalid_status(self): """ Test the api_update_project_watchers method of the flask api. """ - headers = {'Authorization': 'token aaabbbcccddd'} - data = { - 'watcher': 'pingou', - 'status': '42', - } + headers = {"Authorization": "token aaabbbcccddd"} + data = {"watcher": "pingou", "status": "42"} output = self.app.post( - '/api/0/test/watchers/update', headers=headers, data=data) + "/api/0/test/watchers/update", headers=headers, data=data + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - u'error': u'The watch value of "42" is invalid', - u'error_code': u'ENOCODE' - } + "error": 'The watch value of "42" is invalid', + "error_code": "ENOCODE", + }, ) def test_api_update_project_watchers_invalid_user(self): """ Test the api_update_project_watchers method of the flask api. """ - headers = {'Authorization': 'token aaabbbcccddd'} - data = { - 'watcher': 'example', - 'status': '2', - } + headers = {"Authorization": "token aaabbbcccddd"} + data = {"watcher": "example", "status": "2"} output = self.app.post( - '/api/0/test/watchers/update', headers=headers, data=data) + "/api/0/test/watchers/update", headers=headers, data=data + ) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - u'error': u'You are not allowed to modify this project', - u'error_code': u'EMODIFYPROJECTNOTALLOWED' - } + "error": "You are not allowed to modify this project", + "error_code": "EMODIFYPROJECTNOTALLOWED", + }, ) def test_api_update_project_watchers_other_user(self): """ Test the api_update_project_watchers method of the flask api. """ - headers = {'Authorization': 'token aaabbbcccddd'} - data = { - 'watcher': 'foo', - 'status': '2', - } + headers = {"Authorization": "token aaabbbcccddd"} + data = {"watcher": "foo", "status": "2"} output = self.app.post( - '/api/0/test/watchers/update', headers=headers, data=data) + "/api/0/test/watchers/update", headers=headers, data=data + ) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - u'error': u'You are not allowed to modify this project', - u'error_code': u'EMODIFYPROJECTNOTALLOWED' - } + "error": "You are not allowed to modify this project", + "error_code": "EMODIFYPROJECTNOTALLOWED", + }, ) def test_api_update_project_watchers_all_good(self): """ Test the api_update_project_watchers method of the flask api. """ - headers = {'Authorization': 'token aaabbbcccddd'} - data = { - 'watcher': 'pingou', - 'status': 1, - } + headers = {"Authorization": "token aaabbbcccddd"} + data = {"watcher": "pingou", "status": 1} output = self.app.post( - '/api/0/test/watchers/update', headers=headers, data=data) + "/api/0/test/watchers/update", headers=headers, data=data + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - u'message': u'You are now watching issues and PRs on this project', - u'status': u'ok' - } + "message": "You are now watching issues and PRs on this project", + "status": "ok", + }, ) - @patch('pagure.utils.is_admin', MagicMock(return_value=True)) + @patch("pagure.utils.is_admin", MagicMock(return_value=True)) def test_api_update_project_watchers_other_user_admin(self): """ Test the api_update_project_watchers method of the flask api. """ - headers = {'Authorization': 'token aaabbbcccddd'} - data = { - 'watcher': 'foo', - 'status': '2', - } + headers = {"Authorization": "token aaabbbcccddd"} + data = {"watcher": "foo", "status": "2"} output = self.app.post( - '/api/0/test/watchers/update', headers=headers, data=data) + "/api/0/test/watchers/update", headers=headers, data=data + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - u'message': u'You are now watching commits on this project', - u'status': u'ok' - } + "message": "You are now watching commits on this project", + "status": "ok", + }, ) - @patch('pagure.utils.is_admin', MagicMock(return_value=True)) + @patch("pagure.utils.is_admin", MagicMock(return_value=True)) def test_api_update_project_watchers_invalid_user_admin(self): """ Test the api_update_project_watchers method of the flask api. """ - headers = {'Authorization': 'token aaabbbcccddd'} - data = { - 'watcher': 'example', - 'status': '2', - } + headers = {"Authorization": "token aaabbbcccddd"} + data = {"watcher": "example", "status": "2"} output = self.app.post( - '/api/0/test/watchers/update', headers=headers, data=data) + "/api/0/test/watchers/update", headers=headers, data=data + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - u'error': u'Invalid or incomplete input submitted', - u'error_code': u'EINVALIDREQ' - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + }, ) - @patch('pagure.utils.is_admin', MagicMock(return_value=True)) + @patch("pagure.utils.is_admin", MagicMock(return_value=True)) def test_api_update_project_watchers_missing_user_admin(self): """ Test the api_update_project_watchers method of the flask api. """ - headers = {'Authorization': 'token aaabbbcccddd'} - data = { - 'status': '2', - } + headers = {"Authorization": "token aaabbbcccddd"} + data = {"status": "2"} output = self.app.post( - '/api/0/test/watchers/update', headers=headers, data=data) + "/api/0/test/watchers/update", headers=headers, data=data + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, { - u'error': u'Invalid or incomplete input submitted', - u'error_code': u'EINVALIDREQ' - } + "error": "Invalid or incomplete input submitted", + "error_code": "EINVALIDREQ", + }, ) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/test_pagure_flask_api_ui_private_repo.py b/tests/test_pagure_flask_api_ui_private_repo.py index ead19c4..b495f0b 100644 --- a/tests/test_pagure_flask_api_ui_private_repo.py +++ b/tests/test_pagure_flask_api_ui_private_repo.py @@ -13,8 +13,9 @@ import json import pygit2 from mock import patch, MagicMock -sys.path.insert(0, os.path.join(os.path.dirname( - os.path.abspath(__file__)), '..')) +sys.path.insert( + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") +) import pagure.lib.query import tests @@ -40,10 +41,7 @@ FULL_ISSUE_LIST = [ "status": "Open", "tags": [], "title": "Test issue", - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, }, { "assignee": None, @@ -64,10 +62,7 @@ FULL_ISSUE_LIST = [ "status": "Open", "tags": [], "title": "test issue", - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, }, { "assignee": None, @@ -88,10 +83,7 @@ FULL_ISSUE_LIST = [ "status": "Open", "tags": [], "title": "test issue", - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, }, { "assignee": None, @@ -112,10 +104,7 @@ FULL_ISSUE_LIST = [ "status": "Open", "tags": [], "title": "test issue", - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, }, { "assignee": None, @@ -136,10 +125,7 @@ FULL_ISSUE_LIST = [ "status": "Open", "tags": [], "title": "test issue", - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, }, { "assignee": None, @@ -160,10 +146,7 @@ FULL_ISSUE_LIST = [ "status": "Open", "tags": [], "title": "test issue", - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, }, { "assignee": None, @@ -184,10 +167,7 @@ FULL_ISSUE_LIST = [ "status": "Open", "tags": [], "title": "test issue", - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, }, { "assignee": None, @@ -208,11 +188,8 @@ FULL_ISSUE_LIST = [ "status": "Open", "tags": [], "title": "test issue", - "user": { - "fullname": "PY C", - "name": "pingou" - } - } + "user": {"fullname": "PY C", "name": "pingou"}, + }, ] @@ -225,102 +202,101 @@ class PagurePrivateRepotest(tests.Modeltests): """ Set up the environnment, ran before every tests. """ super(PagurePrivateRepotest, self).setUp() - pagure.config.config['TESTING'] = True - pagure.config.config['DATAGREPPER_URL'] = None - pagure.config.config['PRIVATE_PROJECTS'] = True - pagure.config.config['VIRUS_SCAN_ATTACHMENTS'] = False + pagure.config.config["TESTING"] = True + pagure.config.config["DATAGREPPER_URL"] = None + pagure.config.config["PRIVATE_PROJECTS"] = True + pagure.config.config["VIRUS_SCAN_ATTACHMENTS"] = False def set_up_git_repo( - self, new_project=None, branch_from='feature', mtype='FF'): + self, new_project=None, branch_from="feature", mtype="FF" + ): """ Set up the git repo and create the corresponding PullRequest object. """ # Create a git repo to play with - gitrepo = os.path.join(self.path, 'repos', 'pmc.git') + gitrepo = os.path.join(self.path, "repos", "pmc.git") repo = pygit2.init_repository(gitrepo, bare=True) - newpath = tempfile.mkdtemp(prefix='pagure-private-test') - repopath = os.path.join(newpath, 'test') + newpath = tempfile.mkdtemp(prefix="pagure-private-test") + repopath = os.path.join(newpath, "test") clone_repo = pygit2.clone_repository(gitrepo, repopath) # Create a file in that git repo - with open(os.path.join(repopath, 'sources'), 'w') as stream: - stream.write('foo\n bar') - clone_repo.index.add('sources') + with open(os.path.join(repopath, "sources"), "w") as stream: + stream.write("foo\n bar") + clone_repo.index.add("sources") clone_repo.index.write() # Commits the files added tree = clone_repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") clone_repo.create_commit( - 'refs/heads/master', # the name of the reference to update + "refs/heads/master", # the name of the reference to update author, committer, - 'Add sources file for testing', + "Add sources file for testing", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [] + [], ) - refname = 'refs/heads/master:refs/heads/master' + refname = "refs/heads/master:refs/heads/master" ori_remote = clone_repo.remotes[0] PagureRepo.push(ori_remote, refname) - first_commit = repo.revparse_single('HEAD') + first_commit = repo.revparse_single("HEAD") - if mtype == 'merge': - with open(os.path.join(repopath, '.gitignore'), 'w') as stream: - stream.write('*~') - clone_repo.index.add('.gitignore') + if mtype == "merge": + with open(os.path.join(repopath, ".gitignore"), "w") as stream: + stream.write("*~") + clone_repo.index.add(".gitignore") clone_repo.index.write() # Commits the files added tree = clone_repo.index.write_tree() - author = pygit2.Signature( - 'Alice Äuthòr', 'alice@äuthòrs.tld') + author = pygit2.Signature("Alice Äuthòr", "alice@äuthòrs.tld") committer = pygit2.Signature( - 'Cecil Cõmmîttër', 'cecil@cõmmîttërs.tld') + "Cecil Cõmmîttër", "cecil@cõmmîttërs.tld" + ) clone_repo.create_commit( - 'refs/heads/master', + "refs/heads/master", author, committer, - 'Add .gitignore file for testing', + "Add .gitignore file for testing", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [first_commit.oid.hex] + [first_commit.oid.hex], ) - refname = 'refs/heads/master:refs/heads/master' + refname = "refs/heads/master:refs/heads/master" ori_remote = clone_repo.remotes[0] PagureRepo.push(ori_remote, refname) - if mtype == 'conflicts': - with open(os.path.join(repopath, 'sources'), 'w') as stream: - stream.write('foo\n bar\nbaz') - clone_repo.index.add('sources') + if mtype == "conflicts": + with open(os.path.join(repopath, "sources"), "w") as stream: + stream.write("foo\n bar\nbaz") + clone_repo.index.add("sources") clone_repo.index.write() # Commits the files added tree = clone_repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + "Cecil Committer", "cecil@committers.tld" + ) clone_repo.create_commit( - 'refs/heads/master', + "refs/heads/master", author, committer, - 'Add sources conflicting', + "Add sources conflicting", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [first_commit.oid.hex] + [first_commit.oid.hex], ) - refname = 'refs/heads/master:refs/heads/master' + refname = "refs/heads/master:refs/heads/master" ori_remote = clone_repo.remotes[0] PagureRepo.push(ori_remote, refname) @@ -336,64 +312,65 @@ class PagurePrivateRepotest(tests.Modeltests): repo = pygit2.Repository(new_gitrepo) - if mtype != 'nochanges': + if mtype != "nochanges": # Edit the sources file again - with open(os.path.join(new_gitrepo, 'sources'), 'w') as stream: - stream.write('foo\n bar\nbaz\n boose') - repo.index.add('sources') + with open(os.path.join(new_gitrepo, "sources"), "w") as stream: + stream.write("foo\n bar\nbaz\n boose") + repo.index.add("sources") repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + "Cecil Committer", "cecil@committers.tld" + ) repo.create_commit( - 'refs/heads/%s' % branch_from, + "refs/heads/%s" % branch_from, author, committer, - 'A commit on branch %s' % branch_from, + "A commit on branch %s" % branch_from, tree, - [first_commit.oid.hex] + [first_commit.oid.hex], ) - refname = 'refs/heads/%s' % (branch_from) + refname = "refs/heads/%s" % (branch_from) ori_remote = repo.remotes[0] PagureRepo.push(ori_remote, refname) # Create a PR for these changes - project = pagure.lib.query._get_project(self.session, 'pmc') + project = pagure.lib.query._get_project(self.session, "pmc") req = pagure.lib.query.new_pull_request( session=self.session, repo_from=project, branch_from=branch_from, repo_to=project, - branch_to='master', - title='PR from the %s branch' % branch_from, - user='pingou', + branch_to="master", + title="PR from the %s branch" % branch_from, + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'PR from the %s branch' % branch_from) + self.assertEqual(req.title, "PR from the %s branch" % branch_from) shutil.rmtree(newpath) def test_index(self): """ Test the index endpoint. """ - output = self.app.get('/') + output = self.app.get("/") self.assertEqual(output.status_code, 200) self.assertIn( '

All Projects ' '0

', - output.get_data(as_text=True)) + output.get_data(as_text=True), + ) # Add a private project item = pagure.lib.model.Project( user_id=2, # foo - name='test3', - description='test project description', - hook_token='aaabbbeee', + name="test3", + description="test project description", + hook_token="aaabbbeee", private=True, ) @@ -402,44 +379,47 @@ class PagurePrivateRepotest(tests.Modeltests): # Add a public project item = pagure.lib.model.Project( user_id=2, # foo - name='test4', - description='test project description', - hook_token='aaabbbeeeccceee', + name="test4", + description="test project description", + hook_token="aaabbbeeeccceee", ) self.session.add(item) self.session.commit() - output = self.app.get('/?page=abc') + output = self.app.get("/?page=abc") self.assertEqual(output.status_code, 200) output_text = output.get_data(as_text=True) self.assertIn( '

All Projects ' '1

', - output_text) + output_text, + ) - user = tests.FakeUser(username='foo') + user = tests.FakeUser(username="foo") with tests.user_set(self.app.application, user): - output = self.app.get('/', follow_redirects=True) + output = self.app.get("/", follow_redirects=True) output_text = output.get_data(as_text=True) self.assertIn( '

My Projects

', - output_text) - self.assertIn('2 Projects', output_text) + output_text, + ) + self.assertIn("2 Projects", output_text) self.assertNotIn( - 'Forks', output_text) + 'Forks', output_text + ) self.assertEqual( - output_text.count('Groups'), 0) - + output_text.count('Groups'), 0 + ) def test_view_user(self): """ Test the view_user endpoint. """ - output = self.app.get('/user/foo?repopage=abc&forkpage=def') + output = self.app.get("/user/foo?repopage=abc&forkpage=def") self.assertEqual(output.status_code, 200) output_text = output.get_data(as_text=True) self.assertIn( - """ + """ Projects  @@ -447,9 +427,11 @@ class PagurePrivateRepotest(tests.Modeltests): 0 - """, output_text) + """, + output_text, + ) self.assertIn( - """ + """ Forks  @@ -457,9 +439,11 @@ class PagurePrivateRepotest(tests.Modeltests): 0 - """, output_text) + """, + output_text, + ) self.assertIn( - """ + """ Groups  @@ -467,14 +451,16 @@ class PagurePrivateRepotest(tests.Modeltests): 0 - """, output_text) + """, + output_text, + ) # Add a private project item = pagure.lib.model.Project( user_id=2, # foo - name='test3', - description='test project description', - hook_token='aaabbbeee', + name="test3", + description="test project description", + hook_token="aaabbbeee", private=True, ) @@ -483,22 +469,23 @@ class PagurePrivateRepotest(tests.Modeltests): # Add a public project item = pagure.lib.model.Project( user_id=2, # foo - name='test4', - description='test project description', - hook_token='aaabbbeeeccceee', + name="test4", + description="test project description", + hook_token="aaabbbeeeccceee", ) self.session.add(item) self.session.commit() self.gitrepos = tests.create_projects_git( - pagure.config.config['GIT_FOLDER']) + pagure.config.config["GIT_FOLDER"] + ) - output = self.app.get('/user/foo') + output = self.app.get("/user/foo") self.assertEqual(output.status_code, 200) output_text = output.get_data(as_text=True) self.assertIn( - """ + """ Projects  @@ -506,9 +493,11 @@ class PagurePrivateRepotest(tests.Modeltests): 1 - """, output_text) + """, + output_text, + ) self.assertIn( - """ + """ Forks  @@ -516,9 +505,11 @@ class PagurePrivateRepotest(tests.Modeltests): 0 - """, output_text) + """, + output_text, + ) self.assertIn( - """ + """ Groups  @@ -526,11 +517,13 @@ class PagurePrivateRepotest(tests.Modeltests): 0 - """, output_text) + """, + output_text, + ) - user = tests.FakeUser(username='foo') + user = tests.FakeUser(username="foo") with tests.user_set(self.app.application, user): - output = self.app.get('/user/foo') + output = self.app.get("/user/foo") output_text = output.get_data(as_text=True) self.assertIn( """ @@ -541,7 +534,9 @@ class PagurePrivateRepotest(tests.Modeltests): 1 - """, output_text) + """, + output_text, + ) self.assertIn( """ @@ -551,7 +546,9 @@ class PagurePrivateRepotest(tests.Modeltests): 0 - """, output_text) + """, + output_text, + ) self.assertIn( """ @@ -561,11 +558,13 @@ class PagurePrivateRepotest(tests.Modeltests): 0 - """, output_text) + """, + output_text, + ) - user.username = 'pingou' + user.username = "pingou" with tests.user_set(self.app.application, user): - output = self.app.get('/user/foo') + output = self.app.get("/user/foo") output_text = output.get_data(as_text=True) self.assertIn( """ @@ -576,7 +575,9 @@ class PagurePrivateRepotest(tests.Modeltests): 1 - """, output_text) + """, + output_text, + ) self.assertIn( """ @@ -586,7 +587,9 @@ class PagurePrivateRepotest(tests.Modeltests): 0 - """, output_text) + """, + output_text, + ) self.assertIn( """ @@ -596,54 +599,53 @@ class PagurePrivateRepotest(tests.Modeltests): 0 - """, output_text) + """, + output_text, + ) # Check pingou has 0 projects - user.username = 'pingou' + user.username = "pingou" with tests.user_set(self.app.application, user): - output = self.app.get('/', follow_redirects=True) + output = self.app.get("/", follow_redirects=True) output_text = output.get_data(as_text=True) self.assertIn( '

My Projects

', - output_text) - self.assertIn( - '0 Projects
', - output_text) + output_text, + ) + self.assertIn("0 Projects
", output_text) self.assertNotIn( - 'Forks', - output_text) + 'Forks', output_text + ) self.assertEqual( - output_text.count('Groups'), 0) + output_text.count('Groups'), 0 + ) - repo = pagure.lib.query._get_project(self.session, 'test3') + repo = pagure.lib.query._get_project(self.session, "test3") msg = pagure.lib.query.add_user_to_project( - session=self.session, - project=repo, - new_user='pingou', - user='foo', + session=self.session, project=repo, new_user="pingou", user="foo" ) self.session.commit() - self.assertEqual(msg, 'User added') + self.assertEqual(msg, "User added") # New user added to private projects - user.username = 'pingou' + user.username = "pingou" with tests.user_set(self.app.application, user): - output = self.app.get('/', follow_redirects=True) + output = self.app.get("/", follow_redirects=True) output_text = output.get_data(as_text=True) self.assertIn( '

My Projects

', - output_text) - self.assertIn( - '1 Projects
', - output_text) + output_text, + ) + self.assertIn("1 Projects
", output_text) self.assertNotIn( - 'Forks', - output_text) + 'Forks', output_text + ) self.assertEqual( - output_text.count('Groups'), 0) + output_text.count('Groups'), 0 + ) - @patch('pagure.decorators.admin_session_timedout') + @patch("pagure.decorators.admin_session_timedout") def test_private_settings_ui(self, ast): """ Test UI for private repo""" ast.return_value = False @@ -651,9 +653,9 @@ class PagurePrivateRepotest(tests.Modeltests): # Add private repo item = pagure.lib.model.Project( user_id=1, # pingou - name='test4', - description='test project description', - hook_token='aaabbbeeeceee', + name="test4", + description="test project description", + hook_token="aaabbbeeeceee", private=True, ) self.session.add(item) @@ -661,40 +663,44 @@ class PagurePrivateRepotest(tests.Modeltests): # Add a git repo repo_path = os.path.join( - pagure.config.config.get('GIT_FOLDER'), 'test4.git') + pagure.config.config.get("GIT_FOLDER"), "test4.git" + ) if not os.path.exists(repo_path): os.makedirs(repo_path) pygit2.init_repository(repo_path) - user = tests.FakeUser(username='pingou') + user = tests.FakeUser(username="pingou") with tests.user_set(self.app.application, user): tests.create_projects(self.session) - tests.create_projects_git(pagure.config.config.get('GIT_FOLDER')) + tests.create_projects_git(pagure.config.config.get("GIT_FOLDER")) - output = self.app.get('/test/settings') + output = self.app.get("/test/settings") # Check for a public repo self.assertEqual(output.status_code, 200) self.assertNotIn( '', - output.get_data(as_text=True)) + output.get_data(as_text=True), + ) # Check the new project form has 'private' checkbox - output = self.app.get('/new') + output = self.app.get("/new") self.assertEqual(output.status_code, 200) self.assertIn( '', - output.get_data(as_text=True)) + output.get_data(as_text=True), + ) - @patch('pagure.decorators.admin_session_timedout') + @patch("pagure.decorators.admin_session_timedout") def test_private_settings_ui_update_privacy_false(self, ast): """ Test UI for private repo""" ast.return_value = False @@ -702,9 +708,9 @@ class PagurePrivateRepotest(tests.Modeltests): # Add private repo item = pagure.lib.model.Project( user_id=1, # pingou - name='test4', - description='test project description', - hook_token='aaabbbeeeceee', + name="test4", + description="test project description", + hook_token="aaabbbeeeceee", private=True, ) self.session.add(item) @@ -712,44 +718,46 @@ class PagurePrivateRepotest(tests.Modeltests): # Add a git repo repo_path = os.path.join( - pagure.config.config.get('GIT_FOLDER'), 'test4.git') + pagure.config.config.get("GIT_FOLDER"), "test4.git" + ) pygit2.init_repository(repo_path) - user = tests.FakeUser(username='pingou') + user = tests.FakeUser(username="pingou") with tests.user_set(self.app.application, user): # Check for private repo - output = self.app.get('/test4/settings') + output = self.app.get("/test4/settings") self.assertEqual(output.status_code, 200) self.assertIn( '', - output.get_data(as_text=True)) + output.get_data(as_text=True), + ) self.session.commit() - repo = pagure.lib.query._get_project(self.session, 'test4') + repo = pagure.lib.query._get_project(self.session, "test4") self.assertTrue(repo.private) # Make the project public data = { - 'description': 'test project description', - 'private': False, - 'csrf_token': self.get_csrf(), + "description": "test project description", + "private": False, + "csrf_token": self.get_csrf(), } output = self.app.post( - '/test4/update', data=data, follow_redirects=True) + "/test4/update", data=data, follow_redirects=True + ) self.assertEqual(output.status_code, 200) - self.assertIn( - 'Project updated', - output.get_data(as_text=True)) + self.assertIn("Project updated", output.get_data(as_text=True)) self.assertNotIn( '', - output.get_data(as_text=True)) + output.get_data(as_text=True), + ) self.session.commit() - repo = pagure.lib.query._get_project(self.session, 'test4') + repo = pagure.lib.query._get_project(self.session, "test4") self.assertFalse(repo.private) - @patch('pagure.decorators.admin_session_timedout') + @patch("pagure.decorators.admin_session_timedout") def test_private_settings_ui_update_privacy_true(self, ast): """ Test UI for private repo""" ast.return_value = False @@ -757,9 +765,9 @@ class PagurePrivateRepotest(tests.Modeltests): # Add private repo item = pagure.lib.model.Project( user_id=1, # pingou - name='test4', - description='test project description', - hook_token='aaabbbeeeceee', + name="test4", + description="test project description", + hook_token="aaabbbeeeceee", private=False, ) self.session.add(item) @@ -767,45 +775,47 @@ class PagurePrivateRepotest(tests.Modeltests): # Add a git repo repo_path = os.path.join( - pagure.config.config.get('GIT_FOLDER'), 'test4.git') + pagure.config.config.get("GIT_FOLDER"), "test4.git" + ) pygit2.init_repository(repo_path) - user = tests.FakeUser(username='pingou') + user = tests.FakeUser(username="pingou") with tests.user_set(self.app.application, user): # Check for public repo - output = self.app.get('/test4/settings') + output = self.app.get("/test4/settings") self.assertEqual(output.status_code, 200) self.assertNotIn( '', - output.get_data(as_text=True)) + output.get_data(as_text=True), + ) self.session.commit() - repo = pagure.lib.query._get_project(self.session, 'test4') + repo = pagure.lib.query._get_project(self.session, "test4") self.assertFalse(repo.private) # Make the project private data = { - 'description': 'test project description', - 'private': True, - 'csrf_token': self.get_csrf(), + "description": "test project description", + "private": True, + "csrf_token": self.get_csrf(), } output = self.app.post( - '/test4/update', data=data, follow_redirects=True) + "/test4/update", data=data, follow_redirects=True + ) self.assertEqual(output.status_code, 200) - self.assertIn( - 'Project updated', - output.get_data(as_text=True)) + self.assertIn("Project updated", output.get_data(as_text=True)) self.assertNotIn( '', - output.get_data(as_text=True)) + output.get_data(as_text=True), + ) # No change since we can't do public -> private self.session.commit() - repo = pagure.lib.query._get_project(self.session, 'test4') + repo = pagure.lib.query._get_project(self.session, "test4") self.assertFalse(repo.private) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_private_pr(self, send_email): """Test pull request made to the private repo""" @@ -813,40 +823,39 @@ class PagurePrivateRepotest(tests.Modeltests): # Add a private project item = pagure.lib.model.Project( user_id=1, # pingou - name='pmc', - description='test project description', - hook_token='aaabbbeeeceee', + name="pmc", + description="test project description", + hook_token="aaabbbeeeceee", private=True, ) self.session.add(item) self.session.commit() - repo = pagure.lib.query._get_project(self.session, 'pmc') + repo = pagure.lib.query._get_project(self.session, "pmc") msg = pagure.lib.query.add_user_to_project( - session=self.session, - project=repo, - new_user='foo', - user='pingou', + session=self.session, project=repo, new_user="foo", user="pingou" ) self.session.commit() - self.assertEqual(msg, 'User added') + self.assertEqual(msg, "User added") # Create all the git repos tests.create_projects_git( - os.path.join(self.path, 'requests'), bare=True) + os.path.join(self.path, "requests"), bare=True + ) # Add a git repo repo_path = os.path.join( - pagure.config.config.get('REQUESTS_FOLDER'), 'pmc.git') + pagure.config.config.get("REQUESTS_FOLDER"), "pmc.git" + ) if not os.path.exists(repo_path): os.makedirs(repo_path) pygit2.init_repository(repo_path, bare=True) # Check repo was created - Doesn't show on the public page - user = tests.FakeUser(username='pingou') + user = tests.FakeUser(username="pingou") with tests.user_set(self.app.application, user): - output = self.app.get('/user/pingou/') + output = self.app.get("/user/pingou/") self.assertEqual(output.status_code, 200) self.assertIn( """ @@ -857,7 +866,9 @@ class PagurePrivateRepotest(tests.Modeltests): 0 - """, output.get_data(as_text=True)) + """, + output.get_data(as_text=True), + ) self.assertIn( """ @@ -867,10 +878,12 @@ class PagurePrivateRepotest(tests.Modeltests): 0 - """, output.get_data(as_text=True)) + """, + output.get_data(as_text=True), + ) # Shows on the front page - output = self.app.get('/dashboard/projects') + output = self.app.get("/dashboard/projects") self.assertEqual(output.status_code, 200) self.assertIn( """ @@ -881,33 +894,35 @@ class PagurePrivateRepotest(tests.Modeltests): 1 - """, output.get_data(as_text=True)) + """, + output.get_data(as_text=True), + ) - self.set_up_git_repo(new_project=None, branch_from='feature') - project = pagure.lib.query._get_project(self.session, 'pmc') + self.set_up_git_repo(new_project=None, branch_from="feature") + project = pagure.lib.query._get_project(self.session, "pmc") self.assertEqual(len(project.requests), 1) - output = self.app.get('/pmc/pull-request/1') + output = self.app.get("/pmc/pull-request/1") self.assertEqual(output.status_code, 200) # Check repo was created user = tests.FakeUser() with tests.user_set(self.app.application, user): - output = self.app.get('/pmc/pull-requests') + output = self.app.get("/pmc/pull-requests") self.assertEqual(output.status_code, 404) - user = tests.FakeUser(username='pingou') + user = tests.FakeUser(username="pingou") with tests.user_set(self.app.application, user): - output = self.app.get('/pmc/pull-requests') + output = self.app.get("/pmc/pull-requests") self.assertEqual(output.status_code, 200) - user = tests.FakeUser(username='foo') + user = tests.FakeUser(username="foo") with tests.user_set(self.app.application, user): - output = self.app.get('/pmc/pull-requests') + output = self.app.get("/pmc/pull-requests") self.assertEqual(output.status_code, 200) - @patch('pagure.lib.git.update_git') - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.git.update_git") + @patch("pagure.lib.notify.send_email") def test_private_repo_issues_ui(self, p_send_email, p_ugt): """ Test issues made to private repo""" p_send_email.return_value = True @@ -916,98 +931,104 @@ class PagurePrivateRepotest(tests.Modeltests): # Add private repo item = pagure.lib.model.Project( user_id=1, # pingou - name='test4', - description='test project description', - hook_token='aaabbbeeeceee', + name="test4", + description="test project description", + hook_token="aaabbbeeeceee", private=True, ) self.session.add(item) self.session.commit() - for repo in ['GIT_FOLDER', 'TICKETS_FOLDER']: + for repo in ["GIT_FOLDER", "TICKETS_FOLDER"]: # Add a git repo repo_path = os.path.join( - pagure.config.config.get(repo), 'test4.git') + pagure.config.config.get(repo), "test4.git" + ) if not os.path.exists(repo_path): os.makedirs(repo_path) pygit2.init_repository(repo_path) # Check if the private repo issues are publicly not accesible - output = self.app.get('/test4/issues') + output = self.app.get("/test4/issues") self.assertEqual(output.status_code, 404) # Create issues to play with - repo = pagure.lib.query._get_project(self.session, 'test4') + repo = pagure.lib.query._get_project(self.session, "test4") msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue', - content='We should work on this', - user='pingou', + title="Test issue", + content="We should work on this", + user="pingou", ) self.session.commit() - self.assertEqual(msg.title, 'Test issue') + self.assertEqual(msg.title, "Test issue") user = tests.FakeUser() with tests.user_set(self.app.application, user): # Whole list - output = self.app.get('/test4/issues') + output = self.app.get("/test4/issues") self.assertEqual(output.status_code, 404) # Check single issue - output = self.app.get('/test4/issue/1') + output = self.app.get("/test4/issue/1") self.assertEqual(output.status_code, 404) user = tests.FakeUser() with tests.user_set(self.app.application, user): # Whole list - output = self.app.get('/test4/issues') + output = self.app.get("/test4/issues") self.assertEqual(output.status_code, 404) - user = tests.FakeUser(username='pingou') + user = tests.FakeUser(username="pingou") with tests.user_set(self.app.application, user): # Whole list - output = self.app.get('/test4/issues') + output = self.app.get("/test4/issues") self.assertEqual(output.status_code, 200) self.assertIn( - 'Issues - test4 - Pagure', output.get_data(as_text=True)) + "Issues - test4 - Pagure", + output.get_data(as_text=True), + ) self.assertTrue( - ' 1 Open Issues\n' in output.get_data(as_text=True)) + ' 1 Open Issues\n' + in output.get_data(as_text=True) + ) # Check single issue - output = self.app.get('/test4/issue/1') + output = self.app.get("/test4/issue/1") self.assertEqual(output.status_code, 200) - repo = pagure.lib.query._get_project(self.session, 'test4') + repo = pagure.lib.query._get_project(self.session, "test4") msg = pagure.lib.query.add_user_to_project( - session=self.session, - project=repo, - new_user='foo', - user='pingou', + session=self.session, project=repo, new_user="foo", user="pingou" ) self.session.commit() - self.assertEqual(msg, 'User added') + self.assertEqual(msg, "User added") - user.username = 'foo' + user.username = "foo" with tests.user_set(self.app.application, user): # Whole list - output = self.app.get('/test4/issues') + output = self.app.get("/test4/issues") self.assertEqual(output.status_code, 200) self.assertIn( - 'Issues - test4 - Pagure', output.get_data(as_text=True)) + "Issues - test4 - Pagure", + output.get_data(as_text=True), + ) self.assertTrue( - ' 1 Open Issues\n' in output.get_data(as_text=True)) + ' 1 Open Issues\n' + in output.get_data(as_text=True) + ) # Check single issue - output = self.app.get('/test4/issue/1') + output = self.app.get("/test4/issue/1") self.assertEqual(output.status_code, 200) - @patch('pagure.decorators.admin_session_timedout') + @patch("pagure.decorators.admin_session_timedout") def test_private_repo_ui_for_different_repo_user(self, ast): """ Test the private repo for different ACLS""" ast.return_value = False @@ -1015,9 +1036,9 @@ class PagurePrivateRepotest(tests.Modeltests): # Add private repo item = pagure.lib.model.Project( user_id=1, # pingou - name='test4', - description='test project description', - hook_token='aaabbbeeeceee', + name="test4", + description="test project description", + hook_token="aaabbbeeeceee", private=True, ) self.session.add(item) @@ -1026,21 +1047,22 @@ class PagurePrivateRepotest(tests.Modeltests): repo = pagure.lib.query._get_project(self.session, "test4") # Add a git repo repo_path = os.path.join( - pagure.config.config.get('GIT_FOLDER'), 'test4.git') + pagure.config.config.get("GIT_FOLDER"), "test4.git" + ) pygit2.init_repository(repo_path) - user = tests.FakeUser(username='pingou') + user = tests.FakeUser(username="pingou") with tests.user_set(self.app.application, user): # Check for private repo - output = self.app.get('/test4') + output = self.app.get("/test4") self.assertEqual(output.status_code, 200) # Check if the user who doesn't have access to private repo can access it user = tests.FakeUser(username="foo") with tests.user_set(self.app.application, user): - output = self.app.get('/test4') + output = self.app.get("/test4") self.assertEqual(output.status_code, 404) # Add commit access to a user @@ -1049,11 +1071,10 @@ class PagurePrivateRepotest(tests.Modeltests): project=repo, new_user="foo", user="pingou", - access='commit' + access="commit", ) self.session.commit() - repo = pagure.lib.query._get_project(self.session, "test4") self.assertEqual(len(repo.users), 1) @@ -1061,20 +1082,18 @@ class PagurePrivateRepotest(tests.Modeltests): user = tests.FakeUser(username="foo") with tests.user_set(self.app.application, user): - output = self.app.get('/test4') + output = self.app.get("/test4") self.assertEqual(output.status_code, 200) # Making a new user bar item = pagure.lib.model.User( - user='bar', - fullname='bar baz', - password='foo', - default_email='bar@bar.com', + user="bar", + fullname="bar baz", + password="foo", + default_email="bar@bar.com", ) self.session.add(item) - item = pagure.lib.model.UserEmail( - user_id=3, - email='bar@bar.com') + item = pagure.lib.model.UserEmail(user_id=3, email="bar@bar.com") self.session.add(item) self.session.commit() @@ -1083,7 +1102,7 @@ class PagurePrivateRepotest(tests.Modeltests): user = tests.FakeUser(username="bar") with tests.user_set(self.app.application, user): - output = self.app.get('/test4') + output = self.app.get("/test4") self.assertEqual(output.status_code, 404) # Adding a ticket level access to bar @@ -1092,7 +1111,7 @@ class PagurePrivateRepotest(tests.Modeltests): project=repo, new_user="bar", user="pingou", - access='ticket' + access="ticket", ) self.session.commit() @@ -1103,7 +1122,7 @@ class PagurePrivateRepotest(tests.Modeltests): user = tests.FakeUser(username="bar") with tests.user_set(self.app.application, user): - output = self.app.get('/test4') + output = self.app.get("/test4") self.assertEqual(output.status_code, 200) # API checks @@ -1113,214 +1132,211 @@ class PagurePrivateRepotest(tests.Modeltests): # Add private repo item = pagure.lib.model.Project( user_id=1, # pingou - name='test4', - description='test project description', - hook_token='aaabbbeeeceee', + name="test4", + description="test project description", + hook_token="aaabbbeeeceee", private=True, ) self.session.add(item) self.session.commit() # Create a git repo to play with - gitrepo = os.path.join(self.path, 'repos', 'test4.git') + gitrepo = os.path.join(self.path, "repos", "test4.git") repo = pygit2.init_repository(gitrepo, bare=True) - newpath = tempfile.mkdtemp(prefix='pagure-fork-test') - repopath = os.path.join(newpath, 'repos', 'test4') + newpath = tempfile.mkdtemp(prefix="pagure-fork-test") + repopath = os.path.join(newpath, "repos", "test4") clone_repo = pygit2.clone_repository(gitrepo, repopath) # Create a file in that git repo - with open(os.path.join(repopath, 'sources'), 'w') as stream: - stream.write('foo\n bar') - clone_repo.index.add('sources') + with open(os.path.join(repopath, "sources"), "w") as stream: + stream.write("foo\n bar") + clone_repo.index.add("sources") clone_repo.index.write() # Commits the files added tree = clone_repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") clone_repo.create_commit( - 'refs/heads/master', # the name of the reference to update + "refs/heads/master", # the name of the reference to update author, committer, - 'Add sources file for testing', + "Add sources file for testing", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [] + [], ) - refname = 'refs/heads/master:refs/heads/master' + refname = "refs/heads/master:refs/heads/master" ori_remote = clone_repo.remotes[0] PagureRepo.push(ori_remote, refname) # Tag our first commit - first_commit = repo.revparse_single('HEAD') - tagger = pygit2.Signature('Alice Doe', 'adoe@example.com', 12347, 0) + first_commit = repo.revparse_single("HEAD") + tagger = pygit2.Signature("Alice Doe", "adoe@example.com", 12347, 0) repo.create_tag( - "0.0.1", first_commit.oid.hex, pygit2.GIT_OBJ_COMMIT, tagger, - "Release 0.0.1") + "0.0.1", + first_commit.oid.hex, + pygit2.GIT_OBJ_COMMIT, + tagger, + "Release 0.0.1", + ) # Create a token for foo for this project item = pagure.lib.model.Token( - id='foobar_token', + id="foobar_token", user_id=1, project_id=1, - expiration=datetime.datetime.utcnow() + datetime.timedelta( - days=30) + expiration=datetime.datetime.utcnow() + + datetime.timedelta(days=30), ) self.session.add(item) self.session.commit() - item = pagure.lib.model.TokenAcl( - token_id='foobar_token', - acl_id=1, - ) + item = pagure.lib.model.TokenAcl(token_id="foobar_token", acl_id=1) self.session.add(item) self.session.commit() # Check if the admin requests - user = tests.FakeUser(username='pingou') + user = tests.FakeUser(username="pingou") with tests.user_set(self.app.application, user): # Check tags - output = self.app.get('/api/0/test4/git/tags') + output = self.app.get("/api/0/test4/git/tags") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'tags': ['0.0.1'], 'total_tags': 1} - ) + self.assertDictEqual(data, {"tags": ["0.0.1"], "total_tags": 1}) - output = self.app.get('/api/0/test4/git/tags') + output = self.app.get("/api/0/test4/git/tags") self.assertEqual(output.status_code, 404) # Chekc if user is not admin user = tests.FakeUser() with tests.user_set(self.app.application, user): - output = self.app.get('/api/0/test4/git/tags') + output = self.app.get("/api/0/test4/git/tags") self.assertEqual(output.status_code, 404) shutil.rmtree(newpath) # Check before adding - repo = pagure.lib.query._get_project(self.session, 'test4') + repo = pagure.lib.query._get_project(self.session, "test4") self.assertEqual(repo.tags, []) # Adding a tag output = pagure.lib.query.update_tags( - self.session, repo, 'infra', 'pingou') - self.assertEqual(output, ['Project tagged with: infra']) + self.session, repo, "infra", "pingou" + ) + self.assertEqual(output, ["Project tagged with: infra"]) # Check after adding - repo = pagure.lib.query._get_project(self.session, 'test4') + repo = pagure.lib.query._get_project(self.session, "test4") self.assertEqual(len(repo.tags), 1) - self.assertEqual(repo.tags_text, ['infra']) + self.assertEqual(repo.tags_text, ["infra"]) # Check the API - output = self.app.get('/api/0/projects?tags=inf') + output = self.app.get("/api/0/projects?tags=inf") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - del data['pagination'] + del data["pagination"] self.assertDictEqual( data, { - 'args': { - 'fork': None, - 'namespace': None, - 'owner': None, - 'page': 1, - 'pattern': None, - 'per_page': 20, - 'short': False, - 'tags': ['inf'], - 'username': None + "args": { + "fork": None, + "namespace": None, + "owner": None, + "page": 1, + "pattern": None, + "per_page": 20, + "short": False, + "tags": ["inf"], + "username": None, }, - 'projects': [], - 'total_projects': 0 - } + "projects": [], + "total_projects": 0, + }, ) # Request by not a loggged in user - output = self.app.get('/api/0/projects?tags=infra') + output = self.app.get("/api/0/projects?tags=infra") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - del data['pagination'] + del data["pagination"] self.assertDictEqual( data, { - 'args': { - 'fork': None, - 'namespace': None, - 'owner': None, - 'page': 1, - 'pattern': None, - 'per_page': 20, - 'short': False, - 'tags': ['infra'], - 'username': None + "args": { + "fork": None, + "namespace": None, + "owner": None, + "page": 1, + "pattern": None, + "per_page": 20, + "short": False, + "tags": ["infra"], + "username": None, }, - 'projects': [], - 'total_projects': 0 - } + "projects": [], + "total_projects": 0, + }, ) user = tests.FakeUser() with tests.user_set(self.app.application, user): # Request by a non authorized user - output = self.app.get('/api/0/projects?tags=infra') + output = self.app.get("/api/0/projects?tags=infra") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - del data['pagination'] + del data["pagination"] self.assertDictEqual( data, { - 'args': { - 'fork': None, - 'namespace': None, - 'owner': None, - 'page': 1, - 'pattern': None, - 'per_page': 20, - 'short': False, - 'tags': ['infra'], - 'username': None + "args": { + "fork": None, + "namespace": None, + "owner": None, + "page": 1, + "pattern": None, + "per_page": 20, + "short": False, + "tags": ["infra"], + "username": None, }, - 'projects': [], - 'total_projects': 0 - } + "projects": [], + "total_projects": 0, + }, ) - user.username = 'pingou' + user.username = "pingou" with tests.user_set(self.app.application, user): # Private repo username is compulsion to pass - output = self.app.get('/api/0/projects?tags=infra') + output = self.app.get("/api/0/projects?tags=infra") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - del data['pagination'] + del data["pagination"] self.assertDictEqual( data, { - 'args': { - 'fork': None, - 'namespace': None, - 'owner': None, - 'page': 1, - 'pattern': None, - 'per_page': 20, - 'short': False, - 'tags': ['infra'], - 'username': None + "args": { + "fork": None, + "namespace": None, + "owner": None, + "page": 1, + "pattern": None, + "per_page": 20, + "short": False, + "tags": ["infra"], + "username": None, }, - 'projects': [], - 'total_projects': 0 - } + "projects": [], + "total_projects": 0, + }, ) - output = self.app.get('/api/0/projects?username=pingou') + output = self.app.get("/api/0/projects?username=pingou") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['projects'][0]['date_created'] = "1436527638" - data['projects'][0]['date_modified'] = "1436527638" - del data['pagination'] + data["projects"][0]["date_created"] = "1436527638" + data["projects"][0]["date_modified"] = "1436527638" + del data["pagination"] self.assertDictEqual( data, { @@ -1333,7 +1349,7 @@ class PagurePrivateRepotest(tests.Modeltests): "per_page": 20, "short": False, "tags": [], - "username": "pingou" + "username": "pingou", }, "total_projects": 1, "projects": [ @@ -1341,15 +1357,13 @@ class PagurePrivateRepotest(tests.Modeltests): "access_groups": { "admin": [], "commit": [], - "ticket": [] + "ticket": [], }, "access_users": { "admin": [], "commit": [], - "owner": [ - "pingou" - ], - "ticket": [] + "owner": ["pingou"], + "ticket": [], }, "close_status": [], "custom_keys": [], @@ -1365,21 +1379,18 @@ class PagurePrivateRepotest(tests.Modeltests): "parent": None, "priorities": {}, "tags": ["infra"], - "user": { - "fullname": "PY C", - "name": "pingou" - } - }, - ] - } + "user": {"fullname": "PY C", "name": "pingou"}, + } + ], + }, ) - output = self.app.get('/api/0/projects?username=pingou&tags=infra') + output = self.app.get("/api/0/projects?username=pingou&tags=infra") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['projects'][0]['date_created'] = "1436527638" - data['projects'][0]['date_modified'] = "1436527638" - del data['pagination'] + data["projects"][0]["date_created"] = "1436527638" + data["projects"][0]["date_modified"] = "1436527638" + del data["pagination"] self.assertDictEqual( data, { @@ -1392,7 +1403,7 @@ class PagurePrivateRepotest(tests.Modeltests): "per_page": 20, "short": False, "tags": ["infra"], - "username": "pingou" + "username": "pingou", }, "total_projects": 1, "projects": [ @@ -1400,15 +1411,13 @@ class PagurePrivateRepotest(tests.Modeltests): "access_groups": { "admin": [], "commit": [], - "ticket": [] + "ticket": [], }, "access_users": { "admin": [], "commit": [], - "owner": [ - "pingou" - ], - "ticket": [] + "owner": ["pingou"], + "ticket": [], }, "close_status": [], "custom_keys": [], @@ -1424,18 +1433,14 @@ class PagurePrivateRepotest(tests.Modeltests): "parent": None, "priorities": {}, "tags": ["infra"], - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, } - ] - } - + ], + }, ) # Api pull-request views - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_private_repo_fork(self, send_email): """ Test api endpoints in api/fork""" @@ -1444,9 +1449,9 @@ class PagurePrivateRepotest(tests.Modeltests): # Add private repo item = pagure.lib.model.Project( user_id=1, # pingou - name='test4', - description='test project description', - hook_token='aaabbbeeeceee', + name="test4", + description="test project description", + hook_token="aaabbbeeeceee", private=True, ) self.session.add(item) @@ -1455,48 +1460,48 @@ class PagurePrivateRepotest(tests.Modeltests): tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Create a pull-request - repo = pagure.lib.query._get_project(self.session, 'test4') - forked_repo = pagure.lib.query._get_project(self.session, 'test4') + repo = pagure.lib.query._get_project(self.session, "test4") + forked_repo = pagure.lib.query._get_project(self.session, "test4") req = pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") # Check list of PR - output = self.app.get('/api/0/test4/pull-requests') + output = self.app.get("/api/0/test4/pull-requests") self.assertEqual(output.status_code, 404) # Check single PR - output = self.app.get('/api/0/test/pull-request/1') + output = self.app.get("/api/0/test/pull-request/1") self.assertEqual(output.status_code, 404) - user = tests.FakeUser(username='pingou') + user = tests.FakeUser(username="pingou") with tests.user_set(self.app.application, user): # List pull-requests - output = self.app.get('/api/0/test4/pull-requests') + output = self.app.get("/api/0/test4/pull-requests") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['requests'][0]['date_created'] = '1431414800' - data['requests'][0]['updated_on'] = '1431414800' - data['requests'][0]['project']['date_created'] = '1431414800' - data['requests'][0]['project']['date_modified'] = '1431414800' - data['requests'][0]['repo_from']['date_created'] = '1431414800' - data['requests'][0]['repo_from']['date_modified'] = '1431414800' - data['requests'][0]['uid'] = '1431414800' - data['requests'][0]['last_updated'] = '1431414800' - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + data["requests"][0]["date_created"] = "1431414800" + data["requests"][0]["updated_on"] = "1431414800" + data["requests"][0]["project"]["date_created"] = "1431414800" + data["requests"][0]["project"]["date_modified"] = "1431414800" + data["requests"][0]["repo_from"]["date_created"] = "1431414800" + data["requests"][0]["repo_from"]["date_modified"] = "1431414800" + data["requests"][0]["uid"] = "1431414800" + data["requests"][0]["last_updated"] = "1431414800" + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." self.assertDictEqual( data, { @@ -1505,16 +1510,16 @@ class PagurePrivateRepotest(tests.Modeltests): "author": None, "page": 1, "per_page": 20, - "status": True + "status": True, }, "pagination": { - "first": 'http://localhost...', - "last": 'http://localhost...', + "first": "http://localhost...", + "last": "http://localhost...", "next": None, "page": 1, "pages": 1, "per_page": 20, - "prev": None + "prev": None, }, "requests": [ { @@ -1535,15 +1540,13 @@ class PagurePrivateRepotest(tests.Modeltests): "access_groups": { "admin": [], "commit": [], - "ticket": [] + "ticket": [], }, "access_users": { "admin": [], "commit": [], - "owner": [ - "pingou" - ], - "ticket": [] + "owner": ["pingou"], + "ticket": [], }, "close_status": [], "custom_keys": [], @@ -1559,25 +1562,20 @@ class PagurePrivateRepotest(tests.Modeltests): "parent": None, "priorities": {}, "tags": [], - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, }, "remote_git": None, "repo_from": { "access_groups": { "admin": [], "commit": [], - "ticket": [] + "ticket": [], }, "access_users": { "admin": [], "commit": [], - "owner": [ - "pingou" - ], - "ticket": [] + "owner": ["pingou"], + "ticket": [], }, "close_status": [], "custom_keys": [], @@ -1593,10 +1591,7 @@ class PagurePrivateRepotest(tests.Modeltests): "parent": None, "priorities": {}, "tags": [], - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, }, "status": "Open", "tags": [], @@ -1604,48 +1599,46 @@ class PagurePrivateRepotest(tests.Modeltests): "title": "test pull-request", "uid": "1431414800", "updated_on": "1431414800", - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, } ], - "total_requests": 1 - } + "total_requests": 1, + }, ) - headers = {'Authorization': 'token foobar_token'} + headers = {"Authorization": "token foobar_token"} # Access Pull-Request authenticated output = self.app.get( - '/api/0/test4/pull-requests', headers=headers) + "/api/0/test4/pull-requests", headers=headers + ) self.assertEqual(output.status_code, 200) data2 = json.loads(output.get_data(as_text=True)) - data2['requests'][0]['date_created'] = '1431414800' - data2['requests'][0]['updated_on'] = '1431414800' - data2['requests'][0]['project']['date_created'] = '1431414800' - data2['requests'][0]['project']['date_modified'] = '1431414800' - data2['requests'][0]['repo_from']['date_created'] = '1431414800' - data2['requests'][0]['repo_from']['date_modified'] = '1431414800' - data2['requests'][0]['uid'] = '1431414800' - data2['requests'][0]['last_updated'] = '1431414800' - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data2['pagination'][k] = 'http://localhost...' + data2["requests"][0]["date_created"] = "1431414800" + data2["requests"][0]["updated_on"] = "1431414800" + data2["requests"][0]["project"]["date_created"] = "1431414800" + data2["requests"][0]["project"]["date_modified"] = "1431414800" + data2["requests"][0]["repo_from"]["date_created"] = "1431414800" + data2["requests"][0]["repo_from"]["date_modified"] = "1431414800" + data2["requests"][0]["uid"] = "1431414800" + data2["requests"][0]["last_updated"] = "1431414800" + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data2["pagination"][k] = "http://localhost..." self.assertDictEqual(data, data2) # For single PR - output = self.app.get('/api/0/test4/pull-request/1') + output = self.app.get("/api/0/test4/pull-request/1") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['date_created'] = '1431414800' - data['updated_on'] = '1431414800' - data['project']['date_created'] = '1431414800' - data['project']['date_modified'] = '1431414800' - data['repo_from']['date_created'] = '1431414800' - data['repo_from']['date_modified'] = '1431414800' - data['uid'] = '1431414800' - data['last_updated'] = '1431414800' + data["date_created"] = "1431414800" + data["updated_on"] = "1431414800" + data["project"]["date_created"] = "1431414800" + data["project"]["date_modified"] = "1431414800" + data["repo_from"]["date_created"] = "1431414800" + data["repo_from"]["date_modified"] = "1431414800" + data["uid"] = "1431414800" + data["last_updated"] = "1431414800" self.assertDictEqual( data, { @@ -1666,15 +1659,13 @@ class PagurePrivateRepotest(tests.Modeltests): "access_groups": { "admin": [], "commit": [], - "ticket": [] + "ticket": [], }, "access_users": { "admin": [], "commit": [], - "owner": [ - "pingou" - ], - "ticket": [] + "owner": ["pingou"], + "ticket": [], }, "close_status": [], "custom_keys": [], @@ -1690,25 +1681,20 @@ class PagurePrivateRepotest(tests.Modeltests): "parent": None, "priorities": {}, "tags": [], - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, }, "remote_git": None, "repo_from": { - "access_groups": { + "access_groups": { "admin": [], "commit": [], - "ticket": [] + "ticket": [], }, "access_users": { "admin": [], "commit": [], - "owner": [ - "pingou" - ], - "ticket": [] + "owner": ["pingou"], + "ticket": [], }, "close_status": [], "custom_keys": [], @@ -1724,10 +1710,7 @@ class PagurePrivateRepotest(tests.Modeltests): "parent": None, "priorities": {}, "tags": [], - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, }, "status": "Open", "tags": [], @@ -1735,42 +1718,39 @@ class PagurePrivateRepotest(tests.Modeltests): "title": "test pull-request", "uid": "1431414800", "updated_on": "1431414800", - "user": { - "fullname": "PY C", - "name": "pingou" - }, - } - + "user": {"fullname": "PY C", "name": "pingou"}, + }, ) # Access Pull-Request authenticated output = self.app.get( - '/api/0/test4/pull-request/1', headers=headers) + "/api/0/test4/pull-request/1", headers=headers + ) self.assertEqual(output.status_code, 200) data2 = json.loads(output.get_data(as_text=True)) - data2['date_created'] = '1431414800' - data2['project']['date_created'] = '1431414800' - data2['project']['date_modified'] = '1431414800' - data2['repo_from']['date_created'] = '1431414800' - data2['repo_from']['date_modified'] = '1431414800' - data2['uid'] = '1431414800' - data2['date_created'] = '1431414800' - data2['updated_on'] = '1431414800' - data2['last_updated'] = '1431414800' + data2["date_created"] = "1431414800" + data2["project"]["date_created"] = "1431414800" + data2["project"]["date_modified"] = "1431414800" + data2["repo_from"]["date_created"] = "1431414800" + data2["repo_from"]["date_modified"] = "1431414800" + data2["uid"] = "1431414800" + data2["date_created"] = "1431414800" + data2["updated_on"] = "1431414800" + data2["last_updated"] = "1431414800" self.assertDictEqual(data, data2) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_pr_private_repo_add_comment(self, mockemail): """ Test the api_pull_request_add_comment method of the flask api. """ mockemail.return_value = True - pagure.config.config['REQUESTS_FOLDER'] = None + pagure.config.config["REQUESTS_FOLDER"] = None # Add private repo item = pagure.lib.model.Project( user_id=1, # pingou - name='test4', - description='test project description', - hook_token='aaabbbeeeceee', + name="test4", + description="test project description", + hook_token="aaabbbeeeceee", private=True, ) self.session.add(item) @@ -1778,36 +1758,36 @@ class PagurePrivateRepotest(tests.Modeltests): tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Create a pull-request - repo = pagure.lib.query._get_project(self.session, 'test4') - forked_repo = pagure.lib.query._get_project(self.session, 'test4') + repo = pagure.lib.query._get_project(self.session, "test4") + forked_repo = pagure.lib.query._get_project(self.session, "test4") req = pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") # Check comments before self.session.commit() request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual(len(request.comments), 0) - data = { - 'title': 'test issue', - } + data = {"title": "test issue"} # Incomplete request output = self.app.post( - '/api/0/test4/pull-request/1/comment', data=data, headers=headers) + "/api/0/test4/pull-request/1/comment", data=data, headers=headers + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( @@ -1815,48 +1795,46 @@ class PagurePrivateRepotest(tests.Modeltests): { "error": "Invalid or incomplete input submitted", "error_code": "EINVALIDREQ", - "errors": {"comment": ["This field is required."]} - } + "errors": {"comment": ["This field is required."]}, + }, ) # No change self.session.commit() request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual(len(request.comments), 0) - data = { - 'comment': 'This is a very interesting question', - } + data = {"comment": "This is a very interesting question"} # Valid request output = self.app.post( - '/api/0/test4/pull-request/1/comment', data=data, headers=headers) + "/api/0/test4/pull-request/1/comment", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'Comment added'} - ) + self.assertDictEqual(data, {"message": "Comment added"}) # One comment added self.session.commit() request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual(len(request.comments), 1) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_private_repo_pr_add_flag(self, mockemail): """ Test the api_pull_request_add_flag method of the flask api. """ mockemail.return_value = True - pagure.config.config['REQUESTS_FOLDER'] = None + pagure.config.config["REQUESTS_FOLDER"] = None # Add private repo item = pagure.lib.model.Project( user_id=1, # pingou - name='test4', - description='test project description', - hook_token='aaabbbeeeceee', + name="test4", + description="test project description", + hook_token="aaabbbeeeceee", private=True, ) self.session.add(item) @@ -1865,9 +1843,9 @@ class PagurePrivateRepotest(tests.Modeltests): # Add private repo item = pagure.lib.model.Project( user_id=1, # pingou - name='test2', - description='test project description', - hook_token='foo_bar', + name="test2", + description="test project description", + hook_token="foo_bar", private=True, ) self.session.add(item) @@ -1876,77 +1854,74 @@ class PagurePrivateRepotest(tests.Modeltests): tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Invalid project output = self.app.post( - '/api/0/foo/pull-request/1/flag', headers=headers) + "/api/0/foo/pull-request/1/flag", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) # Valid token, wrong project output = self.app.post( - '/api/0/test2/pull-request/1/flag', headers=headers) + "/api/0/test2/pull-request/1/flag", headers=headers + ) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(sorted(data.keys()), ['error', 'error_code']) - self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.value, data['error']) + self.assertEqual(sorted(data.keys()), ["error", "error_code"]) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.name, data['error_code']) + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) # No input output = self.app.post( - '/api/0/test4/pull-request/1/flag', headers=headers) + "/api/0/test4/pull-request/1/flag", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Pull-Request not found", - "error_code": "ENOREQ", - } + data, {"error": "Pull-Request not found", "error_code": "ENOREQ"} ) # Create a pull-request - repo = pagure.lib.query._get_project(self.session, 'test4') - forked_repo = pagure.lib.query._get_project(self.session, 'test4') + repo = pagure.lib.query._get_project(self.session, "test4") + forked_repo = pagure.lib.query._get_project(self.session, "test4") req = pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") # Check comments before self.session.commit() request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual(len(request.flags), 0) data = { - 'username': 'Jenkins', - 'percent': 100, - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'uid': 'jenkins_build_pagure_100+seed', + "username": "Jenkins", + "percent": 100, + "url": "http://jenkins.cloud.fedoraproject.org/", + "uid": "jenkins_build_pagure_100+seed", } # Incomplete request output = self.app.post( - '/api/0/test4/pull-request/1/flag', data=data, headers=headers) + "/api/0/test4/pull-request/1/flag", data=data, headers=headers + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( @@ -1954,127 +1929,136 @@ class PagurePrivateRepotest(tests.Modeltests): { "error": "Invalid or incomplete input submitted", "error_code": "EINVALIDREQ", - "errors": {"comment": ["This field is required."]} - } + "errors": {"comment": ["This field is required."]}, + }, ) # No change self.session.commit() request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual(len(request.flags), 0) data = { - 'username': 'Jenkins', - 'percent': 0, - 'comment': 'Tests failed', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'uid': 'jenkins_build_pagure_100+seed', + "username": "Jenkins", + "percent": 0, + "comment": "Tests failed", + "url": "http://jenkins.cloud.fedoraproject.org/", + "uid": "jenkins_build_pagure_100+seed", } # Valid request output = self.app.post( - '/api/0/test4/pull-request/1/flag', data=data, headers=headers) + "/api/0/test4/pull-request/1/flag", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['flag']['date_created'] = '1510742565' - data['flag']['date_updated'] = '1510742565' - data['flag']['pull_request_uid'] = '62b49f00d489452994de5010565fab81' + data["flag"]["date_created"] = "1510742565" + data["flag"]["date_updated"] = "1510742565" + data["flag"]["pull_request_uid"] = "62b49f00d489452994de5010565fab81" data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( data, { - 'flag': { - 'comment': 'Tests failed', - 'date_created': '1510742565', - 'date_updated': '1510742565', - 'percent': 0, - 'pull_request_uid': '62b49f00d489452994de5010565fab81', - 'status': 'failure', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'user': { - 'default_email': 'bar@pingou.com', - 'emails': ['bar@pingou.com', 'foo@pingou.com'], - 'fullname': 'PY C', - 'name': 'pingou'}, - 'username': 'Jenkins'}, - 'message': 'Flag added', - 'uid': 'jenkins_build_pagure_100+seed', - 'avatar_url': 'https://seccdn.libravatar.org/avatar/...', - 'user': 'pingou' - } + "flag": { + "comment": "Tests failed", + "date_created": "1510742565", + "date_updated": "1510742565", + "percent": 0, + "pull_request_uid": "62b49f00d489452994de5010565fab81", + "status": "failure", + "url": "http://jenkins.cloud.fedoraproject.org/", + "user": { + "default_email": "bar@pingou.com", + "emails": ["bar@pingou.com", "foo@pingou.com"], + "fullname": "PY C", + "name": "pingou", + }, + "username": "Jenkins", + }, + "message": "Flag added", + "uid": "jenkins_build_pagure_100+seed", + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + "user": "pingou", + }, ) # One flag added self.session.commit() request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual(len(request.flags), 1) - self.assertEqual(request.flags[0].comment, 'Tests failed') + self.assertEqual(request.flags[0].comment, "Tests failed") self.assertEqual(request.flags[0].percent, 0) # Update flag data = { - 'username': 'Jenkins', - 'percent': 100, - 'comment': 'Tests passed', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'uid': 'jenkins_build_pagure_100+seed', + "username": "Jenkins", + "percent": 100, + "comment": "Tests passed", + "url": "http://jenkins.cloud.fedoraproject.org/", + "uid": "jenkins_build_pagure_100+seed", } output = self.app.post( - '/api/0/test4/pull-request/1/flag', data=data, headers=headers) + "/api/0/test4/pull-request/1/flag", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['flag']['date_created'] = '1510742565' - data['flag']['date_updated'] = '1510742565' - data['flag']['pull_request_uid'] = '62b49f00d489452994de5010565fab81' + data["flag"]["date_created"] = "1510742565" + data["flag"]["date_updated"] = "1510742565" + data["flag"]["pull_request_uid"] = "62b49f00d489452994de5010565fab81" data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( data, { - 'flag': { - 'comment': 'Tests passed', - 'date_created': '1510742565', - 'date_updated': '1510742565', - 'percent': 100, - 'pull_request_uid': '62b49f00d489452994de5010565fab81', - 'status': 'success', - 'url': 'http://jenkins.cloud.fedoraproject.org/', - 'user': { - 'default_email': 'bar@pingou.com', - 'emails': ['bar@pingou.com', 'foo@pingou.com'], - 'fullname': 'PY C', - 'name': 'pingou'}, - 'username': 'Jenkins'}, - 'message': 'Flag updated', - 'uid': 'jenkins_build_pagure_100+seed', - 'avatar_url': 'https://seccdn.libravatar.org/avatar/...', - 'user': 'pingou' - } + "flag": { + "comment": "Tests passed", + "date_created": "1510742565", + "date_updated": "1510742565", + "percent": 100, + "pull_request_uid": "62b49f00d489452994de5010565fab81", + "status": "success", + "url": "http://jenkins.cloud.fedoraproject.org/", + "user": { + "default_email": "bar@pingou.com", + "emails": ["bar@pingou.com", "foo@pingou.com"], + "fullname": "PY C", + "name": "pingou", + }, + "username": "Jenkins", + }, + "message": "Flag updated", + "uid": "jenkins_build_pagure_100+seed", + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + "user": "pingou", + }, ) # One flag added self.session.commit() request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual(len(request.flags), 1) - self.assertEqual(request.flags[0].comment, 'Tests passed') + self.assertEqual(request.flags[0].comment, "Tests passed") self.assertEqual(request.flags[0].percent, 100) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_private_repo_pr_close(self, send_email): """ Test the api_pull_request_close method of the flask api. """ send_email.return_value = True - pagure.config.config['REQUESTS_FOLDER'] = None + pagure.config.config["REQUESTS_FOLDER"] = None # Add private repo item = pagure.lib.model.Project( user_id=1, # pingou - name='test4', - description='test project description', - hook_token='aaabbbeeeceee', + name="test4", + description="test project description", + hook_token="aaabbbeeeceee", private=True, ) self.session.add(item) @@ -2086,73 +2070,71 @@ class PagurePrivateRepotest(tests.Modeltests): # Add private repo item = pagure.lib.model.Project( user_id=1, # pingou - name='test2', - description='test project description', - hook_token='foo_bar', + name="test2", + description="test project description", + hook_token="foo_bar", private=True, ) self.session.add(item) self.session.commit() # Create the pull-request to close - repo = pagure.lib.query._get_project(self.session, 'test4') - forked_repo = pagure.lib.query._get_project(self.session, 'test4') + repo = pagure.lib.query._get_project(self.session, "test4") + forked_repo = pagure.lib.query._get_project(self.session, "test4") req = pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Invalid project output = self.app.post( - '/api/0/foo/pull-request/1/close', headers=headers) + "/api/0/foo/pull-request/1/close", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) # Valid token, wrong project output = self.app.post( - '/api/0/test2/pull-request/1/close', headers=headers) + "/api/0/test2/pull-request/1/close", headers=headers + ) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(sorted(data.keys()), ['error', 'error_code']) + self.assertEqual(sorted(data.keys()), ["error", "error_code"]) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.value, data['error']) - self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.name, data['error_code']) + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) # Invalid PR output = self.app.post( - '/api/0/test4/pull-request/2/close', headers=headers) + "/api/0/test4/pull-request/2/close", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - {'error': 'Pull-Request not found', 'error_code': "ENOREQ"} + data, {"error": "Pull-Request not found", "error_code": "ENOREQ"} ) # Create a token for foo for this project item = pagure.lib.model.Token( - id='foobar_token', + id="foobar_token", user_id=2, project_id=1, - expiration=datetime.datetime.utcnow() + datetime.timedelta( - days=30) + expiration=datetime.datetime.utcnow() + + datetime.timedelta(days=30), ) self.session.add(item) self.session.commit() @@ -2160,141 +2142,135 @@ class PagurePrivateRepotest(tests.Modeltests): acls = pagure.lib.query.get_acls(self.session) acl = None for acl in acls: - if acl.name == 'pull_request_close': + if acl.name == "pull_request_close": break item = pagure.lib.model.TokenAcl( - token_id='foobar_token', - acl_id=acl.id, + token_id="foobar_token", acl_id=acl.id ) self.session.add(item) self.session.commit() - headers = {'Authorization': 'token foobar_token'} + headers = {"Authorization": "token foobar_token"} # User not admin output = self.app.post( - '/api/0/test4/pull-request/1/close', headers=headers) + "/api/0/test4/pull-request/1/close", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Close PR output = self.app.post( - '/api/0/test4/pull-request/1/close', headers=headers) + "/api/0/test4/pull-request/1/close", headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {"message": "Pull-request closed!"} - ) + self.assertDictEqual(data, {"message": "Pull-request closed!"}) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_private_repo_pr_merge(self, send_email): """ Test the api_pull_request_merge method of the flask api. """ send_email.return_value = True - pagure.config.config['REQUESTS_FOLDER'] = None + pagure.config.config["REQUESTS_FOLDER"] = None # Add private repo item = pagure.lib.model.Project( user_id=1, # pingou - name='test4', - description='test project description', - hook_token='aaabbbeeeceee', + name="test4", + description="test project description", + hook_token="aaabbbeeeceee", private=True, ) self.session.add(item) self.session.commit() - tests.create_projects_git(os.path.join(self.path, 'repos'), bare=True) - tests.create_projects_git(os.path.join(self.path, 'requests'), - bare=True) - tests.add_readme_git_repo(os.path.join(self.path, 'repos', - 'test4.git')) - tests.add_commit_git_repo(os.path.join(self.path, 'repos', - 'test4.git'), - branch='test') + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) + tests.create_projects_git( + os.path.join(self.path, "requests"), bare=True + ) + tests.add_readme_git_repo( + os.path.join(self.path, "repos", "test4.git") + ) + tests.add_commit_git_repo( + os.path.join(self.path, "repos", "test4.git"), branch="test" + ) tests.create_tokens(self.session) tests.create_tokens_acl(self.session) # Add private repo item = pagure.lib.model.Project( user_id=1, # pingou - name='test2', - description='test project description', - hook_token='foo_bar', + name="test2", + description="test project description", + hook_token="foo_bar", private=True, ) self.session.add(item) self.session.commit() # Create the pull-request to close - repo = pagure.lib.query._get_project(self.session, 'test4') - forked_repo = pagure.lib.query._get_project(self.session, 'test4') + repo = pagure.lib.query._get_project(self.session, "test4") + forked_repo = pagure.lib.query._get_project(self.session, "test4") req = pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='test', + branch_from="test", repo_to=repo, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Invalid project output = self.app.post( - '/api/0/foo/pull-request/1/merge', headers=headers) + "/api/0/foo/pull-request/1/merge", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) # Valid token, wrong project output = self.app.post( - '/api/0/test2/pull-request/1/merge', headers=headers) + "/api/0/test2/pull-request/1/merge", headers=headers + ) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(sorted(data.keys()), ['error', 'error_code']) - self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.value, data['error']) + self.assertEqual(sorted(data.keys()), ["error", "error_code"]) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.name, data['error_code']) + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) # Invalid PR output = self.app.post( - '/api/0/test4/pull-request/2/merge', headers=headers) + "/api/0/test4/pull-request/2/merge", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - {'error': 'Pull-Request not found', 'error_code': "ENOREQ"} + data, {"error": "Pull-Request not found", "error_code": "ENOREQ"} ) # Create a token for foo for this project item = pagure.lib.model.Token( - id='foobar_token', + id="foobar_token", user_id=2, project_id=1, - expiration=datetime.datetime.utcnow() + datetime.timedelta( - days=30) + expiration=datetime.datetime.utcnow() + + datetime.timedelta(days=30), ) self.session.add(item) self.session.commit() @@ -2303,59 +2279,54 @@ class PagurePrivateRepotest(tests.Modeltests): acls = pagure.lib.query.get_acls(self.session) acl = None for acl in acls: - if acl.name == 'pull_request_merge': + if acl.name == "pull_request_merge": break item = pagure.lib.model.TokenAcl( - token_id='foobar_token', - acl_id=acl.id, + token_id="foobar_token", acl_id=acl.id ) self.session.add(item) self.session.commit() - headers = {'Authorization': 'token foobar_token'} + headers = {"Authorization": "token foobar_token"} # User not admin output = self.app.post( - '/api/0/test4/pull-request/1/merge', headers=headers) + "/api/0/test4/pull-request/1/merge", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Merge PR output = self.app.post( - '/api/0/test4/pull-request/1/merge', headers=headers) + "/api/0/test4/pull-request/1/merge", headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {"message": "Changes merged!"} - ) + self.assertDictEqual(data, {"message": "Changes merged!"}) def test_api_private_repo_new_issue(self): """ Test the api_new_issue method of the flask api. """ # Add private repo item = pagure.lib.model.Project( user_id=1, # pingou - name='test4', - description='test project description', - hook_token='aaabbbeeeceee', + name="test4", + description="test project description", + hook_token="aaabbbeeeceee", private=True, ) self.session.add(item) self.session.commit() - for repo in ['GIT_FOLDER', 'TICKETS_FOLDER']: + for repo in ["GIT_FOLDER", "TICKETS_FOLDER"]: # Add a git repo repo_path = os.path.join( - pagure.config.config.get(repo), 'test4.git') + pagure.config.config.get(repo), "test4.git" + ) if not os.path.exists(repo_path): os.makedirs(repo_path) pygit2.init_repository(repo_path, bare=True) @@ -2366,28 +2337,28 @@ class PagurePrivateRepotest(tests.Modeltests): # Add private repo item = pagure.lib.model.Project( user_id=1, # pingou - name='test2', - description='test project description', - hook_token='foo_bar', + name="test2", + description="test project description", + hook_token="foo_bar", private=True, ) self.session.add(item) self.session.commit() - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Valid token, wrong project - output = self.app.post('/api/0/test2/new_issue', headers=headers) + output = self.app.post("/api/0/test2/new_issue", headers=headers) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(sorted(data.keys()), ['error', 'error_code']) + self.assertEqual(sorted(data.keys()), ["error", "error_code"]) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.value, data['error']) - self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.name, data['error_code']) + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) # No input - output = self.app.post('/api/0/test4/new_issue', headers=headers) + output = self.app.post("/api/0/test4/new_issue", headers=headers) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( @@ -2397,30 +2368,27 @@ class PagurePrivateRepotest(tests.Modeltests): "error_code": "EINVALIDREQ", "errors": { "issue_content": ["This field is required."], - "title": ["This field is required."] - } - }) + "title": ["This field is required."], + }, + }, + ) - data = { - 'title': 'test issue', - } + data = {"title": "test issue"} # Invalid repo output = self.app.post( - '/api/0/foo/new_issue', data=data, headers=headers) + "/api/0/foo/new_issue", data=data, headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) # Incomplete request output = self.app.post( - '/api/0/test4/new_issue', data=data, headers=headers) + "/api/0/test4/new_issue", data=data, headers=headers + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( @@ -2430,30 +2398,26 @@ class PagurePrivateRepotest(tests.Modeltests): "error_code": "EINVALIDREQ", "errors": { "issue_content": ["This field is required."], - "title": ["This field is required."] - } - - } + "title": ["This field is required."], + }, + }, ) data = { - 'title': 'test issue', - 'issue_content': 'This issue needs attention', + "title": "test issue", + "issue_content": "This issue needs attention", } # Valid request output = self.app.post( - '/api/0/test4/new_issue', data=data, headers=headers) + "/api/0/test4/new_issue", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['issue']['date_created'] = '1431414800' - data['issue']['last_updated'] = '1431414800' + data["issue"]["date_created"] = "1431414800" + data["issue"]["last_updated"] = "1431414800" self.assertDictEqual( - data, - { - 'issue': FULL_ISSUE_LIST[7], - 'message': 'Issue created' - } + data, {"issue": FULL_ISSUE_LIST[7], "message": "Issue created"} ) def test_api_private_repo_view_issues(self): @@ -2461,28 +2425,24 @@ class PagurePrivateRepotest(tests.Modeltests): self.test_api_private_repo_new_issue() # Invalid repo - output = self.app.get('/api/0/foo/issues') + output = self.app.get("/api/0/foo/issues") self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) # List all opened issues - user = tests.FakeUser(username='pingou') + user = tests.FakeUser(username="pingou") with tests.user_set(self.app.application, user): - output = self.app.get('/api/0/test4/issues') + output = self.app.get("/api/0/test4/issues") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['issues'][0]['date_created'] = '1431414800' - data['issues'][0]['last_updated'] = '1431414800' - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + data["issues"][0]["date_created"] = "1431414800" + data["issues"][0]["last_updated"] = "1431414800" + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." self.assertDictEqual( data, @@ -2496,7 +2456,7 @@ class PagurePrivateRepotest(tests.Modeltests): "priority": None, "since": None, "status": None, - "tags": [] + "tags": [], }, "total_issues": 1, "issues": [ @@ -2519,51 +2479,47 @@ class PagurePrivateRepotest(tests.Modeltests): "status": "Open", "tags": [], "title": "test issue", - "user": { - "fullname": "PY C", - "name": "pingou" - - } + "user": {"fullname": "PY C", "name": "pingou"}, } ], - 'pagination': { - u'first': u'http://localhost...', - u'last': u'http://localhost...', - u'next': None, - u'page': 1, - u'pages': 1, - u'per_page': 20, - u'prev': None + "pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "page": 1, + "pages": 1, + "per_page": 20, + "prev": None, }, - } + }, ) # Create private issue - repo = pagure.lib.query._get_project(self.session, 'test4') + repo = pagure.lib.query._get_project(self.session, "test4") msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue', - content='We should work on this', - user='pingou', + title="Test issue", + content="We should work on this", + user="pingou", private=True, ) self.session.commit() - self.assertEqual(msg.title, 'Test issue') + self.assertEqual(msg.title, "Test issue") # Private issues are retrieved - user = tests.FakeUser(username='pingou') + user = tests.FakeUser(username="pingou") with tests.user_set(self.app.application, user): - output = self.app.get('/api/0/test4/issues') + output = self.app.get("/api/0/test4/issues") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['issues'][0]['date_created'] = '1431414800' - data['issues'][0]['last_updated'] = '1431414800' - data['issues'][1]['date_created'] = '1431414800' - data['issues'][1]['last_updated'] = '1431414800' - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + data["issues"][0]["date_created"] = "1431414800" + data["issues"][0]["last_updated"] = "1431414800" + data["issues"][1]["date_created"] = "1431414800" + data["issues"][1]["last_updated"] = "1431414800" + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." self.assertDictEqual( data, @@ -2577,7 +2533,7 @@ class PagurePrivateRepotest(tests.Modeltests): "priority": None, "status": None, "since": None, - "tags": [] + "tags": [], }, "issues": [ { @@ -2599,10 +2555,7 @@ class PagurePrivateRepotest(tests.Modeltests): "status": "Open", "tags": [], "title": "Test issue", - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, }, { "assignee": None, @@ -2623,44 +2576,40 @@ class PagurePrivateRepotest(tests.Modeltests): "status": "Open", "tags": [], "title": "test issue", - "user": { - "fullname": "PY C", - "name": "pingou" - } - } + "user": {"fullname": "PY C", "name": "pingou"}, + }, ], - 'pagination': { - u'first': u'http://localhost...', - u'last': u'http://localhost...', - u'next': None, - u'page': 1, - u'pages': 1, - u'per_page': 20, - u'prev': None + "pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "page": 1, + "pages": 1, + "per_page": 20, + "prev": None, }, - "total_issues": 2 - } - + "total_issues": 2, + }, ) # Access issues authenticated but non-existing token - headers = {'Authorization': 'token aaabbbccc'} - output = self.app.get('/api/0/test4/issues', headers=headers) + headers = {"Authorization": "token aaabbbccc"} + output = self.app.get("/api/0/test4/issues", headers=headers) self.assertEqual(output.status_code, 401) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Access issues authenticated correctly - output = self.app.get('/api/0/test4/issues', headers=headers) + output = self.app.get("/api/0/test4/issues", headers=headers) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['issues'][0]['date_created'] = '1431414800' - data['issues'][0]['last_updated'] = '1431414800' - data['issues'][1]['date_created'] = '1431414800' - data['issues'][1]['last_updated'] = '1431414800' - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + data["issues"][0]["date_created"] = "1431414800" + data["issues"][0]["last_updated"] = "1431414800" + data["issues"][1]["date_created"] = "1431414800" + data["issues"][1]["last_updated"] = "1431414800" + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." self.assertDictEqual( data, @@ -2674,7 +2623,7 @@ class PagurePrivateRepotest(tests.Modeltests): "priority": None, "status": None, "since": None, - "tags": [] + "tags": [], }, "issues": [ { @@ -2696,10 +2645,7 @@ class PagurePrivateRepotest(tests.Modeltests): "status": "Open", "tags": [], "title": "Test issue", - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, }, { "assignee": None, @@ -2720,34 +2666,31 @@ class PagurePrivateRepotest(tests.Modeltests): "status": "Open", "tags": [], "title": "test issue", - "user": { - "fullname": "PY C", - "name": "pingou" - } - } + "user": {"fullname": "PY C", "name": "pingou"}, + }, ], - 'pagination': { - u'first': u'http://localhost...', - u'last': u'http://localhost...', - u'next': None, - u'page': 1, - u'pages': 1, - u'per_page': 20, - u'prev': None + "pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "page": 1, + "pages": 1, + "per_page": 20, + "prev": None, }, - "total_issues": 2 - } - + "total_issues": 2, + }, ) # List closed issue output = self.app.get( - '/api/0/test4/issues?status=Closed', headers=headers) + "/api/0/test4/issues?status=Closed", headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." self.assertDictEqual( data, @@ -2761,30 +2704,31 @@ class PagurePrivateRepotest(tests.Modeltests): "priority": None, "status": "Closed", "since": None, - "tags": [] + "tags": [], }, "issues": [], - 'pagination': { - u'first': u'http://localhost...', - u'last': u'http://localhost...', - u'next': None, - u'page': 1, - u'pages': 0, - u'per_page': 20, - u'prev': None + "pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "page": 1, + "pages": 0, + "per_page": 20, + "prev": None, }, "total_issues": 0, - } + }, ) # List closed issue output = self.app.get( - '/api/0/test4/issues?status=Invalid', headers=headers) + "/api/0/test4/issues?status=Invalid", headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." self.assertDictEqual( data, @@ -2798,34 +2742,35 @@ class PagurePrivateRepotest(tests.Modeltests): "priority": None, "status": "Invalid", "since": None, - "tags": [] + "tags": [], }, "issues": [], - 'pagination': { - u'first': u'http://localhost...', - u'last': u'http://localhost...', - u'next': None, - u'page': 1, - u'pages': 0, - u'per_page': 20, - u'prev': None + "pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "page": 1, + "pages": 0, + "per_page": 20, + "prev": None, }, "total_issues": 0, - } + }, ) # List all issues output = self.app.get( - '/api/0/test4/issues?status=All', headers=headers) + "/api/0/test4/issues?status=All", headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['issues'][0]['date_created'] = '1431414800' - data['issues'][0]['last_updated'] = '1431414800' - data['issues'][1]['date_created'] = '1431414800' - data['issues'][1]['last_updated'] = '1431414800' - for k in ['first', 'last']: - self.assertIsNotNone(data['pagination'][k]) - data['pagination'][k] = 'http://localhost...' + data["issues"][0]["date_created"] = "1431414800" + data["issues"][0]["last_updated"] = "1431414800" + data["issues"][1]["date_created"] = "1431414800" + data["issues"][1]["last_updated"] = "1431414800" + for k in ["first", "last"]: + self.assertIsNotNone(data["pagination"][k]) + data["pagination"][k] = "http://localhost..." self.assertDictEqual( data, @@ -2839,7 +2784,7 @@ class PagurePrivateRepotest(tests.Modeltests): "priority": None, "since": None, "status": "All", - "tags": [] + "tags": [], }, "issues": [ { @@ -2861,10 +2806,7 @@ class PagurePrivateRepotest(tests.Modeltests): "status": "Open", "tags": [], "title": "Test issue", - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, }, { "assignee": None, @@ -2885,24 +2827,20 @@ class PagurePrivateRepotest(tests.Modeltests): "status": "Open", "tags": [], "title": "test issue", - "user": { - "fullname": "PY C", - "name": "pingou" - } - } + "user": {"fullname": "PY C", "name": "pingou"}, + }, ], - 'pagination': { - u'first': u'http://localhost...', - u'last': u'http://localhost...', - u'next': None, - u'page': 1, - u'pages': 1, - u'per_page': 20, - u'prev': None + "pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "page": 1, + "pages": 1, + "per_page": 20, + "prev": None, }, - "total_issues": 2 - } - + "total_issues": 2, + }, ) def test_api_pivate_repo_view_issue(self): @@ -2910,51 +2848,40 @@ class PagurePrivateRepotest(tests.Modeltests): self.test_api_private_repo_new_issue() # Invalid repo - output = self.app.get('/api/0/foo/issue/1') + output = self.app.get("/api/0/foo/issue/1") self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) # Invalid issue for this repo - output = self.app.get('/api/0/test4/issue/1') + output = self.app.get("/api/0/test4/issue/1") self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) # Un-authorized user user = tests.FakeUser() with tests.user_set(self.app.application, user): - output = self.app.get('/api/0/test4/issue/1') + output = self.app.get("/api/0/test4/issue/1") self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + {"error": "Project not found", "error_code": "ENOPROJECT"}, ) # Valid issue - user = tests.FakeUser(username='pingou') + user = tests.FakeUser(username="pingou") with tests.user_set(self.app.application, user): - output = self.app.get('/api/0/test4/issue/1') + output = self.app.get("/api/0/test4/issue/1") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['date_created'] = '1431414800' - data['last_updated'] = '1431414800' + data["date_created"] = "1431414800" + data["last_updated"] = "1431414800" self.assertDictEqual( data, { @@ -2976,35 +2903,33 @@ class PagurePrivateRepotest(tests.Modeltests): "status": "Open", "tags": [], "title": "test issue", - "user": { - "fullname": "PY C", - "name": "pingou" - } - } - + "user": {"fullname": "PY C", "name": "pingou"}, + }, ) - headers = {'Authorization': 'token aaabbbccc'} + headers = {"Authorization": "token aaabbbccc"} # Access issue authenticated but non-existing token - output = self.app.get('/api/0/test4/issue/1', headers=headers) + output = self.app.get("/api/0/test4/issue/1", headers=headers) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(sorted(data.keys()), ['error', 'error_code', 'errors']) self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.value, data['error']) + sorted(data.keys()), ["error", "error_code", "errors"] + ) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.name, data['error_code']) - self.assertEqual(data['errors'], 'Invalid token') + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) + self.assertEqual(data["errors"], "Invalid token") - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Access issue authenticated correctly - output = self.app.get('/api/0/test4/issue/1', headers=headers) + output = self.app.get("/api/0/test4/issue/1", headers=headers) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['date_created'] = '1431414800' - data['last_updated'] = '1431414800' + data["date_created"] = "1431414800" + data["last_updated"] = "1431414800" self.assertDictEqual( data, { @@ -3026,32 +2951,34 @@ class PagurePrivateRepotest(tests.Modeltests): "status": "Open", "tags": [], "title": "test issue", - "user": { - "fullname": "PY C", - "name": "pingou" - } - - } + "user": {"fullname": "PY C", "name": "pingou"}, + }, ) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def test_api_private_repo_change_status_issue(self): """ Test the api_change_status_issue method of the flask api. """ item = pagure.lib.model.Project( user_id=1, # pingou - name='test4', - description='test project description', - hook_token='aaabbbeeeceee', + name="test4", + description="test project description", + hook_token="aaabbbeeeceee", private=True, ) - item.close_status = ['Invalid', 'Insufficient data', 'Fixed', 'Duplicate'] + item.close_status = [ + "Invalid", + "Insufficient data", + "Fixed", + "Duplicate", + ] self.session.add(item) self.session.commit() - for repo in ['GIT_FOLDER', 'TICKETS_FOLDER']: + for repo in ["GIT_FOLDER", "TICKETS_FOLDER"]: # Add a git repo repo_path = os.path.join( - pagure.config.config.get(repo), 'test4.git') + pagure.config.config.get(repo), "test4.git" + ) if not os.path.exists(repo_path): os.makedirs(repo_path) pygit2.init_repository(repo_path, bare=True) @@ -3059,74 +2986,63 @@ class PagurePrivateRepotest(tests.Modeltests): tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Invalid project - output = self.app.post('/api/0/foo/issue/1/status', headers=headers) + output = self.app.post("/api/0/foo/issue/1/status", headers=headers) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) # Valid token, wrong project - user = tests.FakeUser(username='pingou') + user = tests.FakeUser(username="pingou") with tests.user_set(self.app.application, user): output = self.app.post( - '/api/0/test2/issue/1/status', headers=headers) + "/api/0/test2/issue/1/status", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + {"error": "Project not found", "error_code": "ENOPROJECT"}, ) # No input - output = self.app.post('/api/0/test4/issue/1/status', headers=headers) + output = self.app.post("/api/0/test4/issue/1/status", headers=headers) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Issue not found", - "error_code": "ENOISSUE", - } + data, {"error": "Issue not found", "error_code": "ENOISSUE"} ) # Create normal issue - repo = pagure.lib.query._get_project(self.session, 'test4') + repo = pagure.lib.query._get_project(self.session, "test4") msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue #1', - content='We should work on this', - user='pingou', + title="Test issue #1", + content="We should work on this", + user="pingou", private=False, ) self.session.commit() - self.assertEqual(msg.title, 'Test issue #1') + self.assertEqual(msg.title, "Test issue #1") # Check status before - repo = pagure.lib.query._get_project(self.session, 'test4') + repo = pagure.lib.query._get_project(self.session, "test4") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) - self.assertEqual(issue.status, 'Open') + self.assertEqual(issue.status, "Open") - data = { - 'title': 'test issue', - } + data = {"title": "test issue"} - user = tests.FakeUser(username='pingou') + user = tests.FakeUser(username="pingou") with tests.user_set(self.app.application, user): # Incomplete request output = self.app.post( - '/api/0/test4/issue/1/status', data=data, headers=headers) + "/api/0/test4/issue/1/status", data=data, headers=headers + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( @@ -3134,53 +3050,54 @@ class PagurePrivateRepotest(tests.Modeltests): { "error": "Invalid or incomplete input submitted", "error_code": "EINVALIDREQ", - "errors": {"status": ["Not a valid choice"]} - } + "errors": {"status": ["Not a valid choice"]}, + }, ) # No change - repo = pagure.lib.query._get_project(self.session, 'test4') - issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) - self.assertEqual(issue.status, 'Open') + repo = pagure.lib.query._get_project(self.session, "test4") + issue = pagure.lib.query.search_issues( + self.session, repo, issueid=1 + ) + self.assertEqual(issue.status, "Open") - data = { - 'status': 'Open', - } + data = {"status": "Open"} # Valid request but no change output = self.app.post( - '/api/0/test4/issue/1/status', data=data, headers=headers) + "/api/0/test4/issue/1/status", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'No changes'} - ) + self.assertDictEqual(data, {"message": "No changes"}) # No change - repo = pagure.lib.query._get_project(self.session, 'test4') - issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) - self.assertEqual(issue.status, 'Open') + repo = pagure.lib.query._get_project(self.session, "test4") + issue = pagure.lib.query.search_issues( + self.session, repo, issueid=1 + ) + self.assertEqual(issue.status, "Open") - data = { - 'status': 'Fixed', - } + data = {"status": "Fixed"} # Valid request output = self.app.post( - '/api/0/test4/issue/1/status', data=data, headers=headers) + "/api/0/test4/issue/1/status", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( data, - {'message':[ - 'Issue status updated to: Closed (was: Open)', - 'Issue close_status updated to: Fixed' - ]} + { + "message": [ + "Issue status updated to: Closed (was: Open)", + "Issue close_status updated to: Fixed", + ] + }, ) - @patch('pagure.lib.git.update_git') - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.git.update_git") + @patch("pagure.lib.notify.send_email") def test_api_private_repo_comment_issue(self, p_send_email, p_ugt): """ Test the api_comment_issue method of the flask api. """ p_send_email.return_value = True @@ -3188,9 +3105,9 @@ class PagurePrivateRepotest(tests.Modeltests): item = pagure.lib.model.Project( user_id=1, # pingou - name='test4', - description='test project description', - hook_token='aaabbbeeeceee', + name="test4", + description="test project description", + hook_token="aaabbbeeeceee", private=True, ) self.session.add(item) @@ -3198,72 +3115,65 @@ class PagurePrivateRepotest(tests.Modeltests): tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Invalid project - output = self.app.post('/api/0/foo/issue/1/comment', headers=headers) + output = self.app.post("/api/0/foo/issue/1/comment", headers=headers) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Project not found", - "error_code": "ENOPROJECT", - } + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) # Invalid token, right project - headers = {'Authorization': 'token aaabbbccc'} - output = self.app.post('/api/0/test4/issue/1/comment', headers=headers) + headers = {"Authorization": "token aaabbbccc"} + output = self.app.post("/api/0/test4/issue/1/comment", headers=headers) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(sorted(data.keys()), ['error', 'error_code', 'errors']) self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.value, data['error']) + sorted(data.keys()), ["error", "error_code", "errors"] + ) + self.assertEqual(pagure.api.APIERROR.EINVALIDTOK.value, data["error"]) self.assertEqual( - pagure.api.APIERROR.EINVALIDTOK.name, data['error_code']) - self.assertEqual(data['errors'], 'Invalid token') + pagure.api.APIERROR.EINVALIDTOK.name, data["error_code"] + ) + self.assertEqual(data["errors"], "Invalid token") - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # No input - output = self.app.post('/api/0/test4/issue/1/comment', headers=headers) + output = self.app.post("/api/0/test4/issue/1/comment", headers=headers) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - data, - { - "error": "Issue not found", - "error_code": "ENOISSUE", - } + data, {"error": "Issue not found", "error_code": "ENOISSUE"} ) # Create normal issue - repo = pagure.lib.query._get_project(self.session, 'test4') + repo = pagure.lib.query._get_project(self.session, "test4") msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue #1', - content='We should work on this', - user='pingou', + title="Test issue #1", + content="We should work on this", + user="pingou", private=False, - issue_uid='aaabbbccc1', + issue_uid="aaabbbccc1", ) self.session.commit() - self.assertEqual(msg.title, 'Test issue #1') + self.assertEqual(msg.title, "Test issue #1") # Check comments before self.session.commit() - repo = pagure.lib.query._get_project(self.session, 'test4') + repo = pagure.lib.query._get_project(self.session, "test4") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) self.assertEqual(len(issue.comments), 0) - data = { - 'title': 'test issue', - } + data = {"title": "test issue"} # Incomplete request output = self.app.post( - '/api/0/test4/issue/1/comment', data=data, headers=headers) + "/api/0/test4/issue/1/comment", data=data, headers=headers + ) self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( @@ -3271,41 +3181,42 @@ class PagurePrivateRepotest(tests.Modeltests): { "error": "Invalid or incomplete input submitted", "error_code": "EINVALIDREQ", - "errors": {"comment": ["This field is required."]} - } + "errors": {"comment": ["This field is required."]}, + }, ) # No change self.session.commit() - repo = pagure.lib.query._get_project(self.session, 'test4') + repo = pagure.lib.query._get_project(self.session, "test4") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) - self.assertEqual(issue.status, 'Open') + self.assertEqual(issue.status, "Open") - data = { - 'comment': 'This is a very interesting question', - } + data = {"comment": "This is a very interesting question"} # Valid request output = self.app.post( - '/api/0/test4/issue/1/comment', data=data, headers=headers) + "/api/0/test4/issue/1/comment", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( data, - {'message': 'Comment added', - 'avatar_url': 'https://seccdn.libravatar.org/avatar/...', - 'user': 'pingou'} + { + "message": "Comment added", + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + "user": "pingou", + }, ) # One comment added self.session.commit() - repo = pagure.lib.query._get_project(self.session, 'test4') + repo = pagure.lib.query._get_project(self.session, "test4") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) self.assertEqual(len(issue.comments), 1) - @patch('pagure.lib.git.update_git') - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.git.update_git") + @patch("pagure.lib.notify.send_email") def test_api_view_issue_comment(self, p_send_email, p_ugt): """ Test the api_view_issue_comment endpoint. """ p_send_email.return_value = True @@ -3314,23 +3225,23 @@ class PagurePrivateRepotest(tests.Modeltests): self.test_api_private_repo_comment_issue() # View a comment that does not exist - output = self.app.get('/api/0/foo/issue/100/comment/2') + output = self.app.get("/api/0/foo/issue/100/comment/2") self.assertEqual(output.status_code, 404) # Issue exists but not the comment - output = self.app.get('/api/0/test/issue/1/comment/2') + output = self.app.get("/api/0/test/issue/1/comment/2") self.assertEqual(output.status_code, 404) # Issue and comment exists - output = self.app.get('/api/0/test/issue/1/comment/1') + output = self.app.get("/api/0/test/issue/1/comment/1") self.assertEqual(output.status_code, 404) - user = tests.FakeUser(username='pingou') + user = tests.FakeUser(username="pingou") with tests.user_set(self.app.application, user): - output = self.app.get('/api/0/test4/issue/1/comment/1') + output = self.app.get("/api/0/test4/issue/1/comment/1") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['date_created'] = '1435821770' + data["date_created"] = "1435821770" data["comment_date"] = "2015-07-02 09:22" data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( @@ -3346,18 +3257,15 @@ class PagurePrivateRepotest(tests.Modeltests): "id": 1, "parent": None, "reactions": {}, - "user": { - "fullname": "PY C", - "name": "pingou" - } - } + "user": {"fullname": "PY C", "name": "pingou"}, + }, ) # Issue and comment exists, using UID - output = self.app.get('/api/0/test4/issue/aaabbbccc1/comment/1') + output = self.app.get("/api/0/test4/issue/aaabbbccc1/comment/1") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['date_created'] = '1435821770' + data["date_created"] = "1435821770" data["comment_date"] = "2015-07-02 09:22" data["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertDictEqual( @@ -3373,13 +3281,10 @@ class PagurePrivateRepotest(tests.Modeltests): "id": 1, "parent": None, "reactions": {}, - "user": { - "fullname": "PY C", - "name": "pingou" - } - } + "user": {"fullname": "PY C", "name": "pingou"}, + }, ) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/test_pagure_flask_api_user.py b/tests/test_pagure_flask_api_user.py index 6085e7b..37a5091 100644 --- a/tests/test_pagure_flask_api_user.py +++ b/tests/test_pagure_flask_api_user.py @@ -20,8 +20,9 @@ import unittest import json from mock import patch -sys.path.insert(0, os.path.join(os.path.dirname( - os.path.abspath(__file__)), '..')) +sys.path.insert( + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") +) import pagure.api import pagure.config @@ -39,61 +40,69 @@ class PagureFlaskApiUSertests(tests.Modeltests): """ Set up the environnment, ran before every tests. """ super(PagureFlaskApiUSertests, self).setUp() - pagure.config.config['REQUESTS_FOLDER'] = None - + pagure.config.config["REQUESTS_FOLDER"] = None def test_api_users(self): """ Test the api_users function. """ - output = self.app.get('/api/0/users') + output = self.app.get("/api/0/users") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(sorted(data['users']), ['foo', 'pingou']) - self.assertEqual(sorted(data.keys()), ['mention', 'total_users', 'users']) - self.assertEqual(data['total_users'], 2) + self.assertEqual(sorted(data["users"]), ["foo", "pingou"]) + self.assertEqual( + sorted(data.keys()), ["mention", "total_users", "users"] + ) + self.assertEqual(data["total_users"], 2) - output = self.app.get('/api/0/users?pattern=p') + output = self.app.get("/api/0/users?pattern=p") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(data['users'], ['pingou']) - self.assertEqual(sorted(data.keys()), ['mention', 'total_users', 'users']) - self.assertEqual(data['total_users'], 1) + self.assertEqual(data["users"], ["pingou"]) + self.assertEqual( + sorted(data.keys()), ["mention", "total_users", "users"] + ) + self.assertEqual(data["total_users"], 1) def test_api_view_user(self): """ Test the api_view_user method of the flask api The tested user has no project or forks. """ - output = self.app.get('/api/0/user/pingou') + output = self.app.get("/api/0/user/pingou") self.assertEqual(output.status_code, 200) exp = { "forks": [], - 'forks_pagination': { - 'first': 'http://localhost...', - 'last': 'http://localhost...', - 'next': None, - 'forkpage': 1, - 'pages': 0, - 'per_page': 20, - 'prev': None}, + "forks_pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "forkpage": 1, + "pages": 0, + "per_page": 20, + "prev": None, + }, "repos": [], - 'repos_pagination': { - 'first': 'http://localhost...', - 'last': 'http://localhost...', - 'next': None, - 'repopage': 1, - 'pages': 0, - 'per_page': 20, - 'prev': None}, - "user": { "fullname": "PY C", - "name": "pingou", - 'avatar_url': 'https://seccdn.libravatar.org/avatar/...'}} + "repos_pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "repopage": 1, + "pages": 0, + "per_page": 20, + "prev": None, + }, + "user": { + "fullname": "PY C", + "name": "pingou", + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + }, + } data = json.loads(output.get_data(as_text=True)) data["user"]["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." - for k in ['forks_pagination', 'repos_pagination']: - for k2 in ['first', 'last']: + for k in ["forks_pagination", "repos_pagination"]: + for k2 in ["first", "last"]: self.assertIsNotNone(data[k][k2]) - data[k][k2] = 'http://localhost...' + data[k][k2] = "http://localhost..." self.assertEqual(data, exp) def test_api_view_user_with_project(self): @@ -103,47 +112,44 @@ class PagureFlaskApiUSertests(tests.Modeltests): """ tests.create_projects(self.session) - output = self.app.get('/api/0/user/pingou') + output = self.app.get("/api/0/user/pingou") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - data['repos'][0]['date_created'] = "1490272832" - data['repos'][0]['date_modified'] = "1490272832" - data['repos'][1]['date_created'] = "1490272832" - data['repos'][1]['date_modified'] = "1490272832" - data['repos'][2]['date_created'] = "1490272832" - data['repos'][2]['date_modified'] = "1490272832" - for k in ['forks_pagination', 'repos_pagination']: - for k2 in ['first', 'last']: + data["repos"][0]["date_created"] = "1490272832" + data["repos"][0]["date_modified"] = "1490272832" + data["repos"][1]["date_created"] = "1490272832" + data["repos"][1]["date_modified"] = "1490272832" + data["repos"][2]["date_created"] = "1490272832" + data["repos"][2]["date_modified"] = "1490272832" + for k in ["forks_pagination", "repos_pagination"]: + for k2 in ["first", "last"]: self.assertIsNotNone(data[k][k2]) - data[k][k2] = 'http://localhost...' + data[k][k2] = "http://localhost..." expected_data = { "forks": [], - 'forks_pagination': { - 'first': 'http://localhost...', - 'last': 'http://localhost...', - 'next': None, - 'forkpage': 1, - 'pages': 0, - 'per_page': 20, - 'prev': None}, + "forks_pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "forkpage": 1, + "pages": 0, + "per_page": 20, + "prev": None, + }, "repos": [ { - "access_groups": { - "admin": [], - "commit": [], - "ticket": [] - }, + "access_groups": {"admin": [], "commit": [], "ticket": []}, "access_users": { "admin": [], "commit": [], "owner": ["pingou"], - "ticket": [] + "ticket": [], }, "close_status": [ "Invalid", "Insufficient data", "Fixed", - "Duplicate" + "Duplicate", ], "custom_keys": [], "date_created": "1490272832", @@ -158,28 +164,21 @@ class PagureFlaskApiUSertests(tests.Modeltests): "parent": None, "priorities": {}, "tags": [], - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, }, { - "access_groups": { - "admin": [], - "commit": [], - "ticket": [] - }, + "access_groups": {"admin": [], "commit": [], "ticket": []}, "access_users": { "admin": [], "commit": [], "owner": ["pingou"], - "ticket": [] + "ticket": [], }, "close_status": [ "Invalid", "Insufficient data", "Fixed", - "Duplicate" + "Duplicate", ], "custom_keys": [], "date_created": "1490272832", @@ -194,27 +193,21 @@ class PagureFlaskApiUSertests(tests.Modeltests): "parent": None, "priorities": {}, "tags": [], - "user": { - "fullname": "PY C", - "name": "pingou" - } + "user": {"fullname": "PY C", "name": "pingou"}, }, { - "access_groups": { - "admin": [], - "commit": [], - "ticket": []}, + "access_groups": {"admin": [], "commit": [], "ticket": []}, "access_users": { "admin": [], "commit": [], "owner": ["pingou"], - "ticket": [] + "ticket": [], }, "close_status": [ "Invalid", "Insufficient data", "Fixed", - "Duplicate" + "Duplicate", ], "custom_keys": [], "date_created": "1490272832", @@ -229,30 +222,28 @@ class PagureFlaskApiUSertests(tests.Modeltests): "parent": None, "priorities": {}, "tags": [], - "user": { - "fullname": "PY C", - "name": "pingou" - } - } + "user": {"fullname": "PY C", "name": "pingou"}, + }, ], - 'repos_pagination': { - 'first': 'http://localhost...', - 'last': 'http://localhost...', - 'next': None, - 'repopage': 1, - 'pages': 1, - 'per_page': 20, - 'prev': None}, + "repos_pagination": { + "first": "http://localhost...", + "last": "http://localhost...", + "next": None, + "repopage": 1, + "pages": 1, + "per_page": 20, + "prev": None, + }, "user": { "fullname": "PY C", "name": "pingou", - 'avatar_url': 'https://seccdn.libravatar.org/avatar/...' - } + "avatar_url": "https://seccdn.libravatar.org/avatar/...", + }, } data["user"]["avatar_url"] = "https://seccdn.libravatar.org/avatar/..." self.assertEqual(data, expected_data) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_view_user_activity_stats(self, mockemail): """ Test the api_view_user_activity_stats method of the flask user api. """ @@ -262,74 +253,71 @@ class PagureFlaskApiUSertests(tests.Modeltests): tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} # Create a pull-request - repo = pagure.lib.query._get_project(self.session, 'test') - forked_repo = pagure.lib.query._get_project(self.session, 'test') + repo = pagure.lib.query._get_project(self.session, "test") + forked_repo = pagure.lib.query._get_project(self.session, "test") req = pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='test pull-request', - user='pingou', + branch_to="master", + title="test pull-request", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'test pull-request') + self.assertEqual(req.title, "test pull-request") # Check comments before self.session.commit() request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual(len(request.comments), 0) - data = { - 'comment': 'This is a very interesting question', - } + data = {"comment": "This is a very interesting question"} # Valid request output = self.app.post( - '/api/0/test/pull-request/1/comment', data=data, headers=headers) + "/api/0/test/pull-request/1/comment", data=data, headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {'message': 'Comment added'} - ) + self.assertDictEqual(data, {"message": "Comment added"}) # One comment added self.session.commit() request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) + self.session, project_id=1, requestid=1 + ) self.assertEqual(len(request.comments), 1) # Close PR output = self.app.post( - '/api/0/test/pull-request/1/close', headers=headers) + "/api/0/test/pull-request/1/close", headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - data, - {"message": "Pull-request closed!"} - ) + self.assertDictEqual(data, {"message": "Pull-request closed!"}) # PR closed self.session.commit() request = pagure.lib.query.search_pull_requests( - self.session, project_id=1, requestid=1) - self.assertEqual(request.status, 'Closed') + self.session, project_id=1, requestid=1 + ) + self.assertEqual(request.status, "Closed") # Finally retrieve the user's logs - output = self.app.get('/api/0/user/pingou/activity/stats') + output = self.app.get("/api/0/user/pingou/activity/stats") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - date = datetime.datetime.utcnow().date().strftime('%Y-%m-%d') + date = datetime.datetime.utcnow().date().strftime("%Y-%m-%d") self.assertDictEqual(data, {date: 4}) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_view_user_activity_date(self, mockemail): """ Test the api_view_user_activity_date method of the flask user api. """ @@ -337,134 +325,115 @@ class PagureFlaskApiUSertests(tests.Modeltests): self.test_api_view_user_activity_stats() # Invalid date - output = self.app.get('/api/0/user/pingou/activity/AABB') + output = self.app.get("/api/0/user/pingou/activity/AABB") self.assertEqual(output.status_code, 400) # Invalid date - output = self.app.get('/api/0/user/pingou/activity/2016asd') + output = self.app.get("/api/0/user/pingou/activity/2016asd") self.assertEqual(output.status_code, 200) - exp = { - "activities": [], - "date": "2016-01-01" - } + exp = {"activities": [], "date": "2016-01-01"} self.assertEqual(json.loads(output.get_data(as_text=True)), exp) # Date parsed, just not really as expected - output = self.app.get('/api/0/user/pingou/activity/20161245') + output = self.app.get("/api/0/user/pingou/activity/20161245") self.assertEqual(output.status_code, 200) - exp = { - "activities": [], - "date": "1970-08-22" - } + exp = {"activities": [], "date": "1970-08-22"} self.assertEqual(json.loads(output.get_data(as_text=True)), exp) - date = datetime.datetime.utcnow().date().strftime('%Y-%m-%d') + date = datetime.datetime.utcnow().date().strftime("%Y-%m-%d") # Retrieve the user's logs for today - output = self.app.get('/api/0/user/pingou/activity/%s' % date) + output = self.app.get("/api/0/user/pingou/activity/%s" % date) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) exp = { - "activities": [ - { - "date": date, - "date_created": "1477558752", - "type": "pull-request", - "description_mk": "

pingou created PR test#1

", - "id": 1, - "ref_id": "1", - "type": "created", - "user": { - "fullname": "PY C", - "name": "pingou" - } - }, - { - "date": date, - "date_created": "1477558752", - "type": "pull-request", - "description_mk": "

pingou commented on PR test#1

", - "id": 2, - "ref_id": "1", - "type": "commented", - "user": { - "fullname": "PY C", - "name": "pingou" - } - }, - { - "date": date, - "date_created": "1477558752", - "type": "pull-request", - "description_mk": "

pingou closed PR test#1

", - "id": 3, - "ref_id": "1", - "type": "closed", - "user": { - "fullname": "PY C", - "name": "pingou" - } - }, - { - "date": date, - "date_created": "1477558752", - "type": "pull-request", - "description_mk": "

pingou commented on PR test#1

", - "id": 4, - "ref_id": "1", - "type": "commented", - "user": { - "fullname": "PY C", - "name": "pingou" - } - } - ], - "date": date, + "activities": [ + { + "date": date, + "date_created": "1477558752", + "type": "pull-request", + "description_mk": '

pingou created PR test#1

', + "id": 1, + "ref_id": "1", + "type": "created", + "user": {"fullname": "PY C", "name": "pingou"}, + }, + { + "date": date, + "date_created": "1477558752", + "type": "pull-request", + "description_mk": '

pingou commented on PR test#1

', + "id": 2, + "ref_id": "1", + "type": "commented", + "user": {"fullname": "PY C", "name": "pingou"}, + }, + { + "date": date, + "date_created": "1477558752", + "type": "pull-request", + "description_mk": '

pingou closed PR test#1

', + "id": 3, + "ref_id": "1", + "type": "closed", + "user": {"fullname": "PY C", "name": "pingou"}, + }, + { + "date": date, + "date_created": "1477558752", + "type": "pull-request", + "description_mk": '

pingou commented on PR test#1

', + "id": 4, + "ref_id": "1", + "type": "commented", + "user": {"fullname": "PY C", "name": "pingou"}, + }, + ], + "date": date, } - for idx, act in enumerate(data['activities']): - act['date_created'] = '1477558752' - data['activities'][idx] = act + for idx, act in enumerate(data["activities"]): + act["date_created"] = "1477558752" + data["activities"][idx] = act self.assertEqual(data, exp) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_view_user_activity_date_1_activity(self, mockemail): """ Test the api_view_user_activity_date method of the flask user api when the user only did one action. """ tests.create_projects(self.session) - repo = pagure.lib.query._get_project(self.session, 'test') + repo = pagure.lib.query._get_project(self.session, "test") now = datetime.datetime.utcnow() - date = now.date().strftime('%Y-%m-%d') + date = now.date().strftime("%Y-%m-%d") # Create a single commit log log = model.PagureLog( user_id=1, - user_email='foo@bar.com', + user_email="foo@bar.com", project_id=1, - log_type='committed', - ref_id='githash', + log_type="committed", + ref_id="githash", date=now.date(), - date_created=now + date_created=now, ) self.session.add(log) self.session.commit() # Retrieve the user's logs for today output = self.app.get( - '/api/0/user/pingou/activity/%s?grouped=1' % date) + "/api/0/user/pingou/activity/%s?grouped=1" % date + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) exp = { - "activities": [ - { - "description_mk": "

pingou committed on test#githash

" - } - ], - "date": date, + "activities": [ + {"description_mk": "

pingou committed on test#githash

"} + ], + "date": date, } self.assertEqual(data, exp) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_view_user_activity_timezone_negative(self, mockemail): """Test api_view_user_activity{_stats,_date} with the America/ New York timezone, which is 5 hours behind UTC in winter and @@ -472,67 +441,84 @@ class PagureFlaskApiUSertests(tests.Modeltests): will occur on XXXX-02-15 in UTC, but on XXXX-02-14 local. """ tests.create_projects(self.session) - repo = pagure.lib.query._get_project(self.session, 'test') + repo = pagure.lib.query._get_project(self.session, "test") today = datetime.datetime.utcnow().date() year = today.year - if today.year == 2 and today.date <=15: + if today.year == 2 and today.date <= 15: year = year - 1 elif today.year < 2: year = year - 1 dateobj = datetime.datetime(year, 2, 15, 3, 30) - utcdate = '%s-02-15' % year + utcdate = "%s-02-15" % year # the Unix timestamp for YYYY-02-15 12:00 UTC - utcts = str(int( - ( - datetime.datetime(year, 2, 15, 12, 0, tzinfo=pytz.UTC) - - datetime.datetime(1970, 1, 1, tzinfo=pytz.UTC) - ).total_seconds() - )) - localdate = '%s-02-14' % today.year + utcts = str( + int( + ( + datetime.datetime(year, 2, 15, 12, 0, tzinfo=pytz.UTC) + - datetime.datetime(1970, 1, 1, tzinfo=pytz.UTC) + ).total_seconds() + ) + ) + localdate = "%s-02-14" % today.year # the Unix timestamp for YYYY-02-15 18:00 America/New_York - localts = str(int( - ( - datetime.datetime( - year, 2, 14, 17, 0, tzinfo=pytz.timezone('America/New_York')) - - datetime.datetime( - 1970, 1, 1 , tzinfo=pytz.timezone('America/New_York')) - ).total_seconds() - )) + localts = str( + int( + ( + datetime.datetime( + year, + 2, + 14, + 17, + 0, + tzinfo=pytz.timezone("America/New_York"), + ) + - datetime.datetime( + 1970, 1, 1, tzinfo=pytz.timezone("America/New_York") + ) + ).total_seconds() + ) + ) # Create a single commit log log = model.PagureLog( user_id=1, - user_email='foo@bar.com', + user_email="foo@bar.com", project_id=1, - log_type='committed', - ref_id='githash', + log_type="committed", + ref_id="githash", date=dateobj.date(), - date_created=dateobj + date_created=dateobj, ) self.session.add(log) self.session.commit() # Retrieve the user's stats with no timezone specified (==UTC) - output = self.app.get('/api/0/user/pingou/activity/stats') + output = self.app.get("/api/0/user/pingou/activity/stats") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) # date in output should be UTC date self.assertDictEqual(data, {utcdate: 1}) # Now in timestamp format... - output = self.app.get('/api/0/user/pingou/activity/stats?format=timestamp') + output = self.app.get( + "/api/0/user/pingou/activity/stats?format=timestamp" + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) # timestamp in output should be UTC ts self.assertDictEqual(data, {utcts: 1}) # Retrieve the user's stats with local timezone specified - output = self.app.get('/api/0/user/pingou/activity/stats?tz=America/New_York') + output = self.app.get( + "/api/0/user/pingou/activity/stats?tz=America/New_York" + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) # date in output should be local date self.assertDictEqual(data, {localdate: 1}) # Now in timestamp format... - output = self.app.get('/api/0/user/pingou/activity/stats?format=timestamp&tz=America/New_York') + output = self.app.get( + "/api/0/user/pingou/activity/stats?format=timestamp&tz=America/New_York" + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) # timestamp in output should be local ts @@ -540,95 +526,108 @@ class PagureFlaskApiUSertests(tests.Modeltests): # Retrieve the user's logs for 2018-02-15 with no timezone output = self.app.get( - '/api/0/user/pingou/activity/%s?grouped=1' % utcdate) + "/api/0/user/pingou/activity/%s?grouped=1" % utcdate + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) exp = { - "activities": [ - { - "description_mk": "

pingou committed on test#githash

" - } - ], - "date": utcdate, + "activities": [ + {"description_mk": "

pingou committed on test#githash

"} + ], + "date": utcdate, } self.assertEqual(data, exp) # Now retrieve the user's logs for 2018-02-14 with local time output = self.app.get( - '/api/0/user/pingou/activity/%s?grouped=1&tz=America/New_York' % localdate) + "/api/0/user/pingou/activity/%s?grouped=1&tz=America/New_York" + % localdate + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - exp['date'] = localdate + exp["date"] = localdate self.assertEqual(data, exp) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_view_user_activity_timezone_positive(self, mockemail): """Test api_view_user_activity{_stats,_date} with the Asia/ Dubai timezone, which is 4 hours ahead of UTC. The events will occur on XXXX-02-15 in UTC, but on XXXX-02-16 in local time. """ tests.create_projects(self.session) - repo = pagure.lib.query._get_project(self.session, 'test') + repo = pagure.lib.query._get_project(self.session, "test") today = datetime.datetime.utcnow().date() year = today.year - if today.year == 2 and today.date <=15: + if today.year == 2 and today.date <= 15: year = year - 1 elif today.year < 2: year = year - 1 dateobj = datetime.datetime(year, 2, 15, 22, 30) - utcdate = '%s-02-15' % year + utcdate = "%s-02-15" % year # the Unix timestamp for YYYY-02-15 12:00 UTC - utcts = str(int( - ( - datetime.datetime(year, 2, 15, 12, 0, tzinfo=pytz.UTC) - - datetime.datetime(1970, 1, 1, tzinfo=pytz.UTC) - ).total_seconds() - )) - localdate = '%s-02-16' % year + utcts = str( + int( + ( + datetime.datetime(year, 2, 15, 12, 0, tzinfo=pytz.UTC) + - datetime.datetime(1970, 1, 1, tzinfo=pytz.UTC) + ).total_seconds() + ) + ) + localdate = "%s-02-16" % year # the Unix timestamp for YYYY-02-16 9:00 Asia/Dubai - localts = str(int( - ( - datetime.datetime( - year, 2, 16, 8, 0, tzinfo=pytz.timezone('Asia/Dubai')) - - datetime.datetime( - 1970, 1, 1 , tzinfo=pytz.timezone('Asia/Dubai')) - ).total_seconds() - )) + localts = str( + int( + ( + datetime.datetime( + year, 2, 16, 8, 0, tzinfo=pytz.timezone("Asia/Dubai") + ) + - datetime.datetime( + 1970, 1, 1, tzinfo=pytz.timezone("Asia/Dubai") + ) + ).total_seconds() + ) + ) # Create a single commit log log = model.PagureLog( user_id=1, - user_email='foo@bar.com', + user_email="foo@bar.com", project_id=1, - log_type='committed', - ref_id='githash', + log_type="committed", + ref_id="githash", date=dateobj.date(), - date_created=dateobj + date_created=dateobj, ) self.session.add(log) self.session.commit() # Retrieve the user's stats with no timezone specified (==UTC) - output = self.app.get('/api/0/user/pingou/activity/stats') + output = self.app.get("/api/0/user/pingou/activity/stats") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) # date in output should be UTC date self.assertDictEqual(data, {utcdate: 1}) # Now in timestamp format... - output = self.app.get('/api/0/user/pingou/activity/stats?format=timestamp') + output = self.app.get( + "/api/0/user/pingou/activity/stats?format=timestamp" + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) # timestamp in output should be UTC ts self.assertDictEqual(data, {utcts: 1}) # Retrieve the user's stats with local timezone specified - output = self.app.get('/api/0/user/pingou/activity/stats?tz=Asia/Dubai') + output = self.app.get( + "/api/0/user/pingou/activity/stats?tz=Asia/Dubai" + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) # date in output should be local date self.assertDictEqual(data, {localdate: 1}) # Now in timestamp format... - output = self.app.get('/api/0/user/pingou/activity/stats?format=timestamp&tz=Asia/Dubai') + output = self.app.get( + "/api/0/user/pingou/activity/stats?format=timestamp&tz=Asia/Dubai" + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) # timestamp in output should be local ts @@ -636,25 +635,26 @@ class PagureFlaskApiUSertests(tests.Modeltests): # Retrieve the user's logs for 2018-02-15 with no timezone output = self.app.get( - '/api/0/user/pingou/activity/%s?grouped=1' % utcdate) + "/api/0/user/pingou/activity/%s?grouped=1" % utcdate + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) exp = { - "activities": [ - { - "description_mk": "

pingou committed on test#githash

" - } - ], - "date": utcdate, + "activities": [ + {"description_mk": "

pingou committed on test#githash

"} + ], + "date": utcdate, } self.assertEqual(data, exp) # Now retrieve the user's logs for 2018-02-16 with local time output = self.app.get( - '/api/0/user/pingou/activity/%s?grouped=1&tz=Asia/Dubai' % localdate) + "/api/0/user/pingou/activity/%s?grouped=1&tz=Asia/Dubai" + % localdate + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - exp['date'] = localdate + exp["date"] = localdate self.assertEqual(data, exp) @@ -667,732 +667,888 @@ class PagureFlaskApiUsertestrequests(tests.Modeltests): """ Set up the environnment, ran before every tests. """ super(PagureFlaskApiUsertestrequests, self).setUp() - pagure.config.config['REQUESTS_FOLDER'] = None + pagure.config.config["REQUESTS_FOLDER"] = None tests.create_projects(self.session) # Create few pull-requests - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test" + ) pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='open pullrequest by user foo on repo test', - user='foo', + branch_to="master", + title="open pullrequest by user foo on repo test", + user="foo", ) - repo = pagure.lib.query.get_authorized_project(self.session, 'test2') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test2') + repo = pagure.lib.query.get_authorized_project(self.session, "test2") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test2" + ) pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='open pullrequest by user foo on repo test2', - user='foo', + branch_to="master", + title="open pullrequest by user foo on repo test2", + user="foo", ) self.session.commit() - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test" + ) pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='closed pullrequest by user foo on repo test', - user='foo', - status='Closed', + branch_to="master", + title="closed pullrequest by user foo on repo test", + user="foo", + status="Closed", ) - repo = pagure.lib.query.get_authorized_project(self.session, 'test2') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test2') + repo = pagure.lib.query.get_authorized_project(self.session, "test2") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test2" + ) pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='closed pullrequest by user foo on repo test2', - user='foo', - status='Closed', + branch_to="master", + title="closed pullrequest by user foo on repo test2", + user="foo", + status="Closed", ) self.session.commit() - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test" + ) pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='merged pullrequest by user foo on repo test', - user='foo', - status='Merged', + branch_to="master", + title="merged pullrequest by user foo on repo test", + user="foo", + status="Merged", ) - repo = pagure.lib.query.get_authorized_project(self.session, 'test2') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test2') + repo = pagure.lib.query.get_authorized_project(self.session, "test2") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test2" + ) pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='merged pullrequest by user foo on repo test2', - user='foo', - status='Merged', + branch_to="master", + title="merged pullrequest by user foo on repo test2", + user="foo", + status="Merged", ) self.session.commit() - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test" + ) pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='open pullrequest by user pingou on repo test', - user='pingou', + branch_to="master", + title="open pullrequest by user pingou on repo test", + user="pingou", ) self.session.commit() - repo = pagure.lib.query.get_authorized_project(self.session, 'test2') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test2') + repo = pagure.lib.query.get_authorized_project(self.session, "test2") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test2" + ) pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='open pullrequest by user pingou on repo test2', - user='pingou', + branch_to="master", + title="open pullrequest by user pingou on repo test2", + user="pingou", ) self.session.commit() - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test" + ) pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='closed pullrequest by user pingou on repo test', - user='pingou', + branch_to="master", + title="closed pullrequest by user pingou on repo test", + user="pingou", status="Closed", ) self.session.commit() - repo = pagure.lib.query.get_authorized_project(self.session, 'test2') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test2') + repo = pagure.lib.query.get_authorized_project(self.session, "test2") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test2" + ) pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='closed pullrequest by user pingou on repo test2', - user='pingou', + branch_to="master", + title="closed pullrequest by user pingou on repo test2", + user="pingou", status="Closed", ) self.session.commit() - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test" + ) pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='merged pullrequest by user pingou on repo test', - user='pingou', + branch_to="master", + title="merged pullrequest by user pingou on repo test", + user="pingou", status="Merged", ) self.session.commit() - repo = pagure.lib.query.get_authorized_project(self.session, 'test2') - forked_repo = pagure.lib.query.get_authorized_project(self.session, 'test2') + repo = pagure.lib.query.get_authorized_project(self.session, "test2") + forked_repo = pagure.lib.query.get_authorized_project( + self.session, "test2" + ) pagure.lib.query.new_pull_request( session=self.session, repo_from=forked_repo, - branch_from='master', + branch_from="master", repo_to=repo, - branch_to='master', - title='merged pullrequest by user pingou on repo test2', - user='pingou', + branch_to="master", + title="merged pullrequest by user pingou on repo test2", + user="pingou", status="Merged", ) self.session.commit() - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_view_user_requests_filed(self, mockemail): """ Test the api_view_user_requests_filed method of the flask user api """ # First we test without the status parameter. It should default to `open` - output = self.app.get( - '/api/0/user/pingou/requests/filed') + output = self.app.get("/api/0/user/pingou/requests/filed") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 2) + self.assertEqual(len(data["requests"]), 2) self.assertEqual( sorted(data.keys()), - [u'args', u'pagination', u'requests', u'total_requests']) - self.assertEqual(data['requests'][0]['user']['name'], "pingou") - self.assertEqual(data['requests'][1]['user']['name'], "pingou") - self.assertEqual(data['requests'][0]['status'], "Open") - self.assertEqual(data['requests'][1]['status'], "Open") - self.assertEqual(data['requests'][0]['title'], "open pullrequest by user pingou on repo test2") - self.assertEqual(data['requests'][1]['title'], "open pullrequest by user pingou on repo test") - self.assertEqual(data['args']['status'], "open") - self.assertEqual(data['args']['page'], 1) + ["args", "pagination", "requests", "total_requests"], + ) + self.assertEqual(data["requests"][0]["user"]["name"], "pingou") + self.assertEqual(data["requests"][1]["user"]["name"], "pingou") + self.assertEqual(data["requests"][0]["status"], "Open") + self.assertEqual(data["requests"][1]["status"], "Open") + self.assertEqual( + data["requests"][0]["title"], + "open pullrequest by user pingou on repo test2", + ) + self.assertEqual( + data["requests"][1]["title"], + "open pullrequest by user pingou on repo test", + ) + self.assertEqual(data["args"]["status"], "open") + self.assertEqual(data["args"]["page"], 1) # Next test with the status parameter set to `open`. - output = self.app.get( - '/api/0/user/pingou/requests/filed?status=open') + output = self.app.get("/api/0/user/pingou/requests/filed?status=open") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 2) + self.assertEqual(len(data["requests"]), 2) self.assertEqual( sorted(data.keys()), - [u'args', u'pagination', u'requests', u'total_requests']) - self.assertEqual(data['requests'][0]['user']['name'], "pingou") - self.assertEqual(data['requests'][1]['user']['name'], "pingou") - self.assertEqual(data['requests'][0]['status'], "Open") - self.assertEqual(data['requests'][1]['status'], "Open") - self.assertEqual(data['requests'][0]['title'], "open pullrequest by user pingou on repo test2") - self.assertEqual(data['requests'][1]['title'], "open pullrequest by user pingou on repo test") - self.assertEqual(data['args']['status'], "open") - self.assertEqual(data['args']['page'], 1) + ["args", "pagination", "requests", "total_requests"], + ) + self.assertEqual(data["requests"][0]["user"]["name"], "pingou") + self.assertEqual(data["requests"][1]["user"]["name"], "pingou") + self.assertEqual(data["requests"][0]["status"], "Open") + self.assertEqual(data["requests"][1]["status"], "Open") + self.assertEqual( + data["requests"][0]["title"], + "open pullrequest by user pingou on repo test2", + ) + self.assertEqual( + data["requests"][1]["title"], + "open pullrequest by user pingou on repo test", + ) + self.assertEqual(data["args"]["status"], "open") + self.assertEqual(data["args"]["page"], 1) # Next test with the status parameter set to `closed`. output = self.app.get( - '/api/0/user/pingou/requests/filed?status=closed') + "/api/0/user/pingou/requests/filed?status=closed" + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 2) + self.assertEqual(len(data["requests"]), 2) self.assertEqual( sorted(data.keys()), - [u'args', u'pagination', u'requests', u'total_requests']) - self.assertEqual(data['requests'][0]['user']['name'], "pingou") - self.assertEqual(data['requests'][1]['user']['name'], "pingou") - self.assertEqual(data['requests'][0]['status'], "Closed") - self.assertEqual(data['requests'][1]['status'], "Closed") - self.assertEqual(data['requests'][0]['title'], "closed pullrequest by user pingou on repo test2") - self.assertEqual(data['requests'][1]['title'], "closed pullrequest by user pingou on repo test") - self.assertEqual(data['args']['status'], "closed") - self.assertEqual(data['args']['page'], 1) + ["args", "pagination", "requests", "total_requests"], + ) + self.assertEqual(data["requests"][0]["user"]["name"], "pingou") + self.assertEqual(data["requests"][1]["user"]["name"], "pingou") + self.assertEqual(data["requests"][0]["status"], "Closed") + self.assertEqual(data["requests"][1]["status"], "Closed") + self.assertEqual( + data["requests"][0]["title"], + "closed pullrequest by user pingou on repo test2", + ) + self.assertEqual( + data["requests"][1]["title"], + "closed pullrequest by user pingou on repo test", + ) + self.assertEqual(data["args"]["status"], "closed") + self.assertEqual(data["args"]["page"], 1) # Next test with the status parameter set to `merged`. output = self.app.get( - '/api/0/user/pingou/requests/filed?status=merged') + "/api/0/user/pingou/requests/filed?status=merged" + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 2) + self.assertEqual(len(data["requests"]), 2) self.assertEqual( sorted(data.keys()), - [u'args', u'pagination', u'requests', u'total_requests']) - self.assertEqual(data['requests'][0]['user']['name'], "pingou") - self.assertEqual(data['requests'][1]['user']['name'], "pingou") - self.assertEqual(data['requests'][0]['status'], "Merged") - self.assertEqual(data['requests'][1]['status'], "Merged") - self.assertEqual(data['requests'][0]['title'], "merged pullrequest by user pingou on repo test2") - self.assertEqual(data['requests'][1]['title'], "merged pullrequest by user pingou on repo test") - self.assertEqual(data['args']['status'], "merged") - self.assertEqual(data['args']['page'], 1) + ["args", "pagination", "requests", "total_requests"], + ) + self.assertEqual(data["requests"][0]["user"]["name"], "pingou") + self.assertEqual(data["requests"][1]["user"]["name"], "pingou") + self.assertEqual(data["requests"][0]["status"], "Merged") + self.assertEqual(data["requests"][1]["status"], "Merged") + self.assertEqual( + data["requests"][0]["title"], + "merged pullrequest by user pingou on repo test2", + ) + self.assertEqual( + data["requests"][1]["title"], + "merged pullrequest by user pingou on repo test", + ) + self.assertEqual(data["args"]["status"], "merged") + self.assertEqual(data["args"]["page"], 1) # Finally, test with the status parameter set to `all`. - output = self.app.get( - '/api/0/user/pingou/requests/filed?status=all') + output = self.app.get("/api/0/user/pingou/requests/filed?status=all") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 6) + self.assertEqual(len(data["requests"]), 6) self.assertEqual( sorted(data.keys()), - [u'args', u'pagination', u'requests', u'total_requests']) - self.assertEqual(data['requests'][0]['user']['name'], "pingou") - self.assertEqual(data['requests'][1]['user']['name'], "pingou") - self.assertEqual(data['requests'][2]['user']['name'], "pingou") - self.assertEqual(data['requests'][3]['user']['name'], "pingou") - self.assertEqual(data['requests'][4]['user']['name'], "pingou") - self.assertEqual(data['requests'][5]['user']['name'], "pingou") - self.assertEqual(data['requests'][0]['status'], "Merged") - self.assertEqual(data['requests'][1]['status'], "Merged") - self.assertEqual(data['requests'][2]['status'], "Closed") - self.assertEqual(data['requests'][3]['status'], "Closed") - self.assertEqual(data['requests'][4]['status'], "Open") - self.assertEqual(data['requests'][5]['status'], "Open") - self.assertEqual(data['requests'][0]['title'], "merged pullrequest by user pingou on repo test2") - self.assertEqual(data['requests'][1]['title'], "merged pullrequest by user pingou on repo test") - self.assertEqual(data['requests'][2]['title'], "closed pullrequest by user pingou on repo test2") - self.assertEqual(data['requests'][3]['title'], "closed pullrequest by user pingou on repo test") - self.assertEqual(data['requests'][4]['title'], "open pullrequest by user pingou on repo test2") - self.assertEqual(data['requests'][5]['title'], "open pullrequest by user pingou on repo test") - self.assertEqual(data['args']['status'], "all") - self.assertEqual(data['args']['page'], 1) + ["args", "pagination", "requests", "total_requests"], + ) + self.assertEqual(data["requests"][0]["user"]["name"], "pingou") + self.assertEqual(data["requests"][1]["user"]["name"], "pingou") + self.assertEqual(data["requests"][2]["user"]["name"], "pingou") + self.assertEqual(data["requests"][3]["user"]["name"], "pingou") + self.assertEqual(data["requests"][4]["user"]["name"], "pingou") + self.assertEqual(data["requests"][5]["user"]["name"], "pingou") + self.assertEqual(data["requests"][0]["status"], "Merged") + self.assertEqual(data["requests"][1]["status"], "Merged") + self.assertEqual(data["requests"][2]["status"], "Closed") + self.assertEqual(data["requests"][3]["status"], "Closed") + self.assertEqual(data["requests"][4]["status"], "Open") + self.assertEqual(data["requests"][5]["status"], "Open") + self.assertEqual( + data["requests"][0]["title"], + "merged pullrequest by user pingou on repo test2", + ) + self.assertEqual( + data["requests"][1]["title"], + "merged pullrequest by user pingou on repo test", + ) + self.assertEqual( + data["requests"][2]["title"], + "closed pullrequest by user pingou on repo test2", + ) + self.assertEqual( + data["requests"][3]["title"], + "closed pullrequest by user pingou on repo test", + ) + self.assertEqual( + data["requests"][4]["title"], + "open pullrequest by user pingou on repo test2", + ) + self.assertEqual( + data["requests"][5]["title"], + "open pullrequest by user pingou on repo test", + ) + self.assertEqual(data["args"]["status"], "all") + self.assertEqual(data["args"]["page"], 1) # Test page 2 with the status parameter set to `all`. output = self.app.get( - '/api/0/user/pingou/requests/filed?status=all&page=2') + "/api/0/user/pingou/requests/filed?status=all&page=2" + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 0) + self.assertEqual(len(data["requests"]), 0) self.assertEqual( sorted(data.keys()), - [u'args', u'pagination', u'requests', u'total_requests']) - self.assertEqual(data['args']['page'], 2) + ["args", "pagination", "requests", "total_requests"], + ) + self.assertEqual(data["args"]["page"], 2) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_view_user_requests_filed_created(self, mockemail): """ Test the api_view_user_requests_filed method of the flask user api with the created parameter """ today = datetime.datetime.utcnow().date() output = self.app.get( - '/api/0/user/pingou/requests/filed?status=all&created=%s' % ( - today.isoformat())) + "/api/0/user/pingou/requests/filed?status=all&created=%s" + % (today.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 6) + self.assertEqual(len(data["requests"]), 6) yesterday = today - datetime.timedelta(days=1) output = self.app.get( - '/api/0/user/pingou/requests/filed?status=all&created=%s' % ( - yesterday.isoformat())) + "/api/0/user/pingou/requests/filed?status=all&created=%s" + % (yesterday.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 6) + self.assertEqual(len(data["requests"]), 6) tomorrow = today + datetime.timedelta(days=1) output = self.app.get( - '/api/0/user/pingou/requests/filed?status=all&created=%s' % ( - tomorrow.isoformat())) + "/api/0/user/pingou/requests/filed?status=all&created=%s" + % (tomorrow.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 0) + self.assertEqual(len(data["requests"]), 0) output = self.app.get( - '/api/0/user/pingou/requests/filed?status=all&created=..%s' % ( - today.isoformat())) + "/api/0/user/pingou/requests/filed?status=all&created=..%s" + % (today.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 0) + self.assertEqual(len(data["requests"]), 0) output = self.app.get( - '/api/0/user/pingou/requests/filed?status=all&created=..%s' % ( - yesterday.isoformat())) + "/api/0/user/pingou/requests/filed?status=all&created=..%s" + % (yesterday.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 0) + self.assertEqual(len(data["requests"]), 0) thedaybefore = today - datetime.timedelta(days=1) output = self.app.get( - '/api/0/user/pingou/requests/filed?status=all&created=..%s' % ( - thedaybefore.isoformat())) + "/api/0/user/pingou/requests/filed?status=all&created=..%s" + % (thedaybefore.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 0) + self.assertEqual(len(data["requests"]), 0) output = self.app.get( - '/api/0/user/pingou/requests/filed?status=all&created=..%s' % ( - tomorrow.isoformat())) + "/api/0/user/pingou/requests/filed?status=all&created=..%s" + % (tomorrow.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 6) + self.assertEqual(len(data["requests"]), 6) output = self.app.get( - '/api/0/user/pingou/requests/filed?status=all&created=%s..%s' % ( - thedaybefore.isoformat(), tomorrow.isoformat())) + "/api/0/user/pingou/requests/filed?status=all&created=%s..%s" + % (thedaybefore.isoformat(), tomorrow.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 6) + self.assertEqual(len(data["requests"]), 6) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_view_user_requests_filed_updated(self, mockemail): """ Test the api_view_user_requests_filed method of the flask user api with the created parameter """ today = datetime.datetime.utcnow().date() output = self.app.get( - '/api/0/user/pingou/requests/filed?status=all&updated=%s' % ( - today.isoformat())) + "/api/0/user/pingou/requests/filed?status=all&updated=%s" + % (today.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 0) + self.assertEqual(len(data["requests"]), 0) yesterday = today - datetime.timedelta(days=1) output = self.app.get( - '/api/0/user/pingou/requests/filed?status=all&updated=%s' % ( - yesterday.isoformat())) + "/api/0/user/pingou/requests/filed?status=all&updated=%s" + % (yesterday.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 0) + self.assertEqual(len(data["requests"]), 0) tomorrow = today + datetime.timedelta(days=1) output = self.app.get( - '/api/0/user/pingou/requests/filed?status=all&updated=%s' % ( - tomorrow.isoformat())) + "/api/0/user/pingou/requests/filed?status=all&updated=%s" + % (tomorrow.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 6) + self.assertEqual(len(data["requests"]), 6) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_view_user_requests_filed_closed(self, mockemail): """ Test the api_view_user_requests_filed method of the flask user api with the created parameter """ today = datetime.datetime.utcnow().date() output = self.app.get( - '/api/0/user/pingou/requests/filed?status=all&closed=%s' % ( - today.isoformat())) + "/api/0/user/pingou/requests/filed?status=all&closed=%s" + % (today.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 0) + self.assertEqual(len(data["requests"]), 0) yesterday = today - datetime.timedelta(days=1) output = self.app.get( - '/api/0/user/pingou/requests/filed?status=all&closed=%s' % ( - yesterday.isoformat())) + "/api/0/user/pingou/requests/filed?status=all&closed=%s" + % (yesterday.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 0) + self.assertEqual(len(data["requests"]), 0) tomorrow = today + datetime.timedelta(days=1) output = self.app.get( - '/api/0/user/pingou/requests/filed?status=all&closed=%s' % ( - tomorrow.isoformat())) + "/api/0/user/pingou/requests/filed?status=all&closed=%s" + % (tomorrow.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 0) + self.assertEqual(len(data["requests"]), 0) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_view_user_requests_filed_foo(self, mockemail): """ Test the api_view_user_requests_filed method of the flask user api """ # Default data returned output = self.app.get( - '/api/0/user/foo/requests/filed?status=all&per_page=6') + "/api/0/user/foo/requests/filed?status=all&per_page=6" + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 6) + self.assertEqual(len(data["requests"]), 6) self.assertEqual( sorted(data.keys()), - [u'args', u'pagination', u'requests', u'total_requests']) + ["args", "pagination", "requests", "total_requests"], + ) # There are 6 PRs, that's 1 page at 6 results per page - self.assertEqual(data['pagination']['pages'], 1) + self.assertEqual(data["pagination"]["pages"], 1) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_view_user_requests_filed_foo_grp_access(self, mockemail): """ Test when the user has accessed to some PRs via a group. """ # Add the user to a group msg = pagure.lib.query.add_group( self.session, - group_name='some_group', - display_name='Some Group', + group_name="some_group", + display_name="Some Group", description=None, - group_type='bar', - user='pingou', + group_type="bar", + user="pingou", is_admin=False, blacklist=[], ) self.session.commit() # Add the group to the project `test2` - project = pagure.lib.query._get_project(self.session, 'test2') + project = pagure.lib.query._get_project(self.session, "test2") msg = pagure.lib.query.add_group_to_project( session=self.session, project=project, - new_group='some_group', - user='pingou', + new_group="some_group", + user="pingou", ) self.session.commit() - self.assertEqual(msg, 'Group added') + self.assertEqual(msg, "Group added") # Add foo to the group group = pagure.lib.query.search_groups( - self.session, group_name='some_group') + self.session, group_name="some_group" + ) result = pagure.lib.query.add_user_to_group( - self.session, 'foo', group, 'pingou', True) + self.session, "foo", group, "pingou", True + ) self.session.commit() - self.assertEqual( - result, 'User `foo` added to the group `some_group`.') + self.assertEqual(result, "User `foo` added to the group `some_group`.") # Query the API for foo's filed PRs output = self.app.get( - '/api/0/user/foo/requests/filed?status=all&per_page=6') + "/api/0/user/foo/requests/filed?status=all&per_page=6" + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 6) + self.assertEqual(len(data["requests"]), 6) self.assertEqual( sorted(data.keys()), - [u'args', u'pagination', u'requests', u'total_requests']) + ["args", "pagination", "requests", "total_requests"], + ) # There are 6 PRs, that's 1 page at 6 results per page - self.assertEqual(data['pagination']['pages'], 1) + self.assertEqual(data["pagination"]["pages"], 1) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_view_user_requests_actionable(self, mockemail): """ Test the api_view_user_requests_actionable method of the flask user api """ # First we test without the status parameter. It should default to `open` - output = self.app.get( - '/api/0/user/pingou/requests/actionable') + output = self.app.get("/api/0/user/pingou/requests/actionable") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 2) + self.assertEqual(len(data["requests"]), 2) self.assertEqual( sorted(data.keys()), - [u'args', u'pagination', u'requests', u'total_requests']) - self.assertEqual(data['requests'][0]['user']['name'], "foo") - self.assertEqual(data['requests'][1]['user']['name'], "foo") - self.assertEqual(data['requests'][0]['status'], "Open") - self.assertEqual(data['requests'][1]['status'], "Open") - self.assertEqual(data['requests'][0]['title'], "open pullrequest by user foo on repo test2") - self.assertEqual(data['requests'][1]['title'], "open pullrequest by user foo on repo test") - self.assertEqual(data['args']['status'], "open") - self.assertEqual(data['args']['page'], 1) + ["args", "pagination", "requests", "total_requests"], + ) + self.assertEqual(data["requests"][0]["user"]["name"], "foo") + self.assertEqual(data["requests"][1]["user"]["name"], "foo") + self.assertEqual(data["requests"][0]["status"], "Open") + self.assertEqual(data["requests"][1]["status"], "Open") + self.assertEqual( + data["requests"][0]["title"], + "open pullrequest by user foo on repo test2", + ) + self.assertEqual( + data["requests"][1]["title"], + "open pullrequest by user foo on repo test", + ) + self.assertEqual(data["args"]["status"], "open") + self.assertEqual(data["args"]["page"], 1) # Next test with the status parameter set to `open`. output = self.app.get( - '/api/0/user/pingou/requests/actionable?status=open') + "/api/0/user/pingou/requests/actionable?status=open" + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 2) + self.assertEqual(len(data["requests"]), 2) self.assertEqual( sorted(data.keys()), - [u'args', u'pagination', u'requests', u'total_requests']) - self.assertEqual(data['requests'][0]['user']['name'], "foo") - self.assertEqual(data['requests'][1]['user']['name'], "foo") - self.assertEqual(data['requests'][0]['status'], "Open") - self.assertEqual(data['requests'][1]['status'], "Open") - self.assertEqual(data['requests'][0]['title'], "open pullrequest by user foo on repo test2") - self.assertEqual(data['requests'][1]['title'], "open pullrequest by user foo on repo test") - self.assertEqual(data['args']['status'], "open") - self.assertEqual(data['args']['page'], 1) + ["args", "pagination", "requests", "total_requests"], + ) + self.assertEqual(data["requests"][0]["user"]["name"], "foo") + self.assertEqual(data["requests"][1]["user"]["name"], "foo") + self.assertEqual(data["requests"][0]["status"], "Open") + self.assertEqual(data["requests"][1]["status"], "Open") + self.assertEqual( + data["requests"][0]["title"], + "open pullrequest by user foo on repo test2", + ) + self.assertEqual( + data["requests"][1]["title"], + "open pullrequest by user foo on repo test", + ) + self.assertEqual(data["args"]["status"], "open") + self.assertEqual(data["args"]["page"], 1) # Next test with the status parameter set to `closed`. output = self.app.get( - '/api/0/user/pingou/requests/actionable?status=closed') + "/api/0/user/pingou/requests/actionable?status=closed" + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 2) + self.assertEqual(len(data["requests"]), 2) self.assertEqual( sorted(data.keys()), - [u'args', u'pagination', u'requests', u'total_requests']) - self.assertEqual(data['requests'][0]['user']['name'], "foo") - self.assertEqual(data['requests'][1]['user']['name'], "foo") - self.assertEqual(data['requests'][0]['status'], "Closed") - self.assertEqual(data['requests'][1]['status'], "Closed") - self.assertEqual(data['requests'][0]['title'], "closed pullrequest by user foo on repo test2") - self.assertEqual(data['requests'][1]['title'], "closed pullrequest by user foo on repo test") - self.assertEqual(data['args']['status'], "closed") - self.assertEqual(data['args']['page'], 1) + ["args", "pagination", "requests", "total_requests"], + ) + self.assertEqual(data["requests"][0]["user"]["name"], "foo") + self.assertEqual(data["requests"][1]["user"]["name"], "foo") + self.assertEqual(data["requests"][0]["status"], "Closed") + self.assertEqual(data["requests"][1]["status"], "Closed") + self.assertEqual( + data["requests"][0]["title"], + "closed pullrequest by user foo on repo test2", + ) + self.assertEqual( + data["requests"][1]["title"], + "closed pullrequest by user foo on repo test", + ) + self.assertEqual(data["args"]["status"], "closed") + self.assertEqual(data["args"]["page"], 1) # Next test with the status parameter set to `merged`. output = self.app.get( - '/api/0/user/pingou/requests/actionable?status=merged') + "/api/0/user/pingou/requests/actionable?status=merged" + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 2) + self.assertEqual(len(data["requests"]), 2) self.assertEqual( sorted(data.keys()), - [u'args', u'pagination', u'requests', u'total_requests']) - self.assertEqual(data['requests'][0]['user']['name'], "foo") - self.assertEqual(data['requests'][1]['user']['name'], "foo") - self.assertEqual(data['requests'][0]['status'], "Merged") - self.assertEqual(data['requests'][1]['status'], "Merged") - self.assertEqual(data['requests'][0]['title'], "merged pullrequest by user foo on repo test2") - self.assertEqual(data['requests'][1]['title'], "merged pullrequest by user foo on repo test") - self.assertEqual(data['args']['status'], "merged") - self.assertEqual(data['args']['page'], 1) + ["args", "pagination", "requests", "total_requests"], + ) + self.assertEqual(data["requests"][0]["user"]["name"], "foo") + self.assertEqual(data["requests"][1]["user"]["name"], "foo") + self.assertEqual(data["requests"][0]["status"], "Merged") + self.assertEqual(data["requests"][1]["status"], "Merged") + self.assertEqual( + data["requests"][0]["title"], + "merged pullrequest by user foo on repo test2", + ) + self.assertEqual( + data["requests"][1]["title"], + "merged pullrequest by user foo on repo test", + ) + self.assertEqual(data["args"]["status"], "merged") + self.assertEqual(data["args"]["page"], 1) # Finally, test with the status parameter set to `all`. output = self.app.get( - '/api/0/user/pingou/requests/actionable?status=all') + "/api/0/user/pingou/requests/actionable?status=all" + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 6) + self.assertEqual(len(data["requests"]), 6) self.assertEqual( sorted(data.keys()), - [u'args', u'pagination', u'requests', u'total_requests']) - self.assertEqual(data['requests'][0]['user']['name'], "foo") - self.assertEqual(data['requests'][1]['user']['name'], "foo") - self.assertEqual(data['requests'][2]['user']['name'], "foo") - self.assertEqual(data['requests'][3]['user']['name'], "foo") - self.assertEqual(data['requests'][4]['user']['name'], "foo") - self.assertEqual(data['requests'][5]['user']['name'], "foo") - self.assertEqual(data['requests'][0]['status'], "Merged") - self.assertEqual(data['requests'][1]['status'], "Merged") - self.assertEqual(data['requests'][2]['status'], "Closed") - self.assertEqual(data['requests'][3]['status'], "Closed") - self.assertEqual(data['requests'][4]['status'], "Open") - self.assertEqual(data['requests'][5]['status'], "Open") - self.assertEqual(data['requests'][0]['title'], "merged pullrequest by user foo on repo test2") - self.assertEqual(data['requests'][1]['title'], "merged pullrequest by user foo on repo test") - self.assertEqual(data['requests'][2]['title'], "closed pullrequest by user foo on repo test2") - self.assertEqual(data['requests'][3]['title'], "closed pullrequest by user foo on repo test") - self.assertEqual(data['requests'][4]['title'], "open pullrequest by user foo on repo test2") - self.assertEqual(data['requests'][5]['title'], "open pullrequest by user foo on repo test") - self.assertEqual(data['args']['status'], "all") - self.assertEqual(data['args']['page'], 1) + ["args", "pagination", "requests", "total_requests"], + ) + self.assertEqual(data["requests"][0]["user"]["name"], "foo") + self.assertEqual(data["requests"][1]["user"]["name"], "foo") + self.assertEqual(data["requests"][2]["user"]["name"], "foo") + self.assertEqual(data["requests"][3]["user"]["name"], "foo") + self.assertEqual(data["requests"][4]["user"]["name"], "foo") + self.assertEqual(data["requests"][5]["user"]["name"], "foo") + self.assertEqual(data["requests"][0]["status"], "Merged") + self.assertEqual(data["requests"][1]["status"], "Merged") + self.assertEqual(data["requests"][2]["status"], "Closed") + self.assertEqual(data["requests"][3]["status"], "Closed") + self.assertEqual(data["requests"][4]["status"], "Open") + self.assertEqual(data["requests"][5]["status"], "Open") + self.assertEqual( + data["requests"][0]["title"], + "merged pullrequest by user foo on repo test2", + ) + self.assertEqual( + data["requests"][1]["title"], + "merged pullrequest by user foo on repo test", + ) + self.assertEqual( + data["requests"][2]["title"], + "closed pullrequest by user foo on repo test2", + ) + self.assertEqual( + data["requests"][3]["title"], + "closed pullrequest by user foo on repo test", + ) + self.assertEqual( + data["requests"][4]["title"], + "open pullrequest by user foo on repo test2", + ) + self.assertEqual( + data["requests"][5]["title"], + "open pullrequest by user foo on repo test", + ) + self.assertEqual(data["args"]["status"], "all") + self.assertEqual(data["args"]["page"], 1) # Test page 2 with the status parameter set to `all`. output = self.app.get( - '/api/0/user/pingou/requests/actionable?status=all&page=2') + "/api/0/user/pingou/requests/actionable?status=all&page=2" + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 0) + self.assertEqual(len(data["requests"]), 0) self.assertEqual( sorted(data.keys()), - [u'args', u'pagination', u'requests', u'total_requests']) - self.assertEqual(data['args']['page'], 2) - + ["args", "pagination", "requests", "total_requests"], + ) + self.assertEqual(data["args"]["page"], 2) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_view_user_requests_actionable_created(self, mockemail): """ Test the api_view_user_requests_filed method of the flask user api with the created parameter """ today = datetime.datetime.utcnow().date() output = self.app.get( - '/api/0/user/pingou/requests/actionable?status=all&created=%s' % ( - today.isoformat())) + "/api/0/user/pingou/requests/actionable?status=all&created=%s" + % (today.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 6) + self.assertEqual(len(data["requests"]), 6) yesterday = today - datetime.timedelta(days=1) output = self.app.get( - '/api/0/user/pingou/requests/actionable?status=all&created=%s' % ( - yesterday.isoformat())) + "/api/0/user/pingou/requests/actionable?status=all&created=%s" + % (yesterday.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 6) + self.assertEqual(len(data["requests"]), 6) tomorrow = today + datetime.timedelta(days=1) output = self.app.get( - '/api/0/user/pingou/requests/actionable?status=all&created=%s' % ( - tomorrow.isoformat())) + "/api/0/user/pingou/requests/actionable?status=all&created=%s" + % (tomorrow.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 0) + self.assertEqual(len(data["requests"]), 0) output = self.app.get( - '/api/0/user/pingou/requests/actionable?status=all&created=..%s' % ( - today.isoformat())) + "/api/0/user/pingou/requests/actionable?status=all&created=..%s" + % (today.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 0) + self.assertEqual(len(data["requests"]), 0) output = self.app.get( - '/api/0/user/pingou/requests/actionable?status=all&created=..%s' % ( - yesterday.isoformat())) + "/api/0/user/pingou/requests/actionable?status=all&created=..%s" + % (yesterday.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 0) + self.assertEqual(len(data["requests"]), 0) thedaybefore = today - datetime.timedelta(days=1) output = self.app.get( - '/api/0/user/pingou/requests/actionable?status=all&created=..%s' % ( - thedaybefore.isoformat())) + "/api/0/user/pingou/requests/actionable?status=all&created=..%s" + % (thedaybefore.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 0) + self.assertEqual(len(data["requests"]), 0) output = self.app.get( - '/api/0/user/pingou/requests/actionable?status=all&created=..%s' % ( - tomorrow.isoformat())) + "/api/0/user/pingou/requests/actionable?status=all&created=..%s" + % (tomorrow.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 6) + self.assertEqual(len(data["requests"]), 6) output = self.app.get( - '/api/0/user/pingou/requests/actionable?status=all&created=%s..%s' % ( - thedaybefore.isoformat(), tomorrow.isoformat())) + "/api/0/user/pingou/requests/actionable?status=all&created=%s..%s" + % (thedaybefore.isoformat(), tomorrow.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 6) + self.assertEqual(len(data["requests"]), 6) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_view_user_requests_actionable_updated(self, mockemail): """ Test the api_view_user_requests_filed method of the flask user api with the created parameter """ today = datetime.datetime.utcnow().date() output = self.app.get( - '/api/0/user/pingou/requests/actionable?status=all&updated=%s' % ( - today.isoformat())) + "/api/0/user/pingou/requests/actionable?status=all&updated=%s" + % (today.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 0) + self.assertEqual(len(data["requests"]), 0) yesterday = today - datetime.timedelta(days=1) output = self.app.get( - '/api/0/user/pingou/requests/actionable?status=all&updated=%s' % ( - yesterday.isoformat())) + "/api/0/user/pingou/requests/actionable?status=all&updated=%s" + % (yesterday.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 0) + self.assertEqual(len(data["requests"]), 0) tomorrow = today + datetime.timedelta(days=1) output = self.app.get( - '/api/0/user/pingou/requests/actionable?status=all&updated=%s' % ( - tomorrow.isoformat())) + "/api/0/user/pingou/requests/actionable?status=all&updated=%s" + % (tomorrow.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 6) + self.assertEqual(len(data["requests"]), 6) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_api_view_user_requests_actionable_closed(self, mockemail): """ Test the api_view_user_requests_filed method of the flask user api with the created parameter """ today = datetime.datetime.utcnow().date() output = self.app.get( - '/api/0/user/pingou/requests/actionable?status=all&closed=%s' % ( - today.isoformat())) + "/api/0/user/pingou/requests/actionable?status=all&closed=%s" + % (today.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 0) + self.assertEqual(len(data["requests"]), 0) yesterday = today - datetime.timedelta(days=1) output = self.app.get( - '/api/0/user/pingou/requests/actionable?status=all&closed=%s' % ( - yesterday.isoformat())) + "/api/0/user/pingou/requests/actionable?status=all&closed=%s" + % (yesterday.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 0) + self.assertEqual(len(data["requests"]), 0) tomorrow = today + datetime.timedelta(days=1) output = self.app.get( - '/api/0/user/pingou/requests/actionable?status=all&closed=%s' % ( - tomorrow.isoformat())) + "/api/0/user/pingou/requests/actionable?status=all&closed=%s" + % (tomorrow.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual(len(data['requests']), 0) + self.assertEqual(len(data["requests"]), 0) class PagureFlaskApiUsertestissues(tests.Modeltests): @@ -1404,198 +1560,194 @@ class PagureFlaskApiUsertestissues(tests.Modeltests): """ Set up the environnment, ran before every tests. """ super(PagureFlaskApiUsertestissues, self).setUp() - pagure.config.config['REQUESTS_FOLDER'] = None + pagure.config.config["REQUESTS_FOLDER"] = None tests.create_projects(self.session) - repo = pagure.lib.query._get_project(self.session, 'test') + repo = pagure.lib.query._get_project(self.session, "test") # Create issues to play with msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue', - content='We should work on this', - user='pingou', + title="Test issue", + content="We should work on this", + user="pingou", ) self.session.commit() - self.assertEqual(msg.title, 'Test issue') + self.assertEqual(msg.title, "Test issue") def test_user_issues_empty(self): """ Return the list of issues associated with the specified user. """ - output = self.app.get('/api/0/user/foo/issues') + output = self.app.get("/api/0/user/foo/issues") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - for k in ['pagination_issues_assigned', 'pagination_issues_created']: - for k2 in ['first', 'last']: + for k in ["pagination_issues_assigned", "pagination_issues_created"]: + for k2 in ["first", "last"]: self.assertIsNotNone(data[k][k2]) data[k][k2] = None self.assertEqual( data, { - "args": { - "assignee": True, - "author": True, - "closed": None, - "created": None, - "milestones": [], - "no_stones": None, - "order": None, - "order_key": None, - "page": 1, - "since": None, - "status": None, - "tags": [], - "updated": None, - }, - "issues_assigned": [], - "issues_created": [], - 'pagination_issues_assigned': { - 'first': None, - 'last': None, - 'next': None, - 'page': 1, - 'pages': 0, - 'per_page': 20, - 'prev': None}, - 'pagination_issues_created': { - 'first': None, - 'last': None, - 'next': None, - 'page': 1, - 'pages': 0, - 'per_page': 20, - 'prev': None}, - "total_issues_assigned": 0, - "total_issues_assigned_pages": 1, - "total_issues_created": 0, - "total_issues_created_pages": 1 - } + "args": { + "assignee": True, + "author": True, + "closed": None, + "created": None, + "milestones": [], + "no_stones": None, + "order": None, + "order_key": None, + "page": 1, + "since": None, + "status": None, + "tags": [], + "updated": None, + }, + "issues_assigned": [], + "issues_created": [], + "pagination_issues_assigned": { + "first": None, + "last": None, + "next": None, + "page": 1, + "pages": 0, + "per_page": 20, + "prev": None, + }, + "pagination_issues_created": { + "first": None, + "last": None, + "next": None, + "page": 1, + "pages": 0, + "per_page": 20, + "prev": None, + }, + "total_issues_assigned": 0, + "total_issues_assigned_pages": 1, + "total_issues_created": 0, + "total_issues_created_pages": 1, + }, ) def test_user_issues(self): """ Return the list of issues associated with the specified user. """ - output = self.app.get('/api/0/user/pingou/issues') + output = self.app.get("/api/0/user/pingou/issues") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) issues = [] - for issue in data['issues_created']: - issue['date_created'] = '1513111778' - issue['last_updated'] = '1513111778' - issue['project']['date_created'] = '1513111778' - issue['project']['date_modified'] = '1513111778' + for issue in data["issues_created"]: + issue["date_created"] = "1513111778" + issue["last_updated"] = "1513111778" + issue["project"]["date_created"] = "1513111778" + issue["project"]["date_modified"] = "1513111778" issues.append(issue) - data['issues_created'] = issues - for k in ['pagination_issues_assigned', 'pagination_issues_created']: - for k2 in ['first', 'last']: + data["issues_created"] = issues + for k in ["pagination_issues_assigned", "pagination_issues_created"]: + for k2 in ["first", "last"]: self.assertIsNotNone(data[k][k2]) data[k][k2] = None self.assertEqual( data, { - "args": { - "assignee": True, - "author": True, - "closed": None, - "created": None, - "milestones": [], - "no_stones": None, - "order": None, - "order_key": None, - "page": 1, - "since": None, - "status": None, - "tags": [], - "updated": None, - }, - "issues_assigned": [], - "issues_created": [ - { - "assignee": None, - "blocks": [], - "close_status": None, - "closed_at": None, - "closed_by": None, - "comments": [], - "content": "We should work on this", - "custom_fields": [], - "date_created": "1513111778", - "depends": [], - "id": 1, - "last_updated": "1513111778", - "milestone": None, - "priority": None, - "private": False, - "project": { - "access_groups": { - "admin": [], - "commit": [], - "ticket": [] - }, - "access_users": { - "admin": [], - "commit": [], - "owner": [ - "pingou" - ], - "ticket": [] - }, - "close_status": [ - "Invalid", - "Insufficient data", - "Fixed", - "Duplicate" - ], - "custom_keys": [], - "date_created": "1513111778", - "date_modified": "1513111778", - "description": "test project #1", - "fullname": "test", - "id": 1, - "milestones": {}, - "name": "test", - "namespace": None, - "parent": None, - "priorities": {}, + "args": { + "assignee": True, + "author": True, + "closed": None, + "created": None, + "milestones": [], + "no_stones": None, + "order": None, + "order_key": None, + "page": 1, + "since": None, + "status": None, "tags": [], - "url_path": "test", - "user": { - "fullname": "PY C", - "name": "pingou" + "updated": None, + }, + "issues_assigned": [], + "issues_created": [ + { + "assignee": None, + "blocks": [], + "close_status": None, + "closed_at": None, + "closed_by": None, + "comments": [], + "content": "We should work on this", + "custom_fields": [], + "date_created": "1513111778", + "depends": [], + "id": 1, + "last_updated": "1513111778", + "milestone": None, + "priority": None, + "private": False, + "project": { + "access_groups": { + "admin": [], + "commit": [], + "ticket": [], + }, + "access_users": { + "admin": [], + "commit": [], + "owner": ["pingou"], + "ticket": [], + }, + "close_status": [ + "Invalid", + "Insufficient data", + "Fixed", + "Duplicate", + ], + "custom_keys": [], + "date_created": "1513111778", + "date_modified": "1513111778", + "description": "test project #1", + "fullname": "test", + "id": 1, + "milestones": {}, + "name": "test", + "namespace": None, + "parent": None, + "priorities": {}, + "tags": [], + "url_path": "test", + "user": {"fullname": "PY C", "name": "pingou"}, + }, + "status": "Open", + "tags": [], + "title": "Test issue", + "user": {"fullname": "PY C", "name": "pingou"}, } - }, - "status": "Open", - "tags": [], - "title": "Test issue", - "user": { - "fullname": "PY C", - "name": "pingou" - } - } - ], - 'pagination_issues_assigned': { - 'first': None, - 'last': None, - 'next': None, - 'page': 1, - 'pages': 0, - 'per_page': 20, - 'prev': None}, - 'pagination_issues_created': { - 'first': None, - 'last': None, - 'next': None, - 'page': 1, - 'pages': 1, - 'per_page': 20, - 'prev': None}, - "total_issues_assigned": 0, - "total_issues_assigned_pages": 1, - "total_issues_created": 1, - "total_issues_created_pages": 1 - } + ], + "pagination_issues_assigned": { + "first": None, + "last": None, + "next": None, + "page": 1, + "pages": 0, + "per_page": 20, + "prev": None, + }, + "pagination_issues_created": { + "first": None, + "last": None, + "next": None, + "page": 1, + "pages": 1, + "per_page": 20, + "prev": None, + }, + "total_issues_assigned": 0, + "total_issues_assigned_pages": 1, + "total_issues_created": 1, + "total_issues_created_pages": 1, + }, ) def test_user_issues_created(self): @@ -1604,7 +1756,8 @@ class PagureFlaskApiUsertestissues(tests.Modeltests): today = datetime.datetime.utcnow().date() output = self.app.get( - '/api/0/user/pingou/issues?created=%s' % (today.isoformat())) + "/api/0/user/pingou/issues?created=%s" % (today.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertEqual(data["total_issues_assigned"], 0) @@ -1612,7 +1765,8 @@ class PagureFlaskApiUsertestissues(tests.Modeltests): yesterday = today - datetime.timedelta(days=1) output = self.app.get( - '/api/0/user/pingou/issues?created=%s' % (yesterday.isoformat())) + "/api/0/user/pingou/issues?created=%s" % (yesterday.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertEqual(data["total_issues_assigned"], 0) @@ -1620,35 +1774,39 @@ class PagureFlaskApiUsertestissues(tests.Modeltests): tomorrow = today + datetime.timedelta(days=1) output = self.app.get( - '/api/0/user/pingou/issues?created=%s' % (tomorrow.isoformat())) + "/api/0/user/pingou/issues?created=%s" % (tomorrow.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertEqual(data["total_issues_assigned"], 0) self.assertEqual(data["total_issues_created"], 0) output = self.app.get( - '/api/0/user/pingou/issues?created=..%s' % (yesterday.isoformat())) + "/api/0/user/pingou/issues?created=..%s" % (yesterday.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertEqual(data["total_issues_assigned"], 0) self.assertEqual(data["total_issues_created"], 0) output = self.app.get( - '/api/0/user/pingou/issues?created=%s..%s' % ( - yesterday.isoformat(), today.isoformat())) + "/api/0/user/pingou/issues?created=%s..%s" + % (yesterday.isoformat(), today.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertEqual(data["total_issues_assigned"], 0) self.assertEqual(data["total_issues_created"], 0) output = self.app.get( - '/api/0/user/pingou/issues?created=%s..%s' % ( - yesterday.isoformat(), tomorrow.isoformat())) + "/api/0/user/pingou/issues?created=%s..%s" + % (yesterday.isoformat(), tomorrow.isoformat()) + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertEqual(data["total_issues_assigned"], 0) self.assertEqual(data["total_issues_created"], 1) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/test_pagure_flask_docs.py b/tests/test_pagure_flask_docs.py index 55ad7c3..4baa735 100644 --- a/tests/test_pagure_flask_docs.py +++ b/tests/test_pagure_flask_docs.py @@ -20,8 +20,9 @@ import mock import pygit2 from mock import patch -sys.path.insert(0, os.path.join(os.path.dirname( - os.path.abspath(__file__)), '..')) +sys.path.insert( + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") +) import pagure.docs_server import pagure.lib.query @@ -36,68 +37,70 @@ class PagureFlaskDocstests(tests.SimplePagureTest): """ Set up the environnment, ran before every tests. """ super(PagureFlaskDocstests, self).setUp() - pagure.docs_server.APP.config['TESTING'] = True + pagure.docs_server.APP.config["TESTING"] = True pagure.docs_server.SESSION = self.session - pagure.docs_server.APP.config['GIT_FOLDER'] = os.path.join( - self.path, 'repos') - pagure.docs_server.APP.config['TICKETS_FOLDER'] = os.path.join( - self.path, 'tickets') - pagure.docs_server.APP.config['DOCS_FOLDER'] = os.path.join( - self.path, 'repos', 'docs') + pagure.docs_server.APP.config["GIT_FOLDER"] = os.path.join( + self.path, "repos" + ) + pagure.docs_server.APP.config["TICKETS_FOLDER"] = os.path.join( + self.path, "tickets" + ) + pagure.docs_server.APP.config["DOCS_FOLDER"] = os.path.join( + self.path, "repos", "docs" + ) self.app = pagure.docs_server.APP.test_client() def _set_up_doc(self): # forked doc repo - docrepo = os.path.join(self.path, 'repos', 'docs', 'test', 'test.git') + docrepo = os.path.join(self.path, "repos", "docs", "test", "test.git") repo = pygit2.init_repository(docrepo) # Create files in that git repo - with open(os.path.join(docrepo, 'sources'), 'w') as stream: - stream.write('foo\n bar') - repo.index.add('sources') + with open(os.path.join(docrepo, "sources"), "w") as stream: + stream.write("foo\n bar") + repo.index.add("sources") repo.index.write() - folderpart = os.path.join(docrepo, 'folder1', 'folder2') + folderpart = os.path.join(docrepo, "folder1", "folder2") os.makedirs(folderpart) - with open(os.path.join(folderpart, 'test_file'), 'w') as stream: - stream.write('row1\nrow2\nrow3') - repo.index.add(os.path.join('folder1', 'folder2', 'test_file')) + with open(os.path.join(folderpart, "test_file"), "w") as stream: + stream.write("row1\nrow2\nrow3") + repo.index.add(os.path.join("folder1", "folder2", "test_file")) repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") repo.create_commit( - 'refs/heads/master', # the name of the reference to update + "refs/heads/master", # the name of the reference to update author, committer, - 'Add test files and folder', + "Add test files and folder", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [] + [], ) # Push the changes to the bare repo remote = repo.create_remote( - 'origin', os.path.join(self.path, 'repos', 'docs', 'test.git')) + "origin", os.path.join(self.path, "repos", "docs", "test.git") + ) - PagureRepo.push(remote, 'refs/heads/master:refs/heads/master') + PagureRepo.push(remote, "refs/heads/master:refs/heads/master") # Turn on the docs project since it's off by default - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - repo.settings = {'project_documentation': True} + repo = pagure.lib.query.get_authorized_project(self.session, "test") + repo.settings = {"project_documentation": True} self.session.add(repo) self.session.commit() def test_view_docs_no_project(self): """ Test the view_docs endpoint with no project. """ - output = self.app.get('/foo/docs') + output = self.app.get("/foo/docs") self.assertEqual(output.status_code, 404) def test_view_docs_project_no_git(self): @@ -107,145 +110,159 @@ class PagureFlaskDocstests(tests.SimplePagureTest): tests.create_projects(self.session) # Turn on the docs project since it's off by default - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - repo.settings = {'project_documentation': True} + repo = pagure.lib.query.get_authorized_project(self.session, "test") + repo.settings = {"project_documentation": True} self.session.add(repo) self.session.commit() - output = self.app.get('/test/docs', follow_redirects=True) + output = self.app.get("/test/docs", follow_redirects=True) self.assertEqual(output.status_code, 404) self.assertTrue( - '

Documentation not found

' in output.get_data(as_text=True)) + "

Documentation not found

" in output.get_data(as_text=True) + ) - output = self.app.get('/test', follow_redirects=True) + output = self.app.get("/test", follow_redirects=True) self.assertEqual(output.status_code, 404) self.assertTrue( - '

Documentation not found

' in output.get_data(as_text=True)) + "

Documentation not found

" in output.get_data(as_text=True) + ) def test_view_docs_project_no_docs(self): """ Test the view_docs endpoint with a project that disabled the docs. """ tests.create_projects(self.session) - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - tests.create_projects_git(os.path.join(self.path, 'repos', 'docs')) + repo = pagure.lib.query.get_authorized_project(self.session, "test") + tests.create_projects_git(os.path.join(self.path, "repos", "docs")) - output = self.app.get('/test/docs') + output = self.app.get("/test/docs") self.assertEqual(output.status_code, 404) - repo.settings = {'project_documentation': False} + repo.settings = {"project_documentation": False} self.session.add(repo) self.session.commit() - output = self.app.get('/test/docs', follow_redirects=True) + output = self.app.get("/test/docs", follow_redirects=True) self.assertEqual(output.status_code, 404) def test_view_docs_empty_repo(self): """ Test the view_docs endpoint when the git repo is empty. """ tests.create_projects(self.session) repo = pygit2.init_repository( - os.path.join(self.path, 'repos', 'docs', 'test.git'), bare=True) + os.path.join(self.path, "repos", "docs", "test.git"), bare=True + ) # Turn on the docs project since it's off by default - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - repo.settings = {'project_documentation': True} + repo = pagure.lib.query.get_authorized_project(self.session, "test") + repo.settings = {"project_documentation": True} self.session.add(repo) self.session.commit() - output = self.app.get('/test/docs') + output = self.app.get("/test/docs") self.assertEqual(output.status_code, 404) self.assertIn( - '

No content found in the repository, you may want to read ' + "

No content found in the repository, you may want to read " 'the Using the doc repository of your project ' - 'documentation.

', output.get_data(as_text=True)) + "documentation.

", + output.get_data(as_text=True), + ) def test_view_docs(self): """ Test the view_docs endpoint. """ tests.create_projects(self.session) repo = pygit2.init_repository( - os.path.join(self.path, 'repos', 'docs', 'test.git'), bare=True) + os.path.join(self.path, "repos", "docs", "test.git"), bare=True + ) - output = self.app.get('/test/docs') + output = self.app.get("/test/docs") self.assertEqual(output.status_code, 404) self._set_up_doc() # Now check the UI - output = self.app.get('/test/docs') + output = self.app.get("/test/docs") self.assertEqual(output.status_code, 404) - output = self.app.get('/test/sources') + output = self.app.get("/test/sources") self.assertEqual(output.status_code, 200) - self.assertEqual('
foo\n bar
', output.get_data(as_text=True)) + self.assertEqual("
foo\n bar
", output.get_data(as_text=True)) - output = self.app.get('/test/folder1/folder2') + output = self.app.get("/test/folder1/folder2") self.assertEqual(output.status_code, 200) self.assertTrue( '
  • ' - in output.get_data(as_text=True)) + in output.get_data(as_text=True) + ) - output = self.app.get('/test/folder1/folder2/test_file') + output = self.app.get("/test/folder1/folder2/test_file") self.assertEqual(output.status_code, 200) - self.assertEqual('
    row1\nrow2\nrow3
    ', output.get_data(as_text=True)) + self.assertEqual( + "
    row1\nrow2\nrow3
    ", output.get_data(as_text=True) + ) - output = self.app.get('/test/folder1') + output = self.app.get("/test/folder1") self.assertEqual(output.status_code, 200) self.assertTrue( '
  • ' - in output.get_data(as_text=True)) + in output.get_data(as_text=True) + ) - output = self.app.get('/test/folder1/foo') + output = self.app.get("/test/folder1/foo") self.assertEqual(output.status_code, 404) - output = self.app.get('/test/folder1/foo/folder2') + output = self.app.get("/test/folder1/foo/folder2") self.assertEqual(output.status_code, 404) @mock.patch( - 'pagure.lib.encoding_utils.decode', - mock.MagicMock(side_effect=pagure.exceptions.PagureEncodingException)) + "pagure.lib.encoding_utils.decode", + mock.MagicMock(side_effect=pagure.exceptions.PagureEncodingException), + ) def test_view_docs_encoding_error(self): """ Test viewing a file of which we cannot find the encoding. """ tests.create_projects(self.session) repo = pygit2.init_repository( - os.path.join(self.path, 'repos', 'docs', 'test.git'), bare=True) + os.path.join(self.path, "repos", "docs", "test.git"), bare=True + ) - output = self.app.get('/test/docs') + output = self.app.get("/test/docs") self.assertEqual(output.status_code, 404) self._set_up_doc() - output = self.app.get('/test/sources') + output = self.app.get("/test/sources") self.assertEqual(output.status_code, 200) - self.assertEqual('foo\n bar', output.get_data(as_text=True)) + self.assertEqual("foo\n bar", output.get_data(as_text=True)) - output = self.app.get('/test/folder1') + output = self.app.get("/test/folder1") self.assertEqual(output.status_code, 200) self.assertTrue( '
  • ' - in output.get_data(as_text=True)) + in output.get_data(as_text=True) + ) @mock.patch( - 'pagure.lib.encoding_utils.decode', - mock.MagicMock(side_effect=IOError)) + "pagure.lib.encoding_utils.decode", mock.MagicMock(side_effect=IOError) + ) def test_view_docs_unknown_error(self): """ Test viewing a file of which we cannot find the encoding. """ tests.create_projects(self.session) repo = pygit2.init_repository( - os.path.join(self.path, 'repos', 'docs', 'test.git'), bare=True) + os.path.join(self.path, "repos", "docs", "test.git"), bare=True + ) - output = self.app.get('/test/docs') + output = self.app.get("/test/docs") self.assertEqual(output.status_code, 404) self._set_up_doc() - output = self.app.get('/test/sources') + output = self.app.get("/test/sources") self.assertEqual(output.status_code, 500) - output = self.app.get('/test/folder1') + output = self.app.get("/test/folder1") self.assertEqual(output.status_code, 200) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/test_pagure_flask_dump_load_ticket.py b/tests/test_pagure_flask_dump_load_ticket.py index 4494971..c970640 100644 --- a/tests/test_pagure_flask_dump_load_ticket.py +++ b/tests/test_pagure_flask_dump_load_ticket.py @@ -21,8 +21,9 @@ import os import pygit2 from mock import patch -sys.path.insert(0, os.path.join(os.path.dirname( - os.path.abspath(__file__)), '..')) +sys.path.insert( + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") +) import pagure.lib.query import tests @@ -33,8 +34,8 @@ class PagureFlaskDumpLoadTicketTests(tests.Modeltests): a ticket. """ - @patch('pagure.lib.notify.send_email') - @patch('pagure.lib.git._maybe_wait') + @patch("pagure.lib.notify.send_email") + @patch("pagure.lib.git._maybe_wait") def test_dumping_reloading_ticket(self, mw, send_email): """ Test dumping a ticket into a JSON blob. """ mw.side_effect = lambda result: result.get() @@ -43,39 +44,39 @@ class PagureFlaskDumpLoadTicketTests(tests.Modeltests): tests.create_projects(self.session) # Create repo - self.gitrepo = os.path.join(self.path, 'repos', 'tickets', 'test.git') - repopath = os.path.join(self.path, 'repos', 'tickets') + self.gitrepo = os.path.join(self.path, "repos", "tickets", "test.git") + repopath = os.path.join(self.path, "repos", "tickets") os.makedirs(self.gitrepo) repo_obj = pygit2.init_repository(self.gitrepo, bare=True) - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") # Create an issue to play with msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue', - content='We should work on this', - user='pingou', + title="Test issue", + content="We should work on this", + user="pingou", ) - self.assertEqual(msg.title, 'Test issue') + self.assertEqual(msg.title, "Test issue") # Need another two issue to test the dependencie chain msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue #2', - content='Another bug', - user='pingou', + title="Test issue #2", + content="Another bug", + user="pingou", ) - self.assertEqual(msg.title, 'Test issue #2') + self.assertEqual(msg.title, "Test issue #2") msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue #3', - content='That would be nice feature no?', - user='foo', + title="Test issue #3", + content="That would be nice feature no?", + user="foo", ) - self.assertEqual(msg.title, 'Test issue #3') + self.assertEqual(msg.title, "Test issue #3") issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) issue2 = pagure.lib.query.search_issues(self.session, repo, issueid=2) @@ -85,76 +86,75 @@ class PagureFlaskDumpLoadTicketTests(tests.Modeltests): msg = pagure.lib.query.add_issue_comment( session=self.session, issue=issue, - comment='Hey look a comment!', - user='foo', + comment="Hey look a comment!", + user="foo", ) self.session.commit() - self.assertEqual(msg, 'Comment added') + self.assertEqual(msg, "Comment added") msg = pagure.lib.query.add_issue_comment( session=self.session, issue=issue, - comment='crazy right?', - user='pingou', + comment="crazy right?", + user="pingou", ) self.session.commit() - self.assertEqual(msg, 'Comment added') + self.assertEqual(msg, "Comment added") # Assign the ticket to someone msg = pagure.lib.query.add_issue_assignee( - session=self.session, - issue=issue, - assignee='pingou', - user='pingou', + session=self.session, issue=issue, assignee="pingou", user="pingou" ) self.session.commit() - self.assertEqual(msg, 'Issue assigned to pingou') + self.assertEqual(msg, "Issue assigned to pingou") # Add a couple of tags on the ticket msg = pagure.lib.query.add_tag_obj( session=self.session, obj=issue, - tags=[' feature ', 'future '], - user='pingou', + tags=[" feature ", "future "], + user="pingou", ) self.session.commit() - self.assertEqual(msg, 'Issue tagged with: feature, future') + self.assertEqual(msg, "Issue tagged with: feature, future") # Add dependencies msg = pagure.lib.query.add_issue_dependency( session=self.session, issue=issue, issue_blocked=issue2, - user='pingou', + user="pingou", ) self.session.commit() - self.assertEqual(msg, 'Issue marked as depending on: #2') + self.assertEqual(msg, "Issue marked as depending on: #2") msg = pagure.lib.query.add_issue_dependency( - session=self.session, - issue=issue3, - issue_blocked=issue, - user='foo', + session=self.session, issue=issue3, issue_blocked=issue, user="foo" ) self.session.commit() - self.assertEqual(msg, 'Issue marked as depending on: #1') + self.assertEqual(msg, "Issue marked as depending on: #1") # Dump the JSON pagure.lib.git.update_git(issue, repo).wait() repo = pygit2.Repository(self.gitrepo) - cnt = len([commit - for commit in repo.walk( - repo.head.target, pygit2.GIT_SORT_TOPOLOGICAL)]) + cnt = len( + [ + commit + for commit in repo.walk( + repo.head.target, pygit2.GIT_SORT_TOPOLOGICAL + ) + ] + ) self.assertIn(cnt, (9, 10)) - last_commit = repo.revparse_single('HEAD') + last_commit = repo.revparse_single("HEAD") patch = pagure.lib.git.commit_to_patch(repo, last_commit) - for line in patch.split('\n'): - if line.startswith('--- a/'): - fileid = line.split('--- a/')[1] + for line in patch.split("\n"): + if line.startswith("--- a/"): + fileid = line.split("--- a/")[1] break - newpath = tempfile.mkdtemp(prefix='pagure-dump-load') + newpath = tempfile.mkdtemp(prefix="pagure-dump-load") clone_repo = pygit2.clone_repository(self.gitrepo, newpath) self.assertEqual(len(os.listdir(newpath)), 4) - ticket_json = os.path.join(self.path, 'test_ticket.json') + ticket_json = os.path.join(self.path, "test_ticket.json") self.assertFalse(os.path.exists(ticket_json)) shutil.copyfile(os.path.join(newpath, fileid), ticket_json) self.assertTrue(os.path.exists(ticket_json)) @@ -171,35 +171,37 @@ class PagureFlaskDumpLoadTicketTests(tests.Modeltests): tests.create_projects(self.session) # Create repo - self.gitrepo = os.path.join(self.path, 'tickets', 'test.git') - repopath = os.path.join(self.path, 'tickets') + self.gitrepo = os.path.join(self.path, "tickets", "test.git") + repopath = os.path.join(self.path, "tickets") os.makedirs(self.gitrepo) pygit2.init_repository(self.gitrepo, bare=True) pagure.lib.git.update_ticket_from_git( self.session, - reponame='test', + reponame="test", namespace=None, username=None, - issue_uid='foobar', + issue_uid="foobar", json_data=jsondata, - agent='pingou', + agent="pingou", ) # Post loading - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") self.assertEqual(len(repo.issues), 1) issue = pagure.lib.query.search_issues(self.session, repo, issueid=1) # Check after re-loading self.assertEqual(len(issue.comments), 3) self.assertEqual(len(issue.tags), 2) - self.assertEqual(sorted(issue.tags_text), sorted(['future', 'feature'])) - self.assertEqual(issue.assignee.username, 'pingou') + self.assertEqual( + sorted(issue.tags_text), sorted(["future", "feature"]) + ) + self.assertEqual(issue.assignee.username, "pingou") self.assertEqual(issue.children, []) self.assertEqual(issue.parents, []) - self.assertEqual(issue.status, 'Open') + self.assertEqual(issue.status, "Open") -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/test_pagure_flask_form.py b/tests/test_pagure_flask_form.py index 81ae333..b32648d 100644 --- a/tests/test_pagure_flask_form.py +++ b/tests/test_pagure_flask_form.py @@ -20,8 +20,9 @@ import flask import flask_wtf from mock import patch, MagicMock -sys.path.insert(0, os.path.join(os.path.dirname( - os.path.abspath(__file__)), '..')) +sys.path.insert( + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") +) import pagure.forms import tests @@ -30,28 +31,30 @@ import tests class PagureFlaskFormTests(tests.SimplePagureTest): """ Tests for forms of the flask application """ - @patch.dict('pagure.config.config', {'SERVER_NAME': 'localhost.localdomain'}) + @patch.dict( + "pagure.config.config", {"SERVER_NAME": "localhost.localdomain"} + ) def setUp(self): super(PagureFlaskFormTests, self).setUp() def test_csrf_form_no_input(self): """ Test the CSRF validation if not CSRF is specified. """ - with self.app.application.test_request_context(method='POST'): + with self.app.application.test_request_context(method="POST"): flask.g.session = MagicMock() form = pagure.forms.ConfirmationForm() self.assertFalse(form.validate_on_submit()) def test_csrf_form_w_invalid_input(self): """ Test the CSRF validation with an invalid CSRF specified. """ - with self.app.application.test_request_context(method='POST'): + with self.app.application.test_request_context(method="POST"): flask.g.session = MagicMock() form = pagure.forms.ConfirmationForm() - form.csrf_token.data = 'foobar' + form.csrf_token.data = "foobar" self.assertFalse(form.validate_on_submit()) def test_csrf_form_w_input(self): """ Test the CSRF validation with a valid CSRF specified. """ - with self.app.application.test_request_context(method='POST'): + with self.app.application.test_request_context(method="POST"): flask.g.session = MagicMock() form = pagure.forms.ConfirmationForm() form.csrf_token.data = form.csrf_token.current_token @@ -59,101 +62,102 @@ class PagureFlaskFormTests(tests.SimplePagureTest): def test_csrf_form_w_expired_input(self): """ Test the CSRF validation with an expired CSRF specified. """ - with self.app.application.test_request_context(method='POST'): + with self.app.application.test_request_context(method="POST"): flask.g.session = MagicMock() form = pagure.forms.ConfirmationForm() data = form.csrf_token.current_token # CSRF token expired - if hasattr(flask_wtf, '__version__') and \ - tuple( - [int(v) for v in flask_wtf.__version__.split('.')] - ) < (0, 10, 0): + if hasattr(flask_wtf, "__version__") and tuple( + [int(v) for v in flask_wtf.__version__.split(".")] + ) < (0, 10, 0): expires = time.time() - 1 else: expires = ( datetime.datetime.now() - datetime.timedelta(minutes=1) - ).strftime('%Y%m%d%H%M%S') + ).strftime("%Y%m%d%H%M%S") # Change the CSRF format - if hasattr(flask_wtf, '__version__') and \ - tuple([int(e) for e in flask_wtf.__version__.split('.')] - ) >= (0,14,0): + if hasattr(flask_wtf, "__version__") and tuple( + [int(e) for e in flask_wtf.__version__.split(".")] + ) >= (0, 14, 0): import itsdangerous - try: # ItsDangerous-1.0 + + try: # ItsDangerous-1.0 timestamp = itsdangerous.base64_encode( - itsdangerous.encoding.int_to_bytes(int(expires))) - except AttributeError: # ItsDangerous-0.24 + itsdangerous.encoding.int_to_bytes(int(expires)) + ) + except AttributeError: # ItsDangerous-0.24 timestamp = itsdangerous.base64_encode( - itsdangerous.int_to_bytes(int(expires))) + itsdangerous.int_to_bytes(int(expires)) + ) timestamp = timestamp.decode("ascii") - part1, _, part2 = data.split('.', 2) - form.csrf_token.data = '.'.join([part1, timestamp, part2]) + part1, _, part2 = data.split(".", 2) + form.csrf_token.data = ".".join([part1, timestamp, part2]) else: - _, hmac_csrf = data.split('##', 1) - form.csrf_token.data = '%s##%s' % (expires, hmac_csrf) + _, hmac_csrf = data.split("##", 1) + form.csrf_token.data = "%s##%s" % (expires, hmac_csrf) self.assertFalse(form.validate_on_submit()) def test_csrf_form_w_unexpiring_input(self): """ Test the CSRF validation with a CSRF not expiring. """ - pagure.config.config['WTF_CSRF_TIME_LIMIT'] = None - with self.app.application.test_request_context(method='POST'): + pagure.config.config["WTF_CSRF_TIME_LIMIT"] = None + with self.app.application.test_request_context(method="POST"): flask.g.session = MagicMock() form = pagure.forms.ConfirmationForm() data = form.csrf_token.current_token - if hasattr(flask_wtf, '__version__') and \ - tuple([int(e) for e in flask_wtf.__version__.split('.')] - ) >= (0,14,0): + if hasattr(flask_wtf, "__version__") and tuple( + [int(e) for e in flask_wtf.__version__.split(".")] + ) >= (0, 14, 0): form.csrf_token.data = data else: - _, hmac_csrf = data.split('##', 1) + _, hmac_csrf = data.split("##", 1) # CSRF can no longer expire, they have no expiration info - form.csrf_token.data = '##%s' % hmac_csrf + form.csrf_token.data = "##%s" % hmac_csrf self.assertTrue(form.validate_on_submit()) def test_add_user_form(self): """ Test the AddUserForm of pagure.forms """ - with self.app.application.test_request_context(method='POST'): + with self.app.application.test_request_context(method="POST"): flask.g.session = MagicMock() form = pagure.forms.AddUserForm() form.csrf_token.data = form.csrf_token.current_token # No user or access given self.assertFalse(form.validate_on_submit()) # No access given - form.user.data = 'foo' + form.user.data = "foo" self.assertFalse(form.validate_on_submit()) - form.access.data = 'admin' + form.access.data = "admin" self.assertTrue(form.validate_on_submit()) def test_add_user_to_group_form(self): """ Test the AddUserToGroup form of pagure.forms """ - with self.app.application.test_request_context(method='POST'): + with self.app.application.test_request_context(method="POST"): flask.g.session = MagicMock() form = pagure.forms.AddUserToGroupForm() form.csrf_token.data = form.csrf_token.current_token # No user given self.assertFalse(form.validate_on_submit()) - form.user.data = 'foo' + form.user.data = "foo" # Everything given self.assertTrue(form.validate_on_submit()) def test_add_group_form(self): """ Test the AddGroupForm form of pagure.forms """ - with self.app.application.test_request_context(method='POST'): + with self.app.application.test_request_context(method="POST"): flask.g.session = MagicMock() form = pagure.forms.AddGroupForm() form.csrf_token.data = form.csrf_token.current_token # No group given self.assertFalse(form.validate_on_submit()) # No access given - form.group.data = 'gname' + form.group.data = "gname" self.assertFalse(form.validate_on_submit()) - form.access.data = 'admin' + form.access.data = "admin" self.assertTrue(form.validate_on_submit()) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(verbosity=2) - diff --git a/tests/test_pagure_flask_internal.py b/tests/test_pagure_flask_internal.py index 753444b..663cf16 100644 --- a/tests/test_pagure_flask_internal.py +++ b/tests/test_pagure_flask_internal.py @@ -21,8 +21,9 @@ import os import pygit2 from mock import patch, MagicMock, Mock -sys.path.insert(0, os.path.join(os.path.dirname( - os.path.abspath(__file__)), '..')) +sys.path.insert( + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") +) import pagure.lib.query import tests @@ -38,123 +39,115 @@ class PagureFlaskInternaltests(tests.Modeltests): """ Set up the environnment, ran before every tests. """ super(PagureFlaskInternaltests, self).setUp() - pagure.config.config['IP_ALLOWED_INTERNAL'] = list(set( - pagure.config.config['IP_ALLOWED_INTERNAL'] + [None])) + pagure.config.config["IP_ALLOWED_INTERNAL"] = list( + set(pagure.config.config["IP_ALLOWED_INTERNAL"] + [None]) + ) - pagure.config.config['GIT_FOLDER'] = os.path.join( - self.path, 'repos') + pagure.config.config["GIT_FOLDER"] = os.path.join(self.path, "repos") - @patch.dict('pagure.config.config', {'IP_ALLOWED_INTERNAL': []}) + @patch.dict("pagure.config.config", {"IP_ALLOWED_INTERNAL": []}) def test_internal_access_only(self): - output = self.app.post('/pv/ssh/lookupkey/') + output = self.app.post("/pv/ssh/lookupkey/") self.assertEqual(output.status_code, 403) # no internal IP addresses => will fail - output = self.app.post('/pv/ssh/lookupkey/') + output = self.app.post("/pv/ssh/lookupkey/") self.assertEqual(output.status_code, 403) # wrong token => will fail output = self.app.post( - '/pv/ssh/lookupkey/', - headers={"Authorization": "token doesntexist"} + "/pv/ssh/lookupkey/", + headers={"Authorization": "token doesntexist"}, ) self.assertEqual(output.status_code, 401) # correct token => will work pagure.lib.query.add_token_to_user( - self.session, None, ['internal_access'], 'pingou' + self.session, None, ["internal_access"], "pingou" ) token = pagure.lib.query.search_token( - self.session, acls=['internal_access'], user='pingou' + self.session, acls=["internal_access"], user="pingou" ) output = self.app.post( - '/pv/ssh/lookupkey/', - headers={"Authorization": "token %s" % token[0].id} + "/pv/ssh/lookupkey/", + headers={"Authorization": "token %s" % token[0].id}, ) self.assertEqual(output.status_code, 400) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_pull_request_add_comment(self, send_email): """ Test the pull_request_add_comment function. """ send_email.return_value = True tests.create_projects(self.session) - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") req = pagure.lib.query.new_pull_request( session=self.session, repo_from=repo, - branch_from='feature', + branch_from="feature", repo_to=repo, - branch_to='master', - title='PR from the feature branch', - user='pingou', + branch_to="master", + title="PR from the feature branch", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'PR from the feature branch') + self.assertEqual(req.title, "PR from the feature branch") request = repo.requests[0] self.assertEqual(len(request.comments), 0) self.assertEqual(len(request.discussion), 0) - data = { - 'objid': 'foo', - } + data = {"objid": "foo"} # Wrong http request - output = self.app.post('/pv/pull-request/comment/', data=data) + output = self.app.post("/pv/pull-request/comment/", data=data) self.assertEqual(output.status_code, 405) # Invalid request - output = self.app.put('/pv/pull-request/comment/', data=data) + output = self.app.put("/pv/pull-request/comment/", data=data) self.assertEqual(output.status_code, 400) - data = { - 'objid': 'foo', - 'useremail': 'foo@pingou.com', - } + data = {"objid": "foo", "useremail": "foo@pingou.com"} # Invalid objid - output = self.app.put('/pv/pull-request/comment/', data=data) + output = self.app.put("/pv/pull-request/comment/", data=data) self.assertEqual(output.status_code, 404) - data = { - 'objid': request.uid, - 'useremail': 'foo@pingou.com', - } + data = {"objid": request.uid, "useremail": "foo@pingou.com"} # Valid objid, in-complete data for a comment - output = self.app.put('/pv/pull-request/comment/', data=data) + output = self.app.put("/pv/pull-request/comment/", data=data) self.assertEqual(output.status_code, 400) data = { - 'objid': request.uid, - 'useremail': 'foo@pingou.com', - 'comment': 'Looks good to me!', + "objid": request.uid, + "useremail": "foo@pingou.com", + "comment": "Looks good to me!", } # Add comment - output = self.app.put('/pv/pull-request/comment/', data=data) + output = self.app.put("/pv/pull-request/comment/", data=data) self.assertEqual(output.status_code, 200) js_data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual(js_data, {'message': 'Comment added'}) + self.assertDictEqual(js_data, {"message": "Comment added"}) self.session.commit() - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") request = repo.requests[0] self.assertEqual(len(request.comments), 1) self.assertEqual(len(request.discussion), 1) # Check the @internal_access_only - before = pagure.config.config['IP_ALLOWED_INTERNAL'][:] - pagure.config.config['IP_ALLOWED_INTERNAL'] = [] + before = pagure.config.config["IP_ALLOWED_INTERNAL"][:] + pagure.config.config["IP_ALLOWED_INTERNAL"] = [] - output = self.app.put('/pv/pull-request/comment/', data=data) + output = self.app.put("/pv/pull-request/comment/", data=data) self.assertEqual(output.status_code, 403) - pagure.config.config['IP_ALLOWED_INTERNAL'] = before[:] + pagure.config.config["IP_ALLOWED_INTERNAL"] = before[:] - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_ticket_add_comment(self, send_email): """ Test the ticket_add_comment function. """ send_email.return_value = True @@ -162,78 +155,70 @@ class PagureFlaskInternaltests(tests.Modeltests): tests.create_projects(self.session) # Create issues to play with - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue', - content='We should work on this', - user='pingou', + title="Test issue", + content="We should work on this", + user="pingou", ) self.session.commit() - self.assertEqual(msg.title, 'Test issue') + self.assertEqual(msg.title, "Test issue") issue = repo.issues[0] self.assertEqual(len(issue.comments), 0) - data = { - 'objid': 'foo', - } + data = {"objid": "foo"} # Wrong http request - output = self.app.post('/pv/ticket/comment/', data=data) + output = self.app.post("/pv/ticket/comment/", data=data) self.assertEqual(output.status_code, 405) # Invalid request - output = self.app.put('/pv/ticket/comment/', data=data) + output = self.app.put("/pv/ticket/comment/", data=data) self.assertEqual(output.status_code, 400) - data = { - 'objid': 'foo', - 'useremail': 'foo@pingou.com', - } + data = {"objid": "foo", "useremail": "foo@pingou.com"} # Invalid objid - output = self.app.put('/pv/ticket/comment/', data=data) + output = self.app.put("/pv/ticket/comment/", data=data) self.assertEqual(output.status_code, 404) - data = { - 'objid': issue.uid, - 'useremail': 'foo@pingou.com', - } + data = {"objid": issue.uid, "useremail": "foo@pingou.com"} # Valid objid, in-complete data for a comment - output = self.app.put('/pv/ticket/comment/', data=data) + output = self.app.put("/pv/ticket/comment/", data=data) self.assertEqual(output.status_code, 400) data = { - 'objid': issue.uid, - 'useremail': 'foo@pingou.com', - 'comment': 'Looks good to me!', + "objid": issue.uid, + "useremail": "foo@pingou.com", + "comment": "Looks good to me!", } # Add comment - output = self.app.put('/pv/ticket/comment/', data=data) + output = self.app.put("/pv/ticket/comment/", data=data) self.assertEqual(output.status_code, 200) js_data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual(js_data, {'message': 'Comment added'}) + self.assertDictEqual(js_data, {"message": "Comment added"}) self.session.commit() - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = repo.issues[0] self.assertEqual(len(issue.comments), 1) # Check the @internal_access_only - pagure.config.config['IP_ALLOWED_INTERNAL'].remove(None) - before = pagure.config.config['IP_ALLOWED_INTERNAL'][:] - pagure.config.config['IP_ALLOWED_INTERNAL'] = [] + pagure.config.config["IP_ALLOWED_INTERNAL"].remove(None) + before = pagure.config.config["IP_ALLOWED_INTERNAL"][:] + pagure.config.config["IP_ALLOWED_INTERNAL"] = [] - output = self.app.put('/pv/ticket/comment/', data=data) + output = self.app.put("/pv/ticket/comment/", data=data) self.assertEqual(output.status_code, 403) - pagure.config.config['IP_ALLOWED_INTERNAL'] = before[:] + pagure.config.config["IP_ALLOWED_INTERNAL"] = before[:] - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_private_ticket_add_comment(self, send_email): """ Test the ticket_add_comment function on a private ticket. """ send_email.return_value = True @@ -241,87 +226,76 @@ class PagureFlaskInternaltests(tests.Modeltests): tests.create_projects(self.session) # Create issues to play with - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue', - content='We should work on this, really', - user='pingou', + title="Test issue", + content="We should work on this, really", + user="pingou", private=True, ) self.session.commit() - self.assertEqual(msg.title, 'Test issue') + self.assertEqual(msg.title, "Test issue") issue = repo.issues[0] self.assertEqual(len(issue.comments), 0) - data = { - 'objid': 'foo', - } + data = {"objid": "foo"} # Wrong http request - output = self.app.post('/pv/ticket/comment/', data=data) + output = self.app.post("/pv/ticket/comment/", data=data) self.assertEqual(output.status_code, 405) # Invalid request - output = self.app.put('/pv/ticket/comment/', data=data) + output = self.app.put("/pv/ticket/comment/", data=data) self.assertEqual(output.status_code, 400) - data = { - 'objid': 'foo', - 'useremail': 'foo@pingou.com', - } + data = {"objid": "foo", "useremail": "foo@pingou.com"} # Invalid objid - output = self.app.put('/pv/ticket/comment/', data=data) + output = self.app.put("/pv/ticket/comment/", data=data) self.assertEqual(output.status_code, 404) - data = { - 'objid': issue.uid, - 'useremail': 'foo@bar.com', - } + data = {"objid": issue.uid, "useremail": "foo@bar.com"} # Valid objid, un-allowed user for this (private) ticket - output = self.app.put('/pv/ticket/comment/', data=data) + output = self.app.put("/pv/ticket/comment/", data=data) self.assertEqual(output.status_code, 403) - data = { - 'objid': issue.uid, - 'useremail': 'foo@pingou.com', - } + data = {"objid": issue.uid, "useremail": "foo@pingou.com"} # Valid objid, un-allowed user for this (private) ticket - output = self.app.put('/pv/ticket/comment/', data=data) + output = self.app.put("/pv/ticket/comment/", data=data) self.assertEqual(output.status_code, 400) data = { - 'objid': issue.uid, - 'useremail': 'foo@pingou.com', - 'comment': 'Looks good to me!', + "objid": issue.uid, + "useremail": "foo@pingou.com", + "comment": "Looks good to me!", } # Add comment - output = self.app.put('/pv/ticket/comment/', data=data) + output = self.app.put("/pv/ticket/comment/", data=data) self.assertEqual(output.status_code, 200) js_data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual(js_data, {'message': 'Comment added'}) + self.assertDictEqual(js_data, {"message": "Comment added"}) self.session.commit() - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = repo.issues[0] self.assertEqual(len(issue.comments), 1) # Check the @internal_access_only - before = pagure.config.config['IP_ALLOWED_INTERNAL'][:] - pagure.config.config['IP_ALLOWED_INTERNAL'] = [] + before = pagure.config.config["IP_ALLOWED_INTERNAL"][:] + pagure.config.config["IP_ALLOWED_INTERNAL"] = [] - output = self.app.put('/pv/ticket/comment/', data=data) + output = self.app.put("/pv/ticket/comment/", data=data) self.assertEqual(output.status_code, 403) - pagure.config.config['IP_ALLOWED_INTERNAL'] = before[:] + pagure.config.config["IP_ALLOWED_INTERNAL"] = before[:] - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_private_ticket_add_comment_acl(self, send_email): """ Test the ticket_add_comment function on a private ticket. """ send_email.return_value = True @@ -329,84 +303,80 @@ class PagureFlaskInternaltests(tests.Modeltests): tests.create_projects(self.session) # Create issues to play with - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") msg = pagure.lib.query.new_issue( session=self.session, repo=repo, - title='Test issue', - content='We should work on this, really', - user='pingou', + title="Test issue", + content="We should work on this, really", + user="pingou", private=True, ) self.session.commit() - self.assertEqual(msg.title, 'Test issue') + self.assertEqual(msg.title, "Test issue") - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = repo.issues[0] self.assertEqual(len(issue.comments), 0) # Currently, he is just an average user, # He doesn't have any access in this repo data = { - 'objid': issue.uid, - 'useremail': 'foo@bar.com', - 'comment': 'Looks good to me!', + "objid": issue.uid, + "useremail": "foo@bar.com", + "comment": "Looks good to me!", } # Valid objid, un-allowed user for this (private) ticket - output = self.app.put('/pv/ticket/comment/', data=data) + output = self.app.put("/pv/ticket/comment/", data=data) self.assertEqual(output.status_code, 403) - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") # Let's promote him to be a ticketer # He shoudn't be able to comment even then though msg = pagure.lib.query.add_user_to_project( self.session, project=repo, - new_user='foo', - user='pingou', - access='ticket' + new_user="foo", + user="pingou", + access="ticket", ) self.session.commit() - self.assertEqual(msg, 'User added') - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - self.assertEqual( - sorted([u.username for u in repo.users]), ['foo']) - self.assertEqual( - sorted([u.username for u in repo.committers]), []) - self.assertEqual( - sorted([u.username for u in repo.admins]), []) + self.assertEqual(msg, "User added") + repo = pagure.lib.query.get_authorized_project(self.session, "test") + self.assertEqual(sorted([u.username for u in repo.users]), ["foo"]) + self.assertEqual(sorted([u.username for u in repo.committers]), []) + self.assertEqual(sorted([u.username for u in repo.admins]), []) - output = self.app.put('/pv/ticket/comment/', data=data) + output = self.app.put("/pv/ticket/comment/", data=data) self.assertEqual(output.status_code, 403) - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") # Let's promote him to be a committer # He should be able to comment msg = pagure.lib.query.add_user_to_project( self.session, project=repo, - new_user='foo', - user='pingou', - access='commit' + new_user="foo", + user="pingou", + access="commit", ) self.session.commit() - self.assertEqual(msg, 'User access updated') - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - self.assertEqual( - sorted([u.username for u in repo.users]), ['foo']) + self.assertEqual(msg, "User access updated") + repo = pagure.lib.query.get_authorized_project(self.session, "test") + self.assertEqual(sorted([u.username for u in repo.users]), ["foo"]) self.assertEqual( - sorted([u.username for u in repo.committers]), ['foo']) - self.assertEqual( - sorted([u.username for u in repo.admins]), []) + sorted([u.username for u in repo.committers]), ["foo"] + ) + self.assertEqual(sorted([u.username for u in repo.admins]), []) # Add comment - output = self.app.put('/pv/ticket/comment/', data=data) + output = self.app.put("/pv/ticket/comment/", data=data) self.assertEqual(output.status_code, 200) js_data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual(js_data, {'message': 'Comment added'}) + self.assertDictEqual(js_data, {"message": "Comment added"}) - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = repo.issues[0] self.assertEqual(len(issue.comments), 1) @@ -415,41 +385,40 @@ class PagureFlaskInternaltests(tests.Modeltests): msg = pagure.lib.query.add_user_to_project( self.session, project=repo, - new_user='foo', - user='pingou', - access='admin' + new_user="foo", + user="pingou", + access="admin", ) self.session.commit() - self.assertEqual(msg, 'User access updated') + self.assertEqual(msg, "User access updated") - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") + self.assertEqual(sorted([u.username for u in repo.users]), ["foo"]) self.assertEqual( - sorted([u.username for u in repo.users]), ['foo']) - self.assertEqual( - sorted([u.username for u in repo.committers]), ['foo']) - self.assertEqual( - sorted([u.username for u in repo.admins]), ['foo']) + sorted([u.username for u in repo.committers]), ["foo"] + ) + self.assertEqual(sorted([u.username for u in repo.admins]), ["foo"]) # Add comment - output = self.app.put('/pv/ticket/comment/', data=data) + output = self.app.put("/pv/ticket/comment/", data=data) self.assertEqual(output.status_code, 200) js_data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual(js_data, {'message': 'Comment added'}) + self.assertDictEqual(js_data, {"message": "Comment added"}) - repo = pagure.lib.query.get_authorized_project(self.session, 'test') + repo = pagure.lib.query.get_authorized_project(self.session, "test") issue = repo.issues[0] self.assertEqual(len(issue.comments), 2) # Check the @internal_access_only - before = pagure.config.config['IP_ALLOWED_INTERNAL'][:] - pagure.config.config['IP_ALLOWED_INTERNAL'] = [] + before = pagure.config.config["IP_ALLOWED_INTERNAL"][:] + pagure.config.config["IP_ALLOWED_INTERNAL"] = [] - output = self.app.put('/pv/ticket/comment/', data=data) + output = self.app.put("/pv/ticket/comment/", data=data) self.assertEqual(output.status_code, 403) - pagure.config.config['IP_ALLOWED_INTERNAL'] = before[:] + pagure.config.config["IP_ALLOWED_INTERNAL"] = before[:] - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_mergeable_request_pull_FF(self, send_email): """ Test the mergeable_request_pull endpoint with a fast-forward merge. @@ -458,128 +427,125 @@ class PagureFlaskInternaltests(tests.Modeltests): # Create a git repo to play with - origgitrepo = os.path.join(self.path, 'repos', 'test.git') + origgitrepo = os.path.join(self.path, "repos", "test.git") self.assertFalse(os.path.exists(origgitrepo)) os.makedirs(origgitrepo) orig_repo = pygit2.init_repository(origgitrepo, bare=True) - os.makedirs(os.path.join(self.path, 'repos_tmp')) - gitrepo = os.path.join(self.path, 'repos_tmp', 'test.git') + os.makedirs(os.path.join(self.path, "repos_tmp")) + gitrepo = os.path.join(self.path, "repos_tmp", "test.git") repo = pygit2.clone_repository(origgitrepo, gitrepo) # Create a file in that git repo - with open(os.path.join(gitrepo, 'sources'), 'w') as stream: - stream.write('foo\n bar') - repo.index.add('sources') + with open(os.path.join(gitrepo, "sources"), "w") as stream: + stream.write("foo\n bar") + repo.index.add("sources") repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") repo.create_commit( - 'refs/heads/master', # the name of the reference to update + "refs/heads/master", # the name of the reference to update author, committer, - 'Add sources file for testing', + "Add sources file for testing", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [] + [], ) - first_commit = repo.revparse_single('HEAD') - refname = 'refs/heads/master:refs/heads/master' + first_commit = repo.revparse_single("HEAD") + refname = "refs/heads/master:refs/heads/master" ori_remote = repo.remotes[0] PagureRepo.push(ori_remote, refname) # Edit the sources file again - with open(os.path.join(gitrepo, 'sources'), 'w') as stream: - stream.write('foo\n bar\nbaz\n boose') - repo.index.add('sources') + with open(os.path.join(gitrepo, "sources"), "w") as stream: + stream.write("foo\n bar\nbaz\n boose") + repo.index.add("sources") repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") repo.create_commit( - 'refs/heads/feature', # the name of the reference to update + "refs/heads/feature", # the name of the reference to update author, committer, - 'Add baz and boose to the sources\n\n There are more objects to ' - 'consider', + "Add baz and boose to the sources\n\n There are more objects to " + "consider", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [first_commit.oid.hex] + [first_commit.oid.hex], ) - second_commit = repo.revparse_single('HEAD') - refname = 'refs/heads/feature:refs/heads/feature' + second_commit = repo.revparse_single("HEAD") + refname = "refs/heads/feature:refs/heads/feature" ori_remote = repo.remotes[0] PagureRepo.push(ori_remote, refname) # Create a PR for these changes tests.create_projects(self.session) - project = pagure.lib.query.get_authorized_project(self.session, 'test') + project = pagure.lib.query.get_authorized_project(self.session, "test") req = pagure.lib.query.new_pull_request( session=self.session, repo_from=project, - branch_from='feature', + branch_from="feature", repo_to=project, - branch_to='master', - title='PR from the feature branch', - user='pingou', + branch_to="master", + title="PR from the feature branch", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'PR from the feature branch') + self.assertEqual(req.title, "PR from the feature branch") # Check if the PR can be merged - data = { - 'objid': 'blah', - } + data = {"objid": "blah"} # Missing CSRF - output = self.app.post('/pv/pull-request/merge', data=data) + output = self.app.post("/pv/pull-request/merge", data=data) self.assertEqual(output.status_code, 400) user = tests.FakeUser() - user.username = 'pingou' + user.username = "pingou" with tests.user_set(self.app.application, user): - output = self.app.get('/test/adduser') - csrf_token = output.get_data(as_text=True).split( - 'name="csrf_token" type="hidden" value="')[1].split('">')[0] + output = self.app.get("/test/adduser") + csrf_token = ( + output.get_data(as_text=True) + .split('name="csrf_token" type="hidden" value="')[1] + .split('">')[0] + ) # Missing request identifier - data = { - 'csrf_token': csrf_token, - } - output = self.app.post('/pv/pull-request/merge', data=data) + data = {"csrf_token": csrf_token} + output = self.app.post("/pv/pull-request/merge", data=data) self.assertEqual(output.status_code, 404) # With all the desired information - project = pagure.lib.query.get_authorized_project(self.session, 'test') + project = pagure.lib.query.get_authorized_project( + self.session, "test" + ) data = { - 'csrf_token': csrf_token, - 'requestid': project.requests[0].uid, + "csrf_token": csrf_token, + "requestid": project.requests[0].uid, } - output = self.app.post('/pv/pull-request/merge', data=data) + output = self.app.post("/pv/pull-request/merge", data=data) self.assertEqual(output.status_code, 200) exp = { - "code": "FFORWARD", - "message": "The pull-request can be merged and fast-forwarded", - "short_code": "Ok" + "code": "FFORWARD", + "message": "The pull-request can be merged and fast-forwarded", + "short_code": "Ok", } js_data = json.loads(output.get_data(as_text=True)) self.assertDictEqual(js_data, exp) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_mergeable_request_pull_no_change(self, send_email): """ Test the mergeable_request_pull endpoint when there are no changes to merge. @@ -588,119 +554,116 @@ class PagureFlaskInternaltests(tests.Modeltests): # Create a git repo to play with - gitrepo = os.path.join(self.path, 'repos', 'test.git') + gitrepo = os.path.join(self.path, "repos", "test.git") self.assertFalse(os.path.exists(gitrepo)) os.makedirs(gitrepo) repo = pygit2.init_repository(gitrepo) # Create a file in that git repo - with open(os.path.join(gitrepo, 'sources'), 'w') as stream: - stream.write('foo\n bar') - repo.index.add('sources') + with open(os.path.join(gitrepo, "sources"), "w") as stream: + stream.write("foo\n bar") + repo.index.add("sources") repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") repo.create_commit( - 'refs/heads/master', # the name of the reference to update + "refs/heads/master", # the name of the reference to update author, committer, - 'Add sources file for testing', + "Add sources file for testing", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [] + [], ) - first_commit = repo.revparse_single('HEAD') + first_commit = repo.revparse_single("HEAD") # Edit the sources file again - with open(os.path.join(gitrepo, 'sources'), 'w') as stream: - stream.write('foo\n bar\nbaz\n boose') - repo.index.add('sources') + with open(os.path.join(gitrepo, "sources"), "w") as stream: + stream.write("foo\n bar\nbaz\n boose") + repo.index.add("sources") repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") repo.create_commit( - 'refs/heads/master', # the name of the reference to update + "refs/heads/master", # the name of the reference to update author, committer, - 'Add baz and boose to the sources\n\n There are more objects to ' - 'consider', + "Add baz and boose to the sources\n\n There are more objects to " + "consider", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [first_commit.oid.hex] + [first_commit.oid.hex], ) - second_commit = repo.revparse_single('HEAD') + second_commit = repo.revparse_single("HEAD") # Create a PR for these changes tests.create_projects(self.session) - project = pagure.lib.query.get_authorized_project(self.session, 'test') + project = pagure.lib.query.get_authorized_project(self.session, "test") req = pagure.lib.query.new_pull_request( session=self.session, repo_from=project, - branch_from='master', + branch_from="master", repo_to=project, - branch_to='master', - title='PR from the feature branch', - user='pingou', + branch_to="master", + title="PR from the feature branch", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'PR from the feature branch') + self.assertEqual(req.title, "PR from the feature branch") # Check if the PR can be merged - data = { - 'objid': 'blah', - } + data = {"objid": "blah"} # Missing CSRF - output = self.app.post('/pv/pull-request/merge', data=data) + output = self.app.post("/pv/pull-request/merge", data=data) self.assertEqual(output.status_code, 400) user = tests.FakeUser() - user.username = 'pingou' + user.username = "pingou" with tests.user_set(self.app.application, user): - output = self.app.get('/test/adduser') - csrf_token = output.get_data(as_text=True).split( - 'name="csrf_token" type="hidden" value="')[1].split('">')[0] + output = self.app.get("/test/adduser") + csrf_token = ( + output.get_data(as_text=True) + .split('name="csrf_token" type="hidden" value="')[1] + .split('">')[0] + ) # Missing request identifier - data = { - 'csrf_token': csrf_token, - } - output = self.app.post('/pv/pull-request/merge', data=data) + data = {"csrf_token": csrf_token} + output = self.app.post("/pv/pull-request/merge", data=data) self.assertEqual(output.status_code, 404) # With all the desired information - project = pagure.lib.query.get_authorized_project(self.session, 'test') + project = pagure.lib.query.get_authorized_project( + self.session, "test" + ) data = { - 'csrf_token': csrf_token, - 'requestid': project.requests[0].uid, + "csrf_token": csrf_token, + "requestid": project.requests[0].uid, } - output = self.app.post('/pv/pull-request/merge', data=data) + output = self.app.post("/pv/pull-request/merge", data=data) self.assertEqual(output.status_code, 200) exp = { - "code": "NO_CHANGE", - "message": "Nothing to change, git is up to date", - "short_code": "No changes" + "code": "NO_CHANGE", + "message": "Nothing to change, git is up to date", + "short_code": "No changes", } js_data = json.loads(output.get_data(as_text=True)) self.assertDictEqual(js_data, exp) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_mergeable_request_pull_merge(self, send_email): """ Test the mergeable_request_pull endpoint when the changes can be merged with a merge commit. @@ -709,145 +672,142 @@ class PagureFlaskInternaltests(tests.Modeltests): # Create a git repo to play with - origgitrepo = os.path.join(self.path, 'repos', 'test.git') + origgitrepo = os.path.join(self.path, "repos", "test.git") self.assertFalse(os.path.exists(origgitrepo)) os.makedirs(origgitrepo) orig_repo = pygit2.init_repository(origgitrepo, bare=True) - os.makedirs(os.path.join(self.path, 'repos_tmp')) - gitrepo = os.path.join(self.path, 'repos_tmp', 'test.git') + os.makedirs(os.path.join(self.path, "repos_tmp")) + gitrepo = os.path.join(self.path, "repos_tmp", "test.git") repo = pygit2.clone_repository(origgitrepo, gitrepo) # Create a file in that git repo - with open(os.path.join(gitrepo, 'sources'), 'w') as stream: - stream.write('foo\n bar') - repo.index.add('sources') + with open(os.path.join(gitrepo, "sources"), "w") as stream: + stream.write("foo\n bar") + repo.index.add("sources") repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") repo.create_commit( - 'refs/heads/master', # the name of the reference to update + "refs/heads/master", # the name of the reference to update author, committer, - 'Add sources file for testing', + "Add sources file for testing", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [] + [], ) - first_commit = repo.revparse_single('HEAD') - refname = 'refs/heads/master:refs/heads/master' + first_commit = repo.revparse_single("HEAD") + refname = "refs/heads/master:refs/heads/master" ori_remote = repo.remotes[0] PagureRepo.push(ori_remote, refname) # Edit the sources file again - with open(os.path.join(gitrepo, 'sources'), 'w') as stream: - stream.write('foo\n bar\nbaz\n boose') - repo.index.add('sources') + with open(os.path.join(gitrepo, "sources"), "w") as stream: + stream.write("foo\n bar\nbaz\n boose") + repo.index.add("sources") repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") repo.create_commit( - 'refs/heads/feature', # the name of the reference to update + "refs/heads/feature", # the name of the reference to update author, committer, - 'Add baz and boose to the sources\n\n There are more objects to ' - 'consider', + "Add baz and boose to the sources\n\n There are more objects to " + "consider", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [first_commit.oid.hex] + [first_commit.oid.hex], ) - refname = 'refs/heads/feature:refs/heads/feature' + refname = "refs/heads/feature:refs/heads/feature" ori_remote = repo.remotes[0] PagureRepo.push(ori_remote, refname) # Create another file in the master branch - with open(os.path.join(gitrepo, '.gitignore'), 'w') as stream: - stream.write('*~') - repo.index.add('.gitignore') + with open(os.path.join(gitrepo, ".gitignore"), "w") as stream: + stream.write("*~") + repo.index.add(".gitignore") repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") repo.create_commit( - 'refs/heads/master', # the name of the reference to update + "refs/heads/master", # the name of the reference to update author, committer, - 'Add .gitignore file for testing', + "Add .gitignore file for testing", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [first_commit.oid.hex] + [first_commit.oid.hex], ) - refname = 'refs/heads/master:refs/heads/master' + refname = "refs/heads/master:refs/heads/master" ori_remote = repo.remotes[0] PagureRepo.push(ori_remote, refname) # Create a PR for these changes tests.create_projects(self.session) - project = pagure.lib.query.get_authorized_project(self.session, 'test') + project = pagure.lib.query.get_authorized_project(self.session, "test") req = pagure.lib.query.new_pull_request( session=self.session, repo_from=project, - branch_from='feature', + branch_from="feature", repo_to=project, - branch_to='master', - title='PR from the feature branch', - user='pingou', + branch_to="master", + title="PR from the feature branch", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'PR from the feature branch') + self.assertEqual(req.title, "PR from the feature branch") # Check if the PR can be merged data = {} # Missing CSRF - output = self.app.post('/pv/pull-request/merge', data=data) + output = self.app.post("/pv/pull-request/merge", data=data) self.assertEqual(output.status_code, 400) user = tests.FakeUser() - user.username = 'pingou' + user.username = "pingou" with tests.user_set(self.app.application, user): - output = self.app.get('/test/adduser') - csrf_token = output.get_data(as_text=True).split( - 'name="csrf_token" type="hidden" value="')[1].split('">')[0] + output = self.app.get("/test/adduser") + csrf_token = ( + output.get_data(as_text=True) + .split('name="csrf_token" type="hidden" value="')[1] + .split('">')[0] + ) # Missing request identifier - data = { - 'csrf_token': csrf_token, - } - output = self.app.post('/pv/pull-request/merge', data=data) + data = {"csrf_token": csrf_token} + output = self.app.post("/pv/pull-request/merge", data=data) self.assertEqual(output.status_code, 404) # With all the desired information - project = pagure.lib.query.get_authorized_project(self.session, 'test') + project = pagure.lib.query.get_authorized_project( + self.session, "test" + ) data = { - 'csrf_token': csrf_token, - 'requestid': project.requests[0].uid, - 'force': True, + "csrf_token": csrf_token, + "requestid": project.requests[0].uid, + "force": True, } - output = self.app.post('/pv/pull-request/merge', data=data) + output = self.app.post("/pv/pull-request/merge", data=data) self.assertEqual(output.status_code, 200) exp = { - "code": "MERGE", - "message": "The pull-request can be merged with a merge commit", - "short_code": "With merge" + "code": "MERGE", + "message": "The pull-request can be merged with a merge commit", + "short_code": "With merge", } js_data = json.loads(output.get_data(as_text=True)) @@ -855,21 +815,21 @@ class PagureFlaskInternaltests(tests.Modeltests): # Asking a second time will trigger the cache data = { - 'csrf_token': csrf_token, - 'requestid': project.requests[0].uid, + "csrf_token": csrf_token, + "requestid": project.requests[0].uid, } - output = self.app.post('/pv/pull-request/merge', data=data) + output = self.app.post("/pv/pull-request/merge", data=data) self.assertEqual(output.status_code, 200) exp = { - "code": "MERGE", - "message": "The pull-request can be merged with a merge commit", - "short_code": "With merge" + "code": "MERGE", + "message": "The pull-request can be merged with a merge commit", + "short_code": "With merge", } js_data = json.loads(output.get_data(as_text=True)) self.assertDictEqual(js_data, exp) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_mergeable_request_pull_conflicts(self, send_email): """ Test the mergeable_request_pull endpoint when the changes cannot be merged due to conflicts. @@ -877,150 +837,147 @@ class PagureFlaskInternaltests(tests.Modeltests): send_email.return_value = True # Create a git repo to play with - origgitrepo = os.path.join(self.path, 'repos', 'test.git') + origgitrepo = os.path.join(self.path, "repos", "test.git") self.assertFalse(os.path.exists(origgitrepo)) os.makedirs(origgitrepo) orig_repo = pygit2.init_repository(origgitrepo, bare=True) - os.makedirs(os.path.join(self.path, 'repos_tmp')) - gitrepo = os.path.join(self.path, 'repos_tmp', 'test.git') + os.makedirs(os.path.join(self.path, "repos_tmp")) + gitrepo = os.path.join(self.path, "repos_tmp", "test.git") repo = pygit2.clone_repository(origgitrepo, gitrepo) # Create a file in that git repo - with open(os.path.join(gitrepo, 'sources'), 'w') as stream: - stream.write('foo\n bar') - repo.index.add('sources') + with open(os.path.join(gitrepo, "sources"), "w") as stream: + stream.write("foo\n bar") + repo.index.add("sources") repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") repo.create_commit( - 'refs/heads/master', # the name of the reference to update + "refs/heads/master", # the name of the reference to update author, committer, - 'Add sources file for testing', + "Add sources file for testing", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [] + [], ) - first_commit = repo.revparse_single('HEAD') - refname = 'refs/heads/master:refs/heads/master' + first_commit = repo.revparse_single("HEAD") + refname = "refs/heads/master:refs/heads/master" ori_remote = repo.remotes[0] PagureRepo.push(ori_remote, refname) # Edit the sources file again - with open(os.path.join(gitrepo, 'sources'), 'w') as stream: - stream.write('foo\n bar\nbaz\n boose') - repo.index.add('sources') + with open(os.path.join(gitrepo, "sources"), "w") as stream: + stream.write("foo\n bar\nbaz\n boose") + repo.index.add("sources") repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") repo.create_commit( - 'refs/heads/feature', # the name of the reference to update + "refs/heads/feature", # the name of the reference to update author, committer, - 'Add baz and boose to the sources\n\n There are more objects to ' - 'consider', + "Add baz and boose to the sources\n\n There are more objects to " + "consider", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [first_commit.oid.hex] + [first_commit.oid.hex], ) - refname = 'refs/heads/feature:refs/heads/feature' + refname = "refs/heads/feature:refs/heads/feature" ori_remote = repo.remotes[0] PagureRepo.push(ori_remote, refname) # Create another file in the master branch - with open(os.path.join(gitrepo, 'sources'), 'w') as stream: - stream.write('foo\n bar\nbaz\n') - repo.index.add('sources') + with open(os.path.join(gitrepo, "sources"), "w") as stream: + stream.write("foo\n bar\nbaz\n") + repo.index.add("sources") repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") repo.create_commit( - 'refs/heads/master', # the name of the reference to update + "refs/heads/master", # the name of the reference to update author, committer, - 'Add .gitignore file for testing', + "Add .gitignore file for testing", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [first_commit.oid.hex] + [first_commit.oid.hex], ) - refname = 'refs/heads/master:refs/heads/master' + refname = "refs/heads/master:refs/heads/master" ori_remote = repo.remotes[0] PagureRepo.push(ori_remote, refname) # Create a PR for these changes tests.create_projects(self.session) - project = pagure.lib.query.get_authorized_project(self.session, 'test') + project = pagure.lib.query.get_authorized_project(self.session, "test") req = pagure.lib.query.new_pull_request( session=self.session, repo_from=project, - branch_from='feature', + branch_from="feature", repo_to=project, - branch_to='master', - title='PR from the feature branch', - user='pingou', + branch_to="master", + title="PR from the feature branch", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'PR from the feature branch') + self.assertEqual(req.title, "PR from the feature branch") # Check if the PR can be merged data = {} # Missing CSRF - output = self.app.post('/pv/pull-request/merge', data=data) + output = self.app.post("/pv/pull-request/merge", data=data) self.assertEqual(output.status_code, 400) user = tests.FakeUser() - user.username = 'pingou' + user.username = "pingou" with tests.user_set(self.app.application, user): - output = self.app.get('/test/adduser') - csrf_token = output.get_data(as_text=True).split( - 'name="csrf_token" type="hidden" value="')[1].split('">')[0] + output = self.app.get("/test/adduser") + csrf_token = ( + output.get_data(as_text=True) + .split('name="csrf_token" type="hidden" value="')[1] + .split('">')[0] + ) # Missing request identifier - data = { - 'csrf_token': csrf_token, - } - output = self.app.post('/pv/pull-request/merge', data=data) + data = {"csrf_token": csrf_token} + output = self.app.post("/pv/pull-request/merge", data=data) self.assertEqual(output.status_code, 404) # With all the desired information - project = pagure.lib.query.get_authorized_project(self.session, 'test') + project = pagure.lib.query.get_authorized_project( + self.session, "test" + ) data = { - 'csrf_token': csrf_token, - 'requestid': project.requests[0].uid, + "csrf_token": csrf_token, + "requestid": project.requests[0].uid, } - output = self.app.post('/pv/pull-request/merge', data=data) + output = self.app.post("/pv/pull-request/merge", data=data) self.assertEqual(output.status_code, 200) exp = { - "code": "CONFLICTS", - "message": "The pull-request cannot be merged due to conflicts", - "short_code": "Conflicts" + "code": "CONFLICTS", + "message": "The pull-request cannot be merged due to conflicts", + "short_code": "Conflicts", } js_data = json.loads(output.get_data(as_text=True)) self.assertDictEqual(js_data, exp) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_mergeable_request_pull_merge_no_nonff_merges(self, send_email): """ Test the mergeable_request_pull endpoint when the changes can be merged with a merge commit, but project settings prohibit this. @@ -1029,136 +986,135 @@ class PagureFlaskInternaltests(tests.Modeltests): # Create a git repo to play with - origgitrepo = os.path.join(self.path, 'repos', 'test.git') + origgitrepo = os.path.join(self.path, "repos", "test.git") self.assertFalse(os.path.exists(origgitrepo)) os.makedirs(origgitrepo) orig_repo = pygit2.init_repository(origgitrepo, bare=True) - os.makedirs(os.path.join(self.path, 'repos_tmp')) - gitrepo = os.path.join(self.path, 'repos_tmp', 'test.git') + os.makedirs(os.path.join(self.path, "repos_tmp")) + gitrepo = os.path.join(self.path, "repos_tmp", "test.git") repo = pygit2.clone_repository(origgitrepo, gitrepo) # Create a file in that git repo - with open(os.path.join(gitrepo, 'sources'), 'w') as stream: - stream.write('foo\n bar') - repo.index.add('sources') + with open(os.path.join(gitrepo, "sources"), "w") as stream: + stream.write("foo\n bar") + repo.index.add("sources") repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") repo.create_commit( - 'refs/heads/master', # the name of the reference to update + "refs/heads/master", # the name of the reference to update author, committer, - 'Add sources file for testing', + "Add sources file for testing", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [] + [], ) - first_commit = repo.revparse_single('HEAD') - refname = 'refs/heads/master:refs/heads/master' + first_commit = repo.revparse_single("HEAD") + refname = "refs/heads/master:refs/heads/master" ori_remote = repo.remotes[0] PagureRepo.push(ori_remote, refname) # Edit the sources file again - with open(os.path.join(gitrepo, 'sources'), 'w') as stream: - stream.write('foo\n bar\nbaz\n boose') - repo.index.add('sources') + with open(os.path.join(gitrepo, "sources"), "w") as stream: + stream.write("foo\n bar\nbaz\n boose") + repo.index.add("sources") repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") repo.create_commit( - 'refs/heads/feature', # the name of the reference to update + "refs/heads/feature", # the name of the reference to update author, committer, - 'Add baz and boose to the sources\n\n There are more objects to ' - 'consider', + "Add baz and boose to the sources\n\n There are more objects to " + "consider", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [first_commit.oid.hex] + [first_commit.oid.hex], ) - refname = 'refs/heads/feature:refs/heads/feature' + refname = "refs/heads/feature:refs/heads/feature" ori_remote = repo.remotes[0] PagureRepo.push(ori_remote, refname) # Create another file in the master branch - with open(os.path.join(gitrepo, '.gitignore'), 'w') as stream: - stream.write('*~') - repo.index.add('.gitignore') + with open(os.path.join(gitrepo, ".gitignore"), "w") as stream: + stream.write("*~") + repo.index.add(".gitignore") repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") repo.create_commit( - 'refs/heads/master', # the name of the reference to update + "refs/heads/master", # the name of the reference to update author, committer, - 'Add .gitignore file for testing', + "Add .gitignore file for testing", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [first_commit.oid.hex] + [first_commit.oid.hex], ) - refname = 'refs/heads/master:refs/heads/master' + refname = "refs/heads/master:refs/heads/master" ori_remote = repo.remotes[0] PagureRepo.push(ori_remote, refname) # Create a PR for these changes tests.create_projects(self.session) - project = pagure.lib.query.get_authorized_project(self.session, 'test') + project = pagure.lib.query.get_authorized_project(self.session, "test") req = pagure.lib.query.new_pull_request( session=self.session, repo_from=project, - branch_from='feature', + branch_from="feature", repo_to=project, - branch_to='master', - title='PR from the feature branch', - user='pingou', + branch_to="master", + title="PR from the feature branch", + user="pingou", ) - settings = {'disable_non_fast-forward_merges': True} + settings = {"disable_non_fast-forward_merges": True} project.settings = settings self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'PR from the feature branch') + self.assertEqual(req.title, "PR from the feature branch") # Check if the PR can be merged data = {} user = tests.FakeUser() - user.username = 'pingou' + user.username = "pingou" with tests.user_set(self.app.application, user): - output = self.app.get('/test/adduser') - csrf_token = output.get_data(as_text=True).split( - 'name="csrf_token" type="hidden" value="')[1].split('">')[0] + output = self.app.get("/test/adduser") + csrf_token = ( + output.get_data(as_text=True) + .split('name="csrf_token" type="hidden" value="')[1] + .split('">')[0] + ) # With all the desired information - project = pagure.lib.query.get_authorized_project(self.session, 'test') + project = pagure.lib.query.get_authorized_project( + self.session, "test" + ) data = { - 'csrf_token': csrf_token, - 'requestid': project.requests[0].uid, - 'force': True, + "csrf_token": csrf_token, + "requestid": project.requests[0].uid, + "force": True, } - output = self.app.post('/pv/pull-request/merge', data=data) + output = self.app.post("/pv/pull-request/merge", data=data) self.assertEqual(output.status_code, 200) exp = { - "code": "NEEDSREBASE", - "message": "The pull-request must be rebased before merging", - "short_code": "Needs rebase" + "code": "NEEDSREBASE", + "message": "The pull-request must be rebased before merging", + "short_code": "Needs rebase", } js_data = json.loads(output.get_data(as_text=True)) @@ -1166,21 +1122,21 @@ class PagureFlaskInternaltests(tests.Modeltests): # Asking a second time will trigger the cache data = { - 'csrf_token': csrf_token, - 'requestid': project.requests[0].uid, + "csrf_token": csrf_token, + "requestid": project.requests[0].uid, } - output = self.app.post('/pv/pull-request/merge', data=data) + output = self.app.post("/pv/pull-request/merge", data=data) self.assertEqual(output.status_code, 200) exp = { - "code": "NEEDSREBASE", - "message": "The pull-request must be rebased before merging", - "short_code": "Needs rebase" + "code": "NEEDSREBASE", + "message": "The pull-request must be rebased before merging", + "short_code": "Needs rebase", } js_data = json.loads(output.get_data(as_text=True)) self.assertDictEqual(js_data, exp) - @patch('pagure.lib.notify.send_email') + @patch("pagure.lib.notify.send_email") def test_mergeable_request_pull_minimum_score(self, send_email): """ Test the mergeable_request_pull endpoint when the changes can be merged with a merge FF, but project settings enforces vote on @@ -1190,1703 +1146,1606 @@ class PagureFlaskInternaltests(tests.Modeltests): # Create a git repo to play with - origgitrepo = os.path.join(self.path, 'repos', 'test.git') + origgitrepo = os.path.join(self.path, "repos", "test.git") self.assertFalse(os.path.exists(origgitrepo)) os.makedirs(origgitrepo) orig_repo = pygit2.init_repository(origgitrepo, bare=True) - os.makedirs(os.path.join(self.path, 'repos_tmp')) - gitrepo = os.path.join(self.path, 'repos_tmp', 'test.git') + os.makedirs(os.path.join(self.path, "repos_tmp")) + gitrepo = os.path.join(self.path, "repos_tmp", "test.git") repo = pygit2.clone_repository(origgitrepo, gitrepo) # Create a file in that git repo - with open(os.path.join(gitrepo, 'sources'), 'w') as stream: - stream.write('foo\n bar') - repo.index.add('sources') + with open(os.path.join(gitrepo, "sources"), "w") as stream: + stream.write("foo\n bar") + repo.index.add("sources") repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") repo.create_commit( - 'refs/heads/master', # the name of the reference to update + "refs/heads/master", # the name of the reference to update author, committer, - 'Add sources file for testing', + "Add sources file for testing", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [] + [], ) - first_commit = repo.revparse_single('HEAD') - refname = 'refs/heads/master:refs/heads/master' + first_commit = repo.revparse_single("HEAD") + refname = "refs/heads/master:refs/heads/master" ori_remote = repo.remotes[0] PagureRepo.push(ori_remote, refname) # Edit the sources file again - with open(os.path.join(gitrepo, 'sources'), 'w') as stream: - stream.write('foo\n bar\nbaz\n boose') - repo.index.add('sources') + with open(os.path.join(gitrepo, "sources"), "w") as stream: + stream.write("foo\n bar\nbaz\n boose") + repo.index.add("sources") repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") repo.create_commit( - 'refs/heads/feature', # the name of the reference to update + "refs/heads/feature", # the name of the reference to update author, committer, - 'Add baz and boose to the sources\n\n There are more objects to ' - 'consider', + "Add baz and boose to the sources\n\n There are more objects to " + "consider", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [first_commit.oid.hex] + [first_commit.oid.hex], ) - refname = 'refs/heads/feature:refs/heads/feature' + refname = "refs/heads/feature:refs/heads/feature" ori_remote = repo.remotes[0] PagureRepo.push(ori_remote, refname) # Create a PR for these changes tests.create_projects(self.session) - project = pagure.lib.query.get_authorized_project(self.session, 'test') + project = pagure.lib.query.get_authorized_project(self.session, "test") req = pagure.lib.query.new_pull_request( session=self.session, repo_from=project, - branch_from='feature', + branch_from="feature", repo_to=project, - branch_to='master', - title='PR from the feature branch', - user='pingou', + branch_to="master", + title="PR from the feature branch", + user="pingou", ) - settings = {'Minimum_score_to_merge_pull-request': 2} + settings = {"Minimum_score_to_merge_pull-request": 2} project.settings = settings self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'PR from the feature branch') + self.assertEqual(req.title, "PR from the feature branch") # Check if the PR can be merged data = {} user = tests.FakeUser() - user.username = 'pingou' + user.username = "pingou" with tests.user_set(self.app.application, user): - output = self.app.get('/test/adduser') - csrf_token = output.get_data(as_text=True).split( - 'name="csrf_token" type="hidden" value="')[1].split('">')[0] + output = self.app.get("/test/adduser") + csrf_token = ( + output.get_data(as_text=True) + .split('name="csrf_token" type="hidden" value="')[1] + .split('">')[0] + ) # With all the desired information - project = pagure.lib.query.get_authorized_project(self.session, 'test') + project = pagure.lib.query.get_authorized_project( + self.session, "test" + ) data = { - 'csrf_token': csrf_token, - 'requestid': project.requests[0].uid, - 'force': True, + "csrf_token": csrf_token, + "requestid": project.requests[0].uid, + "force": True, } - output = self.app.post('/pv/pull-request/merge', data=data) + output = self.app.post("/pv/pull-request/merge", data=data) self.assertEqual(output.status_code, 400) exp = { - "code": "CONFLICTS", - "message": "Pull-Request does not meet the minimal number " - "of review required: 0/2" + "code": "CONFLICTS", + "message": "Pull-Request does not meet the minimal number " + "of review required: 0/2", } js_data = json.loads(output.get_data(as_text=True)) self.assertDictEqual(js_data, exp) # Verify we get a valid merge_status (not 'unknown') - pub_api_call = self.app.get('/api/0/test/pull-request/1') + pub_api_call = self.app.get("/api/0/test/pull-request/1") data = json.loads(pub_api_call.get_data(as_text=True)) - self.assertIn( - data['cached_merge_status'], ('MERGE', 'FFORWARD')) + self.assertIn(data["cached_merge_status"], ("MERGE", "FFORWARD")) # Asking a second time will trigger the cache data = { - 'csrf_token': csrf_token, - 'requestid': project.requests[0].uid, + "csrf_token": csrf_token, + "requestid": project.requests[0].uid, } - output = self.app.post('/pv/pull-request/merge', data=data) + output = self.app.post("/pv/pull-request/merge", data=data) self.assertEqual(output.status_code, 400) exp = { - "code": "CONFLICTS", - "message": "Pull-Request does not meet the minimal number " - "of review required: 0/2" + "code": "CONFLICTS", + "message": "Pull-Request does not meet the minimal number " + "of review required: 0/2", } js_data = json.loads(output.get_data(as_text=True)) self.assertDictEqual(js_data, exp) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) @patch( - 'pagure.lib.git.merge_pull_request', - MagicMock(side_effect=pagure.exceptions.PagureException('error'))) + "pagure.lib.git.merge_pull_request", + MagicMock(side_effect=pagure.exceptions.PagureException("error")), + ) def test_mergeable_request_pull_merge_pagureerror(self): """ Test the mergeable_request_pull endpoint when the backend raises an GitError exception. """ # Create a git repo to play with - origgitrepo = os.path.join(self.path, 'repos', 'test.git') + origgitrepo = os.path.join(self.path, "repos", "test.git") self.assertFalse(os.path.exists(origgitrepo)) os.makedirs(origgitrepo) orig_repo = pygit2.init_repository(origgitrepo, bare=True) - os.makedirs(os.path.join(self.path, 'repos_tmp')) - gitrepo = os.path.join(self.path, 'repos_tmp', 'test.git') + os.makedirs(os.path.join(self.path, "repos_tmp")) + gitrepo = os.path.join(self.path, "repos_tmp", "test.git") repo = pygit2.clone_repository(origgitrepo, gitrepo) # Create a file in that git repo - with open(os.path.join(gitrepo, 'sources'), 'w') as stream: - stream.write('foo\n bar') - repo.index.add('sources') + with open(os.path.join(gitrepo, "sources"), "w") as stream: + stream.write("foo\n bar") + repo.index.add("sources") repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") repo.create_commit( - 'refs/heads/master', # the name of the reference to update + "refs/heads/master", # the name of the reference to update author, committer, - 'Add sources file for testing', + "Add sources file for testing", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [] + [], ) - first_commit = repo.revparse_single('HEAD') - refname = 'refs/heads/master:refs/heads/master' + first_commit = repo.revparse_single("HEAD") + refname = "refs/heads/master:refs/heads/master" ori_remote = repo.remotes[0] PagureRepo.push(ori_remote, refname) # Edit the sources file again - with open(os.path.join(gitrepo, 'sources'), 'w') as stream: - stream.write('foo\n bar\nbaz\n boose') - repo.index.add('sources') + with open(os.path.join(gitrepo, "sources"), "w") as stream: + stream.write("foo\n bar\nbaz\n boose") + repo.index.add("sources") repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") repo.create_commit( - 'refs/heads/feature', # the name of the reference to update + "refs/heads/feature", # the name of the reference to update author, committer, - 'Add baz and boose to the sources\n\n There are more objects to ' - 'consider', + "Add baz and boose to the sources\n\n There are more objects to " + "consider", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [first_commit.oid.hex] + [first_commit.oid.hex], ) - refname = 'refs/heads/feature:refs/heads/feature' + refname = "refs/heads/feature:refs/heads/feature" ori_remote = repo.remotes[0] PagureRepo.push(ori_remote, refname) # Create another file in the master branch - with open(os.path.join(gitrepo, '.gitignore'), 'w') as stream: - stream.write('*~') - repo.index.add('.gitignore') + with open(os.path.join(gitrepo, ".gitignore"), "w") as stream: + stream.write("*~") + repo.index.add(".gitignore") repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") repo.create_commit( - 'refs/heads/master', # the name of the reference to update + "refs/heads/master", # the name of the reference to update author, committer, - 'Add .gitignore file for testing', + "Add .gitignore file for testing", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [first_commit.oid.hex] + [first_commit.oid.hex], ) - refname = 'refs/heads/master:refs/heads/master' + refname = "refs/heads/master:refs/heads/master" ori_remote = repo.remotes[0] PagureRepo.push(ori_remote, refname) # Create a PR for these changes tests.create_projects(self.session) - project = pagure.lib.query.get_authorized_project(self.session, 'test') + project = pagure.lib.query.get_authorized_project(self.session, "test") req = pagure.lib.query.new_pull_request( session=self.session, repo_from=project, - branch_from='feature', + branch_from="feature", repo_to=project, - branch_to='master', - title='PR from the feature branch', - user='pingou', + branch_to="master", + title="PR from the feature branch", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'PR from the feature branch') + self.assertEqual(req.title, "PR from the feature branch") # Check if the PR can be merged data = {} user = tests.FakeUser() - user.username = 'pingou' + user.username = "pingou" with tests.user_set(self.app.application, user): - output = self.app.get('/test/adduser') + output = self.app.get("/test/adduser") csrf_token = self.get_csrf(output=output) # With all the desired information - project = pagure.lib.query.get_authorized_project(self.session, 'test') + project = pagure.lib.query.get_authorized_project( + self.session, "test" + ) data = { - 'csrf_token': csrf_token, - 'requestid': project.requests[0].uid, - 'force': True, + "csrf_token": csrf_token, + "requestid": project.requests[0].uid, + "force": True, } - output = self.app.post('/pv/pull-request/merge', data=data) + output = self.app.post("/pv/pull-request/merge", data=data) self.assertEqual(output.status_code, 500) - exp = {u'code': u'CONFLICTS', u'message': u'error'} + exp = {"code": "CONFLICTS", "message": "error"} js_data = json.loads(output.get_data(as_text=True)) self.assertDictEqual(js_data, exp) - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) @patch( - 'pagure.lib.git.merge_pull_request', - MagicMock(side_effect=pygit2.GitError('git error'))) + "pagure.lib.git.merge_pull_request", + MagicMock(side_effect=pygit2.GitError("git error")), + ) def test_mergeable_request_pull_merge_giterror(self): """ Test the mergeable_request_pull endpoint when the backend raises an GitError exception. """ # Create a git repo to play with - origgitrepo = os.path.join(self.path, 'repos', 'test.git') + origgitrepo = os.path.join(self.path, "repos", "test.git") self.assertFalse(os.path.exists(origgitrepo)) os.makedirs(origgitrepo) orig_repo = pygit2.init_repository(origgitrepo, bare=True) - os.makedirs(os.path.join(self.path, 'repos_tmp')) - gitrepo = os.path.join(self.path, 'repos_tmp', 'test.git') + os.makedirs(os.path.join(self.path, "repos_tmp")) + gitrepo = os.path.join(self.path, "repos_tmp", "test.git") repo = pygit2.clone_repository(origgitrepo, gitrepo) # Create a file in that git repo - with open(os.path.join(gitrepo, 'sources'), 'w') as stream: - stream.write('foo\n bar') - repo.index.add('sources') + with open(os.path.join(gitrepo, "sources"), "w") as stream: + stream.write("foo\n bar") + repo.index.add("sources") repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") repo.create_commit( - 'refs/heads/master', # the name of the reference to update + "refs/heads/master", # the name of the reference to update author, committer, - 'Add sources file for testing', + "Add sources file for testing", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [] + [], ) - first_commit = repo.revparse_single('HEAD') - refname = 'refs/heads/master:refs/heads/master' + first_commit = repo.revparse_single("HEAD") + refname = "refs/heads/master:refs/heads/master" ori_remote = repo.remotes[0] PagureRepo.push(ori_remote, refname) # Edit the sources file again - with open(os.path.join(gitrepo, 'sources'), 'w') as stream: - stream.write('foo\n bar\nbaz\n boose') - repo.index.add('sources') + with open(os.path.join(gitrepo, "sources"), "w") as stream: + stream.write("foo\n bar\nbaz\n boose") + repo.index.add("sources") repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") repo.create_commit( - 'refs/heads/feature', # the name of the reference to update + "refs/heads/feature", # the name of the reference to update author, committer, - 'Add baz and boose to the sources\n\n There are more objects to ' - 'consider', + "Add baz and boose to the sources\n\n There are more objects to " + "consider", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [first_commit.oid.hex] + [first_commit.oid.hex], ) - refname = 'refs/heads/feature:refs/heads/feature' + refname = "refs/heads/feature:refs/heads/feature" ori_remote = repo.remotes[0] PagureRepo.push(ori_remote, refname) # Create another file in the master branch - with open(os.path.join(gitrepo, '.gitignore'), 'w') as stream: - stream.write('*~') - repo.index.add('.gitignore') + with open(os.path.join(gitrepo, ".gitignore"), "w") as stream: + stream.write("*~") + repo.index.add(".gitignore") repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") repo.create_commit( - 'refs/heads/master', # the name of the reference to update + "refs/heads/master", # the name of the reference to update author, committer, - 'Add .gitignore file for testing', + "Add .gitignore file for testing", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [first_commit.oid.hex] + [first_commit.oid.hex], ) - refname = 'refs/heads/master:refs/heads/master' + refname = "refs/heads/master:refs/heads/master" ori_remote = repo.remotes[0] PagureRepo.push(ori_remote, refname) # Create a PR for these changes tests.create_projects(self.session) - project = pagure.lib.query.get_authorized_project(self.session, 'test') + project = pagure.lib.query.get_authorized_project(self.session, "test") req = pagure.lib.query.new_pull_request( session=self.session, repo_from=project, - branch_from='feature', + branch_from="feature", repo_to=project, - branch_to='master', - title='PR from the feature branch', - user='pingou', + branch_to="master", + title="PR from the feature branch", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'PR from the feature branch') + self.assertEqual(req.title, "PR from the feature branch") # Check if the PR can be merged data = {} user = tests.FakeUser() - user.username = 'pingou' + user.username = "pingou" with tests.user_set(self.app.application, user): - output = self.app.get('/test/adduser') + output = self.app.get("/test/adduser") csrf_token = self.get_csrf(output=output) # With all the desired information - project = pagure.lib.query.get_authorized_project(self.session, 'test') + project = pagure.lib.query.get_authorized_project( + self.session, "test" + ) data = { - 'csrf_token': csrf_token, - 'requestid': project.requests[0].uid, - 'force': True, + "csrf_token": csrf_token, + "requestid": project.requests[0].uid, + "force": True, } - output = self.app.post('/pv/pull-request/merge', data=data) + output = self.app.post("/pv/pull-request/merge", data=data) self.assertEqual(output.status_code, 409) - exp = {u'code': u'CONFLICTS', u'message': u'git error'} + exp = {"code": "CONFLICTS", "message": "git error"} js_data = json.loads(output.get_data(as_text=True)) self.assertDictEqual(js_data, exp) def test_get_branches_of_commit(self): - ''' Test the get_branches_of_commit from the internal API. ''' + """ Test the get_branches_of_commit from the internal API. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'repos')) + tests.create_projects_git(os.path.join(self.path, "repos")) user = tests.FakeUser() - user.username = 'pingou' + user.username = "pingou" with tests.user_set(self.app.application, user): - output = self.app.get('/test/adduser') + output = self.app.get("/test/adduser") self.assertEqual(output.status_code, 200) - csrf_token = output.get_data(as_text=True).split( - 'name="csrf_token" type="hidden" value="')[1].split('">')[0] + csrf_token = ( + output.get_data(as_text=True) + .split('name="csrf_token" type="hidden" value="')[1] + .split('">')[0] + ) # No CSRF token - data = { - 'repo': 'fakerepo', - 'commit_id': 'foo', - } - output = self.app.post('/pv/branches/commit/', data=data) + data = {"repo": "fakerepo", "commit_id": "foo"} + output = self.app.post("/pv/branches/commit/", data=data) self.assertEqual(output.status_code, 400) js_data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - js_data, - {'code': 'ERROR', 'message': 'Invalid input submitted'} + js_data, {"code": "ERROR", "message": "Invalid input submitted"} ) # Invalid repo data = { - 'repo': 'fakerepo', - 'commit_id': 'foo', - 'csrf_token': csrf_token, + "repo": "fakerepo", + "commit_id": "foo", + "csrf_token": csrf_token, } - output = self.app.post('/pv/branches/commit/', data=data) + output = self.app.post("/pv/branches/commit/", data=data) self.assertEqual(output.status_code, 404) js_data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( js_data, { - 'code': 'ERROR', - 'message': 'No repo found with the information provided' - } + "code": "ERROR", + "message": "No repo found with the information provided", + }, ) # Rigth repo, no commit - data = { - 'repo': 'test', - 'csrf_token': csrf_token, - } + data = {"repo": "test", "csrf_token": csrf_token} - output = self.app.post('/pv/branches/commit/', data=data) + output = self.app.post("/pv/branches/commit/", data=data) self.assertEqual(output.status_code, 400) js_data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - js_data, - {'code': 'ERROR', 'message': 'No commit id submitted'} + js_data, {"code": "ERROR", "message": "No commit id submitted"} ) # Request is fine, but git repo doesn't exist item = pagure.lib.model.Project( user_id=1, # pingou - name='test20', - description='test project #20', - hook_token='aaabbbhhh', + name="test20", + description="test project #20", + hook_token="aaabbbhhh", ) self.session.add(item) self.session.commit() - data = { - 'repo': 'test20', - 'commit_id': 'foo', - 'csrf_token': csrf_token, - } - output = self.app.post('/pv/branches/commit/', data=data) + data = {"repo": "test20", "commit_id": "foo", "csrf_token": csrf_token} + output = self.app.post("/pv/branches/commit/", data=data) self.assertEqual(output.status_code, 404) js_data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( js_data, { - 'code': 'ERROR', - 'message': 'No git repo found with the information provided' - } + "code": "ERROR", + "message": "No git repo found with the information provided", + }, ) # Create a git repo to play with - gitrepo = os.path.join(self.path, 'repos', 'test.git') + gitrepo = os.path.join(self.path, "repos", "test.git") self.assertTrue(os.path.exists(gitrepo)) repo = pygit2.Repository(gitrepo) # Create a file in that git repo - with open(os.path.join(gitrepo, 'sources'), 'w') as stream: - stream.write('foo\n bar') - repo.index.add('sources') + with open(os.path.join(gitrepo, "sources"), "w") as stream: + stream.write("foo\n bar") + repo.index.add("sources") repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") repo.create_commit( - 'refs/heads/master', # the name of the reference to update + "refs/heads/master", # the name of the reference to update author, committer, - 'Add sources file for testing', + "Add sources file for testing", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [] + [], ) - first_commit = repo.revparse_single('HEAD') + first_commit = repo.revparse_single("HEAD") # Edit the sources file again - with open(os.path.join(gitrepo, 'sources'), 'w') as stream: - stream.write('foo\n bar\nbaz\n boose') - repo.index.add('sources') + with open(os.path.join(gitrepo, "sources"), "w") as stream: + stream.write("foo\n bar\nbaz\n boose") + repo.index.add("sources") repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") repo.create_commit( - 'refs/heads/feature', # the name of the reference to update + "refs/heads/feature", # the name of the reference to update author, committer, - 'Add baz and boose to the sources\n\n There are more objects to ' - 'consider', + "Add baz and boose to the sources\n\n There are more objects to " + "consider", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [first_commit.oid.hex] + [first_commit.oid.hex], ) # Create another file in the master branch - with open(os.path.join(gitrepo, '.gitignore'), 'w') as stream: - stream.write('*~') - repo.index.add('.gitignore') + with open(os.path.join(gitrepo, ".gitignore"), "w") as stream: + stream.write("*~") + repo.index.add(".gitignore") repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") commit_hash = repo.create_commit( - 'refs/heads/feature_branch', # the name of the reference to update + "refs/heads/feature_branch", # the name of the reference to update author, committer, - 'Add .gitignore file for testing', + "Add .gitignore file for testing", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [first_commit.oid.hex] + [first_commit.oid.hex], ) # All good but the commit id - data = { - 'repo': 'test', - 'commit_id': 'foo', - 'csrf_token': csrf_token, - } - output = self.app.post('/pv/branches/commit/', data=data) + data = {"repo": "test", "commit_id": "foo", "csrf_token": csrf_token} + output = self.app.post("/pv/branches/commit/", data=data) self.assertEqual(output.status_code, 404) js_data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( js_data, { - 'code': 'ERROR', - 'message': 'This commit could not be found in this repo' - } + "code": "ERROR", + "message": "This commit could not be found in this repo", + }, ) # All good data = { - 'repo': 'test', - 'commit_id': commit_hash, - 'csrf_token': csrf_token, + "repo": "test", + "commit_id": commit_hash, + "csrf_token": csrf_token, } - output = self.app.post('/pv/branches/commit/', data=data) + output = self.app.post("/pv/branches/commit/", data=data) self.assertEqual(output.status_code, 200) js_data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - js_data, - { - 'code': 'OK', - 'branches': ['feature_branch'], - } + js_data, {"code": "OK", "branches": ["feature_branch"]} ) def test_get_branches_of_commit_with_unrelated_branches(self): - ''' Test the get_branches_of_commit from the internal API. ''' + """ Test the get_branches_of_commit from the internal API. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'repos')) + tests.create_projects_git(os.path.join(self.path, "repos")) - user = tests.FakeUser(username='pingou') + user = tests.FakeUser(username="pingou") with tests.user_set(self.app.application, user): csrf_token = self.get_csrf() # Create a git repo to play with - gitrepo = os.path.join(self.path, 'repos', 'test.git') + gitrepo = os.path.join(self.path, "repos", "test.git") self.assertTrue(os.path.exists(gitrepo)) repo = pygit2.Repository(gitrepo) # Create a file in that git repo - with open(os.path.join(gitrepo, 'sources'), 'w') as stream: - stream.write('foo\n bar') - repo.index.add('sources') + with open(os.path.join(gitrepo, "sources"), "w") as stream: + stream.write("foo\n bar") + repo.index.add("sources") repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") repo.create_commit( - 'refs/heads/master', # the name of the reference to update + "refs/heads/master", # the name of the reference to update author, committer, - 'Add sources file for testing', + "Add sources file for testing", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [] + [], ) - first_commit = repo.revparse_single('HEAD') + first_commit = repo.revparse_single("HEAD") # Edit the sources file again - with open(os.path.join(gitrepo, 'sources'), 'w') as stream: - stream.write('foo\n bar\nbaz\n boose') - repo.index.add('sources') + with open(os.path.join(gitrepo, "sources"), "w") as stream: + stream.write("foo\n bar\nbaz\n boose") + repo.index.add("sources") repo.index.write() # Commits the files added, but unrelated with the first commit tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") commit = repo.create_commit( - 'refs/heads/feature', # the name of the reference to update + "refs/heads/feature", # the name of the reference to update author, committer, - 'Add baz and boose to the sources\n\n There are more objects to ' - 'consider', + "Add baz and boose to the sources\n\n There are more objects to " + "consider", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [] + [], ) commit_hash = commit.hex # All good data = { - 'repo': 'test', - 'commit_id': commit_hash, - 'csrf_token': csrf_token, + "repo": "test", + "commit_id": commit_hash, + "csrf_token": csrf_token, } - output = self.app.post('/pv/branches/commit/', data=data) + output = self.app.post("/pv/branches/commit/", data=data) self.assertEqual(output.status_code, 200) js_data = json.loads(output.get_data(as_text=True)) - self.assertDictEqual( - js_data, - { - u'code': u'OK', - u'branches': ['feature'], - } - ) + self.assertDictEqual(js_data, {"code": "OK", "branches": ["feature"]}) def test_get_branches_head(self): - ''' Test the get_branches_head from the internal API. ''' + """ Test the get_branches_head from the internal API. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'repos')) + tests.create_projects_git(os.path.join(self.path, "repos")) user = tests.FakeUser() - user.username = 'pingou' + user.username = "pingou" with tests.user_set(self.app.application, user): csrf_token = self.get_csrf() # No CSRF token - data = { - 'repo': 'fakerepo', - } - output = self.app.post('/pv/branches/heads/', data=data) + data = {"repo": "fakerepo"} + output = self.app.post("/pv/branches/heads/", data=data) self.assertEqual(output.status_code, 400) js_data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - js_data, - {'code': 'ERROR', 'message': 'Invalid input submitted'} + js_data, {"code": "ERROR", "message": "Invalid input submitted"} ) # Invalid repo data = { - 'repo': 'fakerepo', - 'commit_id': 'foo', - 'csrf_token': csrf_token, + "repo": "fakerepo", + "commit_id": "foo", + "csrf_token": csrf_token, } - output = self.app.post('/pv/branches/heads/', data=data) + output = self.app.post("/pv/branches/heads/", data=data) self.assertEqual(output.status_code, 404) js_data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( js_data, { - 'code': 'ERROR', - 'message': 'No repo found with the information provided' - } + "code": "ERROR", + "message": "No repo found with the information provided", + }, ) # Rigth repo, no commit - data = { - 'repo': 'test', - 'csrf_token': csrf_token, - } + data = {"repo": "test", "csrf_token": csrf_token} - output = self.app.post('/pv/branches/heads/', data=data) + output = self.app.post("/pv/branches/heads/", data=data) self.assertEqual(output.status_code, 200) js_data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - js_data, - {"branches": {}, "code": "OK", "heads": {}} + js_data, {"branches": {}, "code": "OK", "heads": {}} ) # Request is fine, but git repo doesn't exist item = pagure.lib.model.Project( user_id=1, # pingou - name='test20', - description='test project #20', - hook_token='aaabbbhhh', + name="test20", + description="test project #20", + hook_token="aaabbbhhh", ) self.session.add(item) self.session.commit() - data = { - 'repo': 'test20', - 'csrf_token': csrf_token, - } - output = self.app.post('/pv/branches/heads/', data=data) + data = {"repo": "test20", "csrf_token": csrf_token} + output = self.app.post("/pv/branches/heads/", data=data) self.assertEqual(output.status_code, 404) js_data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( js_data, { - 'code': 'ERROR', - 'message': 'No git repo found with the information provided' - } + "code": "ERROR", + "message": "No git repo found with the information provided", + }, ) # Create a git repo to play with - gitrepo = os.path.join(self.path, 'repos', 'test.git') + gitrepo = os.path.join(self.path, "repos", "test.git") self.assertTrue(os.path.exists(gitrepo)) repo = pygit2.Repository(gitrepo) # Create a file in that git repo - with open(os.path.join(gitrepo, 'sources'), 'w') as stream: - stream.write('foo\n bar') - repo.index.add('sources') + with open(os.path.join(gitrepo, "sources"), "w") as stream: + stream.write("foo\n bar") + repo.index.add("sources") repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") repo.create_commit( - 'refs/heads/master', # the name of the reference to update + "refs/heads/master", # the name of the reference to update author, committer, - 'Add sources file for testing', + "Add sources file for testing", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [] + [], ) - first_commit = repo.revparse_single('HEAD') + first_commit = repo.revparse_single("HEAD") # Edit the sources file again - with open(os.path.join(gitrepo, 'sources'), 'w') as stream: - stream.write('foo\n bar\nbaz\n boose') - repo.index.add('sources') + with open(os.path.join(gitrepo, "sources"), "w") as stream: + stream.write("foo\n bar\nbaz\n boose") + repo.index.add("sources") repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") repo.create_commit( - 'refs/heads/feature', # the name of the reference to update + "refs/heads/feature", # the name of the reference to update author, committer, - 'Add baz and boose to the sources\n\n There are more objects to ' - 'consider', + "Add baz and boose to the sources\n\n There are more objects to " + "consider", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [first_commit.oid.hex] + [first_commit.oid.hex], ) # Create another file in the master branch - with open(os.path.join(gitrepo, '.gitignore'), 'w') as stream: - stream.write('*~') - repo.index.add('.gitignore') + with open(os.path.join(gitrepo, ".gitignore"), "w") as stream: + stream.write("*~") + repo.index.add(".gitignore") repo.index.write() # Commits the files added tree = repo.index.write_tree() - author = pygit2.Signature( - 'Alice Author', 'alice@authors.tld') - committer = pygit2.Signature( - 'Cecil Committer', 'cecil@committers.tld') + author = pygit2.Signature("Alice Author", "alice@authors.tld") + committer = pygit2.Signature("Cecil Committer", "cecil@committers.tld") commit_hash = repo.create_commit( - 'refs/heads/feature_branch', # the name of the reference to update + "refs/heads/feature_branch", # the name of the reference to update author, committer, - 'Add .gitignore file for testing', + "Add .gitignore file for testing", # binary string representing the tree object ID tree, # list of binary strings representing parents of the new commit - [first_commit.oid.hex] + [first_commit.oid.hex], ) # All good - data = { - 'repo': 'test', - 'csrf_token': csrf_token, - } - output = self.app.post('/pv/branches/heads/', data=data) + data = {"repo": "test", "csrf_token": csrf_token} + output = self.app.post("/pv/branches/heads/", data=data) self.assertEqual(output.status_code, 200) js_data = json.loads(output.get_data(as_text=True)) # We can't test the content since the commit hash will change all # the time, so let's just check the structure - self.assertEqual( - sorted(js_data.keys()), ['branches', 'code', 'heads']) - self.assertEqual(js_data['code'], 'OK') - self.assertEqual(len(js_data['heads']), 3) - self.assertEqual(len(js_data['branches']), 3) + self.assertEqual(sorted(js_data.keys()), ["branches", "code", "heads"]) + self.assertEqual(js_data["code"], "OK") + self.assertEqual(len(js_data["heads"]), 3) + self.assertEqual(len(js_data["branches"]), 3) def test_get_stats_commits_no_token(self): - ''' Test the get_stats_commits from the internal API. ''' + """ Test the get_stats_commits from the internal API. """ # No CSRF token - data = { - 'repo': 'fakerepo', - } - output = self.app.post('/pv/stats/commits/authors', data=data) + data = {"repo": "fakerepo"} + output = self.app.post("/pv/stats/commits/authors", data=data) self.assertEqual(output.status_code, 400) js_data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - js_data, - {'code': 'ERROR', 'message': 'Invalid input submitted'} + js_data, {"code": "ERROR", "message": "Invalid input submitted"} ) def test_get_stats_commits_invalid_repo(self): - ''' Test the get_stats_commits from the internal API. ''' + """ Test the get_stats_commits from the internal API. """ user = tests.FakeUser() - user.username = 'pingou' + user.username = "pingou" with tests.user_set(self.app.application, user): csrf_token = self.get_csrf() # Invalid repo - data = { - 'repo': 'fakerepo', - 'csrf_token': csrf_token, - } - output = self.app.post('/pv/stats/commits/authors', data=data) + data = {"repo": "fakerepo", "csrf_token": csrf_token} + output = self.app.post("/pv/stats/commits/authors", data=data) self.assertEqual(output.status_code, 404) js_data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( js_data, - {'code': 'ERROR', - 'message': 'No repo found with the information provided'} + { + "code": "ERROR", + "message": "No repo found with the information provided", + }, ) def test_get_stats_commits_empty_git(self): - ''' Test the get_stats_commits from the internal API. ''' + """ Test the get_stats_commits from the internal API. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'repos')) + tests.create_projects_git(os.path.join(self.path, "repos")) user = tests.FakeUser() - user.username = 'pingou' + user.username = "pingou" with tests.user_set(self.app.application, user): csrf_token = self.get_csrf() # No content in git - data = { - 'repo': 'test', - 'csrf_token': csrf_token, - } - output = self.app.post('/pv/stats/commits/authors', data=data) + data = {"repo": "test", "csrf_token": csrf_token} + output = self.app.post("/pv/stats/commits/authors", data=data) self.assertEqual(output.status_code, 200) js_data = json.loads(output.get_data(as_text=True)) self.assertEqual( - sorted(js_data.keys()), - ['code', 'message', 'task_id', 'url'] + sorted(js_data.keys()), ["code", "message", "task_id", "url"] ) - self.assertEqual(js_data['code'], 'OK') - self.assertEqual(js_data['message'], 'Stats asked') - self.assertTrue(js_data['url'].startswith('/pv/task/')) + self.assertEqual(js_data["code"], "OK") + self.assertEqual(js_data["message"], "Stats asked") + self.assertTrue(js_data["url"].startswith("/pv/task/")) - output = self.app.get(js_data['url']) + output = self.app.get(js_data["url"]) js_data2 = json.loads(output.get_data(as_text=True)) self.assertTrue( - js_data2 in [ - {'results': "reference 'refs/heads/master' not found"}, - {'results': "Reference 'refs/heads/master' not found"} + js_data2 + in [ + {"results": "reference 'refs/heads/master' not found"}, + {"results": "Reference 'refs/heads/master' not found"}, ] ) def test_get_stats_commits_git_populated(self): - ''' Test the get_stats_commits from the internal API. ''' + """ Test the get_stats_commits from the internal API. """ tests.create_projects(self.session) - tests.create_projects_git( - os.path.join(self.path, 'repos'), bare=True) + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) tests.add_content_git_repo( - os.path.join(self.path, 'repos', 'test.git')) + os.path.join(self.path, "repos", "test.git") + ) user = tests.FakeUser() - user.username = 'pingou' + user.username = "pingou" with tests.user_set(self.app.application, user): csrf_token = self.get_csrf() # Content in git - data = { - 'repo': 'test', - 'csrf_token': csrf_token, - } - output = self.app.post('/pv/stats/commits/authors', data=data) + data = {"repo": "test", "csrf_token": csrf_token} + output = self.app.post("/pv/stats/commits/authors", data=data) self.assertEqual(output.status_code, 200) js_data = json.loads(output.get_data(as_text=True)) self.assertEqual( - sorted(js_data.keys()), - ['code', 'message', 'task_id', 'url'] + sorted(js_data.keys()), ["code", "message", "task_id", "url"] ) - self.assertEqual(js_data['code'], 'OK') - self.assertEqual(js_data['message'], 'Stats asked') - self.assertTrue(js_data['url'].startswith('/pv/task/')) + self.assertEqual(js_data["code"], "OK") + self.assertEqual(js_data["message"], "Stats asked") + self.assertTrue(js_data["url"].startswith("/pv/task/")) - output = self.app.get(js_data['url']) + output = self.app.get(js_data["url"]) while output.status_code == 418: - output = self.app.get(js_data['url']) + output = self.app.get(js_data["url"]) js_data2 = json.loads(output.get_data(as_text=True)) - self.assertTrue(js_data2['results'][3] > 1509110062) - js_data2['results'][3] = 1509110062 + self.assertTrue(js_data2["results"][3] > 1509110062) + js_data2["results"][3] = 1509110062 self.assertTrue( - js_data2 in [ + js_data2 + in [ { - 'results': [ + "results": [ 2, - [[2, [[ - 'Alice Author', - 'alice@authors.tld', - 'https://seccdn.libravatar.org/avatar/' - '96c52c78570ffc4cfefcdadf5f8e77aeebcb11e07225df11bbf2fce381cdb8bd' - '?s=32&d=retro' - ]]]], + [ + [ + 2, + [ + [ + "Alice Author", + "alice@authors.tld", + "https://seccdn.libravatar.org/avatar/" + "96c52c78570ffc4cfefcdadf5f8e77aeebcb11e07225df11bbf2fce381cdb8bd" + "?s=32&d=retro", + ] + ], + ] + ], 1, - 1509110062 + 1509110062, ] }, { - 'results': [ + "results": [ 2, - [[2, [[ - 'Alice Author', - 'alice@authors.tld', - 'https://seccdn.libravatar.org/avatar/' - '96c52c78570ffc4cfefcdadf5f8e77aeebcb11e07225df11bbf2fce381cdb8bd' - '?d=retro&s=32' - ]]]], + [ + [ + 2, + [ + [ + "Alice Author", + "alice@authors.tld", + "https://seccdn.libravatar.org/avatar/" + "96c52c78570ffc4cfefcdadf5f8e77aeebcb11e07225df11bbf2fce381cdb8bd" + "?d=retro&s=32", + ] + ], + ] + ], 1, - 1509110062 + 1509110062, ] - } + }, ] ) def test_get_stats_commits_trend_no_token(self): - ''' Test the get_stats_commits_trend from the internal API. ''' + """ Test the get_stats_commits_trend from the internal API. """ # No CSRF token - data = { - 'repo': 'fakerepo', - } - output = self.app.post('/pv/stats/commits/trend', data=data) + data = {"repo": "fakerepo"} + output = self.app.post("/pv/stats/commits/trend", data=data) self.assertEqual(output.status_code, 400) js_data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( - js_data, - {'code': 'ERROR', 'message': 'Invalid input submitted'} + js_data, {"code": "ERROR", "message": "Invalid input submitted"} ) def test_get_stats_commits_trend_invalid_repo(self): """ Test the get_stats_commits_trend from the internal API. """ user = tests.FakeUser() - user.username = 'pingou' + user.username = "pingou" with tests.user_set(self.app.application, user): csrf_token = self.get_csrf() # Invalid repo - data = { - 'repo': 'fakerepo', - 'csrf_token': csrf_token, - } - output = self.app.post('/pv/stats/commits/trend', data=data) + data = {"repo": "fakerepo", "csrf_token": csrf_token} + output = self.app.post("/pv/stats/commits/trend", data=data) self.assertEqual(output.status_code, 404) js_data = json.loads(output.get_data(as_text=True)) self.assertDictEqual( js_data, - {'code': 'ERROR', - 'message': 'No repo found with the information provided'} + { + "code": "ERROR", + "message": "No repo found with the information provided", + }, ) def test_get_stats_commits_trend_empty_git(self): - ''' Test the get_stats_commits_trend from the internal API. ''' + """ Test the get_stats_commits_trend from the internal API. """ tests.create_projects(self.session) - tests.create_projects_git(os.path.join(self.path, 'repos')) + tests.create_projects_git(os.path.join(self.path, "repos")) user = tests.FakeUser() - user.username = 'pingou' + user.username = "pingou" with tests.user_set(self.app.application, user): csrf_token = self.get_csrf() # No content in git - data = { - 'repo': 'test', - 'csrf_token': csrf_token, - } - output = self.app.post('/pv/stats/commits/trend', data=data) + data = {"repo": "test", "csrf_token": csrf_token} + output = self.app.post("/pv/stats/commits/trend", data=data) self.assertEqual(output.status_code, 200) js_data = json.loads(output.get_data(as_text=True)) self.assertEqual( - sorted(js_data.keys()), - ['code', 'message', 'task_id', 'url'] + sorted(js_data.keys()), ["code", "message", "task_id", "url"] ) - self.assertEqual(js_data['code'], 'OK') - self.assertEqual(js_data['message'], 'Stats asked') - self.assertTrue(js_data['url'].startswith('/pv/task/')) + self.assertEqual(js_data["code"], "OK") + self.assertEqual(js_data["message"], "Stats asked") + self.assertTrue(js_data["url"].startswith("/pv/task/")) - output = self.app.get(js_data['url']) + output = self.app.get(js_data["url"]) js_data2 = json.loads(output.get_data(as_text=True)) self.assertTrue( - js_data2 in [ - {'results': "reference 'refs/heads/master' not found"}, - {'results': "Reference 'refs/heads/master' not found"} + js_data2 + in [ + {"results": "reference 'refs/heads/master' not found"}, + {"results": "Reference 'refs/heads/master' not found"}, ] ) def test_get_stats_commits_trend_git_populated(self): - ''' Test the get_stats_commits_trend from the internal API. ''' + """ Test the get_stats_commits_trend from the internal API. """ tests.create_projects(self.session) - tests.create_projects_git( - os.path.join(self.path, 'repos'), bare=True) + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) tests.add_content_git_repo( - os.path.join(self.path, 'repos', 'test.git')) + os.path.join(self.path, "repos", "test.git") + ) user = tests.FakeUser() - user.username = 'pingou' + user.username = "pingou" with tests.user_set(self.app.application, user): csrf_token = self.get_csrf() # Content in git - data = { - 'repo': 'test', - 'csrf_token': csrf_token, - } - output = self.app.post('/pv/stats/commits/trend', data=data) + data = {"repo": "test", "csrf_token": csrf_token} + output = self.app.post("/pv/stats/commits/trend", data=data) self.assertEqual(output.status_code, 200) js_data = json.loads(output.get_data(as_text=True)) self.assertEqual( - sorted(js_data.keys()), - ['code', 'message', 'task_id', 'url'] + sorted(js_data.keys()), ["code", "message", "task_id", "url"] ) - self.assertEqual(js_data['code'], 'OK') - self.assertEqual(js_data['message'], 'Stats asked') - self.assertTrue(js_data['url'].startswith('/pv/task/')) + self.assertEqual(js_data["code"], "OK") + self.assertEqual(js_data["message"], "Stats asked") + self.assertTrue(js_data["url"].startswith("/pv/task/")) - output = self.app.get(js_data['url']) + output = self.app.get(js_data["url"]) js_data2 = json.loads(output.get_data(as_text=True)) today = datetime.datetime.utcnow().date() - self.assertDictEqual( - js_data2, - {'results': [[str(today), 2]]} - ) + self.assertDictEqual(js_data2, {"results": [[str(today), 2]]}) def test_get_project_family_no_project(self): - ''' Test the get_project_family from the internal API. ''' - output = self.app.post('/pv/test/family') + """ Test the get_project_family from the internal API. """ + output = self.app.post("/pv/test/family") self.assertEqual(output.status_code, 404) def test_get_project_family_no_csrf(self): - ''' Test the get_project_family from the internal API. ''' + """ Test the get_project_family from the internal API. """ tests.create_projects(self.session) - tests.create_projects_git( - os.path.join(self.path, 'repos'), bare=True) + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) tests.add_content_git_repo( - os.path.join(self.path, 'repos', 'test.git')) + os.path.join(self.path, "repos", "test.git") + ) - output = self.app.post('/pv/test/family') + output = self.app.post("/pv/test/family") self.assertEqual(output.status_code, 400) js_data = json.loads(output.get_data(as_text=True)) - self.assertEqual( - sorted(js_data.keys()), - ['code', 'message'] - ) - self.assertEqual(js_data['code'], 'ERROR') - self.assertEqual(js_data['message'], 'Invalid input submitted') + self.assertEqual(sorted(js_data.keys()), ["code", "message"]) + self.assertEqual(js_data["code"], "ERROR") + self.assertEqual(js_data["message"], "Invalid input submitted") def test_get_project_family(self): - ''' Test the get_project_family from the internal API. ''' + """ Test the get_project_family from the internal API. """ tests.create_projects(self.session) - tests.create_projects_git( - os.path.join(self.path, 'repos'), bare=True) + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) tests.add_content_git_repo( - os.path.join(self.path, 'repos', 'test.git')) + os.path.join(self.path, "repos", "test.git") + ) user = tests.FakeUser() - user.username = 'pingou' + user.username = "pingou" with tests.user_set(self.app.application, user): csrf_token = self.get_csrf() - data = { - 'csrf_token': csrf_token, - } - output = self.app.post('/pv/test/family', data=data) + data = {"csrf_token": csrf_token} + output = self.app.post("/pv/test/family", data=data) self.assertEqual(output.status_code, 200) js_data = json.loads(output.get_data(as_text=True)) - self.assertEqual( - sorted(js_data.keys()), - ['code', 'family'] - ) - self.assertEqual(js_data['code'], 'OK') - self.assertEqual(js_data['family'], ['test']) + self.assertEqual(sorted(js_data.keys()), ["code", "family"]) + self.assertEqual(js_data["code"], "OK") + self.assertEqual(js_data["family"], ["test"]) def test_get_project_larger_family(self): - ''' Test the get_project_family from the internal API. ''' + """ Test the get_project_family from the internal API. """ tests.create_projects(self.session) - tests.create_projects_git( - os.path.join(self.path, 'repos'), bare=True) + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) # Create a 3rd user item = pagure.lib.model.User( - user='ralph', - fullname='Ralph bar', - password='ralph_foo', - default_email='ralph@bar.com', + user="ralph", + fullname="Ralph bar", + password="ralph_foo", + default_email="ralph@bar.com", ) self.session.add(item) - item = pagure.lib.model.UserEmail( - user_id=3, - email='ralph@bar.com') + item = pagure.lib.model.UserEmail(user_id=3, email="ralph@bar.com") self.session.add(item) self.session.commit() # Create a couple of forks of the test project item = pagure.lib.model.Project( user_id=2, # foo - name='test', + name="test", is_fork=True, parent_id=1, # test - description='test project #1', - hook_token='aaabbbcccddd', - ) - item.close_status = ['Invalid', 'Insufficient data', 'Fixed', 'Duplicate'] + description="test project #1", + hook_token="aaabbbcccddd", + ) + item.close_status = [ + "Invalid", + "Insufficient data", + "Fixed", + "Duplicate", + ] self.session.add(item) item = pagure.lib.model.Project( user_id=3, # Ralph - name='test', + name="test", is_fork=True, parent_id=1, # test - description='test project #1', - hook_token='aaabbbccceee', - ) - item.close_status = ['Invalid', 'Insufficient data', 'Fixed', 'Duplicate'] + description="test project #1", + hook_token="aaabbbccceee", + ) + item.close_status = [ + "Invalid", + "Insufficient data", + "Fixed", + "Duplicate", + ] self.session.add(item) self.session.commit() # Get on with testing user = tests.FakeUser() - user.username = 'pingou' + user.username = "pingou" with tests.user_set(self.app.application, user): csrf_token = self.get_csrf() - data = { - 'csrf_token': csrf_token, - } - output = self.app.post('/pv/test/family', data=data) + data = {"csrf_token": csrf_token} + output = self.app.post("/pv/test/family", data=data) self.assertEqual(output.status_code, 200) js_data = json.loads(output.get_data(as_text=True)) + self.assertEqual(sorted(js_data.keys()), ["code", "family"]) + self.assertEqual(js_data["code"], "OK") self.assertEqual( - sorted(js_data.keys()), - ['code', 'family'] + js_data["family"], ["test", "fork/foo/test", "fork/ralph/test"] ) - self.assertEqual(js_data['code'], 'OK') - self.assertEqual( - js_data['family'], - ['test', 'fork/foo/test', 'fork/ralph/test']) def test_get_project_larger_family_pr_only(self): - ''' Test the get_project_family from the internal API. ''' + """ Test the get_project_family from the internal API. """ tests.create_projects(self.session) - tests.create_projects_git( - os.path.join(self.path, 'repos'), bare=True) + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) # Create a 3rd user item = pagure.lib.model.User( - user='ralph', - fullname='Ralph bar', - password='ralph_foo', - default_email='ralph@bar.com', + user="ralph", + fullname="Ralph bar", + password="ralph_foo", + default_email="ralph@bar.com", ) self.session.add(item) - item = pagure.lib.model.UserEmail( - user_id=3, - email='ralph@bar.com') + item = pagure.lib.model.UserEmail(user_id=3, email="ralph@bar.com") self.session.add(item) self.session.commit() # Create a couple of forks of the test project item = pagure.lib.model.Project( user_id=2, # foo - name='test', + name="test", is_fork=True, parent_id=1, # test - description='test project #1', - hook_token='aaabbbcccddd', - ) - item.close_status = ['Invalid', 'Insufficient data', 'Fixed', 'Duplicate'] + description="test project #1", + hook_token="aaabbbcccddd", + ) + item.close_status = [ + "Invalid", + "Insufficient data", + "Fixed", + "Duplicate", + ] # disable issues in this fork default_repo_settings = item.settings - default_repo_settings['issue_tracker'] = False + default_repo_settings["issue_tracker"] = False item.settings = default_repo_settings self.session.add(item) item = pagure.lib.model.Project( user_id=3, # Ralph - name='test', + name="test", is_fork=True, parent_id=1, # test - description='test project #1', - hook_token='aaabbbccceee', - ) - item.close_status = ['Invalid', 'Insufficient data', 'Fixed', 'Duplicate'] + description="test project #1", + hook_token="aaabbbccceee", + ) + item.close_status = [ + "Invalid", + "Insufficient data", + "Fixed", + "Duplicate", + ] # disable PRs in this fork default_repo_settings = item.settings - default_repo_settings['pull_requests'] = False + default_repo_settings["pull_requests"] = False item.settings = default_repo_settings self.session.add(item) self.session.commit() # Get on with testing user = tests.FakeUser() - user.username = 'pingou' + user.username = "pingou" with tests.user_set(self.app.application, user): csrf_token = self.get_csrf() - data = { - 'csrf_token': csrf_token, - 'allows_pr': '1', - } - output = self.app.post('/pv/test/family', data=data) + data = {"csrf_token": csrf_token, "allows_pr": "1"} + output = self.app.post("/pv/test/family", data=data) self.assertEqual(output.status_code, 200) js_data = json.loads(output.get_data(as_text=True)) - self.assertEqual( - sorted(js_data.keys()), - ['code', 'family'] - ) - self.assertEqual(js_data['code'], 'OK') - self.assertEqual( - js_data['family'], - ['test', 'fork/foo/test']) + self.assertEqual(sorted(js_data.keys()), ["code", "family"]) + self.assertEqual(js_data["code"], "OK") + self.assertEqual(js_data["family"], ["test", "fork/foo/test"]) - data = { - 'csrf_token': csrf_token, - 'allows_issues': '1', - } - output = self.app.post('/pv/test/family', data=data) + data = {"csrf_token": csrf_token, "allows_issues": "1"} + output = self.app.post("/pv/test/family", data=data) self.assertEqual(output.status_code, 200) js_data = json.loads(output.get_data(as_text=True)) - self.assertEqual( - sorted(js_data.keys()), - ['code', 'family'] - ) - self.assertEqual(js_data['code'], 'OK') - self.assertEqual( - js_data['family'], - ['test', 'fork/ralph/test']) + self.assertEqual(sorted(js_data.keys()), ["code", "family"]) + self.assertEqual(js_data["code"], "OK") + self.assertEqual(js_data["family"], ["test", "fork/ralph/test"]) def test_get_pull_request_ready_branch_no_csrf(self): - '''Test the get_pull_request_ready_branch from the internal API + """Test the get_pull_request_ready_branch from the internal API on the main repository - ''' + """ tests.create_projects(self.session) - tests.create_projects_git( - os.path.join(self.path, 'repos'), bare=True) + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) # Query branches on the main repo - data = { - 'repo': 'test', - } - output = self.app.post('/pv/pull-request/ready', data=data) + data = {"repo": "test"} + output = self.app.post("/pv/pull-request/ready", data=data) self.assertEqual(output.status_code, 400) js_data = json.loads(output.get_data(as_text=True)) - self.assertEqual( - sorted(js_data.keys()), - ['code', 'message'] - ) - self.assertEqual(js_data['code'], 'ERROR') - self.assertEqual( - js_data['message'], - 'Invalid input submitted' - ) + self.assertEqual(sorted(js_data.keys()), ["code", "message"]) + self.assertEqual(js_data["code"], "ERROR") + self.assertEqual(js_data["message"], "Invalid input submitted") def test_get_pull_request_ready_branch_no_repo(self): - '''Test the get_pull_request_ready_branch from the internal API + """Test the get_pull_request_ready_branch from the internal API on the main repository - ''' + """ with tests.user_set(self.app.application, tests.FakeUser()): csrf_token = self.get_csrf() # Query branches on an invalid repo - data = { - 'repo': 'test', - 'namespace': 'fake', - 'csrf_token': csrf_token, - } - output = self.app.post('/pv/pull-request/ready', data=data) + data = {"repo": "test", "namespace": "fake", "csrf_token": csrf_token} + output = self.app.post("/pv/pull-request/ready", data=data) self.assertEqual(output.status_code, 404) js_data = json.loads(output.get_data(as_text=True)) + self.assertEqual(sorted(js_data.keys()), ["code", "message"]) + self.assertEqual(js_data["code"], "ERROR") self.assertEqual( - sorted(js_data.keys()), - ['code', 'message'] - ) - self.assertEqual(js_data['code'], 'ERROR') - self.assertEqual( - js_data['message'], - 'No repo found with the information provided' + js_data["message"], "No repo found with the information provided" ) def test_get_pull_request_ready_branch_main_repo_no_branch(self): - '''Test the get_pull_request_ready_branch from the internal API + """Test the get_pull_request_ready_branch from the internal API on the main repository - ''' + """ tests.create_projects(self.session) - tests.create_projects_git( - os.path.join(self.path, 'repos'), bare=True) + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) # Get on with testing user = tests.FakeUser() - user.username = 'pingou' + user.username = "pingou" with tests.user_set(self.app.application, user): csrf_token = self.get_csrf() # Query branches on the main repo - data = { - 'csrf_token': csrf_token, - 'repo': 'test', - } - output = self.app.post('/pv/pull-request/ready', data=data) + data = {"csrf_token": csrf_token, "repo": "test"} + output = self.app.post("/pv/pull-request/ready", data=data) self.assertEqual(output.status_code, 200) js_data = json.loads(output.get_data(as_text=True)) - self.assertEqual( - sorted(js_data.keys()), - ['code', 'task'] - ) - self.assertEqual(js_data['code'], 'OK') + self.assertEqual(sorted(js_data.keys()), ["code", "task"]) + self.assertEqual(js_data["code"], "OK") def test_get_pull_request_ready_branch_on_fork(self): - '''Test the get_pull_request_ready_branch from the internal API on + """Test the get_pull_request_ready_branch from the internal API on a fork - ''' + """ tests.create_projects(self.session) + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) tests.create_projects_git( - os.path.join(self.path, 'repos'), bare=True) - tests.create_projects_git( - os.path.join(self.path, 'repos', 'forks', 'foo'), bare=True) + os.path.join(self.path, "repos", "forks", "foo"), bare=True + ) tests.add_content_git_repo( - os.path.join(self.path, 'repos', 'forks', 'foo', 'test.git'), - branch='feature') + os.path.join(self.path, "repos", "forks", "foo", "test.git"), + branch="feature", + ) # Create foo's fork of the test project item = pagure.lib.model.Project( user_id=2, # foo - name='test', + name="test", is_fork=True, parent_id=1, # test - description='test project #1', - hook_token='aaabbbcccddd', - ) - item.close_status = ['Invalid', 'Insufficient data', 'Fixed', 'Duplicate'] + description="test project #1", + hook_token="aaabbbcccddd", + ) + item.close_status = [ + "Invalid", + "Insufficient data", + "Fixed", + "Duplicate", + ] self.session.add(item) self.session.commit() # Get on with testing user = tests.FakeUser() - user.username = 'pingou' + user.username = "pingou" with tests.user_set(self.app.application, user): csrf_token = self.get_csrf() # Query branches on the Ralph's fork - data = { - 'csrf_token': csrf_token, - 'repo': 'test', - 'repouser': 'foo', - } - output = self.app.post('/pv/pull-request/ready', data=data) + data = {"csrf_token": csrf_token, "repo": "test", "repouser": "foo"} + output = self.app.post("/pv/pull-request/ready", data=data) self.assertEqual(output.status_code, 200) js_data = json.loads(output.get_data(as_text=True)) - self.assertEqual( - sorted(js_data.keys()), - ['code', 'task'] - ) - self.assertEqual(js_data['code'], 'OK') - output = self.app.get('/pv/task/' + js_data['task']) + self.assertEqual(sorted(js_data.keys()), ["code", "task"]) + self.assertEqual(js_data["code"], "OK") + output = self.app.get("/pv/task/" + js_data["task"]) self.assertEqual(output.status_code, 200) js_data = json.loads(output.get_data(as_text=True)) self.assertEqual( js_data, - {'results': { - 'branch_w_pr': {}, - 'new_branch': {'feature': - {'commits': 2, 'target_branch': 'master'}}}} + { + "results": { + "branch_w_pr": {}, + "new_branch": { + "feature": {"commits": 2, "target_branch": "master"} + }, + } + }, ) def test_get_pull_request_ready_branch_on_fork_no_parent_no_pr(self): - '''Test the get_pull_request_ready_branch from the internal API on + """Test the get_pull_request_ready_branch from the internal API on a fork that has no parent repo (deleted) and doesn't allow PR - ''' + """ tests.create_projects(self.session) + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) tests.create_projects_git( - os.path.join(self.path, 'repos'), bare=True) - tests.create_projects_git( - os.path.join(self.path, 'repos', 'forks', 'foo'), bare=True) + os.path.join(self.path, "repos", "forks", "foo"), bare=True + ) tests.add_content_git_repo( - os.path.join(self.path, 'repos', 'forks', 'foo', 'test.git'), - branch='feature') + os.path.join(self.path, "repos", "forks", "foo", "test.git"), + branch="feature", + ) # Create foo's fork of the test project item = pagure.lib.model.Project( user_id=2, # foo - name='test', + name="test", is_fork=True, parent_id=1, # test - description='test project #1', - hook_token='aaabbbcccddd', - ) - item.close_status = ['Invalid', 'Insufficient data', 'Fixed', 'Duplicate'] + description="test project #1", + hook_token="aaabbbcccddd", + ) + item.close_status = [ + "Invalid", + "Insufficient data", + "Fixed", + "Duplicate", + ] self.session.add(item) self.session.commit() settings = item.settings - settings['pull_requests'] = False + settings["pull_requests"] = False item.settings = settings self.session.add(item) self.session.commit() # Delete the parent project - project = pagure.lib.query.get_authorized_project(self.session, 'test') + project = pagure.lib.query.get_authorized_project(self.session, "test") self.session.delete(project) self.session.commit() # Get on with testing user = tests.FakeUser() - user.username = 'pingou' + user.username = "pingou" with tests.user_set(self.app.application, user): csrf_token = self.get_csrf() # Query branches on the Ralph's fork - data = { - 'csrf_token': csrf_token, - 'repo': 'test', - 'repouser': 'foo', - } - output = self.app.post('/pv/pull-request/ready', data=data) + data = {"csrf_token": csrf_token, "repo": "test", "repouser": "foo"} + output = self.app.post("/pv/pull-request/ready", data=data) self.assertEqual(output.status_code, 400) js_data = json.loads(output.get_data(as_text=True)) + self.assertEqual(sorted(js_data.keys()), ["code", "message"]) + self.assertEqual(js_data["code"], "ERROR") self.assertEqual( - sorted(js_data.keys()), - ['code', 'message'] + js_data["message"], "Pull-request have been disabled for this repo" ) - self.assertEqual(js_data['code'], 'ERROR') - self.assertEqual( - js_data['message'], - 'Pull-request have been disabled for this repo') def test_get_pull_request_ready_branch_on_fork_no_parent(self): - '''Test the get_pull_request_ready_branch from the internal API on + """Test the get_pull_request_ready_branch from the internal API on a fork that has no parent repo (deleted). - ''' + """ tests.create_projects(self.session) + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) tests.create_projects_git( - os.path.join(self.path, 'repos'), bare=True) - tests.create_projects_git( - os.path.join(self.path, 'repos', 'forks', 'foo'), bare=True) + os.path.join(self.path, "repos", "forks", "foo"), bare=True + ) tests.add_content_git_repo( - os.path.join(self.path, 'repos', 'forks', 'foo', 'test.git'), - branch='feature') + os.path.join(self.path, "repos", "forks", "foo", "test.git"), + branch="feature", + ) # Create foo's fork of the test project item = pagure.lib.model.Project( user_id=2, # foo - name='test', + name="test", is_fork=True, parent_id=1, # test - description='test project #1', - hook_token='aaabbbcccddd', - ) - item.close_status = ['Invalid', 'Insufficient data', 'Fixed', 'Duplicate'] + description="test project #1", + hook_token="aaabbbcccddd", + ) + item.close_status = [ + "Invalid", + "Insufficient data", + "Fixed", + "Duplicate", + ] self.session.add(item) self.session.commit() settings = item.settings - settings['pull_requests'] = True + settings["pull_requests"] = True item.settings = settings self.session.add(item) self.session.commit() # Delete the parent project - project = pagure.lib.query.get_authorized_project(self.session, 'test') + project = pagure.lib.query.get_authorized_project(self.session, "test") self.session.delete(project) self.session.commit() # Get on with testing user = tests.FakeUser() - user.username = 'pingou' + user.username = "pingou" with tests.user_set(self.app.application, user): csrf_token = self.get_csrf() # Query branches on the Ralph's fork - data = { - 'csrf_token': csrf_token, - 'repo': 'test', - 'repouser': 'foo', - } - output = self.app.post('/pv/pull-request/ready', data=data) + data = {"csrf_token": csrf_token, "repo": "test", "repouser": "foo"} + output = self.app.post("/pv/pull-request/ready", data=data) self.assertEqual(output.status_code, 200) js_data = json.loads(output.get_data(as_text=True)) - self.assertEqual( - sorted(js_data.keys()), - ['code', 'task'] - ) - self.assertEqual(js_data['code'], 'OK') - output = self.app.get('/pv/task/' + js_data['task']) + self.assertEqual(sorted(js_data.keys()), ["code", "task"]) + self.assertEqual(js_data["code"], "OK") + output = self.app.get("/pv/task/" + js_data["task"]) self.assertEqual(output.status_code, 200) js_data = json.loads(output.get_data(as_text=True)) self.assertEqual( js_data, - {'results': { - 'branch_w_pr': {}, - 'new_branch': {'feature': - {'commits': 2, 'target_branch': 'master'}}}} + { + "results": { + "branch_w_pr": {}, + "new_branch": { + "feature": {"commits": 2, "target_branch": "master"} + }, + } + }, ) def test_get_pull_request_ready_branch_matching_target_off(self): - '''Test the get_pull_request_ready_branch from the internal API on + """Test the get_pull_request_ready_branch from the internal API on a fork while PR_TARGET_MATCHING_BRANCH is False - ''' + """ tests.create_projects(self.session) # make sure that head is not unborn tests.add_content_git_repo( - os.path.join(self.path, 'repos', 'test.git'), - branch='master') + os.path.join(self.path, "repos", "test.git"), branch="master" + ) tests.add_content_git_repo( - os.path.join(self.path, 'repos', 'test.git'), - branch='feature') + os.path.join(self.path, "repos", "test.git"), branch="feature" + ) + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) tests.create_projects_git( - os.path.join(self.path, 'repos'), bare=True) - tests.create_projects_git( - os.path.join(self.path, 'repos', 'forks', 'foo'), bare=True) + os.path.join(self.path, "repos", "forks", "foo"), bare=True + ) tests.add_content_git_repo( - os.path.join(self.path, 'repos', 'forks', 'foo', 'test.git'), - branch='feature') + os.path.join(self.path, "repos", "forks", "foo", "test.git"), + branch="feature", + ) # Create foo's fork of the test project item = pagure.lib.model.Project( user_id=2, # foo - name='test', + name="test", is_fork=True, parent_id=1, # test - description='test project #1', - hook_token='aaabbbcccddd', - ) - item.close_status = ['Invalid', 'Insufficient data', 'Fixed', 'Duplicate'] + description="test project #1", + hook_token="aaabbbcccddd", + ) + item.close_status = [ + "Invalid", + "Insufficient data", + "Fixed", + "Duplicate", + ] self.session.add(item) self.session.commit() # Get on with testing user = tests.FakeUser() - user.username = 'pingou' + user.username = "pingou" with tests.user_set(self.app.application, user): csrf_token = self.get_csrf() # Query branches on the Ralph's fork - data = { - 'csrf_token': csrf_token, - 'repo': 'test', - 'repouser': 'foo', - } - output = self.app.post('/pv/pull-request/ready', data=data) + data = {"csrf_token": csrf_token, "repo": "test", "repouser": "foo"} + output = self.app.post("/pv/pull-request/ready", data=data) self.assertEqual(output.status_code, 200) js_data = json.loads(output.get_data(as_text=True)) - self.assertEqual( - sorted(js_data.keys()), - ['code', 'task'] - ) - self.assertEqual(js_data['code'], 'OK') - output = self.app.get('/pv/task/' + js_data['task']) + self.assertEqual(sorted(js_data.keys()), ["code", "task"]) + self.assertEqual(js_data["code"], "OK") + output = self.app.get("/pv/task/" + js_data["task"]) self.assertEqual(output.status_code, 200) js_data = json.loads(output.get_data(as_text=True)) self.assertEqual( js_data, - {'results': { - 'branch_w_pr': {}, - 'new_branch': {'feature': - {'commits': 2, 'target_branch': 'master'}}}} + { + "results": { + "branch_w_pr": {}, + "new_branch": { + "feature": {"commits": 2, "target_branch": "master"} + }, + } + }, ) - @patch.dict('pagure.config.config', {'PR_TARGET_MATCHING_BRANCH': True}) + @patch.dict("pagure.config.config", {"PR_TARGET_MATCHING_BRANCH": True}) def test_get_pull_request_ready_branch_matching_target_on(self): - '''Test the get_pull_request_ready_branch from the internal API on + """Test the get_pull_request_ready_branch from the internal API on a fork while PR_TARGET_MATCHING_BRANCH is True - ''' + """ tests.create_projects(self.session) # make sure that head is not unborn tests.add_content_git_repo( - os.path.join(self.path, 'repos', 'test.git'), - branch='master') + os.path.join(self.path, "repos", "test.git"), branch="master" + ) tests.add_content_git_repo( - os.path.join(self.path, 'repos', 'test.git'), - branch='feature') + os.path.join(self.path, "repos", "test.git"), branch="feature" + ) + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) tests.create_projects_git( - os.path.join(self.path, 'repos'), bare=True) - tests.create_projects_git( - os.path.join(self.path, 'repos', 'forks', 'foo'), bare=True) + os.path.join(self.path, "repos", "forks", "foo"), bare=True + ) tests.add_content_git_repo( - os.path.join(self.path, 'repos', 'forks', 'foo', 'test.git'), + os.path.join(self.path, "repos", "forks", "foo", "test.git"), append="testing from foo's fork", - branch='feature') + branch="feature", + ) # Create foo's fork of the test project item = pagure.lib.model.Project( user_id=2, # foo - name='test', + name="test", is_fork=True, parent_id=1, # test - description='test project #1', - hook_token='aaabbbcccddd', - ) - item.close_status = ['Invalid', 'Insufficient data', 'Fixed', 'Duplicate'] + description="test project #1", + hook_token="aaabbbcccddd", + ) + item.close_status = [ + "Invalid", + "Insufficient data", + "Fixed", + "Duplicate", + ] self.session.add(item) self.session.commit() # Get on with testing user = tests.FakeUser() - user.username = 'pingou' + user.username = "pingou" with tests.user_set(self.app.application, user): csrf_token = self.get_csrf() # Query branches on the Ralph's fork - data = { - 'csrf_token': csrf_token, - 'repo': 'test', - 'repouser': 'foo', - } - output = self.app.post('/pv/pull-request/ready', data=data) + data = {"csrf_token": csrf_token, "repo": "test", "repouser": "foo"} + output = self.app.post("/pv/pull-request/ready", data=data) self.assertEqual(output.status_code, 200) js_data = json.loads(output.get_data(as_text=True)) - self.assertEqual( - sorted(js_data.keys()), - ['code', 'task'] - ) - self.assertEqual(js_data['code'], 'OK') - output = self.app.get('/pv/task/' + js_data['task']) + self.assertEqual(sorted(js_data.keys()), ["code", "task"]) + self.assertEqual(js_data["code"], "OK") + output = self.app.get("/pv/task/" + js_data["task"]) self.assertEqual(output.status_code, 200) js_data = json.loads(output.get_data(as_text=True)) self.assertEqual( js_data, - {'results': { - 'branch_w_pr': {}, - 'new_branch': {'feature': - {'commits': 1, 'target_branch': 'feature'}}}} + { + "results": { + "branch_w_pr": {}, + "new_branch": { + "feature": {"commits": 1, "target_branch": "feature"} + }, + } + }, ) def test_task_info_task_running(self): @@ -2894,33 +2753,39 @@ class PagureFlaskInternaltests(tests.Modeltests): ready. """ task = MagicMock() - task.get = MagicMock(return_value='FAILED') + task.get = MagicMock(return_value="FAILED") task.ready = MagicMock(return_value=False) - with patch('pagure.lib.tasks.get_result', MagicMock(return_value=task)): - output = self.app.get('/pv/task/2') + with patch( + "pagure.lib.tasks.get_result", MagicMock(return_value=task) + ): + output = self.app.get("/pv/task/2") self.assertEqual(output.status_code, 418) def test_task_info_task_passed(self): """ Test the task_info internal API endpoint when the task failed. """ task = MagicMock() - task.get = MagicMock(return_value='PASSED') - with patch('pagure.lib.tasks.get_result', MagicMock(return_value=task)): - output = self.app.get('/pv/task/2') + task.get = MagicMock(return_value="PASSED") + with patch( + "pagure.lib.tasks.get_result", MagicMock(return_value=task) + ): + output = self.app.get("/pv/task/2") self.assertEqual(output.status_code, 200) js_data = json.loads(output.get_data(as_text=True)) - self.assertEqual(js_data, {u'results': u'PASSED'}) + self.assertEqual(js_data, {"results": "PASSED"}) def test_task_info_task_failed(self): """ Test the task_info internal API endpoint when the task failed. """ task = MagicMock() - task.get = MagicMock(return_value=Exception('Random error')) - with patch('pagure.lib.tasks.get_result', MagicMock(return_value=task)): - output = self.app.get('/pv/task/2') + task.get = MagicMock(return_value=Exception("Random error")) + with patch( + "pagure.lib.tasks.get_result", MagicMock(return_value=task) + ): + output = self.app.get("/pv/task/2") self.assertEqual(output.status_code, 200) js_data = json.loads(output.get_data(as_text=True)) - self.assertEqual(js_data, {u'results': u'Random error'}) + self.assertEqual(js_data, {"results": "Random error"}) def test_lookup_ssh_key(self): """ Test the mergeable_request_pull endpoint when the backend @@ -2928,13 +2793,13 @@ class PagureFlaskInternaltests(tests.Modeltests): """ tests.create_projects(self.session) - repo = pagure.lib.query.get_authorized_project(self.session, 'test') - project_key = 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIC4zmifEL8TLLZUZnjAuVL8495DAkpAAM2eBhwHwawBm' - project_key_fp = 'SHA256:ZSUQAqpPDWi90Fs6Ow8Epc8F3qiKVfU+H5ssvo7jiI0' + repo = pagure.lib.query.get_authorized_project(self.session, "test") + project_key = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIC4zmifEL8TLLZUZnjAuVL8495DAkpAAM2eBhwHwawBm" + project_key_fp = "SHA256:ZSUQAqpPDWi90Fs6Ow8Epc8F3qiKVfU+H5ssvo7jiI0" - pingou = pagure.lib.query.get_user(self.session, 'pingou') - user_key = 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDTsfdTcXw4rlU1aQwOTbLOXqossLwpPIk27S/G17kUz' - user_key_fp = 'SHA256:jUJHzrq2Ct6Ubf7Y9rnB6tGnbHM9dMVsveyfPojm+i0' + pingou = pagure.lib.query.get_user(self.session, "pingou") + user_key = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDTsfdTcXw4rlU1aQwOTbLOXqossLwpPIk27S/G17kUz" + user_key_fp = "SHA256:jUJHzrq2Ct6Ubf7Y9rnB6tGnbHM9dMVsveyfPojm+i0" pagure.lib.query.add_sshkey_to_project_or_user( self.session, @@ -2952,105 +2817,91 @@ class PagureFlaskInternaltests(tests.Modeltests): ) self.session.commit() - url = '/pv/ssh/lookupkey/' + url = "/pv/ssh/lookupkey/" - output = self.app.post( - url, - data={'search_key': 'asdf'}, - ) + output = self.app.post(url, data={"search_key": "asdf"}) self.assertEqual(output.status_code, 200) result = json.loads(output.get_data(as_text=True)) - self.assertEqual(result['found'], False) + self.assertEqual(result["found"], False) - output = self.app.post( - url, - data={'search_key': user_key_fp}, - ) + output = self.app.post(url, data={"search_key": user_key_fp}) self.assertEqual(output.status_code, 200) result = json.loads(output.get_data(as_text=True)) - self.assertEqual(result['found'], True) - self.assertEqual(result['username'], 'pingou') - self.assertEqual(result['public_key'], user_key) + self.assertEqual(result["found"], True) + self.assertEqual(result["username"], "pingou") + self.assertEqual(result["public_key"], user_key) output = self.app.post( - url, - data={'search_key': user_key_fp, - 'username': 'pingou'}, + url, data={"search_key": user_key_fp, "username": "pingou"} ) self.assertEqual(output.status_code, 200) result = json.loads(output.get_data(as_text=True)) - self.assertEqual(result['found'], True) - self.assertEqual(result['username'], 'pingou') - self.assertEqual(result['public_key'], user_key) + self.assertEqual(result["found"], True) + self.assertEqual(result["username"], "pingou") + self.assertEqual(result["public_key"], user_key) output = self.app.post( - url, - data={'search_key': user_key_fp, - 'username': 'foo'}, + url, data={"search_key": user_key_fp, "username": "foo"} ) self.assertEqual(output.status_code, 200) result = json.loads(output.get_data(as_text=True)) - self.assertEqual(result['found'], False) + self.assertEqual(result["found"], False) - output = self.app.post( - url, - data={'search_key': project_key_fp}, - ) + output = self.app.post(url, data={"search_key": project_key_fp}) self.assertEqual(output.status_code, 200) result = json.loads(output.get_data(as_text=True)) - self.assertEqual(result['found'], True) - self.assertEqual(result['username'], 'deploykey_test_2') - self.assertEqual(result['public_key'], project_key) - - @patch.dict('pagure.config.config', - {'REPOSPANNER_REGIONS': {'region': {'repo_prefix': 'prefix'}}}) + self.assertEqual(result["found"], True) + self.assertEqual(result["username"], "deploykey_test_2") + self.assertEqual(result["public_key"], project_key) + + @patch.dict( + "pagure.config.config", + {"REPOSPANNER_REGIONS": {"region": {"repo_prefix": "prefix"}}}, + ) def test_check_ssh_access(self): """ Test the SSH access check endpoint. """ tests.create_projects(self.session) - self.session.query(pagure.lib.model.Project).\ - filter(pagure.lib.model.Project.name == 'test2').\ - update({pagure.lib.model.Project.repospanner_region: 'region'}) + self.session.query(pagure.lib.model.Project).filter( + pagure.lib.model.Project.name == "test2" + ).update({pagure.lib.model.Project.repospanner_region: "region"}) self.session.commit() - url = '/pv/ssh/checkaccess/' + url = "/pv/ssh/checkaccess/" + def runtest(project, username, access): output = self.app.post( - url, - data={ - 'gitdir': project, - 'username': username, - } + url, data={"gitdir": project, "username": username} ) self.assertEqual(output.status_code, 200) result = json.loads(output.get_data(as_text=True)) - self.assertEqual(result['access'], access) + self.assertEqual(result["access"], access) return result - runtest('project.git', 'pingou', False) - i1 = runtest('test.git', 'pingou', True) - i2 = runtest('test.git', 'foo', True) - i3 = runtest('tickets/test.git', 'pingou', True) - i4 = runtest('test2.git', 'pingou', True) - runtest('tickets/test.git', 'foo', False) - - self.assertEqual(i1['reponame'], 'test.git') - self.assertEqual(i1['repospanner_reponame'], None) - self.assertEqual(i1['repotype'], 'main') - self.assertEqual(i1['region'], None) - self.assertEqual(i1['project_name'], 'test') - self.assertEqual(i1['project_user'], None) - self.assertEqual(i1['project_namespace'], None) + runtest("project.git", "pingou", False) + i1 = runtest("test.git", "pingou", True) + i2 = runtest("test.git", "foo", True) + i3 = runtest("tickets/test.git", "pingou", True) + i4 = runtest("test2.git", "pingou", True) + runtest("tickets/test.git", "foo", False) + + self.assertEqual(i1["reponame"], "test.git") + self.assertEqual(i1["repospanner_reponame"], None) + self.assertEqual(i1["repotype"], "main") + self.assertEqual(i1["region"], None) + self.assertEqual(i1["project_name"], "test") + self.assertEqual(i1["project_user"], None) + self.assertEqual(i1["project_namespace"], None) self.assertEqual(i1, i2) - self.assertEqual(i3['reponame'], 'tickets/test.git') - self.assertEqual(i3['repospanner_reponame'], None) - self.assertEqual(i3['repotype'], 'tickets') - self.assertEqual(i3['region'], None) - self.assertEqual(i3['project_name'], 'test') - self.assertEqual(i3['project_user'], None) - self.assertEqual(i3['project_namespace'], None) - self.assertEqual(i4['repospanner_reponame'], 'prefix/main/test2') - self.assertEqual(i4['region'], 'region') - - -if __name__ == '__main__': + self.assertEqual(i3["reponame"], "tickets/test.git") + self.assertEqual(i3["repospanner_reponame"], None) + self.assertEqual(i3["repotype"], "tickets") + self.assertEqual(i3["region"], None) + self.assertEqual(i3["project_name"], "test") + self.assertEqual(i3["project_user"], None) + self.assertEqual(i3["project_namespace"], None) + self.assertEqual(i4["repospanner_reponame"], "prefix/main/test2") + self.assertEqual(i4["region"], "region") + + +if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/test_pagure_flask_rebase.py b/tests/test_pagure_flask_rebase.py index b1dabd8..240047f 100644 --- a/tests/test_pagure_flask_rebase.py +++ b/tests/test_pagure_flask_rebase.py @@ -19,8 +19,9 @@ import os import json from mock import patch, MagicMock -sys.path.insert(0, os.path.join(os.path.dirname( - os.path.abspath(__file__)), '..')) +sys.path.insert( + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") +) import pagure.lib.query import pagure.lib.tasks @@ -32,227 +33,238 @@ class PagureRebasetests(tests.Modeltests): maxDiff = None - @patch('pagure.lib.notify.send_email', MagicMock(return_value=True)) + @patch("pagure.lib.notify.send_email", MagicMock(return_value=True)) def setUp(self): """ Set up the environnment, ran before every tests. """ super(PagureRebasetests, self).setUp() - pagure.config.config['REQUESTS_FOLDER'] = None + pagure.config.config["REQUESTS_FOLDER"] = None tests.create_projects(self.session) + tests.create_projects_git(os.path.join(self.path, "repos"), bare=True) tests.create_projects_git( - os.path.join(self.path, 'repos'), bare=True) - tests.create_projects_git( - os.path.join(self.path, 'requests'), bare=True) + os.path.join(self.path, "requests"), bare=True + ) tests.add_content_to_git( - os.path.join(self.path, 'repos', 'test.git'), - branch='master', content="foobarbaz", filename="testfile") + os.path.join(self.path, "repos", "test.git"), + branch="master", + content="foobarbaz", + filename="testfile", + ) tests.add_content_to_git( - os.path.join(self.path, 'repos', 'test.git'), - branch='test', content="foobar", filename="sources") - tests.add_readme_git_repo( - os.path.join(self.path, 'repos', 'test.git')) + os.path.join(self.path, "repos", "test.git"), + branch="test", + content="foobar", + filename="sources", + ) + tests.add_readme_git_repo(os.path.join(self.path, "repos", "test.git")) # Create a PR for these changes - project = pagure.lib.query.get_authorized_project( - self.session, 'test') + project = pagure.lib.query.get_authorized_project(self.session, "test") req = pagure.lib.query.new_pull_request( session=self.session, repo_from=project, - branch_from='test', + branch_from="test", repo_to=project, - branch_to='master', - title='PR from the test branch', - user='pingou', + branch_to="master", + title="PR from the test branch", + user="pingou", ) self.session.commit() self.assertEqual(req.id, 1) - self.assertEqual(req.title, 'PR from the test branch') + self.assertEqual(req.title, "PR from the test branch") self.project = pagure.lib.query.get_authorized_project( - self.session, 'test') + self.session, "test" + ) self.assertEqual(len(project.requests), 1) self.request = self.project.requests[0] def test_merge_status_merge(self): """ Test that the PR can be merged with a merge commit. """ - user = tests.FakeUser(username='pingou') + user = tests.FakeUser(username="pingou") with tests.user_set(self.app.application, user): - data = {'requestid': self.request.uid, 'csrf_token': self.get_csrf()} - output = self.app.post('/pv/pull-request/merge', data=data) + data = { + "requestid": self.request.uid, + "csrf_token": self.get_csrf(), + } + output = self.app.post("/pv/pull-request/merge", data=data) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertEqual( data, { - u'code': u'MERGE', - u'message': u'The pull-request can be merged with a ' - u'merge commit', - u'short_code': u'With merge' - } + "code": "MERGE", + "message": "The pull-request can be merged with a " + "merge commit", + "short_code": "With merge", + }, ) def test_merge_status_needsrebase(self): """ Test that the PR is marked as needing a rebase if the project disables non-fast-forward merges. """ self.project = pagure.lib.query.get_authorized_project( - self.session, 'test') + self.session, "test" + ) settings = self.project.settings - settings['disable_non_fast-forward_merges'] = True + settings["disable_non_fast-forward_merges"] = True self.project.settings = settings self.session.add(self.project) self.session.commit() - user = tests.FakeUser(username='pingou') + user = tests.FakeUser(username="pingou") with tests.user_set(self.app.application, user): - data = {'requestid': self.request.uid, 'csrf_token': self.get_csrf()} - output = self.app.post('/pv/pull-request/merge', data=data) + data = { + "requestid": self.request.uid, + "csrf_token": self.get_csrf(), + } + output = self.app.post("/pv/pull-request/merge", data=data) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertEqual( data, { - u'code': u'NEEDSREBASE', - u'message': u'The pull-request must be rebased before ' - u'merging', - u'short_code': u'Needs rebase' - } + "code": "NEEDSREBASE", + "message": "The pull-request must be rebased before " + "merging", + "short_code": "Needs rebase", + }, ) def test_rebase_task(self): """ Test the rebase PR task and its outcome. """ pagure.lib.tasks.rebase_pull_request( - 'test', namespace=None, user=None, requestid=self.request.id, - user_rebaser='pingou') + "test", + namespace=None, + user=None, + requestid=self.request.id, + user_rebaser="pingou", + ) - user = tests.FakeUser(username='pingou') + user = tests.FakeUser(username="pingou") with tests.user_set(self.app.application, user): - data = {'requestid': self.request.uid, 'csrf_token': self.get_csrf()} - output = self.app.post('/pv/pull-request/merge', data=data) + data = { + "requestid": self.request.uid, + "csrf_token": self.get_csrf(), + } + output = self.app.post("/pv/pull-request/merge", data=data) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertEqual( data, { - u'code': u'FFORWARD', - u'message': u'The pull-request can be merged and ' - u'fast-forwarded', - u'short_code': u'Ok' - } + "code": "FFORWARD", + "message": "The pull-request can be merged and " + "fast-forwarded", + "short_code": "Ok", + }, ) def test_rebase_api_ui_logged_in(self): """ Test the rebase PR API endpoint when logged in from the UI and its outcome. """ - user = tests.FakeUser(username='pingou') + user = tests.FakeUser(username="pingou") with tests.user_set(self.app.application, user): # Get the merge status first so it's cached and can be refreshed csrf_token = self.get_csrf() - data = {'requestid': self.request.uid, 'csrf_token': csrf_token} - output = self.app.post('/pv/pull-request/merge', data=data) + data = {"requestid": self.request.uid, "csrf_token": csrf_token} + output = self.app.post("/pv/pull-request/merge", data=data) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertEqual( data, { - u'code': u'MERGE', - u'message': u'The pull-request can be merged with ' - u'a merge commit', - u'short_code': u'With merge' - } + "code": "MERGE", + "message": "The pull-request can be merged with " + "a merge commit", + "short_code": "With merge", + }, ) - output = self.app.post('/api/0/test/pull-request/1/rebase') + output = self.app.post("/api/0/test/pull-request/1/rebase") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual( - data, - {u'message': u'Pull-request rebased'} - ) + self.assertEqual(data, {"message": "Pull-request rebased"}) - data = {'requestid': self.request.uid, 'csrf_token': csrf_token} - output = self.app.post('/pv/pull-request/merge', data=data) + data = {"requestid": self.request.uid, "csrf_token": csrf_token} + output = self.app.post("/pv/pull-request/merge", data=data) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertEqual( data, { - u'code': u'FFORWARD', - u'message': u'The pull-request can be merged and ' - u'fast-forwarded', - u'short_code': u'Ok' - } + "code": "FFORWARD", + "message": "The pull-request can be merged and " + "fast-forwarded", + "short_code": "Ok", + }, ) - output = self.app.get('/test/pull-request/1') + output = self.app.get("/test/pull-request/1") self.assertEqual(output.status_code, 200) output_text = output.get_data(as_text=True) - self.assertIn('rebased onto', output_text) - repo = pagure.lib.query._get_project(self.session, 'test') + self.assertIn("rebased onto", output_text) + repo = pagure.lib.query._get_project(self.session, "test") self.assertEqual( - repo.requests[0].comments[0].user.username, 'pingou') + repo.requests[0].comments[0].user.username, "pingou" + ) def test_rebase_api_ui_logged_in_different_user(self): """ Test the rebase PR API endpoint when logged in from the UI and its outcome. """ # Add 'foo' to the project 'test' so 'foo' can rebase the PR - repo = pagure.lib.query._get_project(self.session, 'test') + repo = pagure.lib.query._get_project(self.session, "test") msg = pagure.lib.query.add_user_to_project( - session=self.session, - project=repo, - new_user='foo', - user='pingou', + session=self.session, project=repo, new_user="foo", user="pingou" ) self.session.commit() - self.assertEqual(msg, 'User added') + self.assertEqual(msg, "User added") - user = tests.FakeUser(username='foo') + user = tests.FakeUser(username="foo") with tests.user_set(self.app.application, user): # Get the merge status first so it's cached and can be refreshed csrf_token = self.get_csrf() - data = {'requestid': self.request.uid, 'csrf_token': csrf_token} - output = self.app.post('/pv/pull-request/merge', data=data) + data = {"requestid": self.request.uid, "csrf_token": csrf_token} + output = self.app.post("/pv/pull-request/merge", data=data) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertEqual( data, { - u'code': u'MERGE', - u'message': u'The pull-request can be merged with ' - u'a merge commit', - u'short_code': u'With merge' - } + "code": "MERGE", + "message": "The pull-request can be merged with " + "a merge commit", + "short_code": "With merge", + }, ) - output = self.app.post('/api/0/test/pull-request/1/rebase') + output = self.app.post("/api/0/test/pull-request/1/rebase") self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual( - data, - {u'message': u'Pull-request rebased'} - ) + self.assertEqual(data, {"message": "Pull-request rebased"}) - data = {'requestid': self.request.uid, 'csrf_token': csrf_token} - output = self.app.post('/pv/pull-request/merge', data=data) + data = {"requestid": self.request.uid, "csrf_token": csrf_token} + output = self.app.post("/pv/pull-request/merge", data=data) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertEqual( data, { - u'code': u'FFORWARD', - u'message': u'The pull-request can be merged and ' - u'fast-forwarded', - u'short_code': u'Ok' - } + "code": "FFORWARD", + "message": "The pull-request can be merged and " + "fast-forwarded", + "short_code": "Ok", + }, ) - output = self.app.get('/test/pull-request/1') + output = self.app.get("/test/pull-request/1") self.assertEqual(output.status_code, 200) output_text = output.get_data(as_text=True) - self.assertIn('rebased onto', output_text) - repo = pagure.lib.query._get_project(self.session, 'test') - self.assertEqual(repo.requests[0].comments[0].user.username, 'foo') + self.assertIn("rebased onto", output_text) + repo = pagure.lib.query._get_project(self.session, "test") + self.assertEqual(repo.requests[0].comments[0].user.username, "foo") def test_rebase_api_api_logged_in(self): """ Test the rebase PR API endpoint when using an API token and @@ -261,65 +273,72 @@ class PagureRebasetests(tests.Modeltests): tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} - output = self.app.post('/api/0/test/pull-request/1/rebase', headers=headers) + output = self.app.post( + "/api/0/test/pull-request/1/rebase", headers=headers + ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual( - data, - {u'message': u'Pull-request rebased'} - ) + self.assertEqual(data, {"message": "Pull-request rebased"}) - user = tests.FakeUser(username='pingou') + user = tests.FakeUser(username="pingou") with tests.user_set(self.app.application, user): - data = {'requestid': self.request.uid, 'csrf_token': self.get_csrf()} - output = self.app.post('/pv/pull-request/merge', data=data) + data = { + "requestid": self.request.uid, + "csrf_token": self.get_csrf(), + } + output = self.app.post("/pv/pull-request/merge", data=data) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertEqual( data, { - u'code': u'FFORWARD', - u'message': u'The pull-request can be merged and ' - u'fast-forwarded', - u'short_code': u'Ok' - } + "code": "FFORWARD", + "message": "The pull-request can be merged and " + "fast-forwarded", + "short_code": "Ok", + }, ) def test_rebase_api_conflicts(self): """ Test the rebase PR API endpoint when logged in from the UI and its outcome. """ tests.add_content_to_git( - os.path.join(self.path, 'repos', 'test.git'), - branch='master', content="foobar baz") + os.path.join(self.path, "repos", "test.git"), + branch="master", + content="foobar baz", + ) - user = tests.FakeUser(username='pingou') + user = tests.FakeUser(username="pingou") with tests.user_set(self.app.application, user): - output = self.app.post('/api/0/test/pull-request/1/rebase') + output = self.app.post("/api/0/test/pull-request/1/rebase") self.assertEqual(output.status_code, 400) data = json.loads(output.get_data(as_text=True)) self.assertEqual( data, { - u'error': u'Did not manage to rebase this pull-request', - u'error_code': u'ENOCODE' - } + "error": "Did not manage to rebase this pull-request", + "error_code": "ENOCODE", + }, ) - data = {'requestid': self.request.uid, 'csrf_token': self.get_csrf()} - output = self.app.post('/pv/pull-request/merge', data=data) + data = { + "requestid": self.request.uid, + "csrf_token": self.get_csrf(), + } + output = self.app.post("/pv/pull-request/merge", data=data) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) self.assertEqual( data, { - u'code': u'CONFLICTS', - u'message': u'The pull-request cannot be merged due ' - u'to conflicts', - u'short_code': u'Conflicts' - } + "code": "CONFLICTS", + "message": "The pull-request cannot be merged due " + "to conflicts", + "short_code": "Conflicts", + }, ) def test_rebase_api_api_logged_in_unknown_project(self): @@ -328,14 +347,15 @@ class PagureRebasetests(tests.Modeltests): tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} - output = self.app.post('/api/0/unknown/pull-request/1/rebase', headers=headers) + output = self.app.post( + "/api/0/unknown/pull-request/1/rebase", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertEqual( - data, - {u'error': u'Project not found', u'error_code': u'ENOPROJECT'} + data, {"error": "Project not found", "error_code": "ENOPROJECT"} ) def test_rebase_api_api_logged_in_unknown_pr(self): @@ -344,14 +364,15 @@ class PagureRebasetests(tests.Modeltests): tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token aaabbbcccddd'} + headers = {"Authorization": "token aaabbbcccddd"} - output = self.app.post('/api/0/test/pull-request/404/rebase', headers=headers) + output = self.app.post( + "/api/0/test/pull-request/404/rebase", headers=headers + ) self.assertEqual(output.status_code, 404) data = json.loads(output.get_data(as_text=True)) self.assertEqual( - data, - {u'error': u'Pull-Request not found', u'error_code': u'ENOREQ'} + data, {"error": "Pull-Request not found", "error_code": "ENOREQ"} ) def test_rebase_api_api_logged_in_unknown_token(self): @@ -360,22 +381,24 @@ class PagureRebasetests(tests.Modeltests): tests.create_tokens(self.session) tests.create_tokens_acl(self.session) - headers = {'Authorization': 'token unknown'} + headers = {"Authorization": "token unknown"} - output = self.app.post('/api/0/test/pull-request/1/rebase', headers=headers) + output = self.app.post( + "/api/0/test/pull-request/1/rebase", headers=headers + ) self.assertEqual(output.status_code, 401) data = json.loads(output.get_data(as_text=True)) self.assertEqual( data, { - u'error': u'Invalid or expired token. Please visit ' - 'http://localhost.localdomain/settings#api-keys to get ' - 'or renew your API token.', - u'error_code': u'EINVALIDTOK', - u'errors': 'Invalid token', - } + "error": "Invalid or expired token. Please visit " + "http://localhost.localdomain/settings#api-keys to get " + "or renew your API token.", + "error_code": "EINVALIDTOK", + "errors": "Invalid token", + }, ) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/test_pagure_flask_ui_app.py b/tests/test_pagure_flask_ui_app.py index 98207b5..793245d 100644 --- a/tests/test_pagure_flask_ui_app.py +++ b/tests/test_pagure_flask_ui_app.py @@ -22,8 +22,9 @@ import json import pygit2 from mock import patch, MagicMock -sys.path.insert(0, os.path.join(os.path.dirname( - os.path.abspath(__file__)), '..')) +sys.path.insert( + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") +) import pagure.lib.query import tests @@ -33,54 +34,61 @@ class PagureFlaskApptests(tests.Modeltests): """ Tests for flask app controller of pagure """ def test_watch_list(self): - ''' Test for watch list of a user ''' + """ Test for watch list of a user """ - user = tests.FakeUser(username='pingou') + user = tests.FakeUser(username="pingou") with tests.user_set(self.app.application, user): - output = self.app.get('/', follow_redirects=True) + output = self.app.get("/", follow_redirects=True) output_text = output.get_data(as_text=True) self.assertIn( '
    You have no Projects
    ', - output_text) + output_text, + ) tests.create_projects(self.session) - output = self.app.get('/', follow_redirects=True) + output = self.app.get("/", follow_redirects=True) output_text = output.get_data(as_text=True) self.assertIn( '

    My Projects

    ', - output_text) + output_text, + ) def test_view_users(self): """ Test the view_users endpoint. """ - output = self.app.get('/users/?page=abc') + output = self.app.get("/users/?page=abc") self.assertEqual(output.status_code, 200) output_text = output.get_data(as_text=True) self.assertIn( '

    \n Users ' - '2', output_text) + '2', + output_text, + ) self.assertIn( '\n ' '""", + output_text, + ) self.assertIn( - """ + """ Forks  @@ -98,16 +108,18 @@ class PagureFlaskApptests(tests.Modeltests): 0 - """, output_text) + """, + output_text, + ) def test_view_user(self): """ Test the view_user endpoint. """ - output = self.app.get('/user/pingou?repopage=abc&forkpage=def') + output = self.app.get("/user/pingou?repopage=abc&forkpage=def") self.assertEqual(output.status_code, 200) output_text = output.get_data(as_text=True) self.assertIn( - """ + """ Projects  @@ -115,9 +127,11 @@ class PagureFlaskApptests(tests.Modeltests): 0 - """, output_text) + """, + output_text, + ) self.assertIn( - """ + """ Forks  @@ -125,17 +139,20 @@ class PagureFlaskApptests(tests.Modeltests): 0 - """, output_text) + """, + output_text, + ) tests.create_projects(self.session) self.gitrepos = tests.create_projects_git( - pagure.config.config['GIT_FOLDER']) + pagure.config.config["GIT_FOLDER"] + ) - output = self.app.get('/user/pingou?repopage=abc&forkpage=def') + output = self.app.get("/user/pingou?repopage=abc&forkpage=def") self.assertEqual(output.status_code, 200) output_text = output.get_data(as_text=True) self.assertIn( - """ + """ Projects  @@ -143,9 +160,11 @@ class PagureFlaskApptests(tests.Modeltests): 3 - """, output_text) + """, + output_text, + ) self.assertIn( - """ + """ Forks  @@ -153,73 +172,77 @@ class PagureFlaskApptests(tests.Modeltests): 0 - """, output_text) + """, + output_text, + ) self.assertNotIn( 'page 1 of 2', - output_text) + output_text, + ) - @patch.dict('pagure.config.config', {'ENABLE_UI_NEW_PROJECTS': False}) + @patch.dict("pagure.config.config", {"ENABLE_UI_NEW_PROJECTS": False}) def test_new_project_when_turned_off_in_the_ui(self): """ Test the new_project endpoint when new project creation is not allowed in the UI of this pagure instance. """ - user = tests.FakeUser(username='foo') + user = tests.FakeUser(username="foo") with tests.user_set(self.app.application, user): - output = self.app.get('/new/') + output = self.app.get("/new/") self.assertEqual(output.status_code, 404) - data = { - 'description': 'Project #1', - 'name': 'project-1', - } + data = {"description": "Project #1", "name": "project-1"} - output = self.app.post('/new/', data=data, follow_redirects=True) + output = self.app.post("/new/", data=data, follow_redirects=True) self.assertEqual(output.status_code, 404) - @patch.dict('pagure.config.config', {'ENABLE_UI_NEW_PROJECTS': False}) + @patch.dict("pagure.config.config", {"ENABLE_UI_NEW_PROJECTS": False}) def test_new_project_button_when_turned_off_in_the_ui_no_project(self): """ Test the index endpoint when new project creation is not allowed in the UI of this pagure instance. """ - user = tests.FakeUser(username='foo') + user = tests.FakeUser(username="foo") with tests.user_set(self.app.application, user): - output = self.app.get('/', follow_redirects=True) + output = self.app.get("/", follow_redirects=True) self.assertEqual(output.status_code, 200) output_text = output.get_data(as_text=True) self.assertIn( '

    My Projects

    ', - output_text) + output_text, + ) # master template self.assertNotIn( '